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