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