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