]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiSavedSearch.pm
lei edit-search: support relocating lei.q.output
[public-inbox.git] / lib / PublicInbox / LeiSavedSearch.pm
1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # pretends to be like LeiDedupe and also PublicInbox::Inbox
5 package PublicInbox::LeiSavedSearch;
6 use strict;
7 use v5.10.1;
8 use parent qw(PublicInbox::Lock);
9 use PublicInbox::Git;
10 use PublicInbox::OverIdx;
11 use PublicInbox::LeiSearch;
12 use PublicInbox::Config;
13 use PublicInbox::Spawn qw(run_die);
14 use PublicInbox::ContentHash qw(git_sha);
15 use PublicInbox::MID qw(mids_for_index);
16 use Digest::SHA qw(sha256_hex);
17 my $LOCAL_PFX = qr!\A(?:maildir|mh|mbox.+|mmdf):!i; # TODO: put in LeiToMail?
18
19 # move this to PublicInbox::Config if other things use it:
20 my %cquote = ("\n" => '\\n', "\t" => '\\t', "\b" => '\\b');
21 sub cquote_val ($) { # cf. git-config(1)
22         my ($val) = @_;
23         $val =~ s/([\n\t\b])/$cquote{$1}/g;
24         $val;
25 }
26
27 sub ARRAY_FIELDS () { qw(only include exclude) }
28 sub BOOL_FIELDS () {
29         qw(external local remote import-remote import-before threads)
30 }
31
32 sub lss_dir_for ($$;$) {
33         my ($lei, $dstref, $on_fs) = @_;
34         my @n;
35         if ($$dstref =~ m,\Aimaps?://,i) { # already canonicalized
36                 require PublicInbox::URIimap;
37                 my $uri = PublicInbox::URIimap->new($$dstref)->canonical;
38                 $$dstref = $$uri;
39                 @n = ($uri->mailbox);
40         } else {
41                 # can't use Cwd::abs_path since dirname($$dstref) may not exist
42                 $$dstref = $lei->rel2abs($$dstref);
43                 # Maildirs have trailing '/' internally
44                 $$dstref .= '/' if -d $$dstref;
45                 $$dstref =~ tr!/!/!s;
46                 @n = ($$dstref =~ m{([^/]+)/*\z}); # basename
47         }
48         push @n, sha256_hex($$dstref);
49         my $lss_dir = $lei->share_path . '/saved-searches/';
50         my $d = $lss_dir . join('-', @n);
51
52         # fall-back to looking up by st_ino + st_dev in case we're in
53         # a symlinked or bind-mounted path
54         if ($on_fs && !-d $d && -e $$dstref) {
55                 my @cur = stat(_);
56                 my $want = pack('dd', @cur[1,0]); # st_ino + st_dev
57                 my ($c, $o, @st);
58                 for my $g ("$n[0]-*", '*') {
59                         my @maybe = glob("$lss_dir$g/lei.saved-search");
60                         for my $f (@maybe) {
61                                 $c = PublicInbox::Config->git_config_dump($f);
62                                 $o = $c->{'lei.q.output'} // next;
63                                 $o =~ s!$LOCAL_PFX!! or next;
64                                 @st = stat($o) or next;
65                                 next if pack('dd', @st[1,0]) ne $want;
66                                 $f =~ m!\A(.+?)/[^/]+\z! and return $1;
67                         }
68                 }
69         }
70         $d;
71 }
72
73 sub list {
74         my ($lei, $pfx) = @_;
75         my $lss_dir = $lei->share_path.'/saved-searches';
76         return () unless -d $lss_dir;
77         # TODO: persist the cache?  Use another format?
78         my $f = $lei->cache_dir."/saved-tmp.$$.".time.'.config';
79         open my $fh, '>', $f or die "open $f: $!";
80         print $fh "[include]\n";
81         for my $p (glob("$lss_dir/*/lei.saved-search")) {
82                 print $fh "\tpath = ", cquote_val($p), "\n";
83         }
84         close $fh or die "close $f: $!";
85         my $cfg = PublicInbox::Config->git_config_dump($f);
86         unlink($f);
87         my $out = $cfg->get_all('lei.q.output') or return ();
88         map {;
89                 s!$LOCAL_PFX!!;
90                 $_;
91         } @$out
92 }
93
94 sub translate_dedupe ($$$) {
95         my ($self, $lei, $dd) = @_;
96         $dd //= 'content';
97         return 1 if $dd eq 'content'; # the default
98         return $self->{"-dedupe_$dd"} = 1 if ($dd eq 'oid' || $dd eq 'mid');
99         $lei->fail("--dedupe=$dd unsupported with --save");
100 }
101
102 sub up { # updating existing saved search via "lei up"
103         my ($cls, $lei, $dst) = @_;
104         my $f;
105         my $self = bless { ale => $lei->ale }, $cls;
106         my $dir = $dst;
107         output2lssdir($self, $lei, \$dir, \$f) or
108                 return $lei->fail("--save was not used with $dst cwd=".
109                                         $lei->rel2abs('.'));
110         $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
111         $self->{-ovf} = "$dir/over.sqlite3";
112         $self->{'-f'} = $f;
113         $self->{lock_path} = "$self->{-f}.flock";
114         $self;
115 }
116
117 sub new { # new saved search "lei q --save"
118         my ($cls, $lei) = @_;
119         my $self = bless { ale => $lei->ale }, $cls;
120         my $dst = $lei->{ovv}->{dst};
121         my $dir = lss_dir_for($lei, \$dst);
122         require File::Path;
123         File::Path::make_path($dir); # raises on error
124         $self->{-cfg} = {};
125         my $f = $self->{'-f'} = "$dir/lei.saved-search";
126         my $dd = $lei->{opt}->{dedupe};
127         translate_dedupe($self, $lei, $dd) or return;
128         open my $fh, '>', $f or return $lei->fail("open $f: $!");
129         my $sq_dst = PublicInbox::Config::squote_maybe($dst);
130         my $q = $lei->{mset_opt}->{q_raw} // die 'BUG: {q_raw} missing';
131         if (ref $q) {
132                 $q = join("\n", map { "\tq = ".cquote_val($_) } @$q);
133         } else {
134                 $q = "\tq = ".cquote_val($q);
135         }
136         $dst = "$lei->{ovv}->{fmt}:$dst" if $dst !~ m!\Aimaps?://!i;
137         print $fh <<EOM;
138 ; to refresh with new results, run: lei up $sq_dst
139 [lei]
140 $q
141 [lei "q"]
142         output = $dst
143 EOM
144         print $fh "\tdedupe = $dd\n" if $dd;
145         for my $k (ARRAY_FIELDS) {
146                 my $ary = $lei->{opt}->{$k} // next;
147                 for my $x (@$ary) {
148                         print $fh "\t$k = ".cquote_val($x)."\n";
149                 }
150         }
151         for my $k (BOOL_FIELDS) {
152                 my $val = $lei->{opt}->{$k} // next;
153                 print $fh "\t$k = ".($val ? 1 : 0)."\n";
154         }
155         close($fh) or return $lei->fail("close $f: $!");
156         $self->{lock_path} = "$self->{-f}.flock";
157         $self->{-ovf} = "$dir/over.sqlite3";
158         $self;
159 }
160
161 sub description { $_[0]->{qstr} } # for WWW
162
163 sub cfg_set { # called by LeiXSearch
164         my ($self, @args) = @_;
165         my $lk = $self->lock_for_scope; # git-config doesn't wait
166         run_die([qw(git config -f), $self->{'-f'}, @args]);
167 }
168
169 # drop-in for LeiDedupe API
170 sub is_dup {
171         my ($self, $eml, $smsg) = @_;
172         my $oidx = $self->{oidx} // die 'BUG: no {oidx}';
173         my $blob = $smsg ? $smsg->{blob} : undef;
174         my $lk = $self->lock_for_scope_fast;
175         return 1 if $blob && $oidx->blob_exists($blob);
176         if ($self->{-dedupe_mid}) {
177                 for my $mid (@{mids_for_index($eml)}) {
178                         my ($id, $prv);
179                         return 1 if $oidx->next_by_mid($mid, \$id, \$prv);
180                 }
181         }
182         if (my $xoids = PublicInbox::LeiSearch::xoids_for($self, $eml, 1)) {
183                 for my $docid (values %$xoids) {
184                         $oidx->add_xref3($docid, -1, $blob, '.');
185                 }
186                 $oidx->commit_lazy;
187                 if ($self->{-dedupe_oid}) {
188                         $smsg->{blob} //= git_sha(1, $eml)->hexdigest;
189                         exists $xoids->{$smsg->{blob}} ? 1 : undef;
190                 } else {
191                         1;
192                 }
193         } else {
194                 # n.b. above xoids_for fills out eml->{-lei_fake_mid} if needed
195                 unless ($smsg) {
196                         $smsg = bless {}, 'PublicInbox::Smsg';
197                         $smsg->{bytes} = 0;
198                         $smsg->populate($eml);
199                 }
200                 $oidx->begin_lazy;
201                 $smsg->{num} = $oidx->adj_counter('eidx_docid', '+');
202                 $smsg->{blob} //= git_sha(1, $eml)->hexdigest;
203                 $oidx->add_overview($eml, $smsg);
204                 $oidx->add_xref3($smsg->{num}, -1, $smsg->{blob}, '.');
205                 $oidx->commit_lazy;
206                 undef;
207         }
208 }
209
210 sub prepare_dedupe {
211         my ($self) = @_;
212         $self->{oidx} //= do {
213                 my $creat = !-f $self->{-ovf};
214                 my $lk = $self->lock_for_scope; # git-config doesn't wait
215                 my $oidx = PublicInbox::OverIdx->new($self->{-ovf});
216                 $oidx->{-no_fsync} = 1;
217                 $oidx->dbh;
218                 if ($creat) {
219                         $oidx->{dbh}->do('PRAGMA journal_mode = WAL');
220                         $oidx->eidx_prep; # for xref3
221                 }
222                 $oidx
223         };
224 }
225
226 sub over { $_[0]->{oidx} } # for xoids_for
227
228 # don't use ale->git directly since is_dup is called inside
229 # ale->git->cat_async callbacks
230 sub git { $_[0]->{git} //= PublicInbox::Git->new($_[0]->{ale}->git->{git_dir}) }
231
232 sub pause_dedupe {
233         my ($self) = @_;
234         git($self)->cleanup;
235         my $lockfh = delete $self->{lockfh}; # from lock_for_scope_fast;
236         my $oidx = delete($self->{oidx}) // return;
237         $oidx->commit_lazy;
238 }
239
240 sub mm { undef }
241
242 sub altid_map { {} }
243
244 sub cloneurl { [] }
245
246 # find existing directory containing a `lei.saved-search' file based on
247 # $dir_ref which is an output
248 sub output2lssdir {
249         my ($self, $lei, $dir_ref, $fn_ref) = @_;
250         my $dst = $$dir_ref; # imap://$MAILBOX, /path/to/maildir, /path/to/mbox
251         my $dir = lss_dir_for($lei, \$dst, 1);
252         my $f = "$dir/lei.saved-search";
253         if (-f $f && -r _) {
254                 $self->{-cfg} = PublicInbox::Config->git_config_dump($f);
255                 $$dir_ref = $dir;
256                 $$fn_ref = $f;
257                 return 1;
258         }
259         undef;
260 }
261
262 sub edit_begin {
263         my ($self, $lei) = @_;
264         if (ref($self->{-cfg}->{'lei.q.output'})) {
265                 delete $self->{-cfg}->{'lei.q.output'}; # invalid
266                 $lei->err(<<EOM);
267 $self->{-f} has multiple values of lei.q.output
268 please remove redundant ones
269 EOM
270         }
271         $lei->{-lss_for_edit} = $self;
272 }
273
274 sub edit_done {
275         my ($self, $lei) = @_;
276         my $cfg = PublicInbox::Config->git_config_dump($self->{'-f'});
277         my $new_out = $cfg->{'lei.q.output'} // '';
278         return $lei->fail(<<EOM) if ref $new_out;
279 $self->{-f} has multiple values of lei.q.output
280 please edit again
281 EOM
282         return $lei->fail(<<EOM) if $new_out eq '';
283 $self->{-f} needs lei.q.output
284 please edit again
285 EOM
286         my $old_out = $self->{-cfg}->{'lei.q.output'} // '';
287         return if $old_out eq $new_out;
288         my $old_path = $old_out;
289         my $new_path = $new_out;
290         s!$LOCAL_PFX!! for ($old_path, $new_path);
291         my $dir_old = lss_dir_for($lei, \$old_path, 1);
292         my $dir_new = lss_dir_for($lei, \$new_path);
293         return if $dir_new eq $dir_old; # no change, likely
294         return $lei->fail(<<EOM) if -e $dir_new;
295 lei.q.output changed from `$old_out' to `$new_out'
296 However, $dir_new exists
297 EOM
298         # start the conversion asynchronously
299         my $old_sq = PublicInbox::Config::squote_maybe($old_out);
300         my $new_sq = PublicInbox::Config::squote_maybe($new_out);
301         $lei->puts("lei.q.output changed from $old_sq to $new_sq");
302         $lei->qerr("# lei convert $old_sq -o $new_sq");
303         my $v = !$lei->{opt}->{quiet};
304         $lei->{opt} = { output => $new_out, verbose => $v };
305         require PublicInbox::LeiConvert;
306         PublicInbox::LeiConvert::lei_convert($lei, $old_out);
307
308         $lei->fail(<<EOM) if -e $dir_old && !rename($dir_old, $dir_new);
309 E: rename($dir_old, $dir_new) error: $!
310 EOM
311 }
312
313 no warnings 'once';
314 *nntp_url = \&cloneurl;
315 *base_url = \&PublicInbox::Inbox::base_url;
316 *smsg_eml = \&PublicInbox::Inbox::smsg_eml;
317 *smsg_by_mid = \&PublicInbox::Inbox::smsg_by_mid;
318 *msg_by_mid = \&PublicInbox::Inbox::msg_by_mid;
319 *modified = \&PublicInbox::Inbox::modified;
320 *recent = \&PublicInbox::Inbox::recent;
321 *max_git_epoch = *nntp_usable = *msg_by_path = \&mm; # undef
322 *isrch = *search = \&mm; # TODO
323 *DESTROY = \&pause_dedupe;
324
325 1;