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