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