]> Sergey Matveev's repositories - public-inbox.git/blob - script/public-inbox-edit
2a9f0531f7377dfc4f2c02a995c7133eeb579fdd
[public-inbox.git] / script / public-inbox-edit
1 #!/usr/bin/perl -w
2 # Copyright (C) 2019 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 ();
12 use PublicInbox::ContentId qw(content_id);
13 use PublicInbox::MID qw(mid_clean mids);
14 PublicInbox::Admin::check_require('-index');
15 require PublicInbox::MIME;
16 require PublicInbox::InboxWritable;
17 require 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 = eval { 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 = {}; # cid => [ [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::MIME->new($ref);
56                         my $cid = content_id($mime);
57                         my $tuple = [ $ibx, $smsg ];
58                         push @{$found->{$cid} ||= []}, $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         open my $fh, '<', $file or die "open($file) failed: $!";
96         my $orig = do { local $/; <$fh> };
97         my $mime = PublicInbox::MIME->new(\$orig);
98         my $mids = mids($mime->header_obj);
99         find_mid($found, $_, \@ibxs) for (@$mids); # populates $found
100         my $cid = content_id($mime);
101         my $to_edit = $found->{$cid};
102         unless ($to_edit) {
103                 my $nr = scalar(keys %$found);
104                 if ($nr > 0) {
105                         warn <<"";
106 $nr matches to Message-ID(s) in $file, but none matched content
107 Partial matches below:
108
109                         show_found($found);
110                 } elsif ($nr == 0) {
111                         $mids = join('', map { "  <$_>\n" } @$mids);
112                         warn <<"";
113 No matching messages found matching Message-ID(s) in $file
114 $mids
115
116                 }
117                 exit 1;
118         }
119         $found = { $cid => $to_edit };
120 }
121
122 my %tmpopt = (
123         TEMPLATE => 'public-inbox-edit-XXXXXX',
124         TMPDIR => 1,
125         SUFFIX => $opt->{raw} ? '.eml' : '.mbox',
126 );
127
128 foreach my $to_edit (values %$found) {
129         my $edit_fh = File::Temp->new(%tmpopt);
130         $edit_fh->autoflush(1);
131         my $edit_fn = $edit_fh->filename;
132         my ($ibx, $smsg) = @{$to_edit->[0]};
133         my $old_raw = $ibx->msg_by_smsg($smsg);
134         PublicInbox::InboxWritable::cleanup($ibx);
135
136         my $tmp = $$old_raw;
137         if (!$opt->{raw}) {
138                 my $oid = $smsg->{blob};
139                 print $edit_fh "From mboxrd\@$oid Thu Jan  1 00:00:00 1970\n"
140                         or die "failed to write From_ line: $!";
141                 $tmp =~ s/^(>*From )/>$1/gm;
142         }
143         print $edit_fh $tmp or
144                 die "failed to write tempfile for editing: $!";
145
146         # run the editor, respecting spaces/quote
147 retry_edit:
148         if (system(qw(sh -c), $editor.' "$@"', $editor, $edit_fn)) {
149                 if (!(-t STDIN) && !$opt->{force}) {
150                         die "E: $editor failed: $?\n";
151                 }
152                 print STDERR "$editor failed, ";
153                 print STDERR "continuing as forced\n" if $opt->{force};
154                 while (!$opt->{force}) {
155                         print STDERR "(r)etry, (c)ontinue, (q)uit?\n";
156                         chomp(my $op = <STDIN> || '');
157                         $op = lc($op);
158                         goto retry_edit if $op eq 'r';
159                         if ($op eq 'q') {
160                                 # n.b. we'll lose the exit signal, here,
161                                 # oh well; "q" is user-specified anyways.
162                                 exit($? >> 8);
163                         }
164                         last if $op eq 'c'; # continuing
165                         print STDERR "\`$op' not recognized\n";
166                 }
167         }
168
169         # reread the edited file, not using $edit_fh since $EDITOR may
170         # rename/relink $edit_fn
171         open my $new_fh, '<', $edit_fn or
172                 die "can't read edited file ($edit_fn): $!\n";
173         my $new_raw = do { local $/; <$new_fh> };
174
175         if (!$opt->{raw}) {
176                 # get rid of the From we added
177                 $new_raw =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
178
179                 # check if user forgot to purge (in mutt) after editing
180                 if ($new_raw =~ /^From /sm) {
181                         if (-t STDIN) {
182                                 print STDERR <<'';
183 Extra "From " lines detected in new mbox.
184 Did you forget to purge the original message from the mbox after editing?
185
186                                 while (1) {
187                                         print STDERR <<"";
188 (y)es to re-edit, (n)o to continue
189
190                                         chomp(my $op = <STDIN> || '');
191                                         $op = lc($op);
192                                         goto retry_edit if $op eq 'y';
193                                         last if $op eq 'n'; # continuing
194                                         print STDERR "\`$op' not recognized\n";
195                                 }
196                         } else { # non-interactive path
197                                 # unlikely to happen, as extra From lines are
198                                 # only a common mistake (for me) with
199                                 # interactive use
200                                 warn <<"";
201 W: possible message boundary splitting error
202
203                         }
204                 }
205                 # unescape what we escaped:
206                 $new_raw =~ s/^>(>*From )/$1/gm;
207         }
208
209         my $new_mime = PublicInbox::MIME->new(\$new_raw);
210         my $old_mime = PublicInbox::MIME->new($old_raw);
211
212         # make sure we don't compare unwanted headers, since mutt adds
213         # Content-Length, Status, and Lines headers:
214         PublicInbox::Import::drop_unwanted_headers($new_mime);
215         PublicInbox::Import::drop_unwanted_headers($old_mime);
216
217         # allow changing Received: and maybe other headers which can
218         # contain sensitive info.
219         my $nhdr = $new_mime->header_obj;
220         my $ohdr = $old_mime->header_obj;
221         if (($nhdr->as_string eq $ohdr->as_string) &&
222             (content_id($new_mime) eq content_id($old_mime))) {
223                 warn "No change detected to:\n", show_cmd($ibx, $smsg);
224
225                 next unless $opt->{verbose};
226                 # should we consider this machine-parseable?
227                 PublicInbox::AdminEdit::show_rewrites(\*STDOUT, $ibx, []);
228                 next;
229         }
230
231         foreach my $tuple (@$to_edit) {
232                 $ibx = PublicInbox::InboxWritable->new($tuple->[0]);
233                 $smsg = $tuple->[1];
234                 my $im = $ibx->importer(0);
235                 my $commits = $im->replace($old_mime, $new_mime);
236                 $im->done;
237                 unless ($commits) {
238                         warn "Failed to replace:\n", show_cmd($ibx, $smsg);
239                         next;
240                 }
241                 next unless $opt->{verbose};
242                 # should we consider this machine-parseable?
243                 PublicInbox::AdminEdit::show_rewrites(\*STDOUT, $ibx, $commits);
244         }
245 }