]> git.notmuchmail.org Git - notmuch/blob - devel/nmbug/nmbug
befc3d90cb848b965e03cc947bafe84d489a78d3
[notmuch] / devel / nmbug / nmbug
1 #!/usr/bin/env perl
2 # Copyright (c) 2011 David Bremner
3 # License: same as notmuch
4
5 use strict;
6 use warnings;
7 use File::Temp qw(tempdir);
8 use Pod::Usage;
9
10 no encoding;
11
12 my $NMBGIT = $ENV{NMBGIT} || $ENV{HOME}.'/.nmbug';
13
14 $NMBGIT .= '/.git' if (-d $NMBGIT.'/.git');
15
16 my $TAGPREFIX = $ENV{NMBPREFIX} || 'notmuch::';
17
18 # magic hash for git
19 my $EMPTYBLOB = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391';
20
21 # for encoding
22
23 my $ESCAPE_CHAR =       '%';
24 my $NO_ESCAPE =         'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
25                         '0123456789+-_@=.:,';
26 my $MUST_ENCODE =       qr{[^\Q$NO_ESCAPE\E]};
27 my $ESCAPED_RX =        qr{$ESCAPE_CHAR([A-Fa-f0-9]{2})};
28
29 my %command = (
30              archive    => \&do_archive,
31              checkout   => \&do_checkout,
32              commit     => \&do_commit,
33              fetch      => \&do_fetch,
34              help       => \&do_help,
35              log        => \&do_log,
36              merge      => \&do_merge,
37              pull       => \&do_pull,
38              push       => \&do_push,
39              status     => \&do_status,
40              );
41
42 # Convert prefix into form suitable for literal matching against
43 # notmuch dump --format=batch-tag output.
44 my $ENCPREFIX = encode_for_fs ($TAGPREFIX);
45 $ENCPREFIX =~ s/:/%3a/g;
46
47 my $subcommand = shift || usage ();
48
49 if (!exists $command{$subcommand}) {
50   usage ();
51 }
52
53 &{$command{$subcommand}}(@ARGV);
54
55 sub git_pipe {
56   my $envref = (ref $_[0] eq 'HASH') ? shift : {};
57   my $ioref  = (ref $_[0] eq 'ARRAY') ? shift : undef;
58   my $dir = ($_[0] eq '-|' or $_[0] eq '|-') ? shift : undef;
59
60   unshift @_, 'git';
61   $envref->{GIT_DIR} ||= $NMBGIT;
62   spawn ($envref, defined $ioref ? $ioref : (), defined $dir ? $dir : (), @_);
63 }
64
65 sub git {
66   my $fh = git_pipe (@_);
67   my $str = join ('', <$fh>);
68   unless (close $fh) {
69     die "'git @_' exited with nonzero value\n";
70   }
71   chomp($str);
72   return $str;
73 }
74
75 sub spawn {
76   my $envref = (ref $_[0] eq 'HASH') ? shift : {};
77   my $ioref  = (ref $_[0] eq 'ARRAY') ? shift : undef;
78   my $dir = ($_[0] eq '-|' or $_[0] eq '|-') ? shift : '-|';
79
80   die unless @_;
81
82   if (open my $child, $dir) {
83     return $child;
84   }
85   # child
86   while (my ($key, $value) = each %{$envref}) {
87     $ENV{$key} = $value;
88   }
89
90   if (defined $ioref && $dir eq '-|') {
91       open my $fh, '|-', @_ or die "open |- @_: $!";
92       foreach my $line (@{$ioref}) {
93         print $fh $line, "\n";
94       }
95       exit ! close $fh;
96     } else {
97       if ($dir ne '|-') {
98         open STDIN, '<', '/dev/null' or die "reopening stdin: $!"
99       }
100       exec @_;
101       die "exec @_: $!";
102     }
103 }
104
105
106 sub get_tags {
107   my $prefix = shift;
108   my @tags;
109
110   my $fh = spawn ('-|', qw/notmuch search --output=tags/, "*")
111     or die 'error dumping tags';
112
113   while (<$fh>) {
114     chomp ();
115     push @tags, $_ if (m/^$prefix/);
116   }
117   unless (close $fh) {
118     die "'notmuch search --output=tags *' exited with nonzero value\n";
119   }
120   return @tags;
121 }
122
123
124 sub do_archive {
125   system ('git', "--git-dir=$NMBGIT", 'archive', 'HEAD');
126 }
127
128
129 sub is_committed {
130   my $status = shift;
131   return scalar (@{$status->{added}} ) + scalar (@{$status->{deleted}} ) == 0;
132 }
133
134
135 sub do_commit {
136   my @args = @_;
137
138   my $status = compute_status ();
139
140   if ( is_committed ($status) ) {
141     print "Nothing to commit\n";
142     return;
143   }
144
145   my $index = read_tree ('HEAD');
146
147   update_index ($index, $status);
148
149   my $tree = git ( { GIT_INDEX_FILE => $index }, 'write-tree')
150     or die 'no output from write-tree';
151
152   my $parent = git ( 'rev-parse', 'HEAD'  )
153     or die 'no output from rev-parse';
154
155   my $commit = git ([ @args ], 'commit-tree', $tree, '-p', $parent)
156     or die 'commit-tree';
157
158   git ('update-ref', 'HEAD', $commit);
159
160   unlink $index || die "unlink: $!";
161
162 }
163
164 sub read_tree {
165   my $treeish = shift;
166   my $index = $NMBGIT.'/nmbug.index';
167   git ({ GIT_INDEX_FILE => $index }, 'read-tree', '--empty');
168   git ({ GIT_INDEX_FILE => $index }, 'read-tree', $treeish);
169   return $index;
170 }
171
172 sub update_index {
173   my $index = shift;
174   my $status = shift;
175
176   my $git = spawn ({ GIT_DIR => $NMBGIT, GIT_INDEX_FILE => $index },
177                      '|-', qw/git update-index --index-info/)
178     or die 'git update-index';
179
180   foreach my $pair (@{$status->{deleted}}) {
181     index_tags_for_msg ($git, $pair->{id}, 'D', $pair->{tag});
182   }
183
184   foreach my $pair (@{$status->{added}}) {
185     index_tags_for_msg ($git, $pair->{id}, 'A', $pair->{tag});
186   }
187   unless (close $git) {
188     die "'git update-index --index-info' exited with nonzero value\n";
189   }
190
191 }
192
193
194 sub do_fetch {
195   my $remote = shift || 'origin';
196
197   git ('fetch', $remote);
198 }
199
200
201 sub notmuch {
202   my @args = @_;
203   system ('notmuch', @args) == 0 or die  "notmuch @args failed: $?";
204 }
205
206
207 sub index_tags {
208
209   my $index = $NMBGIT.'/nmbug.index';
210
211   my $query = join ' ', map ("tag:\"$_\"", get_tags ($TAGPREFIX));
212
213   my $fh = spawn ('-|', qw/notmuch dump --format=batch-tag --/, $query)
214     or die "notmuch dump: $!";
215
216   git ('read-tree', '--empty');
217   my $git = spawn ({ GIT_DIR => $NMBGIT, GIT_INDEX_FILE => $index },
218                      '|-', qw/git update-index --index-info/)
219     or die 'git update-index';
220
221   while (<$fh>) {
222
223     chomp();
224     my ($rest,$id) = split(/ -- id:/);
225
226     if ($id =~ s/^"(.*)"\s*$/$1/) {
227       # xapian quoted string, dequote.
228       $id =~ s/""/"/g;
229     }
230
231     #strip prefixes from tags before writing
232     my @tags = grep { s/^[+]$ENCPREFIX//; } split (' ', $rest);
233     index_tags_for_msg ($git,$id, 'A', @tags);
234   }
235   unless (close $git) {
236     die "'git update-index --index-info' exited with nonzero value\n";
237   }
238   unless (close $fh) {
239     die "'notmuch dump --format=batch-tag -- $query' exited with nonzero value\n";
240   }
241   return $index;
242 }
243
244 # update the git index to either create or delete an empty file.
245 # Neither argument should be encoded/escaped.
246 sub index_tags_for_msg {
247   my $fh = shift;
248   my $msgid = shift;
249   my $mode = shift;
250
251   my $hash = $EMPTYBLOB;
252   my $blobmode = '100644';
253
254   if ($mode eq 'D') {
255     $blobmode = '0';
256     $hash = '0000000000000000000000000000000000000000';
257   }
258
259   foreach my $tag (@_) {
260     my $tagpath = 'tags/' . encode_for_fs ($msgid) . '/' . encode_for_fs ($tag);
261     print $fh "$blobmode $hash\t$tagpath\n";
262   }
263 }
264
265
266 sub do_checkout {
267   do_sync (action => 'checkout');
268 }
269
270
271 sub do_sync {
272
273   my %args = @_;
274
275   my $status = compute_status ();
276   my ($A_action, $D_action);
277
278   if ($args{action} eq 'checkout') {
279     $A_action = '-';
280     $D_action = '+';
281   } else {
282     $A_action = '+';
283     $D_action = '-';
284   }
285
286   foreach my $pair (@{$status->{added}}) {
287
288     notmuch ('tag', $A_action.$TAGPREFIX.$pair->{tag},
289              'id:'.$pair->{id});
290   }
291
292   foreach my $pair (@{$status->{deleted}}) {
293     notmuch ('tag', $D_action.$TAGPREFIX.$pair->{tag},
294              'id:'.$pair->{id});
295   }
296
297 }
298
299
300 sub insist_committed {
301
302   my $status=compute_status();
303   if ( !is_committed ($status) ) {
304     print "Uncommitted changes to $TAGPREFIX* tags in notmuch
305
306 For a summary of changes, run 'nmbug status'
307 To save your changes,     run 'nmbug commit' before merging/pull
308 To discard your changes,  run 'nmbug checkout'
309 ";
310     exit (1);
311   }
312
313 }
314
315
316 sub do_pull {
317   my $remote = shift || 'origin';
318
319   git ( 'fetch', $remote);
320
321   do_merge ();
322 }
323
324
325 sub do_merge {
326   insist_committed ();
327
328   my $tempwork = tempdir ('/tmp/nmbug-merge.XXXXXX', CLEANUP => 1);
329
330   git ( { GIT_WORK_TREE => $tempwork }, 'checkout', '-f', 'HEAD');
331
332   git ( { GIT_WORK_TREE => $tempwork }, 'merge', 'FETCH_HEAD');
333
334   do_checkout ();
335 }
336
337
338 sub do_log {
339   # we don't want output trapping here, because we want the pager.
340   system ( 'git', "--git-dir=$NMBGIT", 'log', '--name-status', @_);
341 }
342
343
344 sub do_push {
345   my $remote = shift || 'origin';
346
347   git ('push', $remote, 'master');
348 }
349
350
351 sub do_status {
352   my $status = compute_status ();
353
354   my %output = ();
355   foreach my $pair (@{$status->{added}}) {
356     $output{$pair->{id}} ||= {};
357     $output{$pair->{id}}{$pair->{tag}} = 'A'
358   }
359
360   foreach my $pair (@{$status->{deleted}}) {
361     $output{$pair->{id}} ||= {};
362     $output{$pair->{id}}{$pair->{tag}} = 'D'
363   }
364
365   foreach my $pair (@{$status->{missing}}) {
366     $output{$pair->{id}} ||= {};
367     $output{$pair->{id}}{$pair->{tag}} = 'U'
368   }
369
370   if (is_unmerged ()) {
371     foreach my $pair (diff_refs ('A')) {
372       $output{$pair->{id}} ||= {};
373       $output{$pair->{id}}{$pair->{tag}} ||= ' ';
374       $output{$pair->{id}}{$pair->{tag}} .= 'a';
375     }
376
377     foreach my $pair (diff_refs ('D')) {
378       $output{$pair->{id}} ||= {};
379       $output{$pair->{id}}{$pair->{tag}} ||= ' ';
380       $output{$pair->{id}}{$pair->{tag}} .= 'd';
381     }
382   }
383
384   foreach my $id (sort keys %output) {
385     foreach my $tag (sort keys %{$output{$id}}) {
386       printf "%s\t%s\t%s\n", $output{$id}{$tag}, $id, $tag;
387     }
388   }
389 }
390
391
392 sub is_unmerged {
393
394   return 0 if (! -f $NMBGIT.'/FETCH_HEAD');
395
396   my $fetch_head = git ('rev-parse', 'FETCH_HEAD');
397   my $base = git ( 'merge-base', 'HEAD', 'FETCH_HEAD');
398
399   return ($base ne $fetch_head);
400
401 }
402
403 sub compute_status {
404   my %args = @_;
405
406   my @added;
407   my @deleted;
408   my @missing;
409
410   my $index = index_tags ();
411
412   my @maybe_deleted = diff_index ($index, 'D');
413
414   foreach my $pair (@maybe_deleted) {
415
416     my $id = $pair->{id};
417
418     my $fh = spawn ('-|', qw/notmuch search --output=files/,"id:$id")
419       or die "searching for $id";
420     if (!<$fh>) {
421       push @missing, $pair;
422     } else {
423       push @deleted, $pair;
424     }
425     unless (close $fh) {
426       die "'notmuch search --output=files id:$id' exited with nonzero value\n";
427     }
428   }
429
430
431   @added = diff_index ($index, 'A');
432
433   unlink $index || die "unlink $index: $!";
434
435   return { added => [@added], deleted => [@deleted], missing => [@missing] };
436 }
437
438
439 sub diff_index {
440   my $index = shift;
441   my $filter = shift;
442
443   my $fh = git_pipe ({ GIT_INDEX_FILE => $index },
444                   qw/diff-index --cached/,
445                  "--diff-filter=$filter", qw/--name-only HEAD/ );
446
447   my @lines = unpack_diff_lines ($fh);
448   unless (close $fh) {
449     die "'git diff-index --cached --diff-filter=$filter --name-only HEAD' ",
450         "exited with nonzero value\n";
451   }
452   return @lines;
453 }
454
455
456 sub diff_refs {
457   my $filter = shift;
458   my $ref1 = shift || 'HEAD';
459   my $ref2 = shift || 'FETCH_HEAD';
460
461   my $fh= git_pipe ( 'diff', "--diff-filter=$filter", '--name-only',
462                  $ref1, $ref2);
463
464   my @lines = unpack_diff_lines ($fh);
465   unless (close $fh) {
466     die "'git diff --diff-filter=$filter --name-only $ref1 $ref2' ",
467         "exited with nonzero value\n";
468   }
469   return @lines;
470 }
471
472
473 sub unpack_diff_lines {
474   my $fh = shift;
475
476   my @found;
477   while(<$fh>) {
478     chomp ();
479     my ($id,$tag) = m|tags/ ([^/]+) / ([^/]+) |x;
480
481     $id = decode_from_fs ($id);
482     $tag = decode_from_fs ($tag);
483
484     push @found, { id => $id, tag => $tag };
485   }
486
487   return @found;
488 }
489
490
491 sub encode_for_fs {
492   my $str = shift;
493
494   $str =~ s/($MUST_ENCODE)/"$ESCAPE_CHAR".sprintf ("%02x",ord ($1))/ge;
495   return $str;
496 }
497
498
499 sub decode_from_fs {
500   my $str = shift;
501
502   $str =~ s/$ESCAPED_RX/ chr (hex ($1))/eg;
503
504   return $str;
505
506 }
507
508
509 sub usage {
510   pod2usage ();
511   exit (1);
512 }
513
514
515 sub do_help {
516   pod2usage ( -verbose => 2 );
517   exit (0);
518 }
519
520 __END__
521
522 =head1 NAME
523
524 nmbug - manage notmuch tags about notmuch
525
526 =head1 SYNOPSIS
527
528 nmbug subcommand [options]
529
530 B<nmbug help> for more help
531
532 =head1 OPTIONS
533
534 =head2 Most common commands
535
536 =over 8
537
538 =item B<commit> [message]
539
540 Commit appropriately prefixed tags from the notmuch database to
541 git. Any extra arguments are used (one per line) as a commit message.
542
543 =item  B<push> [remote]
544
545 push local nmbug git state to remote repo
546
547 =item  B<pull> [remote]
548
549 pull (merge) remote repo changes to notmuch. B<pull> is equivalent to
550 B<fetch> followed by B<merge>.
551
552 =back
553
554 =head2 Other Useful Commands
555
556 =over 8
557
558 =item B<checkout>
559
560 Update the notmuch database from git. This is mainly useful to discard
561 your changes in notmuch relative to git.
562
563 =item B<fetch> [remote]
564
565 Fetch changes from the remote repo (see merge to bring those changes
566 into notmuch).
567
568 =item B<help> [subcommand]
569
570 print help [for subcommand]
571
572 =item B<log> [parameters]
573
574 A simple wrapper for git log. After running C<nmbug fetch>, you can
575 inspect the changes with C<nmbug log HEAD..FETCH_HEAD>
576
577 =item B<merge>
578
579 Merge changes from FETCH_HEAD into HEAD, and load the result into
580 notmuch.
581
582 =item  B<status>
583
584 Show pending updates in notmuch or git repo. See below for more
585 information about the output format.
586
587 =back
588
589 =head2 Less common commands
590
591 =over 8
592
593 =item B<archive>
594
595 Dump a tar archive (using git archive) of the current nmbug tag set.
596
597 =back
598
599 =head1 STATUS FORMAT
600
601 B<nmbug status> prints lines of the form
602
603    ng Message-Id tag
604
605 where n is a single character representing notmuch database status
606
607 =over 8
608
609 =item B<A>
610
611 Tag is present in notmuch database, but not committed to nmbug
612 (equivalently, tag has been deleted in nmbug repo, e.g. by a pull, but
613 not restored to notmuch database).
614
615 =item B<D>
616
617 Tag is present in nmbug repo, but not restored to notmuch database
618 (equivalently, tag has been deleted in notmuch)
619
620 =item B<U>
621
622 Message is unknown (missing from local notmuch database)
623
624 =back
625
626 The second character (if present) represents a difference between remote
627 git and local. Typically C<nmbug fetch> needs to be run to update this.
628
629 =over 8
630
631
632 =item B<a>
633
634 Tag is present in remote, but not in local git.
635
636
637 =item B<d>
638
639 Tag is present in local git, but not in remote git.
640
641
642 =back
643
644 =head1 DUMP FORMAT
645
646 Each tag $tag for message with Message-Id $id is written to
647 an empty file
648
649         tags/encode($id)/encode($tag)
650
651 The encoding preserves alphanumerics, and the characters "+-_@=.:,"
652 (not the quotes).  All other octets are replaced with '%' followed by
653 a two digit hex number.
654
655 =head1 ENVIRONMENT
656
657 B<NMBGIT> specifies the location of the git repository used by nmbug.
658 If not specified $HOME/.nmbug is used.
659
660 B<NMBPREFIX> specifies the prefix in the notmuch database for tags of
661 interest to nmbug. If not specified 'notmuch::' is used.