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