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