]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
searchidx: fallback to lookup on pre-set article numbers
[public-inbox.git] / lib / PublicInbox / SearchIdx.pm
1 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 # based on notmuch, but with no concept of folders, files or flags
4 #
5 # Indexes mail with Xapian and our (SQLite-based) ::Msgmap for use
6 # with the web and NNTP interfaces.  This index maintains thread
7 # relationships for use by PublicInbox::SearchThread.
8 # This writes to the search index.
9 package PublicInbox::SearchIdx;
10 use strict;
11 use warnings;
12 use Fcntl qw(:flock :DEFAULT);
13 use PublicInbox::MIME;
14 use Email::MIME::ContentType;
15 $Email::MIME::ContentType::STRICT_PARAMS = 0;
16 use base qw(PublicInbox::Search);
17 use PublicInbox::MID qw/mid_clean id_compress mid_mime/;
18 use PublicInbox::MsgIter;
19 use Carp qw(croak);
20 use POSIX qw(strftime);
21 require PublicInbox::Git;
22
23 use constant {
24         MAX_MID_SIZE => 244, # max term size - 1 in Xapian
25         PERM_UMASK => 0,
26         OLD_PERM_GROUP => 1,
27         OLD_PERM_EVERYBODY => 2,
28         PERM_GROUP => 0660,
29         PERM_EVERYBODY => 0664,
30         BATCH_BYTES => 1_000_000,
31         DEBUG => !!$ENV{DEBUG},
32 };
33
34 my %GIT_ESC = (
35         a => "\a",
36         b => "\b",
37         f => "\f",
38         n => "\n",
39         r => "\r",
40         t => "\t",
41         v => "\013",
42 );
43
44 sub git_unquote ($) {
45         my ($s) = @_;
46         return $s unless ($s =~ /\A"(.*)"\z/);
47         $s = $1;
48         $s =~ s/\\([abfnrtv])/$GIT_ESC{$1}/g;
49         $s =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
50         $s;
51 }
52
53 sub new {
54         my ($class, $inbox, $creat) = @_;
55         my $git_dir = $inbox;
56         my $altid;
57         if (ref $inbox) {
58                 $git_dir = $inbox->{mainrepo};
59                 $altid = $inbox->{altid};
60                 if ($altid) {
61                         require PublicInbox::AltId;
62                         $altid = [ map {
63                                 PublicInbox::AltId->new($inbox, $_);
64                         } @$altid ];
65                 }
66         }
67         require Search::Xapian::WritableDatabase;
68         my $self = bless { git_dir => $git_dir, -altid => $altid }, $class;
69         my $perm = $self->_git_config_perm;
70         my $umask = _umask_for($perm);
71         $self->{umask} = $umask;
72         $self->{lock_path} = "$git_dir/ssoma.lock";
73         $self->{git} = PublicInbox::Git->new($git_dir);
74         $self->{creat} = ($creat || 0) == 1;
75         $self;
76 }
77
78 sub _xdb_release {
79         my ($self) = @_;
80         my $xdb = delete $self->{xdb} or croak 'not acquired';
81         $xdb->close;
82         _lock_release($self) if $self->{creat};
83         undef;
84 }
85
86 sub _xdb_acquire {
87         my ($self) = @_;
88         croak 'already acquired' if $self->{xdb};
89         my $dir = PublicInbox::Search->xdir($self->{git_dir});
90         my $flag = Search::Xapian::DB_OPEN;
91         if ($self->{creat}) {
92                 require File::Path;
93                 _lock_acquire($self);
94                 File::Path::mkpath($dir);
95                 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
96         }
97         $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
98 }
99
100 # we only acquire the flock if creating or reindexing;
101 # PublicInbox::Import already has the lock on its own.
102 sub _lock_acquire {
103         my ($self) = @_;
104         croak 'already locked' if $self->{lockfh};
105         sysopen(my $lockfh, $self->{lock_path}, O_WRONLY|O_CREAT) or
106                 die "failed to open lock $self->{lock_path}: $!\n";
107         flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
108         $self->{lockfh} = $lockfh;
109 }
110
111 sub _lock_release {
112         my ($self) = @_;
113         my $lockfh = delete $self->{lockfh} or croak 'not locked';
114         flock($lockfh, LOCK_UN) or die "unlock failed: $!\n";
115         close $lockfh or die "close failed: $!\n";
116 }
117
118 sub add_val ($$$) {
119         my ($doc, $col, $num) = @_;
120         $num = Search::Xapian::sortable_serialise($num);
121         $doc->add_value($col, $num);
122 }
123
124 sub add_values ($$$) {
125         my ($smsg, $bytes, $num) = @_;
126
127         my $ts = $smsg->ts;
128         my $doc = $smsg->{doc};
129         add_val($doc, &PublicInbox::Search::TS, $ts);
130
131         defined($num) and add_val($doc, &PublicInbox::Search::NUM, $num);
132
133         defined($bytes) and add_val($doc, &PublicInbox::Search::BYTES, $bytes);
134
135         add_val($doc, &PublicInbox::Search::LINES,
136                         $smsg->{mime}->body_raw =~ tr!\n!\n!);
137
138         my $yyyymmdd = strftime('%Y%m%d', gmtime($ts));
139         add_val($doc, PublicInbox::Search::YYYYMMDD, $yyyymmdd);
140 }
141
142 sub index_users ($$) {
143         my ($tg, $smsg) = @_;
144
145         my $from = $smsg->from;
146         my $to = $smsg->to;
147         my $cc = $smsg->cc;
148
149         $tg->index_text($from, 1, 'A'); # A - author
150         $tg->increase_termpos;
151         $tg->index_text($to, 1, 'XTO') if $to ne '';
152         $tg->increase_termpos;
153         $tg->index_text($cc, 1, 'XCC') if $cc ne '';
154         $tg->increase_termpos;
155 }
156
157 sub index_text_inc ($$$) {
158         my ($tg, $text, $pfx) = @_;
159         $tg->index_text($text, 1, $pfx);
160         $tg->increase_termpos;
161 }
162
163 sub index_old_diff_fn {
164         my ($tg, $seen, $fa, $fb) = @_;
165
166         # no renames or space support for traditional diffs,
167         # find the number of leading common paths to strip:
168         my @fa = split('/', $fa);
169         my @fb = split('/', $fb);
170         while (scalar(@fa) && scalar(@fb)) {
171                 $fa = join('/', @fa);
172                 $fb = join('/', @fb);
173                 if ($fa eq $fb) {
174                         index_text_inc($tg, $fa,'XDFN') unless $seen->{$fa}++;
175                         return 1;
176                 }
177                 shift @fa;
178                 shift @fb;
179         }
180         0;
181 }
182
183 sub index_diff ($$$) {
184         my ($tg, $lines, $doc) = @_;
185         my %seen;
186         my $in_diff;
187         foreach (@$lines) {
188                 if ($in_diff && s/^ //) { # diff context
189                         index_text_inc($tg, $_, 'XDFCTX');
190                 } elsif (/^-- $/) { # email signature begins
191                         $in_diff = undef;
192                 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
193                         my ($fa, $fb) = ($1, $2);
194                         my $fn = (split('/', git_unquote($fa), 2))[1];
195                         index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
196                         $fn = (split('/', git_unquote($fb), 2))[1];
197                         index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
198                         $in_diff = 1;
199                 # traditional diff:
200                 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
201                         my ($opt, $fa, $fb) = ($1, $2, $3);
202                         # only support unified:
203                         next unless $opt =~ /[uU]/;
204                         $in_diff = index_old_diff_fn($tg, \%seen, $fa, $fb);
205                 } elsif (m!^--- ("?a/.+)!) {
206                         my $fn = (split('/', git_unquote($1), 2))[1];
207                         index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
208                         $in_diff = 1;
209                 } elsif (m!^\+\+\+ ("?b/.+)!)  {
210                         my $fn = (split('/', git_unquote($1), 2))[1];
211                         index_text_inc($tg, $fn, 'XDFN') unless $seen{$fn}++;
212                         $in_diff = 1;
213                 } elsif (/^--- (\S+)/) {
214                         $in_diff = $1;
215                 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
216                         $in_diff = index_old_diff_fn($tg, \%seen, $in_diff, $1);
217                 } elsif ($in_diff && s/^\+//) { # diff added
218                         index_text_inc($tg, $_, 'XDFB');
219                 } elsif ($in_diff && s/^-//) { # diff removed
220                         index_text_inc($tg, $_, 'XDFA');
221                 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
222                         my ($ba, $bb) = ($1, $2);
223                         index_git_blob_id($doc, 'XDFPRE', $ba);
224                         index_git_blob_id($doc, 'XDFPOST', $bb);
225                         $in_diff = 1;
226                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
227                         # traditional diff w/o -p
228                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
229                         # hunk header context
230                         index_text_inc($tg, $1, 'XDFHH');
231                 # ignore the following lines:
232                 } elsif (/^(?:dis)similarity index/) {
233                 } elsif (/^(?:old|new) mode/) {
234                 } elsif (/^(?:deleted|new) file mode/) {
235                 } elsif (/^(?:copy|rename) (?:from|to) /) {
236                 } elsif (/^(?:dis)?similarity index /) {
237                 } elsif (/^\\ No newline at end of file/) {
238                 } elsif (/^Binary files .* differ/) {
239                 } elsif ($_ eq '') {
240                         $in_diff = undef;
241                 } else {
242                         warn "non-diff line: $_\n" if DEBUG && $_ ne '';
243                         $in_diff = undef;
244                 }
245         }
246 }
247
248 sub index_body ($$$) {
249         my ($tg, $lines, $doc) = @_;
250         my $txt = join("\n", @$lines);
251         $tg->index_text($txt, !!$doc, $doc ? 'XNQ' : 'XQUOT');
252         $tg->increase_termpos;
253         # does it look like a diff?
254         if ($doc && $txt =~ /^(?:diff|---|\+\+\+) /ms) {
255                 $txt = undef;
256                 index_diff($tg, $lines, $doc);
257         }
258         @$lines = ();
259 }
260
261 sub add_message {
262         my ($self, $mime, $bytes, $num, $blob) = @_; # mime = Email::MIME object
263         my $db = $self->{xdb};
264
265         my ($doc_id, $old_tid);
266         my $mid = mid_clean(mid_mime($mime));
267
268         eval {
269                 die 'Message-ID too long' if length($mid) > MAX_MID_SIZE;
270                 my $smsg = $self->lookup_message($mid);
271                 if ($smsg) {
272                         # convert a ghost to a regular message
273                         # it will also clobber any existing regular message
274                         $doc_id = $smsg->{doc_id};
275                         $old_tid = $smsg->thread_id;
276                 }
277                 $smsg = PublicInbox::SearchMsg->new($mime);
278                 my $doc = $smsg->{doc};
279                 $doc->add_term('Q' . $mid);
280
281                 my $subj = $smsg->subject;
282                 if ($subj ne '') {
283                         my $path = $self->subject_path($subj);
284                         $doc->add_term('XPATH' . id_compress($path));
285                 }
286
287                 add_values($smsg, $bytes, $num);
288
289                 my $tg = $self->term_generator;
290
291                 $tg->set_document($doc);
292                 $tg->index_text($subj, 1, 'S') if $subj;
293                 $tg->increase_termpos;
294
295                 index_users($tg, $smsg);
296
297                 msg_iter($mime, sub {
298                         my ($part, $depth, @idx) = @{$_[0]};
299                         my $ct = $part->content_type || 'text/plain';
300                         my $fn = $part->filename;
301                         if (defined $fn && $fn ne '') {
302                                 $tg->index_text($fn, 1, 'XFN');
303                         }
304
305                         return if $ct =~ m!\btext/x?html\b!i;
306
307                         my $s = eval { $part->body_str };
308                         if ($@) {
309                                 if ($ct =~ m!\btext/plain\b!i) {
310                                         # Try to assume UTF-8 because Alpine
311                                         # seems to do wacky things and set
312                                         # charset=X-UNKNOWN
313                                         $part->charset_set('UTF-8');
314                                         $s = eval { $part->body_str };
315                                         $s = $part->body if $@;
316                                 }
317                         }
318                         defined $s or return;
319
320                         my (@orig, @quot);
321                         my $body = $part->body;
322                         my @lines = split(/\n/, $body);
323                         while (defined(my $l = shift @lines)) {
324                                 if ($l =~ /^>/) {
325                                         index_body($tg, \@orig, $doc) if @orig;
326                                         push @quot, $l;
327                                 } else {
328                                         index_body($tg, \@quot, 0) if @quot;
329                                         push @orig, $l;
330                                 }
331                         }
332                         index_body($tg, \@quot, 0) if @quot;
333                         index_body($tg, \@orig, $doc) if @orig;
334                 });
335
336                 link_message($self, $smsg, $old_tid);
337                 $tg->index_text($mid, 1, 'XMID');
338                 $doc->set_data($smsg->to_doc_data($blob));
339
340                 if (my $altid = $self->{-altid}) {
341                         foreach my $alt (@$altid) {
342                                 my $id = $alt->mid2alt($mid);
343                                 next unless defined $id;
344                                 $doc->add_term($alt->{xprefix} . $id);
345                         }
346                 }
347                 if (defined $doc_id) {
348                         $db->replace_document($doc_id, $doc);
349                 } else {
350                         $doc_id = $db->add_document($doc);
351                 }
352         };
353
354         if ($@) {
355                 warn "failed to index message <$mid>: $@\n";
356                 return undef;
357         }
358         $doc_id;
359 }
360
361 # returns deleted doc_id on success, undef on missing
362 sub remove_message {
363         my ($self, $mid) = @_;
364         my $db = $self->{xdb};
365         my $doc_id;
366         $mid = mid_clean($mid);
367
368         eval {
369                 $doc_id = $self->find_unique_doc_id('Q' . $mid);
370                 if (defined $doc_id) {
371                         $db->delete_document($doc_id);
372                 } else {
373                         warn "cannot remove non-existent <$mid>\n";
374                 }
375         };
376
377         if ($@) {
378                 warn "failed to remove message <$mid>: $@\n";
379                 return undef;
380         }
381         $doc_id;
382 }
383
384 sub term_generator { # write-only
385         my ($self) = @_;
386
387         my $tg = $self->{term_generator};
388         return $tg if $tg;
389
390         $tg = Search::Xapian::TermGenerator->new;
391         $tg->set_stemmer($self->stemmer);
392
393         $self->{term_generator} = $tg;
394 }
395
396 # increments last_thread_id counter
397 # returns a 64-bit integer represented as a hex string
398 sub next_thread_id {
399         my ($self) = @_;
400         my $db = $self->{xdb};
401         my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
402
403         $db->set_metadata('last_thread_id', ++$last_thread_id);
404
405         $last_thread_id;
406 }
407
408 sub link_message {
409         my ($self, $smsg, $old_tid) = @_;
410         my $doc = $smsg->{doc};
411         my $mid = $smsg->mid;
412         my $mime = $smsg->{mime};
413         my $hdr = $mime->header_obj;
414
415         # last References should be IRT, but some mail clients do things
416         # out of order, so trust IRT over References iff IRT exists
417         my @refs = ($hdr->header_raw('References'),
418                         $hdr->header_raw('In-Reply-To'));
419         @refs = ((join(' ', @refs)) =~ /<([^>]+)>/g);
420
421         my $tid;
422         if (@refs) {
423                 my %uniq = ($mid => 1);
424                 my @orig_refs = @refs;
425                 @refs = ();
426
427                 # prevent circular references via References: here:
428                 foreach my $ref (@orig_refs) {
429                         if (length($ref) > MAX_MID_SIZE) {
430                                 warn "References: <$ref> too long, ignoring\n";
431                         }
432                         next if $uniq{$ref};
433                         $uniq{$ref} = 1;
434                         push @refs, $ref;
435                 }
436         }
437
438         if (@refs) {
439                 $smsg->{references} = '<'.join('> <', @refs).'>';
440
441                 # first ref *should* be the thread root,
442                 # but we can never trust clients to do the right thing
443                 my $ref = shift @refs;
444                 $tid = $self->_resolve_mid_to_tid($ref);
445                 $self->merge_threads($tid, $old_tid) if defined $old_tid;
446
447                 # the rest of the refs should point to this tid:
448                 foreach $ref (@refs) {
449                         my $ptid = $self->_resolve_mid_to_tid($ref);
450                         merge_threads($self, $tid, $ptid);
451                 }
452         } else {
453                 $tid = defined $old_tid ? $old_tid : $self->next_thread_id;
454         }
455         $doc->add_term('G' . $tid);
456 }
457
458 sub index_blob {
459         my ($self, $mime, $bytes, $num, $blob) = @_;
460         $self->add_message($mime, $bytes, $num, $blob);
461 }
462
463 sub index_git_blob_id {
464         my ($doc, $pfx, $objid) = @_;
465
466         my $len = length($objid);
467         for (my $len = length($objid); $len >= 7; ) {
468                 $doc->add_term($pfx.$objid);
469                 $objid = substr($objid, 0, --$len);
470         }
471 }
472
473 sub unindex_blob {
474         my ($self, $mime) = @_;
475         my $mid = eval { mid_clean(mid_mime($mime)) };
476         $self->remove_message($mid) if defined $mid;
477 }
478
479 sub index_mm {
480         my ($self, $mime) = @_;
481         my $mid = mid_clean(mid_mime($mime));
482         my $mm = $self->{mm};
483         my $num = $mm->mid_insert($mid);
484
485         # fallback to num_for since filters like RubyLang set the number
486         defined $num ? $num : $mm->num_for($mid);
487 }
488
489 sub unindex_mm {
490         my ($self, $mime) = @_;
491         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
492 }
493
494 sub index_mm2 {
495         my ($self, $mime, $bytes, $blob) = @_;
496         my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
497         index_blob($self, $mime, $bytes, $num, $blob);
498 }
499
500 sub unindex_mm2 {
501         my ($self, $mime) = @_;
502         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
503         unindex_blob($self, $mime);
504 }
505
506 sub index_both {
507         my ($self, $mime, $bytes, $blob) = @_;
508         my $num = index_mm($self, $mime);
509         index_blob($self, $mime, $bytes, $num, $blob);
510 }
511
512 sub unindex_both {
513         my ($self, $mime) = @_;
514         unindex_blob($self, $mime);
515         unindex_mm($self, $mime);
516 }
517
518 sub do_cat_mail {
519         my ($git, $blob, $sizeref) = @_;
520         my $mime = eval {
521                 my $str = $git->cat_file($blob, $sizeref);
522                 # fixup bugs from import:
523                 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
524                 PublicInbox::MIME->new($str);
525         };
526         $@ ? undef : $mime;
527 }
528
529 sub index_sync {
530         my ($self, $opts) = @_;
531         with_umask($self, sub { $self->_index_sync($opts) });
532 }
533
534 sub batch_adjust ($$$$) {
535         my ($max, $bytes, $batch_cb, $latest) = @_;
536         $$max -= $bytes;
537         if ($$max <= 0) {
538                 $$max = BATCH_BYTES;
539                 $batch_cb->($latest, 1);
540         }
541 }
542
543 sub rlog {
544         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
545         my $hex = '[a-f0-9]';
546         my $h40 = $hex .'{40}';
547         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
548         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
549         my $git = $self->{git};
550         my $latest;
551         my $bytes;
552         my $max = BATCH_BYTES;
553         local $/ = "\n";
554         my $line;
555         while (defined($line = <$log>)) {
556                 if ($line =~ /$addmsg/o) {
557                         my $blob = $1;
558                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
559                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
560                         $add_cb->($self, $mime, $bytes, $blob);
561                 } elsif ($line =~ /$delmsg/o) {
562                         my $blob = $1;
563                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
564                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
565                         $del_cb->($self, $mime);
566                 } elsif ($line =~ /^commit ($h40)/o) {
567                         $latest = $1;
568                 }
569         }
570         $batch_cb->($latest, 0);
571 }
572
573 sub _msgmap_init {
574         my ($self) = @_;
575         $self->{mm} = eval {
576                 require PublicInbox::Msgmap;
577                 PublicInbox::Msgmap->new($self->{git_dir}, 1);
578         };
579 }
580
581 sub _git_log {
582         my ($self, $range) = @_;
583         $self->{git}->popen(qw/log --reverse --no-notes --no-color
584                                 --raw -r --no-abbrev/, $range);
585 }
586
587 # indexes all unindexed messages
588 sub _index_sync {
589         my ($self, $opts) = @_;
590         my $tip = $opts->{ref} || 'HEAD';
591         my $reindex = $opts->{reindex};
592         my ($mkey, $last_commit, $lx, $xlog);
593         $self->{git}->batch_prepare;
594         my $xdb = _xdb_acquire($self);
595         $xdb->begin_transaction;
596         do {
597                 $xlog = undef;
598                 $mkey = 'last_commit';
599                 $last_commit = $xdb->get_metadata('last_commit');
600                 $lx = $last_commit;
601                 if ($reindex) {
602                         $lx = '';
603                         $mkey = undef if $last_commit ne '';
604                 }
605                 $xdb->cancel_transaction;
606                 $xdb = _xdb_release($self);
607
608                 # ensure we leak no FDs to "git log"
609                 my $range = $lx eq '' ? $tip : "$lx..$tip";
610                 $xlog = _git_log($self, $range);
611
612                 $xdb = _xdb_acquire($self);
613                 $xdb->begin_transaction;
614         } while ($xdb->get_metadata('last_commit') ne $last_commit);
615
616         my $mm = _msgmap_init($self);
617         my $dbh = $mm->{dbh} if $mm;
618         my $mm_only;
619         my $cb = sub {
620                 my ($commit, $more) = @_;
621                 if ($dbh) {
622                         $mm->last_commit($commit) if $commit;
623                         $dbh->commit;
624                 }
625                 if (!$mm_only) {
626                         $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
627                         $xdb->commit_transaction;
628                         $xdb = _xdb_release($self);
629                 }
630                 # let another process do some work... <
631                 if ($more) {
632                         if (!$mm_only) {
633                                 $xdb = _xdb_acquire($self);
634                                 $xdb->begin_transaction;
635                         }
636                         $dbh->begin_work if $dbh;
637                 }
638         };
639
640         if ($mm) {
641                 $dbh->begin_work;
642                 my $lm = $mm->last_commit || '';
643                 if ($lm eq $lx) {
644                         # Common case is the indexes are synced,
645                         # we only need to run git-log once:
646                         rlog($self, $xlog, *index_both, *unindex_both, $cb);
647                 } else {
648                         # Uncommon case, msgmap and xapian are out-of-sync
649                         # do not care for performance (but git is fast :>)
650                         # This happens if we have to reindex Xapian since
651                         # msgmap is a frozen format and our Xapian format
652                         # is evolving.
653                         my $r = $lm eq '' ? $tip : "$lm..$tip";
654
655                         # first, ensure msgmap is up-to-date:
656                         my $mkey_prev = $mkey;
657                         $mkey = undef; # ignore xapian, for now
658                         my $mlog = _git_log($self, $r);
659                         $mm_only = 1;
660                         rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
661                         $mm_only = $mlog = undef;
662
663                         # now deal with Xapian
664                         $mkey = $mkey_prev;
665                         $dbh = undef;
666                         rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
667                 }
668         } else {
669                 # user didn't install DBD::SQLite and DBI
670                 rlog($self, $xlog, *index_blob, *unindex_blob, $cb);
671         }
672 }
673
674 # this will create a ghost as necessary
675 sub _resolve_mid_to_tid {
676         my ($self, $mid) = @_;
677
678         my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
679         $smsg->thread_id;
680 }
681
682 sub create_ghost {
683         my ($self, $mid) = @_;
684
685         my $tid = $self->next_thread_id;
686         my $doc = Search::Xapian::Document->new;
687         $doc->add_term('Q' . $mid);
688         $doc->add_term('G' . $tid);
689         $doc->add_term('T' . 'ghost');
690
691         my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
692         $self->{xdb}->add_document($doc);
693
694         $smsg;
695 }
696
697 sub merge_threads {
698         my ($self, $winner_tid, $loser_tid) = @_;
699         return if $winner_tid == $loser_tid;
700         my ($head, $tail) = $self->find_doc_ids('G' . $loser_tid);
701         my $db = $self->{xdb};
702
703         for (; $head != $tail; $head->inc) {
704                 my $docid = $head->get_docid;
705                 my $doc = $db->get_document($docid);
706                 $doc->remove_term('G' . $loser_tid);
707                 $doc->add_term('G' . $winner_tid);
708                 $db->replace_document($docid, $doc);
709         }
710 }
711
712 sub _read_git_config_perm {
713         my ($self) = @_;
714         my @cmd = qw(config core.sharedRepository);
715         my $fh = PublicInbox::Git->new($self->{git_dir})->popen(@cmd);
716         local $/ = "\n";
717         my $perm = <$fh>;
718         chomp $perm if defined $perm;
719         $perm;
720 }
721
722 sub _git_config_perm {
723         my $self = shift;
724         my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
725         return PERM_GROUP if (!defined($perm) || $perm eq '');
726         return PERM_UMASK if ($perm eq 'umask');
727         return PERM_GROUP if ($perm eq 'group');
728         if ($perm =~ /\A(?:all|world|everybody)\z/) {
729                 return PERM_EVERYBODY;
730         }
731         return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
732         return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
733
734         my $i = oct($perm);
735         return PERM_UMASK if ($i == PERM_UMASK);
736         return PERM_GROUP if ($i == OLD_PERM_GROUP);
737         return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
738
739         if (($i & 0600) != 0600) {
740                 die "core.sharedRepository mode invalid: ".
741                     sprintf('%.3o', $i) . "\nOwner must have permissions\n";
742         }
743         ($i & 0666);
744 }
745
746 sub _umask_for {
747         my ($perm) = @_; # _git_config_perm return value
748         my $rv = $perm;
749         return umask if $rv == 0;
750
751         # set +x bit if +r or +w were set
752         $rv |= 0100 if ($rv & 0600);
753         $rv |= 0010 if ($rv & 0060);
754         $rv |= 0001 if ($rv & 0006);
755         (~$rv & 0777);
756 }
757
758 sub with_umask {
759         my ($self, $cb) = @_;
760         my $old = umask $self->{umask};
761         my $rv = eval { $cb->() };
762         my $err = $@;
763         umask $old;
764         die $err if $err;
765         $rv;
766 }
767
768 sub DESTROY {
769         # order matters for unlocking
770         $_[0]->{xdb} = undef;
771         $_[0]->{lockfh} = undef;
772 }
773
774 1;