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