]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
index: account for CRLF conversion when storing bytes
[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                 -inbox => $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         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::Eml->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         readline($self->{in}) 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', PublicInbox::Eml) on mismatch
218 # (:MARK, PublicInbox::Eml) 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 = PublicInbox::Eml or 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) = @{$_[0]};
275         $ts = 0 if $ts < 0; # git uses unsigned times
276         "$ts $zone";
277 }
278
279 sub extract_cmt_info ($;$) {
280         my ($mime, $smsg) = @_;
281         # $mime is PublicInbox::Eml, but remains Email::MIME-compatible
282         $smsg //= bless {}, 'PublicInbox::Smsg';
283
284         my $hdr = $mime->header_obj;
285         $smsg->populate($hdr);
286
287         my $sender = '';
288         my $from = delete($smsg->{From}) // '';
289         my ($email) = PublicInbox::Address::emails($from);
290         my ($name) = PublicInbox::Address::names($from);
291         if (!defined($name) || !defined($email)) {
292                 $sender = $hdr->header('Sender') // '';
293                 $name //= (PublicInbox::Address::names($sender))[0];
294                 $email //= (PublicInbox::Address::emails($sender))[0];
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 $subject = delete($smsg->{Subject}) // '(no subject)';
321         utf8::encode($subject);
322         my $at = git_timestamp(delete $smsg->{-ds});
323         my $ct = git_timestamp(delete $smsg->{-ts});
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, $smsg) = @_;
370
371         my ($author, $at, $ct, $subject) = extract_cmt_info($mime, $smsg);
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 ($smsg) {
402                 $smsg->{blob} = $self->get_mark(":$blob");
403                 $smsg->{raw_bytes} = $n;
404                 $smsg->{-raw_email} = \$raw_email;
405         }
406         my $ref = $self->{ref};
407         my $commit = $self->{mark}++;
408         my $parent = $tip =~ /\A:/ ? $tip : undef;
409
410         unless ($parent) {
411                 print $w "reset $ref\n" or wfail;
412         }
413
414         print $w "commit $ref\nmark :$commit\n",
415                 "author $author $at\n",
416                 "committer $self->{ident} $ct\n" or wfail;
417         print $w "data ", (length($subject) + 1), "\n",
418                 $subject, "\n\n" or wfail;
419         if ($tip ne '') {
420                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
421         }
422         clean_tree_v2($self, $w, $path);
423         print $w "M 100644 :$blob $path\n\n" or wfail;
424         $self->{nchg}++;
425         $self->{tip} = ":$commit";
426 }
427
428 sub run_die ($;$$) {
429         my ($cmd, $env, $rdr) = @_;
430         my $pid = spawn($cmd, $env, $rdr);
431         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
432         $? == 0 or die join(' ', @$cmd) . " failed: $?\n";
433 }
434
435 my @INIT_FILES = ('HEAD' => "ref: refs/heads/master\n",
436                 'description' => <<EOD,
437 Unnamed repository; edit this file 'description' to name the repository.
438 EOD
439                 'config' => <<EOC);
440 [core]
441         repositoryFormatVersion = 0
442         filemode = true
443         bare = true
444 [repack]
445         writeBitmaps = true
446 EOC
447
448 sub init_bare {
449         my ($dir) = @_; # or self
450         $dir = $dir->{git}->{git_dir} if ref($dir);
451         require File::Path;
452         File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
453         for (my $i = 0; $i < @INIT_FILES; $i++) {
454                 my $f = $dir.'/'.$INIT_FILES[$i++];
455                 next if -f $f;
456                 open my $fh, '>', $f or die "open $f: $!";
457                 print $fh $INIT_FILES[$i] or die "print $f: $!";
458                 close $fh or die "close $f: $!";
459         }
460 }
461
462 sub done {
463         my ($self) = @_;
464         my $w = delete $self->{out} or return;
465         my $r = delete $self->{in} or die 'BUG: missing {in} when done';
466         print $w "done\n" or wfail;
467         my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
468         waitpid($pid, 0) == $pid or die 'fast-import did not finish';
469         $? == 0 or die "fast-import failed: $?";
470
471         _update_git_info($self, 1) if delete $self->{nchg};
472
473         $self->lock_release;
474
475         $self->{git}->cleanup;
476 }
477
478 sub atfork_child {
479         my ($self) = @_;
480         foreach my $f (qw(in out)) {
481                 next unless defined($self->{$f});
482                 close $self->{$f} or die "failed to close import[$f]: $!\n";
483         }
484 }
485
486 sub digest2mid ($$) {
487         my ($dig, $hdr) = @_;
488         my $b64 = $dig->clone->b64digest;
489         # Make our own URLs nicer:
490         # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
491         $b64 =~ tr!+/=!-_!d;
492
493         # Add a date prefix to prevent a leading '-' in case that trips
494         # up some tools (e.g. if a Message-ID were a expected as a
495         # command-line arg)
496         my $dt = msg_datestamp($hdr);
497         $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
498         "$dt.$b64" . '@z';
499 }
500
501 sub rewrite_commit ($$$$) {
502         my ($self, $oids, $buf, $mime) = @_;
503         my ($author, $at, $ct, $subject);
504         if ($mime) {
505                 ($author, $at, $ct, $subject) = extract_cmt_info($mime);
506         } else {
507                 $author = '<>';
508                 $subject = 'purged '.join(' ', @$oids);
509         }
510         @$oids = ();
511         $subject .= "\n";
512         foreach my $i (0..$#$buf) {
513                 my $l = $buf->[$i];
514                 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
515                         $at //= $1;
516                         $buf->[$i] = "author $author $at\n";
517                 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
518                         $ct //= $1;
519                         $buf->[$i] = "committer $self->{ident} $ct\n";
520                 } elsif ($l =~ /^data ([0-9]+)/) {
521                         $buf->[$i++] = "data " . length($subject) . "\n";
522                         $buf->[$i] = $subject;
523                         last;
524                 }
525         }
526 }
527
528 # returns the new commit OID if a replacement was done
529 # returns undef if nothing was done
530 sub replace_oids {
531         my ($self, $mime, $replace_map) = @_; # oid => raw string
532         my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
533         my $old = $self->{'ref'};
534         my $git = $self->{git};
535         my @export = (qw(fast-export --no-data --use-done-feature), $old);
536         my $rd = $git->popen(@export);
537         my ($r, $w) = $self->gfi_start;
538         my @buf;
539         my $nreplace = 0;
540         my @oids;
541         my ($done, $mark);
542         my $tree = $self->{-tree};
543         while (<$rd>) {
544                 if (/^reset (?:.+)/) {
545                         push @buf, "reset $tmp\n";
546                 } elsif (/^commit (?:.+)/) {
547                         if (@buf) {
548                                 print $w @buf or wfail;
549                                 @buf = ();
550                         }
551                         push @buf, "commit $tmp\n";
552                 } elsif (/^data ([0-9]+)/) {
553                         # only commit message, so $len is small:
554                         my $len = $1; # + 1 for trailing "\n"
555                         push @buf, $_;
556                         my $n = read($rd, my $buf, $len) or die "read: $!";
557                         $len == $n or die "short read ($n < $len)";
558                         push @buf, $buf;
559                 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
560                         my ($oid, $path) = ($1, $2);
561                         $tree->{$path} = 1;
562                         my $sref = $replace_map->{$oid};
563                         if (defined $sref) {
564                                 push @oids, $oid;
565                                 my $n = length($$sref);
566                                 push @buf, "M 100644 inline $path\ndata $n\n";
567                                 push @buf, $$sref; # hope CoW works...
568                                 push @buf, "\n";
569                         } else {
570                                 push @buf, $_;
571                         }
572                 } elsif (/^D (\w+)/) {
573                         my $path = $1;
574                         push @buf, $_ if $tree->{$path};
575                 } elsif ($_ eq "\n") {
576                         if (@oids) {
577                                 if (!$mime) {
578                                         my $out = join('', @buf);
579                                         $out =~ s/^/# /sgm;
580                                         warn "purge rewriting\n", $out, "\n";
581                                 }
582                                 rewrite_commit($self, \@oids, \@buf, $mime);
583                                 $nreplace++;
584                         }
585                         print $w @buf, "\n" or wfail;
586                         @buf = ();
587                 } elsif ($_ eq "done\n") {
588                         $done = 1;
589                 } elsif (/^mark :([0-9]+)$/) {
590                         push @buf, $_;
591                         $mark = $1;
592                 } else {
593                         push @buf, $_;
594                 }
595         }
596         close $rd or die "close fast-export failed: $?";
597         if (@buf) {
598                 print $w @buf or wfail;
599         }
600         die 'done\n not seen from fast-export' unless $done;
601         chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
602         $self->{nchg} = 0; # prevent _update_git_info until update-ref:
603         $self->done;
604         my @git = ('git', "--git-dir=$git->{git_dir}");
605
606         run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
607
608         run_die([@git, qw(update-ref -d), $tmp]);
609
610         return if $nreplace == 0;
611
612         run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
613
614         # check that old OIDs are gone
615         my $err = 0;
616         foreach my $oid (keys %$replace_map) {
617                 my @info = $git->check($oid);
618                 if (@info) {
619                         warn "$oid not replaced\n";
620                         $err++;
621                 }
622         }
623         _update_git_info($self, 0);
624         die "Failed to replace $err object(s)\n" if $err;
625         $cmt;
626 }
627
628 1;
629 __END__
630 =pod
631
632 =head1 NAME
633
634 PublicInbox::Import - message importer for public-inbox v1 inboxes
635
636 =head1 VERSION
637
638 version 1.0
639
640 =head1 SYNOPSIS
641
642         use PublicInbox::Eml;
643         # PublicInbox::Eml exists as of public-inbox 1.5.0,
644         # Email::MIME was used in older versions
645
646         use PublicInbox::Git;
647         use PublicInbox::Import;
648
649         chomp(my $git_dir = `git rev-parse --git-dir`);
650         $git_dir or die "GIT_DIR= must be specified\n";
651         my $git = PublicInbox::Git->new($git_dir);
652         my @committer = ('inbox', 'inbox@example.org');
653         my $im = PublicInbox::Import->new($git, @committer);
654
655         # to add a message:
656         my $message = "From: <u\@example.org>\n".
657                 "Subject: test message \n" .
658                 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
659                 "Message-ID: <m\@example.org>\n".
660                 "\ntest message";
661         my $parsed = PublicInbox::Eml->new($message);
662         my $ret = $im->add($parsed);
663         if (!defined $ret) {
664                 warn "duplicate: ",
665                         $parsed->header_obj->header_raw('Message-ID'), "\n";
666         } else {
667                 print "imported at mark $ret\n";
668         }
669         $im->done;
670
671         # to remove a message
672         my $junk = PublicInbox::Eml->new($message);
673         my ($mark, $orig) = $im->remove($junk);
674         if ($mark eq 'MISSING') {
675                 print "not found\n";
676         } elsif ($mark eq 'MISMATCH') {
677                 print "Message exists but does not match\n\n",
678                         $orig->as_string, "\n",;
679         } else {
680                 print "removed at mark $mark\n\n",
681                         $orig->as_string, "\n";
682         }
683         $im->done;
684
685 =head1 DESCRIPTION
686
687 An importer and remover for public-inboxes which takes C<PublicInbox::Eml>
688 or L<Email::MIME> messages as input and stores them in a git repository as
689 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
690 except it does not allow duplicate Message-IDs.
691
692 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
693
694 =head1 METHODS
695
696 =cut
697
698 =head2 new
699
700         my $im = PublicInbox::Import->new($git, @committer);
701
702 Initialize a new PublicInbox::Import object.
703
704 =head2 add
705
706         my $parsed = PublicInbox::Eml->new($message);
707         $im->add($parsed);
708
709 Adds a message to to the git repository.  This will acquire
710 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
711
712 Messages added will not be visible to other processes until L</done>
713 is called, but L</remove> may be called on them.
714
715 =head2 remove
716
717         my $junk = PublicInbox::Eml->new($message);
718         my ($code, $orig) = $im->remove($junk);
719
720 Removes a message from the repository.  On success, it returns
721 a ':'-prefixed numeric code representing the git-fast-import
722 mark and the original messages as a PublicInbox::Eml
723 (or Email::MIME) object.
724 If the message could not be found, the code is "MISSING"
725 and the original message is undef.  If there is a mismatch where
726 the "Message-ID" is matched but the subject and body do not match,
727 the returned code is "MISMATCH" and the conflicting message
728 is returned as orig.
729
730 =head2 done
731
732 Finalizes the L<git-fast-import(1)> and unlocks the repository.
733 Calling this is required to finalize changes to a repository.
734
735 =head1 SEE ALSO
736
737 L<Email::MIME>
738
739 =head1 CONTACT
740
741 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
742
743 The mail archives are hosted at L<https://public-inbox.org/meta/>
744
745 =head1 COPYRIGHT
746
747 Copyright (C) 2016-2020 all contributors L<mailto:meta@public-inbox.org>
748
749 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
750
751 =cut