]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
spawn (and thus popen_rd) die on failure
[public-inbox.git] / lib / PublicInbox / Import.pm
1 # Copyright (C) 2016-2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # git fast-import-based ssoma-mda MDA replacement
5 # This is only ever run by public-inbox-mda, public-inbox-learn
6 # and public-inbox-watch. Not the WWW or NNTP code which only
7 # requires read-only access.
8 package PublicInbox::Import;
9 use strict;
10 use warnings;
11 use base qw(PublicInbox::Lock);
12 use PublicInbox::Spawn qw(spawn);
13 use PublicInbox::MID qw(mids mid2path);
14 use PublicInbox::Address;
15 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
16 use PublicInbox::ContentId qw(content_digest);
17 use PublicInbox::MDA;
18 use POSIX qw(strftime);
19
20 sub new {
21         # we can't change arg order, this is documented in POD
22         # and external projects may rely on it:
23         my ($class, $git, $name, $email, $ibx) = @_;
24         my $ref = 'refs/heads/master';
25         if ($ibx) {
26                 $ref = $ibx->{ref_head} || 'refs/heads/master';
27                 $name ||= $ibx->{name};
28                 $email ||= $ibx->{-primary_address};
29                 $git ||= $ibx->git;
30         }
31         bless {
32                 git => $git,
33                 ident => "$name <$email>",
34                 mark => 1,
35                 ref => $ref,
36                 -inbox => $ibx,
37                 path_type => '2/38', # or 'v2'
38                 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
39                 bytes_added => 0,
40         }, $class
41 }
42
43 # idempotent start function
44 sub gfi_start {
45         my ($self) = @_;
46
47         return ($self->{in}, $self->{out}) if $self->{pid};
48
49         my ($in_r, $in_w, $out_r, $out_w);
50         pipe($in_r, $in_w) or die "pipe failed: $!";
51         pipe($out_r, $out_w) or die "pipe failed: $!";
52         my $git = $self->{git};
53
54         $self->lock_acquire;
55
56         local $/ = "\n";
57         my $ref = $self->{ref};
58         chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
59         if ($self->{path_type} ne '2/38' && $self->{tip}) {
60                 local $/ = "\0";
61                 my @tree = $git->qx(qw(ls-tree -r -z --name-only), $ref);
62                 chomp @tree;
63                 $self->{-tree} = { map { $_ => 1 } @tree };
64         }
65
66         my $git_dir = $git->{git_dir};
67         my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
68                         --quiet --done --date-format=raw));
69         my $rdr = { 0 => $out_r, 1 => $in_w };
70         my $pid = spawn(\@cmd, undef, $rdr);
71         $out_w->autoflush(1);
72         $self->{in} = $in_r;
73         $self->{out} = $out_w;
74         $self->{pid} = $pid;
75         $self->{nchg} = 0;
76         binmode $out_w, ':raw' or die "binmode :raw failed: $!";
77         binmode $in_r, ':raw' or die "binmode :raw failed: $!";
78         ($in_r, $out_w);
79 }
80
81 sub wfail () { die "write to fast-import failed: $!" }
82
83 sub now_raw () { time . ' +0000' }
84
85 sub norm_body ($) {
86         my ($mime) = @_;
87         my $b = $mime->body_raw;
88         $b =~ s/(\r?\n)+\z//s;
89         $b
90 }
91
92 # only used for v1 (ssoma) inboxes
93 sub _check_path ($$$$) {
94         my ($r, $w, $tip, $path) = @_;
95         return if $tip eq '';
96         print $w "ls $tip $path\n" or wfail;
97         local $/ = "\n";
98         defined(my $info = <$r>) or die "EOF from fast-import: $!";
99         $info =~ /\Amissing / ? undef : $info;
100 }
101
102 sub _cat_blob ($$$) {
103         my ($r, $w, $oid) = @_;
104         print $w "cat-blob $oid\n" or wfail;
105         local $/ = "\n";
106         my $info = <$r>;
107         defined $info or die "EOF from fast-import / cat-blob: $!";
108         $info =~ /\A[a-f0-9]{40} blob ([0-9]+)\n\z/ or return;
109         my $left = $1;
110         my $offset = 0;
111         my $buf = '';
112         my $n;
113         while ($left > 0) {
114                 $n = read($r, $buf, $left, $offset);
115                 defined($n) or die "read cat-blob failed: $!";
116                 $n == 0 and die 'fast-export (cat-blob) died';
117                 $left -= $n;
118                 $offset += $n;
119         }
120         $n = read($r, my $lf, 1);
121         defined($n) or die "read final byte of cat-blob failed: $!";
122         die "bad read on final byte: <$lf>" if $lf ne "\n";
123
124         # fixup some bugginess in old versions:
125         $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
126         \$buf;
127 }
128
129 sub cat_blob {
130         my ($self, $oid) = @_;
131         my ($r, $w) = $self->gfi_start;
132         _cat_blob($r, $w, $oid);
133 }
134
135 sub check_remove_v1 {
136         my ($r, $w, $tip, $path, $mime) = @_;
137
138         my $info = _check_path($r, $w, $tip, $path) or return ('MISSING',undef);
139         $info =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $info";
140         my $oid = $1;
141         my $msg = _cat_blob($r, $w, $oid) or die "BUG: cat-blob $1 failed";
142         my $cur = PublicInbox::MIME->new($msg);
143         my $cur_s = $cur->header('Subject');
144         $cur_s = '' unless defined $cur_s;
145         my $cur_m = $mime->header('Subject');
146         $cur_m = '' unless defined $cur_m;
147         if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
148                 return ('MISMATCH', $cur);
149         }
150         (undef, $cur);
151 }
152
153 sub checkpoint {
154         my ($self) = @_;
155         return unless $self->{pid};
156         print { $self->{out} } "checkpoint\n" or wfail;
157         undef;
158 }
159
160 sub progress {
161         my ($self, $msg) = @_;
162         return unless $self->{pid};
163         print { $self->{out} } "progress $msg\n" or wfail;
164         $self->{in}->getline eq "progress $msg\n" or die
165                 "progress $msg not received\n";
166         undef;
167 }
168
169 sub _update_git_info ($$) {
170         my ($self, $do_gc) = @_;
171         # for compatibility with existing ssoma installations
172         # we can probably remove this entirely by 2020
173         my $git_dir = $self->{git}->{git_dir};
174         my @cmd = ('git', "--git-dir=$git_dir");
175         my $index = "$git_dir/ssoma.index";
176         if (-e $index && !$ENV{FAST}) {
177                 my $env = { GIT_INDEX_FILE => $index };
178                 run_die([@cmd, qw(read-tree -m -v -i), $self->{ref}], $env);
179         }
180         run_die([@cmd, 'update-server-info']);
181         my $ibx = $self->{-inbox};
182         ($ibx && $self->{path_type} eq '2/38') and eval {
183                 require PublicInbox::SearchIdx;
184                 my $s = PublicInbox::SearchIdx->new($ibx);
185                 $s->index_sync({ ref => $self->{ref} });
186         };
187         eval { run_die([@cmd, qw(gc --auto)]) } if $do_gc;
188 }
189
190 sub barrier {
191         my ($self) = @_;
192
193         # For safety, we ensure git checkpoint is complete before because
194         # the data in git is still more important than what is in Xapian
195         # in v2.  Performance may be gained by delaying the ->progress
196         # call but we lose safety
197         if ($self->{nchg}) {
198                 $self->checkpoint;
199                 $self->progress('checkpoint');
200                 _update_git_info($self, 0);
201                 $self->{nchg} = 0;
202         }
203 }
204
205 # used for v2
206 sub get_mark {
207         my ($self, $mark) = @_;
208         die "not active\n" unless $self->{pid};
209         my ($r, $w) = $self->gfi_start;
210         print $w "get-mark $mark\n" or wfail;
211         defined(my $oid = <$r>) or die "get-mark failed, need git 2.6.0+\n";
212         chomp($oid);
213         $oid;
214 }
215
216 # returns undef on non-existent
217 # ('MISMATCH', Email::MIME) on mismatch
218 # (:MARK, Email::MIME) on success
219 #
220 # v2 callers should check with Xapian before calling this as
221 # it is not idempotent.
222 sub remove {
223         my ($self, $mime, $msg) = @_; # mime = Email::MIME
224
225         my $path_type = $self->{path_type};
226         my ($path, $err, $cur, $blob);
227
228         my ($r, $w) = $self->gfi_start;
229         my $tip = $self->{tip};
230         if ($path_type eq '2/38') {
231                 $path = mid2path(v1_mid0($mime));
232                 ($err, $cur) = check_remove_v1($r, $w, $tip, $path, $mime);
233                 return ($err, $cur) if $err;
234         } else {
235                 my $sref;
236                 if (ref($mime) eq 'SCALAR') { # optimization used by V2Writable
237                         $sref = $mime;
238                 } else { # XXX should not be necessary:
239                         my $str = $mime->as_string;
240                         $sref = \$str;
241                 }
242                 my $len = length($$sref);
243                 $blob = $self->{mark}++;
244                 print $w "blob\nmark :$blob\ndata $len\n",
245                         $$sref, "\n" or wfail;
246         }
247
248         my $ref = $self->{ref};
249         my $commit = $self->{mark}++;
250         my $parent = $tip =~ /\A:/ ? $tip : undef;
251         unless ($parent) {
252                 print $w "reset $ref\n" or wfail;
253         }
254         my $ident = $self->{ident};
255         my $now = now_raw();
256         $msg ||= 'rm';
257         my $len = length($msg) + 1;
258         print $w "commit $ref\nmark :$commit\n",
259                 "author $ident $now\n",
260                 "committer $ident $now\n",
261                 "data $len\n$msg\n\n",
262                 'from ', ($parent ? $parent : $tip), "\n" or wfail;
263         if (defined $path) {
264                 print $w "D $path\n\n" or wfail;
265         } else {
266                 clean_tree_v2($self, $w, 'd');
267                 print $w "M 100644 :$blob d\n\n" or wfail;
268         }
269         $self->{nchg}++;
270         (($self->{tip} = ":$commit"), $cur);
271 }
272
273 sub git_timestamp {
274         my ($ts, $zone) = @_;
275         $ts = 0 if $ts < 0; # git uses unsigned times
276         "$ts $zone";
277 }
278
279 sub extract_cmt_info ($) {
280         my ($mime) = @_;
281
282         my $sender = '';
283         my $from = $mime->header('From');
284         $from ||= '';
285         my ($email) = PublicInbox::Address::emails($from);
286         my ($name) = PublicInbox::Address::names($from);
287         if (!defined($name) || !defined($email)) {
288                 $sender = $mime->header('Sender');
289                 $sender ||= '';
290                 if (!defined($name)) {
291                         ($name) = PublicInbox::Address::names($sender);
292                 }
293                 if (!defined($email)) {
294                         ($email) = PublicInbox::Address::emails($sender);
295                 }
296         }
297         if (defined $email) {
298                 # quiet down wide character warnings with utf8::encode
299                 utf8::encode($email);
300         } else {
301                 $email = '';
302                 warn "no email in From: $from or Sender: $sender\n";
303         }
304
305         # git gets confused with:
306         #  "'A U Thor <u@example.com>' via foo" <foo@example.com>
307         # ref:
308         # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
309         if (defined $name) {
310                 $name =~ tr/<>//d;
311                 utf8::encode($name);
312         } else {
313                 $name = '';
314                 warn "no name in From: $from or Sender: $sender\n";
315         }
316
317         my $hdr = $mime->header_obj;
318
319         my $subject = $hdr->header('Subject');
320         $subject = '(no subject)' unless defined $subject;
321         # Mime decoding can create nulls replace them with spaces to protect git
322         $subject =~ tr/\0/ /;
323         utf8::encode($subject);
324         my $at = git_timestamp(my @at = msg_datestamp($hdr));
325         my $ct = git_timestamp(my @ct = msg_timestamp($hdr));
326         ($name, $email, $at, $ct, $subject);
327 }
328
329 # kill potentially confusing/misleading headers
330 sub drop_unwanted_headers ($) {
331         my ($mime) = @_;
332
333         $mime->header_set($_) for qw(bytes lines content-length status);
334         $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
335 }
336
337 # used by V2Writable, too
338 sub append_mid ($$) {
339         my ($hdr, $mid0) = @_;
340         # @cur is likely empty if we need to call this sub, but it could
341         # have random unparseable crap which we'll preserve, too.
342         my @cur = $hdr->header_raw('Message-ID');
343         $hdr->header_set('Message-ID', @cur, "<$mid0>");
344 }
345
346 sub v1_mid0 ($) {
347         my ($mime) = @_;
348         my $hdr = $mime->header_obj;
349         my $mids = mids($hdr);
350
351         if (!scalar(@$mids)) { # spam often has no Message-Id
352                 my $mid0 = digest2mid(content_digest($mime), $hdr);
353                 append_mid($hdr, $mid0);
354                 return $mid0;
355         }
356         $mids->[0];
357 }
358 sub clean_tree_v2 ($$$) {
359         my ($self, $w, $keep) = @_;
360         my $tree = $self->{-tree} or return; #v2 only
361         delete $tree->{$keep};
362         foreach (keys %$tree) {
363                 print $w "D $_\n" or wfail;
364         }
365         %$tree = ($keep => 1);
366 }
367
368 # returns undef on duplicate
369 # returns the :MARK of the most recent commit
370 sub add {
371         my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
372
373         my ($name, $email, $at, $ct, $subject) = extract_cmt_info($mime);
374         my $path_type = $self->{path_type};
375         my $path;
376         if ($path_type eq '2/38') {
377                 $path = mid2path(v1_mid0($mime));
378         } else { # v2 layout, one file:
379                 $path = 'm';
380         }
381
382         my ($r, $w) = $self->gfi_start;
383         my $tip = $self->{tip};
384         if ($path_type eq '2/38') {
385                 _check_path($r, $w, $tip, $path) and return;
386         }
387
388         drop_unwanted_headers($mime);
389
390         # spam check:
391         if ($check_cb) {
392                 $mime = $check_cb->($mime) or return;
393         }
394
395         my $blob = $self->{mark}++;
396         my $raw_email = $mime->{-public_inbox_raw} // $mime->as_string;
397         my $n = length($raw_email);
398         $self->{bytes_added} += $n;
399         print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
400         print $w $raw_email, "\n" or wfail;
401
402         # v2: we need this for Xapian
403         if ($self->{want_object_info}) {
404                 my $oid = $self->get_mark(":$blob");
405                 $self->{last_object} = [ $oid, $n, \$raw_email ];
406         }
407         my $ref = $self->{ref};
408         my $commit = $self->{mark}++;
409         my $parent = $tip =~ /\A:/ ? $tip : undef;
410
411         unless ($parent) {
412                 print $w "reset $ref\n" or wfail;
413         }
414
415         print $w "commit $ref\nmark :$commit\n",
416                 "author $name <$email> $at\n",
417                 "committer $self->{ident} $ct\n" or wfail;
418         print $w "data ", (length($subject) + 1), "\n",
419                 $subject, "\n\n" or wfail;
420         if ($tip ne '') {
421                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
422         }
423         clean_tree_v2($self, $w, $path);
424         print $w "M 100644 :$blob $path\n\n" or wfail;
425         $self->{nchg}++;
426         $self->{tip} = ":$commit";
427 }
428
429 sub run_die ($;$$) {
430         my ($cmd, $env, $rdr) = @_;
431         my $pid = spawn($cmd, $env, $rdr);
432         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
433         $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
434 }
435
436 sub init_bare {
437         my ($dir) = @_;
438         my @cmd = (qw(git init --bare -q), $dir);
439         run_die(\@cmd);
440         # set a reasonable default:
441         @cmd = (qw/git config/, "--file=$dir/config",
442                 'repack.writeBitmaps', 'true');
443         run_die(\@cmd);
444 }
445
446 sub done {
447         my ($self) = @_;
448         my $w = delete $self->{out} or return;
449         my $r = delete $self->{in} or die 'BUG: missing {in} when done';
450         print $w "done\n" or wfail;
451         my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
452         waitpid($pid, 0) == $pid or die 'fast-import did not finish';
453         $? == 0 or die "fast-import failed: $?";
454
455         _update_git_info($self, 1) if delete $self->{nchg};
456
457         $self->lock_release;
458
459         $self->{git}->cleanup;
460 }
461
462 sub atfork_child {
463         my ($self) = @_;
464         foreach my $f (qw(in out)) {
465                 next unless defined($self->{$f});
466                 close $self->{$f} or die "failed to close import[$f]: $!\n";
467         }
468 }
469
470 sub digest2mid ($$) {
471         my ($dig, $hdr) = @_;
472         my $b64 = $dig->clone->b64digest;
473         # Make our own URLs nicer:
474         # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
475         $b64 =~ tr!+/=!-_!d;
476
477         # Add a date prefix to prevent a leading '-' in case that trips
478         # up some tools (e.g. if a Message-ID were a expected as a
479         # command-line arg)
480         my $dt = msg_datestamp($hdr);
481         $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
482         "$dt.$b64" . '@z';
483 }
484
485 sub rewrite_commit ($$$$) {
486         my ($self, $oids, $buf, $mime) = @_;
487         my ($name, $email, $at, $ct, $subject);
488         if ($mime) {
489                 ($name, $email, $at, $ct, $subject) = extract_cmt_info($mime);
490         } else {
491                 $name = $email = '';
492                 $subject = 'purged '.join(' ', @$oids);
493         }
494         @$oids = ();
495         $subject .= "\n";
496         foreach my $i (0..$#$buf) {
497                 my $l = $buf->[$i];
498                 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
499                         $at //= $1;
500                         $buf->[$i] = "author $name <$email> $at\n";
501                 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
502                         $ct //= $1;
503                         $buf->[$i] = "committer $self->{ident} $ct\n";
504                 } elsif ($l =~ /^data ([0-9]+)/) {
505                         $buf->[$i++] = "data " . length($subject) . "\n";
506                         $buf->[$i] = $subject;
507                         last;
508                 }
509         }
510 }
511
512 # returns the new commit OID if a replacement was done
513 # returns undef if nothing was done
514 sub replace_oids {
515         my ($self, $mime, $replace_map) = @_; # oid => raw string
516         my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
517         my $old = $self->{'ref'};
518         my $git = $self->{git};
519         my @export = (qw(fast-export --no-data --use-done-feature), $old);
520         my $rd = $git->popen(@export);
521         my ($r, $w) = $self->gfi_start;
522         my @buf;
523         my $nreplace = 0;
524         my @oids;
525         my ($done, $mark);
526         my $tree = $self->{-tree};
527         while (<$rd>) {
528                 if (/^reset (?:.+)/) {
529                         push @buf, "reset $tmp\n";
530                 } elsif (/^commit (?:.+)/) {
531                         if (@buf) {
532                                 $w->print(@buf) or wfail;
533                                 @buf = ();
534                         }
535                         push @buf, "commit $tmp\n";
536                 } elsif (/^data ([0-9]+)/) {
537                         # only commit message, so $len is small:
538                         my $len = $1; # + 1 for trailing "\n"
539                         push @buf, $_;
540                         my $n = read($rd, my $buf, $len) or die "read: $!";
541                         $len == $n or die "short read ($n < $len)";
542                         push @buf, $buf;
543                 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
544                         my ($oid, $path) = ($1, $2);
545                         $tree->{$path} = 1;
546                         my $sref = $replace_map->{$oid};
547                         if (defined $sref) {
548                                 push @oids, $oid;
549                                 my $n = length($$sref);
550                                 push @buf, "M 100644 inline $path\ndata $n\n";
551                                 push @buf, $$sref; # hope CoW works...
552                                 push @buf, "\n";
553                         } else {
554                                 push @buf, $_;
555                         }
556                 } elsif (/^D (\w+)/) {
557                         my $path = $1;
558                         push @buf, $_ if $tree->{$path};
559                 } elsif ($_ eq "\n") {
560                         if (@oids) {
561                                 if (!$mime) {
562                                         my $out = join('', @buf);
563                                         $out =~ s/^/# /sgm;
564                                         warn "purge rewriting\n", $out, "\n";
565                                 }
566                                 rewrite_commit($self, \@oids, \@buf, $mime);
567                                 $nreplace++;
568                         }
569                         $w->print(@buf, "\n") or wfail;
570                         @buf = ();
571                 } elsif ($_ eq "done\n") {
572                         $done = 1;
573                 } elsif (/^mark :([0-9]+)$/) {
574                         push @buf, $_;
575                         $mark = $1;
576                 } else {
577                         push @buf, $_;
578                 }
579         }
580         close $rd or die "close fast-export failed: $?";
581         if (@buf) {
582                 $w->print(@buf) or wfail;
583         }
584         die 'done\n not seen from fast-export' unless $done;
585         chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
586         $self->{nchg} = 0; # prevent _update_git_info until update-ref:
587         $self->done;
588         my @git = ('git', "--git-dir=$git->{git_dir}");
589
590         run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
591
592         run_die([@git, qw(update-ref -d), $tmp]);
593
594         return if $nreplace == 0;
595
596         run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
597
598         # check that old OIDs are gone
599         my $err = 0;
600         foreach my $oid (keys %$replace_map) {
601                 my @info = $git->check($oid);
602                 if (@info) {
603                         warn "$oid not replaced\n";
604                         $err++;
605                 }
606         }
607         _update_git_info($self, 0);
608         die "Failed to replace $err object(s)\n" if $err;
609         $cmt;
610 }
611
612 1;
613 __END__
614 =pod
615
616 =head1 NAME
617
618 PublicInbox::Import - message importer for public-inbox v1 inboxes
619
620 =head1 VERSION
621
622 version 1.0
623
624 =head1 SYNOPSIS
625
626         use Email::MIME;
627         use PublicInbox::Git;
628         use PublicInbox::Import;
629
630         chomp(my $git_dir = `git rev-parse --git-dir`);
631         $git_dir or die "GIT_DIR= must be specified\n";
632         my $git = PublicInbox::Git->new($git_dir);
633         my @committer = ('inbox', 'inbox@example.org');
634         my $im = PublicInbox::Import->new($git, @committer);
635
636         # to add a message:
637         my $message = "From: <u\@example.org>\n".
638                 "Subject: test message \n" .
639                 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
640                 "Message-ID: <m\@example.org>\n".
641                 "\ntest message";
642         my $parsed = Email::MIME->new($message);
643         my $ret = $im->add($parsed);
644         if (!defined $ret) {
645                 warn "duplicate: ",
646                         $parsed->header_obj->header_raw('Message-ID'), "\n";
647         } else {
648                 print "imported at mark $ret\n";
649         }
650         $im->done;
651
652         # to remove a message
653         my $junk = Email::MIME->new($message);
654         my ($mark, $orig) = $im->remove($junk);
655         if ($mark eq 'MISSING') {
656                 print "not found\n";
657         } elsif ($mark eq 'MISMATCH') {
658                 print "Message exists but does not match\n\n",
659                         $orig->as_string, "\n",;
660         } else {
661                 print "removed at mark $mark\n\n",
662                         $orig->as_string, "\n";
663         }
664         $im->done;
665
666 =head1 DESCRIPTION
667
668 An importer and remover for public-inboxes which takes L<Email::MIME>
669 messages as input and stores them in a git repository as
670 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
671 except it does not allow duplicate Message-IDs.
672
673 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
674
675 =head1 METHODS
676
677 =cut
678
679 =head2 new
680
681         my $im = PublicInbox::Import->new($git, @committer);
682
683 Initialize a new PublicInbox::Import object.
684
685 =head2 add
686
687         my $parsed = Email::MIME->new($message);
688         $im->add($parsed);
689
690 Adds a message to to the git repository.  This will acquire
691 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
692
693 Messages added will not be visible to other processes until L</done>
694 is called, but L</remove> may be called on them.
695
696 =head2 remove
697
698         my $junk = Email::MIME->new($message);
699         my ($code, $orig) = $im->remove($junk);
700
701 Removes a message from the repository.  On success, it returns
702 a ':'-prefixed numeric code representing the git-fast-import
703 mark and the original messages as an Email::MIME object.
704 If the message could not be found, the code is "MISSING"
705 and the original message is undef.  If there is a mismatch where
706 the "Message-ID" is matched but the subject and body do not match,
707 the returned code is "MISMATCH" and the conflicting message
708 is returned as orig.
709
710 =head2 done
711
712 Finalizes the L<git-fast-import(1)> and unlocks the repository.
713 Calling this is required to finalize changes to a repository.
714
715 =head1 SEE ALSO
716
717 L<Email::MIME>
718
719 =head1 CONTACT
720
721 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
722
723 The mail archives are hosted at L<https://public-inbox.org/meta/>
724
725 =head1 COPYRIGHT
726
727 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
728
729 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
730
731 =cut