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