]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/MailDiff.pm
hoist MailDiff and ContentDigestDbg out of lei
[public-inbox.git] / lib / PublicInbox / MailDiff.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::MailDiff;
4 use v5.12;
5 use File::Temp 0.19 (); # 0.19 for ->newdir
6 use PublicInbox::ContentHash qw(content_digest);
7 use PublicInbox::ContentDigestDbg;
8 use Data::Dumper ();
9 use PublicInbox::MsgIter qw(msg_part_text);
10
11 sub write_part { # Eml->each_part callback
12         my ($ary, $self) = @_;
13         my ($part, $depth, $idx) = @$ary;
14         if ($idx ne '1' || $self->{-raw_hdr}) {
15                 open my $fh, '>', "$self->{curdir}/$idx.hdr" or die "open: $!";
16                 print $fh ${$part->{hdr}} or die "print $!";
17                 close $fh or die "close $!";
18         }
19         my $ct = $part->content_type || 'text/plain';
20         my ($s, $err) = msg_part_text($part, $ct);
21         my $sfx = defined($s) ? 'txt' : 'bin';
22         open my $fh, '>', "$self->{curdir}/$idx.$sfx" or die "open: $!";
23         print $fh ($s // $part->body) or die "print $!";
24         close $fh or die "close $!";
25 }
26
27 # public
28 sub dump_eml ($$$) {
29         my ($self, $dir, $eml) = @_;
30         local $self->{curdir} = $dir;
31         mkdir $dir or die "mkdir($dir): $!";
32         $eml->each_part(\&write_part, $self);
33
34         open my $fh, '>', "$dir/content_digest" or die "open: $!";
35         my $dig = PublicInbox::ContentDigestDbg->new($fh);
36         local $Data::Dumper::Useqq = 1;
37         local $Data::Dumper::Terse = 1;
38         content_digest($eml, $dig);
39         print $fh "\n", $dig->hexdigest, "\n" or die "print $!";
40         close $fh or die "close: $!";
41 }
42
43 # public
44 sub prep_a ($$) {
45         my ($self, $eml) = @_;
46         $self->{tmp} = File::Temp->newdir('mail-diff-XXXX', TMPDIR => 1);
47         dump_eml($self, "$self->{tmp}/a", $eml);
48 }
49
50 1;