]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiToMail.pm
lei_to_mail: start --augment, dedupe, bz2 and xz
[public-inbox.git] / lib / PublicInbox / LeiToMail.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Writes PublicInbox::Eml objects atomically to a mbox variant or Maildir
5 package PublicInbox::LeiToMail;
6 use strict;
7 use v5.10.1;
8 use PublicInbox::Eml;
9 use PublicInbox::Lock;
10 use PublicInbox::ProcessPipe;
11 use PublicInbox::SharedKV;
12 use PublicInbox::Spawn qw(which spawn popen_rd);
13 use PublicInbox::ContentHash qw(content_hash);
14 use Symbol qw(gensym);
15 use IO::Handle; # ->autoflush
16 use Fcntl qw(SEEK_SET);
17
18 my %kw2char = ( # Maildir characters
19         draft => 'D',
20         flagged => 'F',
21         answered => 'R',
22         seen => 'S'
23 );
24
25 my %kw2status = (
26         flagged => [ 'X-Status' => 'F' ],
27         answered => [ 'X-Status' => 'A' ],
28         seen => [ 'Status' => 'R' ],
29         draft => [ 'X-Status' => 'T' ],
30 );
31
32 sub _mbox_hdr_buf ($$$) {
33         my ($eml, $type, $kw) = @_;
34         $eml->header_set($_) for (qw(Lines Bytes Content-Length));
35         my %hdr; # set Status, X-Status
36         for my $k (@$kw) {
37                 if (my $ent = $kw2status{$k}) {
38                         push @{$hdr{$ent->[0]}}, $ent->[1];
39                 } else { # X-Label?
40                         warn "TODO: keyword `$k' not supported for mbox\n";
41                 }
42         }
43         while (my ($name, $chars) = each %hdr) {
44                 $eml->header_set($name, join('', sort @$chars));
45         }
46         my $buf = delete $eml->{hdr};
47
48         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
49         $$buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
50
51         substr($$buf, 0, 0, # prepend From line
52                 "From lei\@$type Thu Jan  1 00:00:00 1970$eml->{crlf}");
53         $buf;
54 }
55
56 sub write_in_full ($$$) {
57         my ($fh, $buf, $atomic) = @_;
58         if ($atomic) {
59                 defined(my $w = syswrite($fh, $$buf)) or die "write: $!";
60                 $w == length($$buf) or die "short write: $w != ".length($$buf);
61         } else {
62                 print $fh $$buf or die "print: $!";
63         }
64 }
65
66 sub eml2mboxrd ($;$) {
67         my ($eml, $kw) = @_;
68         my $buf = _mbox_hdr_buf($eml, 'mboxrd', $kw);
69         if (my $bdy = delete $eml->{bdy}) {
70                 $$bdy =~ s/^(>*From )/>$1/gm;
71                 $$buf .= $eml->{crlf};
72                 substr($$bdy, 0, 0, $$buf); # prepend header
73                 $buf = $bdy;
74         }
75         $$buf .= $eml->{crlf};
76         $buf;
77 }
78
79 sub eml2mboxo {
80         my ($eml, $kw) = @_;
81         my $buf = _mbox_hdr_buf($eml, 'mboxo', $kw);
82         if (my $bdy = delete $eml->{bdy}) {
83                 $$bdy =~ s/^From />From /gm;
84                 $$buf .= $eml->{crlf};
85                 substr($$bdy, 0, 0, $$buf); # prepend header
86                 $buf = $bdy;
87         }
88         $$buf .= $eml->{crlf};
89         $buf;
90 }
91
92 # mboxcl still escapes "From " lines
93 sub eml2mboxcl {
94         my ($eml, $kw) = @_;
95         my $buf = _mbox_hdr_buf($eml, 'mboxcl', $kw);
96         my $crlf = $eml->{crlf};
97         if (my $bdy = delete $eml->{bdy}) {
98                 $$bdy =~ s/^From />From /gm;
99                 $$buf .= 'Content-Length: '.length($$bdy).$crlf.$crlf;
100                 substr($$bdy, 0, 0, $$buf); # prepend header
101                 $buf = $bdy;
102         }
103         $$buf .= $crlf;
104         $buf;
105 }
106
107 # mboxcl2 has no "From " escaping
108 sub eml2mboxcl2 {
109         my ($eml, $kw) = @_;
110         my $buf = _mbox_hdr_buf($eml, 'mboxcl2', $kw);
111         my $crlf = $eml->{crlf};
112         if (my $bdy = delete $eml->{bdy}) {
113                 $$buf .= 'Content-Length: '.length($$bdy).$crlf.$crlf;
114                 substr($$bdy, 0, 0, $$buf); # prepend header
115                 $buf = $bdy;
116         }
117         $$buf .= $crlf;
118         $buf;
119 }
120
121 sub mkmaildir ($) {
122         my ($maildir) = @_;
123         for (qw(new tmp cur)) {
124                 my $d = "$maildir/$_";
125                 next if -d $d;
126                 require File::Path;
127                 if (!File::Path::mkpath($d) && !-d $d) {
128                         die "failed to mkpath($d): $!\n";
129                 }
130         }
131 }
132
133 sub git_to_mail { # git->cat_async callback
134         my ($bref, $oid, $type, $size, $arg) = @_;
135         if ($type ne 'blob') {
136                 if ($type eq 'missing') {
137                         warn "missing $oid\n";
138                 } else {
139                         warn "unexpected type=$type for $oid\n";
140                 }
141         }
142         if ($size > 0) {
143                 my ($write_cb, $kw) = @$arg;
144                 $write_cb->($bref, $oid, $kw);
145         }
146 }
147
148 sub reap_compress { # dwaitpid callback
149         my ($lei, $pid) = @_;
150         my $cmd = delete $lei->{"pid.$pid"};
151         return if $? == 0;
152         $lei->fail("@$cmd failed", $? >> 8);
153 }
154
155 # all of these support -c for stdout and -d for decompression,
156 # mutt is commonly distributed with hooks for gz, bz2 and xz, at least
157 # { foo => '' } means "--foo" is passed to the command-line,
158 # otherwise { foo => '--bar' } passes "--bar"
159 our %zsfx2cmd = (
160         gz => [ qw(GZIP pigz gzip), {
161                 rsyncable => '', threads => '-p' } ],
162         bz2 => [ 'bzip2', {} ],
163         xz => [ 'xz', { threads => '-T' } ],
164         # XXX does anybody care for these?  I prefer zstd on entire FSes,
165         # so it's probably not necessary on a per-file basis
166         # zst => [ 'zstd', { -default => [ qw(-q) ], # it's noisy by default
167         #       rsyncable => '', threads => '-T' } ],
168         # zz => [ 'pigz', { -default => [ '--zlib' ],
169         #       rsyncable => '', threads => '-p' }],
170         # lzo => [ 'lzop', {} ],
171         # lzma => [ 'lzma', {} ],
172 );
173
174 sub zsfx2cmd ($$$) {
175         my ($zsfx, $decompress, $lei) = @_;
176         my $x = $zsfx2cmd{$zsfx} // die "no support for suffix=.$zsfx";
177         my @info = @$x;
178         my $cmd_opt = pop @info;
179         my @cmd = (undef, $decompress ? qw(-dc) : qw(-c));
180         for my $exe (@info) {
181                 # I think respecting client's ENV{GZIP} is OK, not sure
182                 # about ENV overrides for other, less-common compressors
183                 if ($exe eq uc($exe)) {
184                         $exe = $lei->{env}->{$exe} or next;
185                 }
186                 $cmd[0] = which($exe) and last;
187         }
188         $cmd[0] // die join(' or ', @info)." missing for .$zsfx";
189         # push @cmd, @{$cmd_opt->{-default}} if $cmd_opt->{-default};
190         for my $bool (qw(rsyncable)) {
191                 my $switch = $cmd_opt->{rsyncable} // next;
192                 push @cmd, '--'.($switch || $bool);
193         }
194         for my $key (qw(threads)) { # support compression level?
195                 my $switch = $cmd_opt->{$key} // next;
196                 my $val = $lei->{opt}->{$key} // next;
197                 push @cmd, $switch, $val;
198         }
199         \@cmd;
200 }
201
202 sub compress_dst {
203         my ($out, $zsfx, $lei) = @_;
204         my $cmd = zsfx2cmd($zsfx, undef, $lei);
205         pipe(my ($r, $w)) or die "pipe: $!";
206         my $rdr = { 0 => $r, 1 => $out, 2 => $lei->{2} };
207         my $pid = spawn($cmd, $lei->{env}, $rdr);
208         $lei->{"pid.$pid"} = $cmd;
209         my $pp = gensym;
210         tie *$pp, 'PublicInbox::ProcessPipe', $pid, $w, \&reap_compress, $lei;
211         my $pipe_lk = ($lei->{opt}->{jobs} // 0) > 1 ?
212                         PublicInbox::Lock->new_tmp($zsfx) : undef;
213         ($pp, $pipe_lk);
214 }
215
216 sub decompress_src ($$$) {
217         my ($in, $zsfx, $lei) = @_;
218         my $cmd = zsfx2cmd($zsfx, 1, $lei);
219         my $rdr = { 0 => $in, 2 => $lei->{2} };
220         popen_rd($cmd, $lei->{env}, $rdr);
221 }
222
223 sub dup_src ($) {
224         my ($in) = @_;
225         open my $dup, '+>>&', $in or die "dup: $!";
226         $dup;
227 }
228
229 # --augment existing output destination, without duplicating anything
230 sub _augment { # MboxReader eml_cb
231         my ($eml, $lei) = @_;
232         $lei->{skv}->set_maybe(content_hash($eml), '');
233 }
234
235 sub _mbox_write_cb ($$$$) {
236         my ($cls, $mbox, $dst, $lei) = @_;
237         my $m = "eml2$mbox";
238         my $eml2mbox = $cls->can($m) or die "$cls->$m missing";
239         my ($out, $pipe_lk);
240         open $out, '+>>', $dst or die "open $dst: $!";
241         # Perl does SEEK_END even with O_APPEND :<
242         seek($out, 0, SEEK_SET) or die "seek $dst: $!";
243         my $atomic = !!(($lei->{opt}->{jobs} // 0) > 1);
244         $lei->{skv} = PublicInbox::SharedKV->new;
245         $lei->{skv}->dbh;
246         state $zsfx_allow = join('|', keys %zsfx2cmd);
247         my ($zsfx) = ($dst =~ /\.($zsfx_allow)\z/);
248         if ($lei->{opt}->{augment}) {
249                 my $rd = $zsfx ? decompress_src($out, $zsfx, $lei) :
250                                 dup_src($out);
251                 PublicInbox::MboxReader->$mbox($rd, \&_augment, $lei);
252         } else {
253                 truncate($out, 0) or die "truncate $dst: $!";
254         }
255         ($out, $pipe_lk) = compress_dst($out, $zsfx, $lei) if $zsfx;
256         sub {
257                 my ($buf, $oid, $kw) = @_;
258                 my $eml = PublicInbox::Eml->new($buf);
259                 if ($lei->{skv}->set_maybe(content_hash($eml), '')) {
260                         $buf = $eml2mbox->($eml, $kw);
261                         my $lock = $pipe_lk->lock_for_scope if $pipe_lk;
262                         write_in_full($out, $buf, $atomic);
263                 }
264         }
265 }
266
267 sub write_cb { # returns a callback for git_to_mail
268         my ($cls, $dst, $lei) = @_;
269         if ($dst =~ s!\A(mbox(?:rd|cl|cl2|o))?:!!) {
270                 _mbox_write_cb($cls, $1, $dst, $lei);
271         }
272 }
273
274 1;