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