1#!/usr/bin/perl -w
2
3use strict;
4
5sub run_cmd_pipe {
6 if ($^O eq 'MSWin32') {
7 my @invalid = grep {m/[":*]/} @_;
8 die "$^O does not support: @invalid\n" if @invalid;
9 my @args = map { m/ /o ? "\"$_\"": $_ } @_;
10 return qx{@args};
11 } else {
12 my $fh = undef;
13 open($fh, '-|', @_) or die;
14 return <$fh>;
15 }
16}
17
18my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
19
20if (!defined $GIT_DIR) {
21 exit(1); # rev-parse would have already said "not a git repo"
22}
23chomp($GIT_DIR);
24
25sub refresh {
26 my $fh;
27 open $fh, 'git update-index --refresh |'
28 or die;
29 while (<$fh>) {
30 ;# ignore 'needs update'
31 }
32 close $fh;
33}
34
35sub list_untracked {
36 map {
37 chomp $_;
38 $_;
39 }
40 run_cmd_pipe(qw(git ls-files --others
41 --exclude-per-directory=.gitignore),
42 "--exclude-from=$GIT_DIR/info/exclude",
43 '--', @_);
44}
45
46my $status_fmt = '%12s %12s %s';
47my $status_head = sprintf($status_fmt, 'staged', 'unstaged', 'path');
48
49# Returns list of hashes, contents of each of which are:
50# PRINT: print message
51# VALUE: pathname
52# BINARY: is a binary path
53# INDEX: is index different from HEAD?
54# FILE: is file different from index?
55# INDEX_ADDDEL: is it add/delete between HEAD and index?
56# FILE_ADDDEL: is it add/delete between index and file?
57
58sub list_modified {
59 my ($only) = @_;
60 my (%data, @return);
61 my ($add, $del, $adddel, $file);
62
63 for (run_cmd_pipe(qw(git diff-index --cached
64 --numstat --summary HEAD))) {
65 if (($add, $del, $file) =
66 /^([-\d]+) ([-\d]+) (.*)/) {
67 my ($change, $bin);
68 if ($add eq '-' && $del eq '-') {
69 $change = 'binary';
70 $bin = 1;
71 }
72 else {
73 $change = "+$add/-$del";
74 }
75 $data{$file} = {
76 INDEX => $change,
77 BINARY => $bin,
78 FILE => 'nothing',
79 }
80 }
81 elsif (($adddel, $file) =
82 /^ (create|delete) mode [0-7]+ (.*)$/) {
83 $data{$file}{INDEX_ADDDEL} = $adddel;
84 }
85 }
86
87 for (run_cmd_pipe(qw(git diff-files --numstat --summary))) {
88 if (($add, $del, $file) =
89 /^([-\d]+) ([-\d]+) (.*)/) {
90 if (!exists $data{$file}) {
91 $data{$file} = +{
92 INDEX => 'unchanged',
93 BINARY => 0,
94 };
95 }
96 my ($change, $bin);
97 if ($add eq '-' && $del eq '-') {
98 $change = 'binary';
99 $bin = 1;
100 }
101 else {
102 $change = "+$add/-$del";
103 }
104 $data{$file}{FILE} = $change;
105 if ($bin) {
106 $data{$file}{BINARY} = 1;
107 }
108 }
109 elsif (($adddel, $file) =
110 /^ (create|delete) mode [0-7]+ (.*)$/) {
111 $data{$file}{FILE_ADDDEL} = $adddel;
112 }
113 }
114
115 for (sort keys %data) {
116 my $it = $data{$_};
117
118 if ($only) {
119 if ($only eq 'index-only') {
120 next if ($it->{INDEX} eq 'unchanged');
121 }
122 if ($only eq 'file-only') {
123 next if ($it->{FILE} eq 'nothing');
124 }
125 }
126 push @return, +{
127 VALUE => $_,
128 PRINT => (sprintf $status_fmt,
129 $it->{INDEX}, $it->{FILE}, $_),
130 %$it,
131 };
132 }
133 return @return;
134}
135
136sub find_unique {
137 my ($string, @stuff) = @_;
138 my $found = undef;
139 for (my $i = 0; $i < @stuff; $i++) {
140 my $it = $stuff[$i];
141 my $hit = undef;
142 if (ref $it) {
143 if ((ref $it) eq 'ARRAY') {
144 $it = $it->[0];
145 }
146 else {
147 $it = $it->{VALUE};
148 }
149 }
150 eval {
151 if ($it =~ /^$string/) {
152 $hit = 1;
153 };
154 };
155 if (defined $hit && defined $found) {
156 return undef;
157 }
158 if ($hit) {
159 $found = $i + 1;
160 }
161 }
162 return $found;
163}
164
165sub list_and_choose {
166 my ($opts, @stuff) = @_;
167 my (@chosen, @return);
168 my $i;
169
170 TOPLOOP:
171 while (1) {
172 my $last_lf = 0;
173
174 if ($opts->{HEADER}) {
175 if (!$opts->{LIST_FLAT}) {
176 print " ";
177 }
178 print "$opts->{HEADER}\n";
179 }
180 for ($i = 0; $i < @stuff; $i++) {
181 my $chosen = $chosen[$i] ? '*' : ' ';
182 my $print = $stuff[$i];
183 if (ref $print) {
184 if ((ref $print) eq 'ARRAY') {
185 $print = $print->[0];
186 }
187 else {
188 $print = $print->{PRINT};
189 }
190 }
191 printf("%s%2d: %s", $chosen, $i+1, $print);
192 if (($opts->{LIST_FLAT}) &&
193 (($i + 1) % ($opts->{LIST_FLAT}))) {
194 print "\t";
195 $last_lf = 0;
196 }
197 else {
198 print "\n";
199 $last_lf = 1;
200 }
201 }
202 if (!$last_lf) {
203 print "\n";
204 }
205
206 return if ($opts->{LIST_ONLY});
207
208 print $opts->{PROMPT};
209 if ($opts->{SINGLETON}) {
210 print "> ";
211 }
212 else {
213 print ">> ";
214 }
215 my $line = <STDIN>;
216 last if (!$line);
217 chomp $line;
218 my $donesomething = 0;
219 for my $choice (split(/[\s,]+/, $line)) {
220 my $choose = 1;
221 my ($bottom, $top);
222
223 # Input that begins with '-'; unchoose
224 if ($choice =~ s/^-//) {
225 $choose = 0;
226 }
227 # A range can be specified like 5-7
228 if ($choice =~ /^(\d+)-(\d+)$/) {
229 ($bottom, $top) = ($1, $2);
230 }
231 elsif ($choice =~ /^\d+$/) {
232 $bottom = $top = $choice;
233 }
234 elsif ($choice eq '*') {
235 $bottom = 1;
236 $top = 1 + @stuff;
237 }
238 else {
239 $bottom = $top = find_unique($choice, @stuff);
240 if (!defined $bottom) {
241 print "Huh ($choice)?\n";
242 next TOPLOOP;
243 }
244 }
245 if ($opts->{SINGLETON} && $bottom != $top) {
246 print "Huh ($choice)?\n";
247 next TOPLOOP;
248 }
249 for ($i = $bottom-1; $i <= $top-1; $i++) {
250 next if (@stuff <= $i);
251 $chosen[$i] = $choose;
252 $donesomething++;
253 }
254 }
255 last if (!$donesomething || $opts->{IMMEDIATE});
256 }
257 for ($i = 0; $i < @stuff; $i++) {
258 if ($chosen[$i]) {
259 push @return, $stuff[$i];
260 }
261 }
262 return @return;
263}
264
265sub status_cmd {
266 list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
267 list_modified());
268 print "\n";
269}
270
271sub say_n_paths {
272 my $did = shift @_;
273 my $cnt = scalar @_;
274 print "$did ";
275 if (1 < $cnt) {
276 print "$cnt paths\n";
277 }
278 else {
279 print "one path\n";
280 }
281}
282
283sub update_cmd {
284 my @mods = list_modified('file-only');
285 return if (!@mods);
286
287 my @update = list_and_choose({ PROMPT => 'Update',
288 HEADER => $status_head, },
289 @mods);
290 if (@update) {
291 system(qw(git update-index --add --remove --),
292 map { $_->{VALUE} } @update);
293 say_n_paths('updated', @update);
294 }
295 print "\n";
296}
297
298sub revert_cmd {
299 my @update = list_and_choose({ PROMPT => 'Revert',
300 HEADER => $status_head, },
301 list_modified());
302 if (@update) {
303 my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
304 map { $_->{VALUE} } @update);
305 my $fh;
306 open $fh, '| git update-index --index-info'
307 or die;
308 for (@lines) {
309 print $fh $_;
310 }
311 close($fh);
312 for (@update) {
313 if ($_->{INDEX_ADDDEL} &&
314 $_->{INDEX_ADDDEL} eq 'create') {
315 system(qw(git update-index --force-remove --),
316 $_->{VALUE});
317 print "note: $_->{VALUE} is untracked now.\n";
318 }
319 }
320 refresh();
321 say_n_paths('reverted', @update);
322 }
323 print "\n";
324}
325
326sub add_untracked_cmd {
327 my @add = list_and_choose({ PROMPT => 'Add untracked' },
328 list_untracked());
329 if (@add) {
330 system(qw(git update-index --add --), @add);
331 say_n_paths('added', @add);
332 }
333 print "\n";
334}
335
336sub parse_diff {
337 my ($path) = @_;
338 my @diff = run_cmd_pipe(qw(git diff-files -p --), $path);
339 my (@hunk) = { TEXT => [] };
340
341 for (@diff) {
342 if (/^@@ /) {
343 push @hunk, { TEXT => [] };
344 }
345 push @{$hunk[-1]{TEXT}}, $_;
346 }
347 return @hunk;
348}
349
350sub hunk_splittable {
351 my ($text) = @_;
352
353 my @s = split_hunk($text);
354 return (1 < @s);
355}
356
357sub parse_hunk_header {
358 my ($line) = @_;
359 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
360 $line =~ /^@@ -(\d+)(?:,(\d+)) \+(\d+)(?:,(\d+)) @@/;
361 return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
362}
363
364sub split_hunk {
365 my ($text) = @_;
366 my @split = ();
367
368 # If there are context lines in the middle of a hunk,
369 # it can be split, but we would need to take care of
370 # overlaps later.
371
372 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) = parse_hunk_header($text->[0]);
373 my $hunk_start = 1;
374 my $next_hunk_start;
375
376 OUTER:
377 while (1) {
378 my $next_hunk_start = undef;
379 my $i = $hunk_start - 1;
380 my $this = +{
381 TEXT => [],
382 OLD => $o_ofs,
383 NEW => $n_ofs,
384 OCNT => 0,
385 NCNT => 0,
386 ADDDEL => 0,
387 POSTCTX => 0,
388 };
389
390 while (++$i < @$text) {
391 my $line = $text->[$i];
392 if ($line =~ /^ /) {
393 if ($this->{ADDDEL} &&
394 !defined $next_hunk_start) {
395 # We have seen leading context and
396 # adds/dels and then here is another
397 # context, which is trailing for this
398 # split hunk and leading for the next
399 # one.
400 $next_hunk_start = $i;
401 }
402 push @{$this->{TEXT}}, $line;
403 $this->{OCNT}++;
404 $this->{NCNT}++;
405 if (defined $next_hunk_start) {
406 $this->{POSTCTX}++;
407 }
408 next;
409 }
410
411 # add/del
412 if (defined $next_hunk_start) {
413 # We are done with the current hunk and
414 # this is the first real change for the
415 # next split one.
416 $hunk_start = $next_hunk_start;
417 $o_ofs = $this->{OLD} + $this->{OCNT};
418 $n_ofs = $this->{NEW} + $this->{NCNT};
419 $o_ofs -= $this->{POSTCTX};
420 $n_ofs -= $this->{POSTCTX};
421 push @split, $this;
422 redo OUTER;
423 }
424 push @{$this->{TEXT}}, $line;
425 $this->{ADDDEL}++;
426 if ($line =~ /^-/) {
427 $this->{OCNT}++;
428 }
429 else {
430 $this->{NCNT}++;
431 }
432 }
433
434 push @split, $this;
435 last;
436 }
437
438 for my $hunk (@split) {
439 $o_ofs = $hunk->{OLD};
440 $n_ofs = $hunk->{NEW};
441 $o_cnt = $hunk->{OCNT};
442 $n_cnt = $hunk->{NCNT};
443
444 my $head = ("@@ -$o_ofs" .
445 (($o_cnt != 1) ? ",$o_cnt" : '') .
446 " +$n_ofs" .
447 (($n_cnt != 1) ? ",$n_cnt" : '') .
448 " @@\n");
449 unshift @{$hunk->{TEXT}}, $head;
450 }
451 return map { $_->{TEXT} } @split;
452}
453
454sub find_last_o_ctx {
455 my ($it) = @_;
456 my $text = $it->{TEXT};
457 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) = parse_hunk_header($text->[0]);
458 my $i = @{$text};
459 my $last_o_ctx = $o_ofs + $o_cnt;
460 while (0 < --$i) {
461 my $line = $text->[$i];
462 if ($line =~ /^ /) {
463 $last_o_ctx--;
464 next;
465 }
466 last;
467 }
468 return $last_o_ctx;
469}
470
471sub merge_hunk {
472 my ($prev, $this) = @_;
473 my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
474 parse_hunk_header($prev->{TEXT}[0]);
475 my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
476 parse_hunk_header($this->{TEXT}[0]);
477
478 my (@line, $i, $ofs, $o_cnt, $n_cnt);
479 $ofs = $o0_ofs;
480 $o_cnt = $n_cnt = 0;
481 for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
482 my $line = $prev->{TEXT}[$i];
483 if ($line =~ /^\+/) {
484 $n_cnt++;
485 push @line, $line;
486 next;
487 }
488
489 last if ($o1_ofs <= $ofs);
490
491 $o_cnt++;
492 $ofs++;
493 if ($line =~ /^ /) {
494 $n_cnt++;
495 }
496 push @line, $line;
497 }
498
499 for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
500 my $line = $this->{TEXT}[$i];
501 if ($line =~ /^\+/) {
502 $n_cnt++;
503 push @line, $line;
504 next;
505 }
506 $ofs++;
507 $o_cnt++;
508 if ($line =~ /^ /) {
509 $n_cnt++;
510 }
511 push @line, $line;
512 }
513 my $head = ("@@ -$o0_ofs" .
514 (($o_cnt != 1) ? ",$o_cnt" : '') .
515 " +$n0_ofs" .
516 (($n_cnt != 1) ? ",$n_cnt" : '') .
517 " @@\n");
518 @{$prev->{TEXT}} = ($head, @line);
519}
520
521sub coalesce_overlapping_hunks {
522 my (@in) = @_;
523 my @out = ();
524
525 my ($last_o_ctx);
526
527 for (grep { $_->{USE} } @in) {
528 my $text = $_->{TEXT};
529 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
530 parse_hunk_header($text->[0]);
531 if (defined $last_o_ctx &&
532 $o_ofs <= $last_o_ctx) {
533 merge_hunk($out[-1], $_);
534 }
535 else {
536 push @out, $_;
537 }
538 $last_o_ctx = find_last_o_ctx($out[-1]);
539 }
540 return @out;
541}
542
543sub help_patch_cmd {
544 print <<\EOF ;
545y - stage this hunk
546n - do not stage this hunk
547a - stage this and all the remaining hunks
548d - do not stage this hunk nor any of the remaining hunks
549j - leave this hunk undecided, see next undecided hunk
550J - leave this hunk undecided, see next hunk
551k - leave this hunk undecided, see previous undecided hunk
552K - leave this hunk undecided, see previous hunk
553s - split the current hunk into smaller hunks
554EOF
555}
556
557sub patch_update_cmd {
558 my @mods = list_modified('file-only');
559 @mods = grep { !($_->{BINARY}) } @mods;
560 return if (!@mods);
561
562 my ($it) = list_and_choose({ PROMPT => 'Patch update',
563 SINGLETON => 1,
564 IMMEDIATE => 1,
565 HEADER => $status_head, },
566 @mods);
567 return if (!$it);
568
569 my ($ix, $num);
570 my $path = $it->{VALUE};
571 my ($head, @hunk) = parse_diff($path);
572 for (@{$head->{TEXT}}) {
573 print;
574 }
575 $num = scalar @hunk;
576 $ix = 0;
577
578 while (1) {
579 my ($prev, $next, $other, $undecided, $i);
580 $other = '';
581
582 if ($num <= $ix) {
583 $ix = 0;
584 }
585 for ($i = 0; $i < $ix; $i++) {
586 if (!defined $hunk[$i]{USE}) {
587 $prev = 1;
588 $other .= '/k';
589 last;
590 }
591 }
592 if ($ix) {
593 $other .= '/K';
594 }
595 for ($i = $ix + 1; $i < $num; $i++) {
596 if (!defined $hunk[$i]{USE}) {
597 $next = 1;
598 $other .= '/j';
599 last;
600 }
601 }
602 if ($ix < $num - 1) {
603 $other .= '/J';
604 }
605 for ($i = 0; $i < $num; $i++) {
606 if (!defined $hunk[$i]{USE}) {
607 $undecided = 1;
608 last;
609 }
610 }
611 last if (!$undecided);
612
613 if (hunk_splittable($hunk[$ix]{TEXT})) {
614 $other .= '/s';
615 }
616 for (@{$hunk[$ix]{TEXT}}) {
617 print;
618 }
619 print "Stage this hunk [y/n/a/d$other/?]? ";
620 my $line = <STDIN>;
621 if ($line) {
622 if ($line =~ /^y/i) {
623 $hunk[$ix]{USE} = 1;
624 }
625 elsif ($line =~ /^n/i) {
626 $hunk[$ix]{USE} = 0;
627 }
628 elsif ($line =~ /^a/i) {
629 while ($ix < $num) {
630 if (!defined $hunk[$ix]{USE}) {
631 $hunk[$ix]{USE} = 1;
632 }
633 $ix++;
634 }
635 next;
636 }
637 elsif ($line =~ /^d/i) {
638 while ($ix < $num) {
639 if (!defined $hunk[$ix]{USE}) {
640 $hunk[$ix]{USE} = 0;
641 }
642 $ix++;
643 }
644 next;
645 }
646 elsif ($other =~ /K/ && $line =~ /^K/) {
647 $ix--;
648 next;
649 }
650 elsif ($other =~ /J/ && $line =~ /^J/) {
651 $ix++;
652 next;
653 }
654 elsif ($other =~ /k/ && $line =~ /^k/) {
655 while (1) {
656 $ix--;
657 last if (!$ix ||
658 !defined $hunk[$ix]{USE});
659 }
660 next;
661 }
662 elsif ($other =~ /j/ && $line =~ /^j/) {
663 while (1) {
664 $ix++;
665 last if ($ix >= $num ||
666 !defined $hunk[$ix]{USE});
667 }
668 next;
669 }
670 elsif ($other =~ /s/ && $line =~ /^s/) {
671 my @split = split_hunk($hunk[$ix]{TEXT});
672 if (1 < @split) {
673 print "Split into ",
674 scalar(@split), " hunks.\n";
675 }
676 splice(@hunk, $ix, 1,
677 map { +{ TEXT => $_, USE => undef } }
678 @split);
679 $num = scalar @hunk;
680 next;
681 }
682 else {
683 help_patch_cmd($other);
684 next;
685 }
686 # soft increment
687 while (1) {
688 $ix++;
689 last if ($ix >= $num ||
690 !defined $hunk[$ix]{USE});
691 }
692 }
693 }
694
695 @hunk = coalesce_overlapping_hunks(@hunk);
696
697 my ($o_lofs, $n_lofs) = (0, 0);
698 my @result = ();
699 for (@hunk) {
700 my $text = $_->{TEXT};
701 my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
702 parse_hunk_header($text->[0]);
703
704 if (!$_->{USE}) {
705 if (!defined $o_cnt) { $o_cnt = 1; }
706 if (!defined $n_cnt) { $n_cnt = 1; }
707
708 # We would have added ($n_cnt - $o_cnt) lines
709 # to the postimage if we were to use this hunk,
710 # but we didn't. So the line number that the next
711 # hunk starts at would be shifted by that much.
712 $n_lofs -= ($n_cnt - $o_cnt);
713 next;
714 }
715 else {
716 if ($n_lofs) {
717 $n_ofs += $n_lofs;
718 $text->[0] = ("@@ -$o_ofs" .
719 ((defined $o_cnt)
720 ? ",$o_cnt" : '') .
721 " +$n_ofs" .
722 ((defined $n_cnt)
723 ? ",$n_cnt" : '') .
724 " @@\n");
725 }
726 for (@$text) {
727 push @result, $_;
728 }
729 }
730 }
731
732 if (@result) {
733 my $fh;
734
735 open $fh, '| git apply --cached';
736 for (@{$head->{TEXT}}, @result) {
737 print $fh $_;
738 }
739 if (!close $fh) {
740 for (@{$head->{TEXT}}, @result) {
741 print STDERR $_;
742 }
743 }
744 refresh();
745 }
746
747 print "\n";
748}
749
750sub diff_cmd {
751 my @mods = list_modified('index-only');
752 @mods = grep { !($_->{BINARY}) } @mods;
753 return if (!@mods);
754 my (@them) = list_and_choose({ PROMPT => 'Review diff',
755 IMMEDIATE => 1,
756 HEADER => $status_head, },
757 @mods);
758 return if (!@them);
759 system(qw(git diff-index -p --cached HEAD --),
760 map { $_->{VALUE} } @them);
761}
762
763sub quit_cmd {
764 print "Bye.\n";
765 exit(0);
766}
767
768sub help_cmd {
769 print <<\EOF ;
770status - show paths with changes
771update - add working tree state to the staged set of changes
772revert - revert staged set of changes back to the HEAD version
773patch - pick hunks and update selectively
774diff - view diff between HEAD and index
775add untracked - add contents of untracked files to the staged set of changes
776EOF
777}
778
779sub main_loop {
780 my @cmd = ([ 'status', \&status_cmd, ],
781 [ 'update', \&update_cmd, ],
782 [ 'revert', \&revert_cmd, ],
783 [ 'add untracked', \&add_untracked_cmd, ],
784 [ 'patch', \&patch_update_cmd, ],
785 [ 'diff', \&diff_cmd, ],
786 [ 'quit', \&quit_cmd, ],
787 [ 'help', \&help_cmd, ],
788 );
789 while (1) {
790 my ($it) = list_and_choose({ PROMPT => 'What now',
791 SINGLETON => 1,
792 LIST_FLAT => 4,
793 HEADER => '*** Commands ***',
794 IMMEDIATE => 1 }, @cmd);
795 if ($it) {
796 eval {
797 $it->[1]->();
798 };
799 if ($@) {
800 print "$@";
801 }
802 }
803 }
804}
805
806my @z;
807
808refresh();
809status_cmd();
810main_loop();