]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
b50c662c70b22ce73f000910e4b297482b1d0cfb
[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 parent qw(PublicInbox::Lock);
11 use v5.10.1;
12 use PublicInbox::Spawn qw(spawn popen_rd);
13 use PublicInbox::MID qw(mids mid2path);
14 use PublicInbox::Address;
15 use PublicInbox::Smsg;
16 use PublicInbox::MsgTime qw(msg_datestamp);
17 use PublicInbox::ContentHash qw(content_digest);
18 use PublicInbox::MDA;
19 use PublicInbox::Eml;
20 use POSIX qw(strftime);
21
22 sub new {
23         # we can't change arg order, this is documented in POD
24         # and external projects may rely on it:
25         my ($class, $git, $name, $email, $ibx) = @_;
26         my $ref = 'refs/heads/master';
27         if ($ibx) {
28                 $ref = $ibx->{ref_head} // 'refs/heads/master';
29                 $name //= $ibx->{name};
30                 $email //= $ibx->{-primary_address};
31                 $git //= $ibx->git;
32         }
33         bless {
34                 git => $git,
35                 ident => "$name <$email>",
36                 mark => 1,
37                 ref => $ref,
38                 ibx => $ibx,
39                 path_type => '2/38', # or 'v2'
40                 lock_path => "$git->{git_dir}/ssoma.lock", # v2 changes this
41                 bytes_added => 0,
42         }, $class
43 }
44
45 # idempotent start function
46 sub gfi_start {
47         my ($self) = @_;
48
49         return ($self->{in}, $self->{out}) if $self->{pid};
50
51         my ($out_r, $out_w);
52         pipe($out_r, $out_w) or die "pipe failed: $!";
53         my $git = $self->{git};
54
55         $self->lock_acquire;
56
57         local $/ = "\n";
58         my $ref = $self->{ref};
59         chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $ref));
60         if ($self->{path_type} ne '2/38' && $self->{tip}) {
61                 local $/ = "\0";
62                 my @tree = $git->qx(qw(ls-tree -r -z --name-only), $ref);
63                 chomp @tree;
64                 $self->{-tree} = { map { $_ => 1 } @tree };
65         }
66
67         my $git_dir = $git->{git_dir};
68         my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
69                         --quiet --done --date-format=raw));
70         my ($in_r, $pid) = popen_rd(\@cmd, undef, { 0 => $out_r });
71         $out_w->autoflush(1);
72         $self->{in} = $in_r;
73         $self->{out} = $out_w;
74         $self->{pid} = $pid;
75         $self->{nchg} = 0;
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::Eml->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         readline($self->{in}) 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->{ibx};
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', PublicInbox::Eml) on mismatch
216 # (:MARK, PublicInbox::Eml) 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 = PublicInbox::Eml or 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) = @{$_[0]};
273         $ts = 0 if $ts < 0; # git uses unsigned times
274         "$ts $zone";
275 }
276
277 sub extract_cmt_info ($;$) {
278         my ($mime, $smsg) = @_;
279         # $mime is PublicInbox::Eml, but remains Email::MIME-compatible
280         $smsg //= bless {}, 'PublicInbox::Smsg';
281
282         my $hdr = $mime->header_obj;
283         $smsg->populate($hdr);
284
285         my $sender = '';
286         my $from = delete($smsg->{From}) // '';
287         my ($email) = PublicInbox::Address::emails($from);
288         my ($name) = PublicInbox::Address::names($from);
289         if (!defined($name) || !defined($email)) {
290                 $sender = $hdr->header('Sender') // '';
291                 $name //= (PublicInbox::Address::names($sender))[0];
292                 $email //= (PublicInbox::Address::emails($sender))[0];
293         }
294         if (defined $email) {
295                 # Email::Address::XS may leave quoted '<' in addresses,
296                 # which git-fast-import doesn't like
297                 $email =~ tr/<>//d;
298
299                 # quiet down wide character warnings with utf8::encode
300                 utf8::encode($email);
301         } else {
302                 $email = '';
303                 warn "no email in From: $from or Sender: $sender\n";
304         }
305
306         # git gets confused with:
307         #  "'A U Thor <u@example.com>' via foo" <foo@example.com>
308         # ref:
309         # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
310         if (defined $name) {
311                 $name =~ tr/<>//d;
312                 utf8::encode($name);
313         } else {
314                 $name = '';
315                 warn "no name in From: $from or Sender: $sender\n";
316         }
317
318         my $subject = delete($smsg->{Subject}) // '(no subject)';
319         utf8::encode($subject);
320         my $at = git_timestamp(delete $smsg->{-ds});
321         my $ct = git_timestamp(delete $smsg->{-ts});
322         ("$name <$email>", $at, $ct, $subject);
323 }
324
325 # kill potentially confusing/misleading headers
326 sub drop_unwanted_headers ($) {
327         my ($mime) = @_;
328
329         $mime->header_set($_) for qw(Bytes Lines Content-Length Status);
330         $mime->header_set($_) for @PublicInbox::MDA::BAD_HEADERS;
331 }
332
333 # used by V2Writable, too
334 sub append_mid ($$) {
335         my ($hdr, $mid0) = @_;
336         # @cur is likely empty if we need to call this sub, but it could
337         # have random unparseable crap which we'll preserve, too.
338         my @cur = $hdr->header_raw('Message-ID');
339         $hdr->header_set('Message-ID', @cur, "<$mid0>");
340 }
341
342 sub v1_mid0 ($) {
343         my ($mime) = @_;
344         my $hdr = $mime->header_obj;
345         my $mids = mids($hdr);
346
347         if (!scalar(@$mids)) { # spam often has no Message-ID
348                 my $mid0 = digest2mid(content_digest($mime), $hdr);
349                 append_mid($hdr, $mid0);
350                 return $mid0;
351         }
352         $mids->[0];
353 }
354 sub clean_tree_v2 ($$$) {
355         my ($self, $w, $keep) = @_;
356         my $tree = $self->{-tree} or return; #v2 only
357         delete $tree->{$keep};
358         foreach (keys %$tree) {
359                 print $w "D $_\n" or wfail;
360         }
361         %$tree = ($keep => 1);
362 }
363
364 # returns undef on duplicate
365 # returns the :MARK of the most recent commit
366 sub add {
367         my ($self, $mime, $check_cb, $smsg) = @_;
368
369         my ($author, $at, $ct, $subject) = extract_cmt_info($mime, $smsg);
370         my $path_type = $self->{path_type};
371         my $path;
372         if ($path_type eq '2/38') {
373                 $path = mid2path(v1_mid0($mime));
374         } else { # v2 layout, one file:
375                 $path = 'm';
376         }
377
378         my ($r, $w) = $self->gfi_start;
379         my $tip = $self->{tip};
380         if ($path_type eq '2/38') {
381                 _check_path($r, $w, $tip, $path) and return;
382         }
383
384         drop_unwanted_headers($mime);
385
386         # spam check:
387         if ($check_cb) {
388                 $mime = $check_cb->($mime, $self->{ibx}) or return;
389         }
390
391         my $blob = $self->{mark}++;
392         my $raw_email = $mime->{-public_inbox_raw} // $mime->as_string;
393         my $n = length($raw_email);
394         $self->{bytes_added} += $n;
395         print $w "blob\nmark :$blob\ndata ", $n, "\n" or wfail;
396         print $w $raw_email, "\n" or wfail;
397
398         # v2: we need this for Xapian
399         if ($smsg) {
400                 $smsg->{blob} = $self->get_mark(":$blob");
401                 $smsg->{raw_bytes} = $n;
402                 $smsg->{-raw_email} = \$raw_email;
403         }
404         my $ref = $self->{ref};
405         my $commit = $self->{mark}++;
406         my $parent = $tip =~ /\A:/ ? $tip : undef;
407
408         unless ($parent) {
409                 print $w "reset $ref\n" or wfail;
410         }
411
412         print $w "commit $ref\nmark :$commit\n",
413                 "author $author $at\n",
414                 "committer $self->{ident} $ct\n" or wfail;
415         print $w "data ", (length($subject) + 1), "\n",
416                 $subject, "\n\n" or wfail;
417         if ($tip ne '') {
418                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
419         }
420         clean_tree_v2($self, $w, $path);
421         print $w "M 100644 :$blob $path\n\n" or wfail;
422         $self->{nchg}++;
423         $self->{tip} = ":$commit";
424 }
425
426 sub run_die ($;$$) {
427         my ($cmd, $env, $rdr) = @_;
428         my $pid = spawn($cmd, $env, $rdr);
429         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
430         $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
431 }
432
433 my @INIT_FILES = ('HEAD' => "ref: refs/heads/master\n",
434                 'description' => <<EOD,
435 Unnamed repository; edit this file 'description' to name the repository.
436 EOD
437                 'config' => <<EOC);
438 [core]
439         repositoryFormatVersion = 0
440         filemode = true
441         bare = true
442 [repack]
443         writeBitmaps = true
444 EOC
445
446 sub init_bare {
447         my ($dir) = @_; # or self
448         $dir = $dir->{git}->{git_dir} if ref($dir);
449         require File::Path;
450         File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
451         for (my $i = 0; $i < @INIT_FILES; $i++) {
452                 my $f = $dir.'/'.$INIT_FILES[$i++];
453                 next if -f $f;
454                 open my $fh, '>', $f or die "open $f: $!";
455                 print $fh $INIT_FILES[$i] or die "print $f: $!";
456                 close $fh or die "close $f: $!";
457         }
458 }
459
460 sub done {
461         my ($self) = @_;
462         my $w = delete $self->{out} or return;
463         my $r = delete $self->{in} or die 'BUG: missing {in} when done';
464         print $w "done\n" or wfail;
465         my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
466         waitpid($pid, 0) == $pid or die 'fast-import did not finish';
467         $? == 0 or die "fast-import failed: $?";
468
469         my $nchg = delete $self->{nchg};
470         _update_git_info($self, 1) if $nchg;
471         $self->lock_release(!!$nchg);
472
473         $self->{git}->cleanup;
474 }
475
476 sub atfork_child {
477         my ($self) = @_;
478         foreach my $f (qw(in out)) {
479                 next unless defined($self->{$f});
480                 close $self->{$f} or die "failed to close import[$f]: $!\n";
481         }
482 }
483
484 sub digest2mid ($$) {
485         my ($dig, $hdr) = @_;
486         my $b64 = $dig->clone->b64digest;
487         # Make our own URLs nicer:
488         # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
489         $b64 =~ tr!+/=!-_!d;
490
491         # Add a date prefix to prevent a leading '-' in case that trips
492         # up some tools (e.g. if a Message-ID were a expected as a
493         # command-line arg)
494         my $dt = msg_datestamp($hdr);
495         $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
496         "$dt.$b64" . '@z';
497 }
498
499 sub rewrite_commit ($$$$) {
500         my ($self, $oids, $buf, $mime) = @_;
501         my ($author, $at, $ct, $subject);
502         if ($mime) {
503                 ($author, $at, $ct, $subject) = extract_cmt_info($mime);
504         } else {
505                 $author = '<>';
506                 $subject = 'purged '.join(' ', @$oids);
507         }
508         @$oids = ();
509         $subject .= "\n";
510         foreach my $i (0..$#$buf) {
511                 my $l = $buf->[$i];
512                 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
513                         $at //= $1;
514                         $buf->[$i] = "author $author $at\n";
515                 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
516                         $ct //= $1;
517                         $buf->[$i] = "committer $self->{ident} $ct\n";
518                 } elsif ($l =~ /^data ([0-9]+)/) {
519                         $buf->[$i++] = "data " . length($subject) . "\n";
520                         $buf->[$i] = $subject;
521                         last;
522                 }
523         }
524 }
525
526 # returns the new commit OID if a replacement was done
527 # returns undef if nothing was done
528 sub replace_oids {
529         my ($self, $mime, $replace_map) = @_; # oid => raw string
530         my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
531         my $old = $self->{'ref'};
532         my $git = $self->{git};
533         my @export = (qw(fast-export --no-data --use-done-feature), $old);
534         my $rd = $git->popen(@export);
535         my ($r, $w) = $self->gfi_start;
536         my @buf;
537         my $nreplace = 0;
538         my @oids;
539         my ($done, $mark);
540         my $tree = $self->{-tree};
541         while (<$rd>) {
542                 if (/^reset (?:.+)/) {
543                         push @buf, "reset $tmp\n";
544                 } elsif (/^commit (?:.+)/) {
545                         if (@buf) {
546                                 print $w @buf or wfail;
547                                 @buf = ();
548                         }
549                         push @buf, "commit $tmp\n";
550                 } elsif (/^data ([0-9]+)/) {
551                         # only commit message, so $len is small:
552                         my $len = $1; # + 1 for trailing "\n"
553                         push @buf, $_;
554                         my $n = read($rd, my $buf, $len) or die "read: $!";
555                         $len == $n or die "short read ($n < $len)";
556                         push @buf, $buf;
557                 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
558                         my ($oid, $path) = ($1, $2);
559                         $tree->{$path} = 1;
560                         my $sref = $replace_map->{$oid};
561                         if (defined $sref) {
562                                 push @oids, $oid;
563                                 my $n = length($$sref);
564                                 push @buf, "M 100644 inline $path\ndata $n\n";
565                                 push @buf, $$sref; # hope CoW works...
566                                 push @buf, "\n";
567                         } else {
568                                 push @buf, $_;
569                         }
570                 } elsif (/^D (\w+)/) {
571                         my $path = $1;
572                         push @buf, $_ if $tree->{$path};
573                 } elsif ($_ eq "\n") {
574                         if (@oids) {
575                                 if (!$mime) {
576                                         my $out = join('', @buf);
577                                         $out =~ s/^/# /sgm;
578                                         warn "purge rewriting\n", $out, "\n";
579                                 }
580                                 rewrite_commit($self, \@oids, \@buf, $mime);
581                                 $nreplace++;
582                         }
583                         print $w @buf, "\n" or wfail;
584                         @buf = ();
585                 } elsif ($_ eq "done\n") {
586                         $done = 1;
587                 } elsif (/^mark :([0-9]+)$/) {
588                         push @buf, $_;
589                         $mark = $1;
590                 } else {
591                         push @buf, $_;
592                 }
593         }
594         close $rd or die "close fast-export failed: $?";
595         if (@buf) {
596                 print $w @buf or wfail;
597         }
598         die 'done\n not seen from fast-export' unless $done;
599         chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
600         $self->{nchg} = 0; # prevent _update_git_info until update-ref:
601         $self->done;
602         my @git = ('git', "--git-dir=$git->{git_dir}");
603
604         run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
605
606         run_die([@git, qw(update-ref -d), $tmp]);
607
608         return if $nreplace == 0;
609
610         run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
611
612         # check that old OIDs are gone
613         my $err = 0;
614         foreach my $oid (keys %$replace_map) {
615                 my @info = $git->check($oid);
616                 if (@info) {
617                         warn "$oid not replaced\n";
618                         $err++;
619                 }
620         }
621         _update_git_info($self, 0);
622         die "Failed to replace $err object(s)\n" if $err;
623         $cmt;
624 }
625
626 1;
627 __END__
628 =pod
629
630 =head1 NAME
631
632 PublicInbox::Import - message importer for public-inbox v1 inboxes
633
634 =head1 VERSION
635
636 version 1.0
637
638 =head1 SYNOPSIS
639
640         use PublicInbox::Eml;
641         # PublicInbox::Eml exists as of public-inbox 1.5.0,
642         # Email::MIME was used in older versions
643
644         use PublicInbox::Git;
645         use PublicInbox::Import;
646
647         chomp(my $git_dir = `git rev-parse --git-dir`);
648         $git_dir or die "GIT_DIR= must be specified\n";
649         my $git = PublicInbox::Git->new($git_dir);
650         my @committer = ('inbox', 'inbox@example.org');
651         my $im = PublicInbox::Import->new($git, @committer);
652
653         # to add a message:
654         my $message = "From: <u\@example.org>\n".
655                 "Subject: test message \n" .
656                 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
657                 "Message-ID: <m\@example.org>\n".
658                 "\ntest message";
659         my $parsed = PublicInbox::Eml->new($message);
660         my $ret = $im->add($parsed);
661         if (!defined $ret) {
662                 warn "duplicate: ",
663                         $parsed->header_obj->header_raw('Message-ID'), "\n";
664         } else {
665                 print "imported at mark $ret\n";
666         }
667         $im->done;
668
669         # to remove a message
670         my $junk = PublicInbox::Eml->new($message);
671         my ($mark, $orig) = $im->remove($junk);
672         if ($mark eq 'MISSING') {
673                 print "not found\n";
674         } elsif ($mark eq 'MISMATCH') {
675                 print "Message exists but does not match\n\n",
676                         $orig->as_string, "\n",;
677         } else {
678                 print "removed at mark $mark\n\n",
679                         $orig->as_string, "\n";
680         }
681         $im->done;
682
683 =head1 DESCRIPTION
684
685 An importer and remover for public-inboxes which takes C<PublicInbox::Eml>
686 or L<Email::MIME> messages as input and stores them in a git repository as
687 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
688 except it does not allow duplicate Message-IDs.
689
690 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
691
692 =head1 METHODS
693
694 =cut
695
696 =head2 new
697
698         my $im = PublicInbox::Import->new($git, @committer);
699
700 Initialize a new PublicInbox::Import object.
701
702 =head2 add
703
704         my $parsed = PublicInbox::Eml->new($message);
705         $im->add($parsed);
706
707 Adds a message to to the git repository.  This will acquire
708 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
709
710 Messages added will not be visible to other processes until L</done>
711 is called, but L</remove> may be called on them.
712
713 =head2 remove
714
715         my $junk = PublicInbox::Eml->new($message);
716         my ($code, $orig) = $im->remove($junk);
717
718 Removes a message from the repository.  On success, it returns
719 a ':'-prefixed numeric code representing the git-fast-import
720 mark and the original messages as a PublicInbox::Eml
721 (or Email::MIME) object.
722 If the message could not be found, the code is "MISSING"
723 and the original message is undef.  If there is a mismatch where
724 the "Message-ID" is matched but the subject and body do not match,
725 the returned code is "MISMATCH" and the conflicting message
726 is returned as orig.
727
728 =head2 done
729
730 Finalizes the L<git-fast-import(1)> and unlocks the repository.
731 Calling this is required to finalize changes to a repository.
732
733 =head1 SEE ALSO
734
735 L<Email::MIME>
736
737 =head1 CONTACT
738
739 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
740
741 The mail archives are hosted at L<https://public-inbox.org/meta/>
742
743 =head1 COPYRIGHT
744
745 Copyright (C) 2016-2020 all contributors L<mailto:meta@public-inbox.org>
746
747 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
748
749 =cut