]> Sergey Matveev's repositories - public-inbox.git/blob - script/public-inbox-edit
inboxwritable: rename mime_from_path to eml_from_path
[public-inbox.git] / script / public-inbox-edit
1 #!/usr/bin/perl -w
2 # Copyright (C) 2019-2020 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 #
5 # Used for editing messages in a public-inbox.
6 # Supports v2 inboxes only, for now.
7 use strict;
8 use warnings;
9 use Getopt::Long qw(:config gnu_getopt no_ignore_case auto_abbrev);
10 use PublicInbox::AdminEdit;
11 use File::Temp 0.19 (); # 0.19 for TMPDIR
12 use PublicInbox::ContentHash qw(content_hash);
13 use PublicInbox::MID qw(mid_clean mids);
14 PublicInbox::Admin::check_require('-index');
15 use PublicInbox::Eml;
16 use PublicInbox::InboxWritable qw(eml_from_path);
17 use PublicInbox::Import;
18
19 my $usage = "$0 -m MESSAGE_ID [--all] [INBOX_DIRS]";
20 my $opt = { verbose => 1, all => 0, -min_inbox_version => 2, raw => 0 };
21 my @opt = qw(mid|m=s file|F=s raw);
22 GetOptions($opt, @PublicInbox::AdminEdit::OPT, @opt) or
23         die "bad command-line args\n$usage\n";
24
25 my $cfg = PublicInbox::Config->new;
26 my $editor = $ENV{MAIL_EDITOR}; # e.g. "mutt -f"
27 unless (defined $editor) {
28         my $k = 'publicinbox.mailEditor';
29         $editor = $cfg->{lc($k)} if $cfg;
30         unless (defined $editor) {
31                 warn "\`$k' not configured, trying \`git var GIT_EDITOR'\n";
32                 chomp($editor = `git var GIT_EDITOR`);
33                 warn "Will use $editor to edit mail\n";
34         }
35 }
36
37 my $mid = $opt->{mid};
38 my $file = $opt->{file};
39 if (defined $mid && defined $file) {
40         die "the --mid and --file options are mutually exclusive\n";
41 }
42
43 my @ibxs = PublicInbox::Admin::resolve_inboxes(\@ARGV, $opt, $cfg);
44 PublicInbox::AdminEdit::check_editable(\@ibxs);
45
46 my $found = {}; # chash => [ [ibx, smsg] [, [ibx, smsg] ] ]
47
48 sub find_mid ($$$) {
49         my ($found, $mid, $ibxs) = @_;
50         foreach my $ibx (@$ibxs) {
51                 my $over = $ibx->over;
52                 my ($id, $prev);
53                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
54                         my $ref = $ibx->msg_by_smsg($smsg);
55                         my $mime = PublicInbox::Eml->new($ref);
56                         my $chash = content_hash($mime);
57                         my $tuple = [ $ibx, $smsg ];
58                         push @{$found->{$chash} ||= []}, $tuple
59                 }
60                 PublicInbox::InboxWritable::cleanup($ibx);
61         }
62         $found;
63 }
64
65 sub show_cmd ($$) {
66         my ($ibx, $smsg) = @_;
67         " GIT_DIR=$ibx->{inboxdir}/all.git \\\n    git show $smsg->{blob}\n";
68 }
69
70 sub show_found ($) {
71         my ($found) = @_;
72         foreach my $to_edit (values %$found) {
73                 foreach my $tuple (@$to_edit) {
74                         my ($ibx, $smsg) = @$tuple;
75                         warn show_cmd($ibx, $smsg);
76                 }
77         }
78 }
79
80 if (defined($mid)) {
81         $mid = mid_clean($mid);
82         find_mid($found, $mid, \@ibxs);
83         my $nr = scalar(keys %$found);
84         die "No message found for <$mid>\n" unless $nr;
85         if ($nr > 1) {
86                 warn <<"";
87 Multiple messages with different content found matching
88 <$mid>:
89
90                 show_found($found);
91                 die "Use --force to edit all of them\n" if !$opt->{force};
92                 warn "Will edit all of them\n";
93         }
94 } else {
95         my $eml = eml_from_path($file) or die "open($file) failed: $!";
96         my $mids = mids($eml->header_obj);
97         find_mid($found, $_, \@ibxs) for (@$mids); # populates $found
98         my $chash = content_hash($eml);
99         my $to_edit = $found->{$chash};
100         unless ($to_edit) {
101                 my $nr = scalar(keys %$found);
102                 if ($nr > 0) {
103                         warn <<"";
104 $nr matches to Message-ID(s) in $file, but none matched content
105 Partial matches below:
106
107                         show_found($found);
108                 } elsif ($nr == 0) {
109                         $mids = join('', map { "  <$_>\n" } @$mids);
110                         warn <<"";
111 No matching messages found matching Message-ID(s) in $file
112 $mids
113
114                 }
115                 exit 1;
116         }
117         $found = { $chash => $to_edit };
118 }
119
120 my %tmpopt = (
121         TEMPLATE => 'public-inbox-edit-XXXXXX',
122         TMPDIR => 1,
123         SUFFIX => $opt->{raw} ? '.eml' : '.mbox',
124 );
125
126 foreach my $to_edit (values %$found) {
127         my $edit_fh = File::Temp->new(%tmpopt);
128         $edit_fh->autoflush(1);
129         my $edit_fn = $edit_fh->filename;
130         my ($ibx, $smsg) = @{$to_edit->[0]};
131         my $old_raw = $ibx->msg_by_smsg($smsg);
132         PublicInbox::InboxWritable::cleanup($ibx);
133
134         my $tmp = $$old_raw;
135         if (!$opt->{raw}) {
136                 my $oid = $smsg->{blob};
137                 print $edit_fh "From mboxrd\@$oid Thu Jan  1 00:00:00 1970\n"
138                         or die "failed to write From_ line: $!";
139                 $tmp =~ s/^(>*From )/>$1/gm;
140         }
141         print $edit_fh $tmp or
142                 die "failed to write tempfile for editing: $!";
143
144         # run the editor, respecting spaces/quote
145 retry_edit:
146         if (system(qw(sh -c), $editor.' "$@"', $editor, $edit_fn)) {
147                 if (!(-t STDIN) && !$opt->{force}) {
148                         die "E: $editor failed: $?\n";
149                 }
150                 print STDERR "$editor failed, ";
151                 print STDERR "continuing as forced\n" if $opt->{force};
152                 while (!$opt->{force}) {
153                         print STDERR "(r)etry, (c)ontinue, (q)uit?\n";
154                         chomp(my $op = <STDIN> || '');
155                         $op = lc($op);
156                         goto retry_edit if $op eq 'r';
157                         if ($op eq 'q') {
158                                 # n.b. we'll lose the exit signal, here,
159                                 # oh well; "q" is user-specified anyways.
160                                 exit($? >> 8);
161                         }
162                         last if $op eq 'c'; # continuing
163                         print STDERR "\`$op' not recognized\n";
164                 }
165         }
166
167         # reread the edited file, not using $edit_fh since $EDITOR may
168         # rename/relink $edit_fn
169         open my $new_fh, '<', $edit_fn or
170                 die "can't read edited file ($edit_fn): $!\n";
171         my $new_raw = do { local $/; <$new_fh> };
172
173         if (!$opt->{raw}) {
174                 # get rid of the From we added
175                 $new_raw =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
176
177                 # check if user forgot to purge (in mutt) after editing
178                 if ($new_raw =~ /^From /sm) {
179                         if (-t STDIN) {
180                                 print STDERR <<'';
181 Extra "From " lines detected in new mbox.
182 Did you forget to purge the original message from the mbox after editing?
183
184                                 while (1) {
185                                         print STDERR <<"";
186 (y)es to re-edit, (n)o to continue
187
188                                         chomp(my $op = <STDIN> || '');
189                                         $op = lc($op);
190                                         goto retry_edit if $op eq 'y';
191                                         last if $op eq 'n'; # continuing
192                                         print STDERR "\`$op' not recognized\n";
193                                 }
194                         } else { # non-interactive path
195                                 # unlikely to happen, as extra From lines are
196                                 # only a common mistake (for me) with
197                                 # interactive use
198                                 warn <<"";
199 W: possible message boundary splitting error
200
201                         }
202                 }
203                 # unescape what we escaped:
204                 $new_raw =~ s/^>(>*From )/$1/gm;
205         }
206
207         my $new_mime = PublicInbox::Eml->new(\$new_raw);
208         my $old_mime = PublicInbox::Eml->new($old_raw);
209
210         # make sure we don't compare unwanted headers, since mutt adds
211         # Content-Length, Status, and Lines headers:
212         PublicInbox::Import::drop_unwanted_headers($new_mime);
213         PublicInbox::Import::drop_unwanted_headers($old_mime);
214
215         # allow changing Received: and maybe other headers which can
216         # contain sensitive info.
217         my $nhdr = $new_mime->header_obj;
218         my $ohdr = $old_mime->header_obj;
219         if (($nhdr->as_string eq $ohdr->as_string) &&
220             (content_hash($new_mime) eq content_hash($old_mime))) {
221                 warn "No change detected to:\n", show_cmd($ibx, $smsg);
222
223                 next unless $opt->{verbose};
224                 # should we consider this machine-parseable?
225                 PublicInbox::AdminEdit::show_rewrites(\*STDOUT, $ibx, []);
226                 next;
227         }
228
229         foreach my $tuple (@$to_edit) {
230                 $ibx = PublicInbox::InboxWritable->new($tuple->[0]);
231                 $smsg = $tuple->[1];
232                 my $im = $ibx->importer(0);
233                 my $commits = $im->replace($old_mime, $new_mime);
234                 $im->done;
235                 unless ($commits) {
236                         warn "Failed to replace:\n", show_cmd($ibx, $smsg);
237                         next;
238                 }
239                 next unless $opt->{verbose};
240                 # should we consider this machine-parseable?
241                 PublicInbox::AdminEdit::show_rewrites(\*STDOUT, $ibx, $commits);
242         }
243 }