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