]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
git: ->qx: respect caller's $/ in array context
[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                 close $r;
28                 $h eq '' ? 'refs/heads/master' : $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                         return if $oidx->blob_exists($smsg->{blob});
417                 }
418         }
419         my $ref = $self->{ref};
420         my $commit = $self->{mark}++;
421         my $parent = $tip =~ /\A:/ ? $tip : undef;
422
423         unless ($parent) {
424                 print $w "reset $ref\n" or wfail;
425         }
426
427         print $w "commit $ref\nmark :$commit\n",
428                 "author $author $at\n",
429                 "committer $self->{ident} $ct\n" or wfail;
430         print $w "data ", (length($subject) + 1), "\n",
431                 $subject, "\n\n" or wfail;
432         if ($tip ne '') {
433                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
434         }
435         clean_tree_v2($self, $w, $path);
436         print $w "M 100644 :$blob $path\n\n" or wfail;
437         $self->{nchg}++;
438         $self->{tip} = ":$commit";
439 }
440
441 my @INIT_FILES = ('HEAD' => undef, # filled in at runtime
442                 'description' => <<EOD,
443 Unnamed repository; edit this file 'description' to name the repository.
444 EOD
445                 'config' => <<EOC);
446 [core]
447         repositoryFormatVersion = 0
448         filemode = true
449         bare = true
450 [repack]
451         writeBitmaps = true
452 EOC
453
454 sub init_bare {
455         my ($dir, $head) = @_; # or self
456         $dir = $dir->{git}->{git_dir} if ref($dir);
457         require File::Path;
458         File::Path::mkpath([ map { "$dir/$_" } qw(objects/info refs/heads) ]);
459         $INIT_FILES[1] //= 'ref: '.default_branch."\n";
460         my @fn_contents = @INIT_FILES;
461         $fn_contents[1] = "ref: refs/heads/$head\n" if defined $head;
462         while (my ($fn, $contents) = splice(@fn_contents, 0, 2)) {
463                 my $f = $dir.'/'.$fn;
464                 next if -f $f;
465                 open my $fh, '>', $f or die "open $f: $!";
466                 print $fh $contents or die "print $f: $!";
467                 close $fh or die "close $f: $!";
468         }
469 }
470
471 # true if locked and active
472 sub active { !!$_[0]->{out} }
473
474 sub done {
475         my ($self) = @_;
476         my $w = delete $self->{out} or return;
477         eval {
478                 my $r = delete $self->{in} or die 'BUG: missing {in} when done';
479                 print $w "done\n" or wfail;
480                 close $r or die "fast-import failed: $?"; # ProcessPipe::CLOSE
481         };
482         my $wait_err = $@;
483         my $nchg = delete $self->{nchg};
484         if ($nchg && !$wait_err) {
485                 eval { _update_git_info($self, 1) };
486                 warn "E: $self->{git}->{git_dir} update info: $@\n" if $@;
487         }
488         $self->lock_release(!!$nchg);
489         $self->{git}->cleanup;
490         die $wait_err if $wait_err;
491 }
492
493 sub atfork_child {
494         my ($self) = @_;
495         foreach my $f (qw(in out)) {
496                 next unless defined($self->{$f});
497                 close $self->{$f} or die "failed to close import[$f]: $!\n";
498         }
499 }
500
501 sub digest2mid ($$) {
502         my ($dig, $hdr) = @_;
503         my $b64 = $dig->clone->b64digest;
504         # Make our own URLs nicer:
505         # See "Base 64 Encoding with URL and Filename Safe Alphabet" in RFC4648
506         $b64 =~ tr!+/=!-_!d;
507
508         # Add a date prefix to prevent a leading '-' in case that trips
509         # up some tools (e.g. if a Message-ID were a expected as a
510         # command-line arg)
511         my $dt = msg_datestamp($hdr);
512         $dt = POSIX::strftime('%Y%m%d%H%M%S', gmtime($dt));
513         "$dt.$b64" . '@z';
514 }
515
516 sub rewrite_commit ($$$$) {
517         my ($self, $oids, $buf, $mime) = @_;
518         my ($author, $at, $ct, $subject);
519         if ($mime) {
520                 ($author, $at, $ct, $subject) = extract_cmt_info($mime);
521         } else {
522                 $author = '<>';
523                 $subject = 'purged '.join(' ', @$oids);
524         }
525         @$oids = ();
526         $subject .= "\n";
527         foreach my $i (0..$#$buf) {
528                 my $l = $buf->[$i];
529                 if ($l =~ /^author .* ([0-9]+ [\+-]?[0-9]+)$/) {
530                         $at //= $1;
531                         $buf->[$i] = "author $author $at\n";
532                 } elsif ($l =~ /^committer .* ([0-9]+ [\+-]?[0-9]+)$/) {
533                         $ct //= $1;
534                         $buf->[$i] = "committer $self->{ident} $ct\n";
535                 } elsif ($l =~ /^data ([0-9]+)/) {
536                         $buf->[$i++] = "data " . length($subject) . "\n";
537                         $buf->[$i] = $subject;
538                         last;
539                 }
540         }
541 }
542
543 # returns the new commit OID if a replacement was done
544 # returns undef if nothing was done
545 sub replace_oids {
546         my ($self, $mime, $replace_map) = @_; # oid => raw string
547         my $tmp = "refs/heads/replace-".((keys %$replace_map)[0]);
548         my $old = $self->{'ref'};
549         my $git = $self->{git};
550         my @export = (qw(fast-export --no-data --use-done-feature), $old);
551         my $rd = $git->popen(@export);
552         my ($r, $w) = $self->gfi_start;
553         my @buf;
554         my $nreplace = 0;
555         my @oids;
556         my ($done, $mark);
557         my $tree = $self->{-tree};
558         while (<$rd>) {
559                 if (/^reset (?:.+)/) {
560                         push @buf, "reset $tmp\n";
561                 } elsif (/^commit (?:.+)/) {
562                         if (@buf) {
563                                 print $w @buf or wfail;
564                                 @buf = ();
565                         }
566                         push @buf, "commit $tmp\n";
567                 } elsif (/^data ([0-9]+)/) {
568                         # only commit message, so $len is small:
569                         my $len = $1; # + 1 for trailing "\n"
570                         push @buf, $_;
571                         my $n = read($rd, my $buf, $len) or die "read: $!";
572                         $len == $n or die "short read ($n < $len)";
573                         push @buf, $buf;
574                 } elsif (/^M 100644 ([a-f0-9]+) (\w+)/) {
575                         my ($oid, $path) = ($1, $2);
576                         $tree->{$path} = 1;
577                         my $sref = $replace_map->{$oid};
578                         if (defined $sref) {
579                                 push @oids, $oid;
580                                 my $n = length($$sref);
581                                 push @buf, "M 100644 inline $path\ndata $n\n";
582                                 push @buf, $$sref; # hope CoW works...
583                                 push @buf, "\n";
584                         } else {
585                                 push @buf, $_;
586                         }
587                 } elsif (/^D (\w+)/) {
588                         my $path = $1;
589                         push @buf, $_ if $tree->{$path};
590                 } elsif ($_ eq "\n") {
591                         if (@oids) {
592                                 if (!$mime) {
593                                         my $out = join('', @buf);
594                                         $out =~ s/^/# /sgm;
595                                         warn "purge rewriting\n", $out, "\n";
596                                 }
597                                 rewrite_commit($self, \@oids, \@buf, $mime);
598                                 $nreplace++;
599                         }
600                         print $w @buf, "\n" or wfail;
601                         @buf = ();
602                 } elsif ($_ eq "done\n") {
603                         $done = 1;
604                 } elsif (/^mark :([0-9]+)$/) {
605                         push @buf, $_;
606                         $mark = $1;
607                 } else {
608                         push @buf, $_;
609                 }
610         }
611         close $rd or die "close fast-export failed: $?";
612         if (@buf) {
613                 print $w @buf or wfail;
614         }
615         die 'done\n not seen from fast-export' unless $done;
616         chomp(my $cmt = $self->get_mark(":$mark")) if $nreplace;
617         $self->{nchg} = 0; # prevent _update_git_info until update-ref:
618         $self->done;
619         my @git = ('git', "--git-dir=$git->{git_dir}");
620
621         run_die([@git, qw(update-ref), $old, $tmp]) if $nreplace;
622
623         run_die([@git, qw(update-ref -d), $tmp]);
624
625         return if $nreplace == 0;
626
627         run_die([@git, qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
628
629         # check that old OIDs are gone
630         my $err = 0;
631         foreach my $oid (keys %$replace_map) {
632                 my @info = $git->check($oid);
633                 if (@info) {
634                         warn "$oid not replaced\n";
635                         $err++;
636                 }
637         }
638         _update_git_info($self, 0);
639         die "Failed to replace $err object(s)\n" if $err;
640         $cmt;
641 }
642
643 1;
644 __END__
645 =pod
646
647 =head1 NAME
648
649 PublicInbox::Import - message importer for public-inbox v1 inboxes
650
651 =head1 VERSION
652
653 version 1.0
654
655 =head1 SYNOPSIS
656
657         use PublicInbox::Eml;
658         # PublicInbox::Eml exists as of public-inbox 1.5.0,
659         # Email::MIME was used in older versions
660
661         use PublicInbox::Git;
662         use PublicInbox::Import;
663
664         chomp(my $git_dir = `git rev-parse --git-dir`);
665         $git_dir or die "GIT_DIR= must be specified\n";
666         my $git = PublicInbox::Git->new($git_dir);
667         my @committer = ('inbox', 'inbox@example.org');
668         my $im = PublicInbox::Import->new($git, @committer);
669
670         # to add a message:
671         my $message = "From: <u\@example.org>\n".
672                 "Subject: test message \n" .
673                 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
674                 "Message-ID: <m\@example.org>\n".
675                 "\ntest message";
676         my $parsed = PublicInbox::Eml->new($message);
677         my $ret = $im->add($parsed);
678         if (!defined $ret) {
679                 warn "duplicate: ", $parsed->header_raw('Message-ID'), "\n";
680         } else {
681                 print "imported at mark $ret\n";
682         }
683         $im->done;
684
685         # to remove a message
686         my $junk = PublicInbox::Eml->new($message);
687         my ($mark, $orig) = $im->remove($junk);
688         if ($mark eq 'MISSING') {
689                 print "not found\n";
690         } elsif ($mark eq 'MISMATCH') {
691                 print "Message exists but does not match\n\n",
692                         $orig->as_string, "\n",;
693         } else {
694                 print "removed at mark $mark\n\n",
695                         $orig->as_string, "\n";
696         }
697         $im->done;
698
699 =head1 DESCRIPTION
700
701 An importer and remover for public-inboxes which takes C<PublicInbox::Eml>
702 or L<Email::MIME> messages as input and stores them in a git repository as
703 documented in L<https://public-inbox.org/public-inbox-v1-format.txt>,
704 except it does not allow duplicate Message-IDs.
705
706 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
707
708 =head1 METHODS
709
710 =cut
711
712 =head2 new
713
714         my $im = PublicInbox::Import->new($git, @committer);
715
716 Initialize a new PublicInbox::Import object.
717
718 =head2 add
719
720         my $parsed = PublicInbox::Eml->new($message);
721         $im->add($parsed);
722
723 Adds a message to to the git repository.  This will acquire
724 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
725
726 Messages added will not be visible to other processes until L</done>
727 is called, but L</remove> may be called on them.
728
729 =head2 remove
730
731         my $junk = PublicInbox::Eml->new($message);
732         my ($code, $orig) = $im->remove($junk);
733
734 Removes a message from the repository.  On success, it returns
735 a ':'-prefixed numeric code representing the git-fast-import
736 mark and the original messages as a PublicInbox::Eml
737 (or Email::MIME) object.
738 If the message could not be found, the code is "MISSING"
739 and the original message is undef.  If there is a mismatch where
740 the "Message-ID" is matched but the subject and body do not match,
741 the returned code is "MISMATCH" and the conflicting message
742 is returned as orig.
743
744 =head2 done
745
746 Finalizes the L<git-fast-import(1)> and unlocks the repository.
747 Calling this is required to finalize changes to a repository.
748
749 =head1 SEE ALSO
750
751 L<Email::MIME>
752
753 =head1 CONTACT
754
755 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
756
757 The mail archives are hosted at L<https://public-inbox.org/meta/>
758
759 =head1 COPYRIGHT
760
761 Copyright (C) 2016-2020 all contributors L<mailto:meta@public-inbox.org>
762
763 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
764
765 =cut