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