THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1872 lines
45KB

  1. #!/usr/bin/perl
  2. use 5.008;
  3. use strict;
  4. use warnings;
  5. use Git qw(unquote_path);
  6. use Git::I18N;
  7. binmode(STDOUT, ":raw");
  8. my $repo = Git->repository();
  9. my $menu_use_color = $repo->get_colorbool('color.interactive');
  10. my ($prompt_color, $header_color, $help_color) =
  11. $menu_use_color ? (
  12. $repo->get_color('color.interactive.prompt', 'bold blue'),
  13. $repo->get_color('color.interactive.header', 'bold'),
  14. $repo->get_color('color.interactive.help', 'red bold'),
  15. ) : ();
  16. my $error_color = ();
  17. if ($menu_use_color) {
  18. my $help_color_spec = ($repo->config('color.interactive.help') or
  19. 'red bold');
  20. $error_color = $repo->get_color('color.interactive.error',
  21. $help_color_spec);
  22. }
  23. my $diff_use_color = $repo->get_colorbool('color.diff');
  24. my ($fraginfo_color) =
  25. $diff_use_color ? (
  26. $repo->get_color('color.diff.frag', 'cyan'),
  27. ) : ();
  28. my ($diff_plain_color) =
  29. $diff_use_color ? (
  30. $repo->get_color('color.diff.plain', ''),
  31. ) : ();
  32. my ($diff_old_color) =
  33. $diff_use_color ? (
  34. $repo->get_color('color.diff.old', 'red'),
  35. ) : ();
  36. my ($diff_new_color) =
  37. $diff_use_color ? (
  38. $repo->get_color('color.diff.new', 'green'),
  39. ) : ();
  40. my $normal_color = $repo->get_color("", "reset");
  41. my $diff_algorithm = $repo->config('diff.algorithm');
  42. my $diff_filter = $repo->config('interactive.difffilter');
  43. my $use_readkey = 0;
  44. my $use_termcap = 0;
  45. my %term_escapes;
  46. sub ReadMode;
  47. sub ReadKey;
  48. if ($repo->config_bool("interactive.singlekey")) {
  49. eval {
  50. require Term::ReadKey;
  51. Term::ReadKey->import;
  52. $use_readkey = 1;
  53. };
  54. if (!$use_readkey) {
  55. print STDERR "missing Term::ReadKey, disabling interactive.singlekey\n";
  56. }
  57. eval {
  58. require Term::Cap;
  59. my $termcap = Term::Cap->Tgetent;
  60. foreach (values %$termcap) {
  61. $term_escapes{$_} = 1 if /^\e/;
  62. }
  63. $use_termcap = 1;
  64. };
  65. }
  66. sub colored {
  67. my $color = shift;
  68. my $string = join("", @_);
  69. if (defined $color) {
  70. # Put a color code at the beginning of each line, a reset at the end
  71. # color after newlines that are not at the end of the string
  72. $string =~ s/(\n+)(.)/$1$color$2/g;
  73. # reset before newlines
  74. $string =~ s/(\n+)/$normal_color$1/g;
  75. # codes at beginning and end (if necessary):
  76. $string =~ s/^/$color/;
  77. $string =~ s/$/$normal_color/ unless $string =~ /\n$/;
  78. }
  79. return $string;
  80. }
  81. # command line options
  82. my $patch_mode_only;
  83. my $patch_mode;
  84. my $patch_mode_revision;
  85. sub apply_patch;
  86. sub apply_patch_for_checkout_commit;
  87. sub apply_patch_for_stash;
  88. my %patch_modes = (
  89. 'stage' => {
  90. DIFF => 'diff-files -p',
  91. APPLY => sub { apply_patch 'apply --cached', @_; },
  92. APPLY_CHECK => 'apply --cached',
  93. FILTER => 'file-only',
  94. IS_REVERSE => 0,
  95. },
  96. 'stash' => {
  97. DIFF => 'diff-index -p HEAD',
  98. APPLY => sub { apply_patch 'apply --cached', @_; },
  99. APPLY_CHECK => 'apply --cached',
  100. FILTER => undef,
  101. IS_REVERSE => 0,
  102. },
  103. 'reset_head' => {
  104. DIFF => 'diff-index -p --cached',
  105. APPLY => sub { apply_patch 'apply -R --cached', @_; },
  106. APPLY_CHECK => 'apply -R --cached',
  107. FILTER => 'index-only',
  108. IS_REVERSE => 1,
  109. },
  110. 'reset_nothead' => {
  111. DIFF => 'diff-index -R -p --cached',
  112. APPLY => sub { apply_patch 'apply --cached', @_; },
  113. APPLY_CHECK => 'apply --cached',
  114. FILTER => 'index-only',
  115. IS_REVERSE => 0,
  116. },
  117. 'checkout_index' => {
  118. DIFF => 'diff-files -p',
  119. APPLY => sub { apply_patch 'apply -R', @_; },
  120. APPLY_CHECK => 'apply -R',
  121. FILTER => 'file-only',
  122. IS_REVERSE => 1,
  123. },
  124. 'checkout_head' => {
  125. DIFF => 'diff-index -p',
  126. APPLY => sub { apply_patch_for_checkout_commit '-R', @_ },
  127. APPLY_CHECK => 'apply -R',
  128. FILTER => undef,
  129. IS_REVERSE => 1,
  130. },
  131. 'checkout_nothead' => {
  132. DIFF => 'diff-index -R -p',
  133. APPLY => sub { apply_patch_for_checkout_commit '', @_ },
  134. APPLY_CHECK => 'apply',
  135. FILTER => undef,
  136. IS_REVERSE => 0,
  137. },
  138. 'worktree_head' => {
  139. DIFF => 'diff-index -p',
  140. APPLY => sub { apply_patch 'apply -R', @_ },
  141. APPLY_CHECK => 'apply -R',
  142. FILTER => undef,
  143. IS_REVERSE => 1,
  144. },
  145. 'worktree_nothead' => {
  146. DIFF => 'diff-index -R -p',
  147. APPLY => sub { apply_patch 'apply', @_ },
  148. APPLY_CHECK => 'apply',
  149. FILTER => undef,
  150. IS_REVERSE => 0,
  151. },
  152. );
  153. $patch_mode = 'stage';
  154. my %patch_mode_flavour = %{$patch_modes{$patch_mode}};
  155. sub run_cmd_pipe {
  156. if ($^O eq 'MSWin32') {
  157. my @invalid = grep {m/[":*]/} @_;
  158. die "$^O does not support: @invalid\n" if @invalid;
  159. my @args = map { m/ /o ? "\"$_\"": $_ } @_;
  160. return qx{@args};
  161. } else {
  162. my $fh = undef;
  163. open($fh, '-|', @_) or die;
  164. return <$fh>;
  165. }
  166. }
  167. my ($GIT_DIR) = run_cmd_pipe(qw(git rev-parse --git-dir));
  168. if (!defined $GIT_DIR) {
  169. exit(1); # rev-parse would have already said "not a git repo"
  170. }
  171. chomp($GIT_DIR);
  172. sub refresh {
  173. my $fh;
  174. open $fh, 'git update-index --refresh |'
  175. or die;
  176. while (<$fh>) {
  177. ;# ignore 'needs update'
  178. }
  179. close $fh;
  180. }
  181. sub list_untracked {
  182. map {
  183. chomp $_;
  184. unquote_path($_);
  185. }
  186. run_cmd_pipe(qw(git ls-files --others --exclude-standard --), @ARGV);
  187. }
  188. # TRANSLATORS: you can adjust this to align "git add -i" status menu
  189. my $status_fmt = __('%12s %12s %s');
  190. my $status_head = sprintf($status_fmt, __('staged'), __('unstaged'), __('path'));
  191. {
  192. my $initial;
  193. sub is_initial_commit {
  194. $initial = system('git rev-parse HEAD -- >/dev/null 2>&1') != 0
  195. unless defined $initial;
  196. return $initial;
  197. }
  198. }
  199. {
  200. my $empty_tree;
  201. sub get_empty_tree {
  202. return $empty_tree if defined $empty_tree;
  203. $empty_tree = run_cmd_pipe(qw(git hash-object -t tree /dev/null));
  204. chomp $empty_tree;
  205. return $empty_tree;
  206. }
  207. }
  208. sub get_diff_reference {
  209. my $ref = shift;
  210. if (defined $ref and $ref ne 'HEAD') {
  211. return $ref;
  212. } elsif (is_initial_commit()) {
  213. return get_empty_tree();
  214. } else {
  215. return 'HEAD';
  216. }
  217. }
  218. # Returns list of hashes, contents of each of which are:
  219. # VALUE: pathname
  220. # BINARY: is a binary path
  221. # INDEX: is index different from HEAD?
  222. # FILE: is file different from index?
  223. # INDEX_ADDDEL: is it add/delete between HEAD and index?
  224. # FILE_ADDDEL: is it add/delete between index and file?
  225. # UNMERGED: is the path unmerged
  226. sub list_modified {
  227. my ($only) = @_;
  228. my (%data, @return);
  229. my ($add, $del, $adddel, $file);
  230. my $reference = get_diff_reference($patch_mode_revision);
  231. for (run_cmd_pipe(qw(git diff-index --cached
  232. --numstat --summary), $reference,
  233. '--', @ARGV)) {
  234. if (($add, $del, $file) =
  235. /^([-\d]+) ([-\d]+) (.*)/) {
  236. my ($change, $bin);
  237. $file = unquote_path($file);
  238. if ($add eq '-' && $del eq '-') {
  239. $change = __('binary');
  240. $bin = 1;
  241. }
  242. else {
  243. $change = "+$add/-$del";
  244. }
  245. $data{$file} = {
  246. INDEX => $change,
  247. BINARY => $bin,
  248. FILE => __('nothing'),
  249. }
  250. }
  251. elsif (($adddel, $file) =
  252. /^ (create|delete) mode [0-7]+ (.*)$/) {
  253. $file = unquote_path($file);
  254. $data{$file}{INDEX_ADDDEL} = $adddel;
  255. }
  256. }
  257. for (run_cmd_pipe(qw(git diff-files --ignore-submodules=dirty --numstat --summary --raw --), @ARGV)) {
  258. if (($add, $del, $file) =
  259. /^([-\d]+) ([-\d]+) (.*)/) {
  260. $file = unquote_path($file);
  261. my ($change, $bin);
  262. if ($add eq '-' && $del eq '-') {
  263. $change = __('binary');
  264. $bin = 1;
  265. }
  266. else {
  267. $change = "+$add/-$del";
  268. }
  269. $data{$file}{FILE} = $change;
  270. if ($bin) {
  271. $data{$file}{BINARY} = 1;
  272. }
  273. }
  274. elsif (($adddel, $file) =
  275. /^ (create|delete) mode [0-7]+ (.*)$/) {
  276. $file = unquote_path($file);
  277. $data{$file}{FILE_ADDDEL} = $adddel;
  278. }
  279. elsif (/^:[0-7]+ [0-7]+ [0-9a-f]+ [0-9a-f]+ (.) (.*)$/) {
  280. $file = unquote_path($2);
  281. if (!exists $data{$file}) {
  282. $data{$file} = +{
  283. INDEX => __('unchanged'),
  284. BINARY => 0,
  285. };
  286. }
  287. if ($1 eq 'U') {
  288. $data{$file}{UNMERGED} = 1;
  289. }
  290. }
  291. }
  292. for (sort keys %data) {
  293. my $it = $data{$_};
  294. if ($only) {
  295. if ($only eq 'index-only') {
  296. next if ($it->{INDEX} eq __('unchanged'));
  297. }
  298. if ($only eq 'file-only') {
  299. next if ($it->{FILE} eq __('nothing'));
  300. }
  301. }
  302. push @return, +{
  303. VALUE => $_,
  304. %$it,
  305. };
  306. }
  307. return @return;
  308. }
  309. sub find_unique {
  310. my ($string, @stuff) = @_;
  311. my $found = undef;
  312. for (my $i = 0; $i < @stuff; $i++) {
  313. my $it = $stuff[$i];
  314. my $hit = undef;
  315. if (ref $it) {
  316. if ((ref $it) eq 'ARRAY') {
  317. $it = $it->[0];
  318. }
  319. else {
  320. $it = $it->{VALUE};
  321. }
  322. }
  323. eval {
  324. if ($it =~ /^$string/) {
  325. $hit = 1;
  326. };
  327. };
  328. if (defined $hit && defined $found) {
  329. return undef;
  330. }
  331. if ($hit) {
  332. $found = $i + 1;
  333. }
  334. }
  335. return $found;
  336. }
  337. # inserts string into trie and updates count for each character
  338. sub update_trie {
  339. my ($trie, $string) = @_;
  340. foreach (split //, $string) {
  341. $trie = $trie->{$_} ||= {COUNT => 0};
  342. $trie->{COUNT}++;
  343. }
  344. }
  345. # returns an array of tuples (prefix, remainder)
  346. sub find_unique_prefixes {
  347. my @stuff = @_;
  348. my @return = ();
  349. # any single prefix exceeding the soft limit is omitted
  350. # if any prefix exceeds the hard limit all are omitted
  351. # 0 indicates no limit
  352. my $soft_limit = 0;
  353. my $hard_limit = 3;
  354. # build a trie modelling all possible options
  355. my %trie;
  356. foreach my $print (@stuff) {
  357. if ((ref $print) eq 'ARRAY') {
  358. $print = $print->[0];
  359. }
  360. elsif ((ref $print) eq 'HASH') {
  361. $print = $print->{VALUE};
  362. }
  363. update_trie(\%trie, $print);
  364. push @return, $print;
  365. }
  366. # use the trie to find the unique prefixes
  367. for (my $i = 0; $i < @return; $i++) {
  368. my $ret = $return[$i];
  369. my @letters = split //, $ret;
  370. my %search = %trie;
  371. my ($prefix, $remainder);
  372. my $j;
  373. for ($j = 0; $j < @letters; $j++) {
  374. my $letter = $letters[$j];
  375. if ($search{$letter}{COUNT} == 1) {
  376. $prefix = substr $ret, 0, $j + 1;
  377. $remainder = substr $ret, $j + 1;
  378. last;
  379. }
  380. else {
  381. my $prefix = substr $ret, 0, $j;
  382. return ()
  383. if ($hard_limit && $j + 1 > $hard_limit);
  384. }
  385. %search = %{$search{$letter}};
  386. }
  387. if (ord($letters[0]) > 127 ||
  388. ($soft_limit && $j + 1 > $soft_limit)) {
  389. $prefix = undef;
  390. $remainder = $ret;
  391. }
  392. $return[$i] = [$prefix, $remainder];
  393. }
  394. return @return;
  395. }
  396. # filters out prefixes which have special meaning to list_and_choose()
  397. sub is_valid_prefix {
  398. my $prefix = shift;
  399. return (defined $prefix) &&
  400. !($prefix =~ /[\s,]/) && # separators
  401. !($prefix =~ /^-/) && # deselection
  402. !($prefix =~ /^\d+/) && # selection
  403. ($prefix ne '*') && # "all" wildcard
  404. ($prefix ne '?'); # prompt help
  405. }
  406. # given a prefix/remainder tuple return a string with the prefix highlighted
  407. # for now use square brackets; later might use ANSI colors (underline, bold)
  408. sub highlight_prefix {
  409. my $prefix = shift;
  410. my $remainder = shift;
  411. if (!defined $prefix) {
  412. return $remainder;
  413. }
  414. if (!is_valid_prefix($prefix)) {
  415. return "$prefix$remainder";
  416. }
  417. if (!$menu_use_color) {
  418. return "[$prefix]$remainder";
  419. }
  420. return "$prompt_color$prefix$normal_color$remainder";
  421. }
  422. sub error_msg {
  423. print STDERR colored $error_color, @_;
  424. }
  425. sub list_and_choose {
  426. my ($opts, @stuff) = @_;
  427. my (@chosen, @return);
  428. if (!@stuff) {
  429. return @return;
  430. }
  431. my $i;
  432. my @prefixes = find_unique_prefixes(@stuff) unless $opts->{LIST_ONLY};
  433. TOPLOOP:
  434. while (1) {
  435. my $last_lf = 0;
  436. if ($opts->{HEADER}) {
  437. if (!$opts->{LIST_FLAT}) {
  438. print " ";
  439. }
  440. print colored $header_color, "$opts->{HEADER}\n";
  441. }
  442. for ($i = 0; $i < @stuff; $i++) {
  443. my $chosen = $chosen[$i] ? '*' : ' ';
  444. my $print = $stuff[$i];
  445. my $ref = ref $print;
  446. my $highlighted = highlight_prefix(@{$prefixes[$i]})
  447. if @prefixes;
  448. if ($ref eq 'ARRAY') {
  449. $print = $highlighted || $print->[0];
  450. }
  451. elsif ($ref eq 'HASH') {
  452. my $value = $highlighted || $print->{VALUE};
  453. $print = sprintf($status_fmt,
  454. $print->{INDEX},
  455. $print->{FILE},
  456. $value);
  457. }
  458. else {
  459. $print = $highlighted || $print;
  460. }
  461. printf("%s%2d: %s", $chosen, $i+1, $print);
  462. if (($opts->{LIST_FLAT}) &&
  463. (($i + 1) % ($opts->{LIST_FLAT}))) {
  464. print "\t";
  465. $last_lf = 0;
  466. }
  467. else {
  468. print "\n";
  469. $last_lf = 1;
  470. }
  471. }
  472. if (!$last_lf) {
  473. print "\n";
  474. }
  475. return if ($opts->{LIST_ONLY});
  476. print colored $prompt_color, $opts->{PROMPT};
  477. if ($opts->{SINGLETON}) {
  478. print "> ";
  479. }
  480. else {
  481. print ">> ";
  482. }
  483. my $line = <STDIN>;
  484. if (!$line) {
  485. print "\n";
  486. $opts->{ON_EOF}->() if $opts->{ON_EOF};
  487. last;
  488. }
  489. chomp $line;
  490. last if $line eq '';
  491. if ($line eq '?') {
  492. $opts->{SINGLETON} ?
  493. singleton_prompt_help_cmd() :
  494. prompt_help_cmd();
  495. next TOPLOOP;
  496. }
  497. for my $choice (split(/[\s,]+/, $line)) {
  498. my $choose = 1;
  499. my ($bottom, $top);
  500. # Input that begins with '-'; unchoose
  501. if ($choice =~ s/^-//) {
  502. $choose = 0;
  503. }
  504. # A range can be specified like 5-7 or 5-.
  505. if ($choice =~ /^(\d+)-(\d*)$/) {
  506. ($bottom, $top) = ($1, length($2) ? $2 : 1 + @stuff);
  507. }
  508. elsif ($choice =~ /^\d+$/) {
  509. $bottom = $top = $choice;
  510. }
  511. elsif ($choice eq '*') {
  512. $bottom = 1;
  513. $top = 1 + @stuff;
  514. }
  515. else {
  516. $bottom = $top = find_unique($choice, @stuff);
  517. if (!defined $bottom) {
  518. error_msg sprintf(__("Huh (%s)?\n"), $choice);
  519. next TOPLOOP;
  520. }
  521. }
  522. if ($opts->{SINGLETON} && $bottom != $top) {
  523. error_msg sprintf(__("Huh (%s)?\n"), $choice);
  524. next TOPLOOP;
  525. }
  526. for ($i = $bottom-1; $i <= $top-1; $i++) {
  527. next if (@stuff <= $i || $i < 0);
  528. $chosen[$i] = $choose;
  529. }
  530. }
  531. last if ($opts->{IMMEDIATE} || $line eq '*');
  532. }
  533. for ($i = 0; $i < @stuff; $i++) {
  534. if ($chosen[$i]) {
  535. push @return, $stuff[$i];
  536. }
  537. }
  538. return @return;
  539. }
  540. sub singleton_prompt_help_cmd {
  541. print colored $help_color, __ <<'EOF' ;
  542. Prompt help:
  543. 1 - select a numbered item
  544. foo - select item based on unique prefix
  545. - (empty) select nothing
  546. EOF
  547. }
  548. sub prompt_help_cmd {
  549. print colored $help_color, __ <<'EOF' ;
  550. Prompt help:
  551. 1 - select a single item
  552. 3-5 - select a range of items
  553. 2-3,6-9 - select multiple ranges
  554. foo - select item based on unique prefix
  555. -... - unselect specified items
  556. * - choose all items
  557. - (empty) finish selecting
  558. EOF
  559. }
  560. sub status_cmd {
  561. list_and_choose({ LIST_ONLY => 1, HEADER => $status_head },
  562. list_modified());
  563. print "\n";
  564. }
  565. sub say_n_paths {
  566. my $did = shift @_;
  567. my $cnt = scalar @_;
  568. if ($did eq 'added') {
  569. printf(__n("added %d path\n", "added %d paths\n",
  570. $cnt), $cnt);
  571. } elsif ($did eq 'updated') {
  572. printf(__n("updated %d path\n", "updated %d paths\n",
  573. $cnt), $cnt);
  574. } elsif ($did eq 'reverted') {
  575. printf(__n("reverted %d path\n", "reverted %d paths\n",
  576. $cnt), $cnt);
  577. } else {
  578. printf(__n("touched %d path\n", "touched %d paths\n",
  579. $cnt), $cnt);
  580. }
  581. }
  582. sub update_cmd {
  583. my @mods = list_modified('file-only');
  584. return if (!@mods);
  585. my @update = list_and_choose({ PROMPT => __('Update'),
  586. HEADER => $status_head, },
  587. @mods);
  588. if (@update) {
  589. system(qw(git update-index --add --remove --),
  590. map { $_->{VALUE} } @update);
  591. say_n_paths('updated', @update);
  592. }
  593. print "\n";
  594. }
  595. sub revert_cmd {
  596. my @update = list_and_choose({ PROMPT => __('Revert'),
  597. HEADER => $status_head, },
  598. list_modified());
  599. if (@update) {
  600. if (is_initial_commit()) {
  601. system(qw(git rm --cached),
  602. map { $_->{VALUE} } @update);
  603. }
  604. else {
  605. my @lines = run_cmd_pipe(qw(git ls-tree HEAD --),
  606. map { $_->{VALUE} } @update);
  607. my $fh;
  608. open $fh, '| git update-index --index-info'
  609. or die;
  610. for (@lines) {
  611. print $fh $_;
  612. }
  613. close($fh);
  614. for (@update) {
  615. if ($_->{INDEX_ADDDEL} &&
  616. $_->{INDEX_ADDDEL} eq 'create') {
  617. system(qw(git update-index --force-remove --),
  618. $_->{VALUE});
  619. printf(__("note: %s is untracked now.\n"), $_->{VALUE});
  620. }
  621. }
  622. }
  623. refresh();
  624. say_n_paths('reverted', @update);
  625. }
  626. print "\n";
  627. }
  628. sub add_untracked_cmd {
  629. my @add = list_and_choose({ PROMPT => __('Add untracked') },
  630. list_untracked());
  631. if (@add) {
  632. system(qw(git update-index --add --), @add);
  633. say_n_paths('added', @add);
  634. } else {
  635. print __("No untracked files.\n");
  636. }
  637. print "\n";
  638. }
  639. sub run_git_apply {
  640. my $cmd = shift;
  641. my $fh;
  642. open $fh, '| git ' . $cmd . " --allow-overlap";
  643. print $fh @_;
  644. return close $fh;
  645. }
  646. sub parse_diff {
  647. my ($path) = @_;
  648. my @diff_cmd = split(" ", $patch_mode_flavour{DIFF});
  649. if (defined $diff_algorithm) {
  650. splice @diff_cmd, 1, 0, "--diff-algorithm=${diff_algorithm}";
  651. }
  652. if (defined $patch_mode_revision) {
  653. push @diff_cmd, get_diff_reference($patch_mode_revision);
  654. }
  655. my @diff = run_cmd_pipe("git", @diff_cmd, "--", $path);
  656. my @colored = ();
  657. if ($diff_use_color) {
  658. my @display_cmd = ("git", @diff_cmd, qw(--color --), $path);
  659. if (defined $diff_filter) {
  660. # quotemeta is overkill, but sufficient for shell-quoting
  661. my $diff = join(' ', map { quotemeta } @display_cmd);
  662. @display_cmd = ("$diff | $diff_filter");
  663. }
  664. @colored = run_cmd_pipe(@display_cmd);
  665. }
  666. my (@hunk) = { TEXT => [], DISPLAY => [], TYPE => 'header' };
  667. if (@colored && @colored != @diff) {
  668. print STDERR
  669. "fatal: mismatched output from interactive.diffFilter\n",
  670. "hint: Your filter must maintain a one-to-one correspondence\n",
  671. "hint: between its input and output lines.\n";
  672. exit 1;
  673. }
  674. for (my $i = 0; $i < @diff; $i++) {
  675. if ($diff[$i] =~ /^@@ /) {
  676. push @hunk, { TEXT => [], DISPLAY => [],
  677. TYPE => 'hunk' };
  678. }
  679. push @{$hunk[-1]{TEXT}}, $diff[$i];
  680. push @{$hunk[-1]{DISPLAY}},
  681. (@colored ? $colored[$i] : $diff[$i]);
  682. }
  683. return @hunk;
  684. }
  685. sub parse_diff_header {
  686. my $src = shift;
  687. my $head = { TEXT => [], DISPLAY => [], TYPE => 'header' };
  688. my $mode = { TEXT => [], DISPLAY => [], TYPE => 'mode' };
  689. my $deletion = { TEXT => [], DISPLAY => [], TYPE => 'deletion' };
  690. for (my $i = 0; $i < @{$src->{TEXT}}; $i++) {
  691. my $dest =
  692. $src->{TEXT}->[$i] =~ /^(old|new) mode (\d+)$/ ? $mode :
  693. $src->{TEXT}->[$i] =~ /^deleted file/ ? $deletion :
  694. $head;
  695. push @{$dest->{TEXT}}, $src->{TEXT}->[$i];
  696. push @{$dest->{DISPLAY}}, $src->{DISPLAY}->[$i];
  697. }
  698. return ($head, $mode, $deletion);
  699. }
  700. sub hunk_splittable {
  701. my ($text) = @_;
  702. my @s = split_hunk($text);
  703. return (1 < @s);
  704. }
  705. sub parse_hunk_header {
  706. my ($line) = @_;
  707. my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
  708. $line =~ /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
  709. $o_cnt = 1 unless defined $o_cnt;
  710. $n_cnt = 1 unless defined $n_cnt;
  711. return ($o_ofs, $o_cnt, $n_ofs, $n_cnt);
  712. }
  713. sub format_hunk_header {
  714. my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) = @_;
  715. return ("@@ -$o_ofs" .
  716. (($o_cnt != 1) ? ",$o_cnt" : '') .
  717. " +$n_ofs" .
  718. (($n_cnt != 1) ? ",$n_cnt" : '') .
  719. " @@\n");
  720. }
  721. sub split_hunk {
  722. my ($text, $display) = @_;
  723. my @split = ();
  724. if (!defined $display) {
  725. $display = $text;
  726. }
  727. # If there are context lines in the middle of a hunk,
  728. # it can be split, but we would need to take care of
  729. # overlaps later.
  730. my ($o_ofs, undef, $n_ofs) = parse_hunk_header($text->[0]);
  731. my $hunk_start = 1;
  732. OUTER:
  733. while (1) {
  734. my $next_hunk_start = undef;
  735. my $i = $hunk_start - 1;
  736. my $this = +{
  737. TEXT => [],
  738. DISPLAY => [],
  739. TYPE => 'hunk',
  740. OLD => $o_ofs,
  741. NEW => $n_ofs,
  742. OCNT => 0,
  743. NCNT => 0,
  744. ADDDEL => 0,
  745. POSTCTX => 0,
  746. USE => undef,
  747. };
  748. while (++$i < @$text) {
  749. my $line = $text->[$i];
  750. my $display = $display->[$i];
  751. if ($line =~ /^\\/) {
  752. push @{$this->{TEXT}}, $line;
  753. push @{$this->{DISPLAY}}, $display;
  754. next;
  755. }
  756. if ($line =~ /^ /) {
  757. if ($this->{ADDDEL} &&
  758. !defined $next_hunk_start) {
  759. # We have seen leading context and
  760. # adds/dels and then here is another
  761. # context, which is trailing for this
  762. # split hunk and leading for the next
  763. # one.
  764. $next_hunk_start = $i;
  765. }
  766. push @{$this->{TEXT}}, $line;
  767. push @{$this->{DISPLAY}}, $display;
  768. $this->{OCNT}++;
  769. $this->{NCNT}++;
  770. if (defined $next_hunk_start) {
  771. $this->{POSTCTX}++;
  772. }
  773. next;
  774. }
  775. # add/del
  776. if (defined $next_hunk_start) {
  777. # We are done with the current hunk and
  778. # this is the first real change for the
  779. # next split one.
  780. $hunk_start = $next_hunk_start;
  781. $o_ofs = $this->{OLD} + $this->{OCNT};
  782. $n_ofs = $this->{NEW} + $this->{NCNT};
  783. $o_ofs -= $this->{POSTCTX};
  784. $n_ofs -= $this->{POSTCTX};
  785. push @split, $this;
  786. redo OUTER;
  787. }
  788. push @{$this->{TEXT}}, $line;
  789. push @{$this->{DISPLAY}}, $display;
  790. $this->{ADDDEL}++;
  791. if ($line =~ /^-/) {
  792. $this->{OCNT}++;
  793. }
  794. else {
  795. $this->{NCNT}++;
  796. }
  797. }
  798. push @split, $this;
  799. last;
  800. }
  801. for my $hunk (@split) {
  802. $o_ofs = $hunk->{OLD};
  803. $n_ofs = $hunk->{NEW};
  804. my $o_cnt = $hunk->{OCNT};
  805. my $n_cnt = $hunk->{NCNT};
  806. my $head = format_hunk_header($o_ofs, $o_cnt, $n_ofs, $n_cnt);
  807. my $display_head = $head;
  808. unshift @{$hunk->{TEXT}}, $head;
  809. if ($diff_use_color) {
  810. $display_head = colored($fraginfo_color, $head);
  811. }
  812. unshift @{$hunk->{DISPLAY}}, $display_head;
  813. }
  814. return @split;
  815. }
  816. sub find_last_o_ctx {
  817. my ($it) = @_;
  818. my $text = $it->{TEXT};
  819. my ($o_ofs, $o_cnt) = parse_hunk_header($text->[0]);
  820. my $i = @{$text};
  821. my $last_o_ctx = $o_ofs + $o_cnt;
  822. while (0 < --$i) {
  823. my $line = $text->[$i];
  824. if ($line =~ /^ /) {
  825. $last_o_ctx--;
  826. next;
  827. }
  828. last;
  829. }
  830. return $last_o_ctx;
  831. }
  832. sub merge_hunk {
  833. my ($prev, $this) = @_;
  834. my ($o0_ofs, $o0_cnt, $n0_ofs, $n0_cnt) =
  835. parse_hunk_header($prev->{TEXT}[0]);
  836. my ($o1_ofs, $o1_cnt, $n1_ofs, $n1_cnt) =
  837. parse_hunk_header($this->{TEXT}[0]);
  838. my (@line, $i, $ofs, $o_cnt, $n_cnt);
  839. $ofs = $o0_ofs;
  840. $o_cnt = $n_cnt = 0;
  841. for ($i = 1; $i < @{$prev->{TEXT}}; $i++) {
  842. my $line = $prev->{TEXT}[$i];
  843. if ($line =~ /^\+/) {
  844. $n_cnt++;
  845. push @line, $line;
  846. next;
  847. } elsif ($line =~ /^\\/) {
  848. push @line, $line;
  849. next;
  850. }
  851. last if ($o1_ofs <= $ofs);
  852. $o_cnt++;
  853. $ofs++;
  854. if ($line =~ /^ /) {
  855. $n_cnt++;
  856. }
  857. push @line, $line;
  858. }
  859. for ($i = 1; $i < @{$this->{TEXT}}; $i++) {
  860. my $line = $this->{TEXT}[$i];
  861. if ($line =~ /^\+/) {
  862. $n_cnt++;
  863. push @line, $line;
  864. next;
  865. } elsif ($line =~ /^\\/) {
  866. push @line, $line;
  867. next;
  868. }
  869. $ofs++;
  870. $o_cnt++;
  871. if ($line =~ /^ /) {
  872. $n_cnt++;
  873. }
  874. push @line, $line;
  875. }
  876. my $head = format_hunk_header($o0_ofs, $o_cnt, $n0_ofs, $n_cnt);
  877. @{$prev->{TEXT}} = ($head, @line);
  878. }
  879. sub coalesce_overlapping_hunks {
  880. my (@in) = @_;
  881. my @out = ();
  882. my ($last_o_ctx, $last_was_dirty);
  883. my $ofs_delta = 0;
  884. for (@in) {
  885. if ($_->{TYPE} ne 'hunk') {
  886. push @out, $_;
  887. next;
  888. }
  889. my $text = $_->{TEXT};
  890. my ($o_ofs, $o_cnt, $n_ofs, $n_cnt) =
  891. parse_hunk_header($text->[0]);
  892. unless ($_->{USE}) {
  893. $ofs_delta += $o_cnt - $n_cnt;
  894. # If this hunk has been edited then subtract
  895. # the delta that is due to the edit.
  896. if ($_->{OFS_DELTA}) {
  897. $ofs_delta -= $_->{OFS_DELTA};
  898. }
  899. next;
  900. }
  901. if ($ofs_delta) {
  902. if ($patch_mode_flavour{IS_REVERSE}) {
  903. $o_ofs -= $ofs_delta;
  904. } else {
  905. $n_ofs += $ofs_delta;
  906. }
  907. $_->{TEXT}->[0] = format_hunk_header($o_ofs, $o_cnt,
  908. $n_ofs, $n_cnt);
  909. }
  910. # If this hunk was edited then adjust the offset delta
  911. # to reflect the edit.
  912. if ($_->{OFS_DELTA}) {
  913. $ofs_delta += $_->{OFS_DELTA};
  914. }
  915. if (defined $last_o_ctx &&
  916. $o_ofs <= $last_o_ctx &&
  917. !$_->{DIRTY} &&
  918. !$last_was_dirty) {
  919. merge_hunk($out[-1], $_);
  920. }
  921. else {
  922. push @out, $_;
  923. }
  924. $last_o_ctx = find_last_o_ctx($out[-1]);
  925. $last_was_dirty = $_->{DIRTY};
  926. }
  927. return @out;
  928. }
  929. sub reassemble_patch {
  930. my $head = shift;
  931. my @patch;
  932. # Include everything in the header except the beginning of the diff.
  933. push @patch, (grep { !/^[-+]{3}/ } @$head);
  934. # Then include any headers from the hunk lines, which must
  935. # come before any actual hunk.
  936. while (@_ && $_[0] !~ /^@/) {
  937. push @patch, shift;
  938. }
  939. # Then begin the diff.
  940. push @patch, grep { /^[-+]{3}/ } @$head;
  941. # And then the actual hunks.
  942. push @patch, @_;
  943. return @patch;
  944. }
  945. sub color_diff {
  946. return map {
  947. colored((/^@/ ? $fraginfo_color :
  948. /^\+/ ? $diff_new_color :
  949. /^-/ ? $diff_old_color :
  950. $diff_plain_color),
  951. $_);
  952. } @_;
  953. }
  954. my %edit_hunk_manually_modes = (
  955. stage => N__(
  956. "If the patch applies cleanly, the edited hunk will immediately be
  957. marked for staging."),
  958. stash => N__(
  959. "If the patch applies cleanly, the edited hunk will immediately be
  960. marked for stashing."),
  961. reset_head => N__(
  962. "If the patch applies cleanly, the edited hunk will immediately be
  963. marked for unstaging."),
  964. reset_nothead => N__(
  965. "If the patch applies cleanly, the edited hunk will immediately be
  966. marked for applying."),
  967. checkout_index => N__(
  968. "If the patch applies cleanly, the edited hunk will immediately be
  969. marked for discarding."),
  970. checkout_head => N__(
  971. "If the patch applies cleanly, the edited hunk will immediately be
  972. marked for discarding."),
  973. checkout_nothead => N__(
  974. "If the patch applies cleanly, the edited hunk will immediately be
  975. marked for applying."),
  976. worktree_head => N__(
  977. "If the patch applies cleanly, the edited hunk will immediately be
  978. marked for discarding."),
  979. worktree_nothead => N__(
  980. "If the patch applies cleanly, the edited hunk will immediately be
  981. marked for applying."),
  982. );
  983. sub recount_edited_hunk {
  984. local $_;
  985. my ($oldtext, $newtext) = @_;
  986. my ($o_cnt, $n_cnt) = (0, 0);
  987. for (@{$newtext}[1..$#{$newtext}]) {
  988. my $mode = substr($_, 0, 1);
  989. if ($mode eq '-') {
  990. $o_cnt++;
  991. } elsif ($mode eq '+') {
  992. $n_cnt++;
  993. } elsif ($mode eq ' ' or $mode eq "\n") {
  994. $o_cnt++;
  995. $n_cnt++;
  996. }
  997. }
  998. my ($o_ofs, undef, $n_ofs, undef) =
  999. parse_hunk_header($newtext->[0]);
  1000. $newtext->[0] = format_hunk_header($o_ofs, $o_cnt, $n_ofs, $n_cnt);
  1001. my (undef, $orig_o_cnt, undef, $orig_n_cnt) =
  1002. parse_hunk_header($oldtext->[0]);
  1003. # Return the change in the number of lines inserted by this hunk
  1004. return $orig_o_cnt - $orig_n_cnt - $o_cnt + $n_cnt;
  1005. }
  1006. sub edit_hunk_manually {
  1007. my ($oldtext) = @_;
  1008. my $hunkfile = $repo->repo_path . "/addp-hunk-edit.diff";
  1009. my $fh;
  1010. open $fh, '>', $hunkfile
  1011. or die sprintf(__("failed to open hunk edit file for writing: %s"), $!);
  1012. print $fh Git::comment_lines __("Manual hunk edit mode -- see bottom for a quick guide.\n");
  1013. print $fh @$oldtext;
  1014. my $is_reverse = $patch_mode_flavour{IS_REVERSE};
  1015. my ($remove_plus, $remove_minus) = $is_reverse ? ('-', '+') : ('+', '-');
  1016. my $comment_line_char = Git::get_comment_line_char;
  1017. print $fh Git::comment_lines sprintf(__ <<EOF, $remove_minus, $remove_plus, $comment_line_char),
  1018. ---
  1019. To remove '%s' lines, make them ' ' lines (context).
  1020. To remove '%s' lines, delete them.
  1021. Lines starting with %s will be removed.
  1022. EOF
  1023. __($edit_hunk_manually_modes{$patch_mode}),
  1024. # TRANSLATORS: 'it' refers to the patch mentioned in the previous messages.
  1025. __ <<EOF2 ;
  1026. If it does not apply cleanly, you will be given an opportunity to
  1027. edit again. If all lines of the hunk are removed, then the edit is
  1028. aborted and the hunk is left unchanged.
  1029. EOF2
  1030. close $fh;
  1031. chomp(my $editor = run_cmd_pipe(qw(git var GIT_EDITOR)));
  1032. system('sh', '-c', $editor.' "$@"', $editor, $hunkfile);
  1033. if ($? != 0) {
  1034. return undef;
  1035. }
  1036. open $fh, '<', $hunkfile
  1037. or die sprintf(__("failed to open hunk edit file for reading: %s"), $!);
  1038. my @newtext = grep { !/^\Q$comment_line_char\E/ } <$fh>;
  1039. close $fh;
  1040. unlink $hunkfile;
  1041. # Abort if nothing remains
  1042. if (!grep { /\S/ } @newtext) {
  1043. return undef;
  1044. }
  1045. # Reinsert the first hunk header if the user accidentally deleted it
  1046. if ($newtext[0] !~ /^@/) {
  1047. unshift @newtext, $oldtext->[0];
  1048. }
  1049. return \@newtext;
  1050. }
  1051. sub diff_applies {
  1052. return run_git_apply($patch_mode_flavour{APPLY_CHECK} . ' --check',
  1053. map { @{$_->{TEXT}} } @_);
  1054. }
  1055. sub _restore_terminal_and_die {
  1056. ReadMode 'restore';
  1057. print "\n";
  1058. exit 1;
  1059. }
  1060. sub prompt_single_character {
  1061. if ($use_readkey) {
  1062. local $SIG{TERM} = \&_restore_terminal_and_die;
  1063. local $SIG{INT} = \&_restore_terminal_and_die;
  1064. ReadMode 'cbreak';
  1065. my $key = ReadKey 0;
  1066. ReadMode 'restore';
  1067. if ($use_termcap and $key eq "\e") {
  1068. while (!defined $term_escapes{$key}) {
  1069. my $next = ReadKey 0.5;
  1070. last if (!defined $next);
  1071. $key .= $next;
  1072. }
  1073. $key =~ s/\e/^[/;
  1074. }
  1075. print "$key" if defined $key;
  1076. print "\n";
  1077. return $key;
  1078. } else {
  1079. return <STDIN>;
  1080. }
  1081. }
  1082. sub prompt_yesno {
  1083. my ($prompt) = @_;
  1084. while (1) {
  1085. print colored $prompt_color, $prompt;
  1086. my $line = prompt_single_character;
  1087. return undef unless defined $line;
  1088. return 0 if $line =~ /^n/i;
  1089. return 1 if $line =~ /^y/i;
  1090. }
  1091. }
  1092. sub edit_hunk_loop {
  1093. my ($head, $hunks, $ix) = @_;
  1094. my $hunk = $hunks->[$ix];
  1095. my $text = $hunk->{TEXT};
  1096. while (1) {
  1097. my $newtext = edit_hunk_manually($text);
  1098. if (!defined $newtext) {
  1099. return undef;
  1100. }
  1101. my $newhunk = {
  1102. TEXT => $newtext,
  1103. TYPE => $hunk->{TYPE},
  1104. USE => 1,
  1105. DIRTY => 1,
  1106. };
  1107. $newhunk->{OFS_DELTA} = recount_edited_hunk($text, $newtext);
  1108. # If this hunk has already been edited then add the
  1109. # offset delta of the previous edit to get the real
  1110. # delta from the original unedited hunk.
  1111. $hunk->{OFS_DELTA} and
  1112. $newhunk->{OFS_DELTA} += $hunk->{OFS_DELTA};
  1113. if (diff_applies($head,
  1114. @{$hunks}[0..$ix-1],
  1115. $newhunk,
  1116. @{$hunks}[$ix+1..$#{$hunks}])) {
  1117. $newhunk->{DISPLAY} = [color_diff(@{$newtext})];
  1118. return $newhunk;
  1119. }
  1120. else {
  1121. prompt_yesno(
  1122. # TRANSLATORS: do not translate [y/n]
  1123. # The program will only accept that input
  1124. # at this point.
  1125. # Consider translating (saying "no" discards!) as
  1126. # (saying "n" for "no" discards!) if the translation
  1127. # of the word "no" does not start with n.
  1128. __('Your edited hunk does not apply. Edit again '
  1129. . '(saying "no" discards!) [y/n]? ')
  1130. ) or return undef;
  1131. }
  1132. }
  1133. }
  1134. my %help_patch_modes = (
  1135. stage => N__(
  1136. "y - stage this hunk
  1137. n - do not stage this hunk
  1138. q - quit; do not stage this hunk or any of the remaining ones
  1139. a - stage this hunk and all later hunks in the file
  1140. d - do not stage this hunk or any of the later hunks in the file"),
  1141. stash => N__(
  1142. "y - stash this hunk
  1143. n - do not stash this hunk
  1144. q - quit; do not stash this hunk or any of the remaining ones
  1145. a - stash this hunk and all later hunks in the file
  1146. d - do not stash this hunk or any of the later hunks in the file"),
  1147. reset_head => N__(
  1148. "y - unstage this hunk
  1149. n - do not unstage this hunk
  1150. q - quit; do not unstage this hunk or any of the remaining ones
  1151. a - unstage this hunk and all later hunks in the file
  1152. d - do not unstage this hunk or any of the later hunks in the file"),
  1153. reset_nothead => N__(
  1154. "y - apply this hunk to index
  1155. n - do not apply this hunk to index
  1156. q - quit; do not apply this hunk or any of the remaining ones
  1157. a - apply this hunk and all later hunks in the file
  1158. d - do not apply this hunk or any of the later hunks in the file"),
  1159. checkout_index => N__(
  1160. "y - discard this hunk from worktree
  1161. n - do not discard this hunk from worktree
  1162. q - quit; do not discard this hunk or any of the remaining ones
  1163. a - discard this hunk and all later hunks in the file
  1164. d - do not discard this hunk or any of the later hunks in the file"),
  1165. checkout_head => N__(
  1166. "y - discard this hunk from index and worktree
  1167. n - do not discard this hunk from index and worktree
  1168. q - quit; do not discard this hunk or any of the remaining ones
  1169. a - discard this hunk and all later hunks in the file
  1170. d - do not discard this hunk or any of the later hunks in the file"),
  1171. checkout_nothead => N__(
  1172. "y - apply this hunk to index and worktree
  1173. n - do not apply this hunk to index and worktree
  1174. q - quit; do not apply this hunk or any of the remaining ones
  1175. a - apply this hunk and all later hunks in the file
  1176. d - do not apply this hunk or any of the later hunks in the file"),
  1177. worktree_head => N__(
  1178. "y - discard this hunk from worktree
  1179. n - do not discard this hunk from worktree
  1180. q - quit; do not discard this hunk or any of the remaining ones
  1181. a - discard this hunk and all later hunks in the file
  1182. d - do not discard this hunk or any of the later hunks in the file"),
  1183. worktree_nothead => N__(
  1184. "y - apply this hunk to worktree
  1185. n - do not apply this hunk to worktree
  1186. q - quit; do not apply this hunk or any of the remaining ones
  1187. a - apply this hunk and all later hunks in the file
  1188. d - do not apply this hunk or any of the later hunks in the file"),
  1189. );
  1190. sub help_patch_cmd {
  1191. local $_;
  1192. my $other = $_[0] . ",?";
  1193. print colored $help_color, __($help_patch_modes{$patch_mode}), "\n",
  1194. map { "$_\n" } grep {
  1195. my $c = quotemeta(substr($_, 0, 1));
  1196. $other =~ /,$c/
  1197. } split "\n", __ <<EOF ;
  1198. g - select a hunk to go to
  1199. / - search for a hunk matching the given regex
  1200. j - leave this hunk undecided, see next undecided hunk
  1201. J - leave this hunk undecided, see next hunk
  1202. k - leave this hunk undecided, see previous undecided hunk
  1203. K - leave this hunk undecided, see previous hunk
  1204. s - split the current hunk into smaller hunks
  1205. e - manually edit the current hunk
  1206. ? - print help
  1207. EOF
  1208. }
  1209. sub apply_patch {
  1210. my $cmd = shift;
  1211. my $ret = run_git_apply $cmd, @_;
  1212. if (!$ret) {
  1213. print STDERR @_;
  1214. }
  1215. return $ret;
  1216. }
  1217. sub apply_patch_for_checkout_commit {
  1218. my $reverse = shift;
  1219. my $applies_index = run_git_apply 'apply '.$reverse.' --cached --check', @_;
  1220. my $applies_worktree = run_git_apply 'apply '.$reverse.' --check', @_;
  1221. if ($applies_worktree && $applies_index) {
  1222. run_git_apply 'apply '.$reverse.' --cached', @_;
  1223. run_git_apply 'apply '.$reverse, @_;
  1224. return 1;
  1225. } elsif (!$applies_index) {
  1226. print colored $error_color, __("The selected hunks do not apply to the index!\n");
  1227. if (prompt_yesno __("Apply them to the worktree anyway? ")) {
  1228. return run_git_apply 'apply '.$reverse, @_;
  1229. } else {
  1230. print colored $error_color, __("Nothing was applied.\n");
  1231. return 0;
  1232. }
  1233. } else {
  1234. print STDERR @_;
  1235. return 0;
  1236. }
  1237. }
  1238. sub patch_update_cmd {
  1239. my @all_mods = list_modified($patch_mode_flavour{FILTER});
  1240. error_msg sprintf(__("ignoring unmerged: %s\n"), $_->{VALUE})
  1241. for grep { $_->{UNMERGED} } @all_mods;
  1242. @all_mods = grep { !$_->{UNMERGED} } @all_mods;
  1243. my @mods = grep { !($_->{BINARY}) } @all_mods;
  1244. my @them;
  1245. if (!@mods) {
  1246. if (@all_mods) {
  1247. print STDERR __("Only binary files changed.\n");
  1248. } else {
  1249. print STDERR __("No changes.\n");
  1250. }
  1251. return 0;
  1252. }
  1253. if ($patch_mode_only) {
  1254. @them = @mods;
  1255. }
  1256. else {
  1257. @them = list_and_choose({ PROMPT => __('Patch update'),
  1258. HEADER => $status_head, },
  1259. @mods);
  1260. }
  1261. for (@them) {
  1262. return 0 if patch_update_file($_->{VALUE});
  1263. }
  1264. }
  1265. # Generate a one line summary of a hunk.
  1266. sub summarize_hunk {
  1267. my $rhunk = shift;
  1268. my $summary = $rhunk->{TEXT}[0];
  1269. # Keep the line numbers, discard extra context.
  1270. $summary =~ s/@@(.*?)@@.*/$1 /s;
  1271. $summary .= " " x (20 - length $summary);
  1272. # Add some user context.
  1273. for my $line (@{$rhunk->{TEXT}}) {
  1274. if ($line =~ m/^[+-].*\w/) {
  1275. $summary .= $line;
  1276. last;
  1277. }
  1278. }
  1279. chomp $summary;
  1280. return substr($summary, 0, 80) . "\n";
  1281. }
  1282. # Print a one-line summary of each hunk in the array ref in
  1283. # the first argument, starting with the index in the 2nd.
  1284. sub display_hunks {
  1285. my ($hunks, $i) = @_;
  1286. my $ctr = 0;
  1287. $i ||= 0;
  1288. for (; $i < @$hunks && $ctr < 20; $i++, $ctr++) {
  1289. my $status = " ";
  1290. if (defined $hunks->[$i]{USE}) {
  1291. $status = $hunks->[$i]{USE} ? "+" : "-";
  1292. }
  1293. printf "%s%2d: %s",
  1294. $status,
  1295. $i + 1,
  1296. summarize_hunk($hunks->[$i]);
  1297. }
  1298. return $i;
  1299. }
  1300. my %patch_update_prompt_modes = (
  1301. stage => {
  1302. mode => N__("Stage mode change [y,n,q,a,d%s,?]? "),
  1303. deletion => N__("Stage deletion [y,n,q,a,d%s,?]? "),
  1304. hunk => N__("Stage this hunk [y,n,q,a,d%s,?]? "),
  1305. },
  1306. stash => {
  1307. mode => N__("Stash mode change [y,n,q,a,d%s,?]? "),
  1308. deletion => N__("Stash deletion [y,n,q,a,d%s,?]? "),
  1309. hunk => N__("Stash this hunk [y,n,q,a,d%s,?]? "),
  1310. },
  1311. reset_head => {
  1312. mode => N__("Unstage mode change [y,n,q,a,d%s,?]? "),
  1313. deletion => N__("Unstage deletion [y,n,q,a,d%s,?]? "),
  1314. hunk => N__("Unstage this hunk [y,n,q,a,d%s,?]? "),
  1315. },
  1316. reset_nothead => {
  1317. mode => N__("Apply mode change to index [y,n,q,a,d%s,?]? "),
  1318. deletion => N__("Apply deletion to index [y,n,q,a,d%s,?]? "),
  1319. hunk => N__("Apply this hunk to index [y,n,q,a,d%s,?]? "),
  1320. },
  1321. checkout_index => {
  1322. mode => N__("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
  1323. deletion => N__("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
  1324. hunk => N__("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
  1325. },
  1326. checkout_head => {
  1327. mode => N__("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
  1328. deletion => N__("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
  1329. hunk => N__("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
  1330. },
  1331. checkout_nothead => {
  1332. mode => N__("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
  1333. deletion => N__("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
  1334. hunk => N__("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
  1335. },
  1336. worktree_head => {
  1337. mode => N__("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
  1338. deletion => N__("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
  1339. hunk => N__("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
  1340. },
  1341. worktree_nothead => {
  1342. mode => N__("Apply mode change to worktree [y,n,q,a,d%s,?]? "),
  1343. deletion => N__("Apply deletion to worktree [y,n,q,a,d%s,?]? "),
  1344. hunk => N__("Apply this hunk to worktree [y,n,q,a,d%s,?]? "),
  1345. },
  1346. );
  1347. sub patch_update_file {
  1348. my $quit = 0;
  1349. my ($ix, $num);
  1350. my $path = shift;
  1351. my ($head, @hunk) = parse_diff($path);
  1352. ($head, my $mode, my $deletion) = parse_diff_header($head);
  1353. for (@{$head->{DISPLAY}}) {
  1354. print;
  1355. }
  1356. if (@{$mode->{TEXT}}) {
  1357. unshift @hunk, $mode;
  1358. }
  1359. if (@{$deletion->{TEXT}}) {
  1360. foreach my $hunk (@hunk) {
  1361. push @{$deletion->{TEXT}}, @{$hunk->{TEXT}};
  1362. push @{$deletion->{DISPLAY}}, @{$hunk->{DISPLAY}};
  1363. }
  1364. @hunk = ($deletion);
  1365. }
  1366. $num = scalar @hunk;
  1367. $ix = 0;
  1368. while (1) {
  1369. my ($prev, $next, $other, $undecided, $i);
  1370. $other = '';
  1371. if ($num <= $ix) {
  1372. $ix = 0;
  1373. }
  1374. for ($i = 0; $i < $ix; $i++) {
  1375. if (!defined $hunk[$i]{USE}) {
  1376. $prev = 1;
  1377. $other .= ',k';
  1378. last;
  1379. }
  1380. }
  1381. if ($ix) {
  1382. $other .= ',K';
  1383. }
  1384. for ($i = $ix + 1; $i < $num; $i++) {
  1385. if (!defined $hunk[$i]{USE}) {
  1386. $next = 1;
  1387. $other .= ',j';
  1388. last;
  1389. }
  1390. }
  1391. if ($ix < $num - 1) {
  1392. $other .= ',J';
  1393. }
  1394. if ($num > 1) {
  1395. $other .= ',g,/';
  1396. }
  1397. for ($i = 0; $i < $num; $i++) {
  1398. if (!defined $hunk[$i]{USE}) {
  1399. $undecided = 1;
  1400. last;
  1401. }
  1402. }
  1403. last if (!$undecided);
  1404. if ($hunk[$ix]{TYPE} eq 'hunk' &&
  1405. hunk_splittable($hunk[$ix]{TEXT})) {
  1406. $other .= ',s';
  1407. }
  1408. if ($hunk[$ix]{TYPE} eq 'hunk') {
  1409. $other .= ',e';
  1410. }
  1411. for (@{$hunk[$ix]{DISPLAY}}) {
  1412. print;
  1413. }
  1414. print colored $prompt_color, "(", ($ix+1), "/$num) ",
  1415. sprintf(__($patch_update_prompt_modes{$patch_mode}{$hunk[$ix]{TYPE}}), $other);
  1416. my $line = prompt_single_character;
  1417. last unless defined $line;
  1418. if ($line) {
  1419. if ($line =~ /^y/i) {
  1420. $hunk[$ix]{USE} = 1;
  1421. }
  1422. elsif ($line =~ /^n/i) {
  1423. $hunk[$ix]{USE} = 0;
  1424. }
  1425. elsif ($line =~ /^a/i) {
  1426. while ($ix < $num) {
  1427. if (!defined $hunk[$ix]{USE}) {
  1428. $hunk[$ix]{USE} = 1;
  1429. }
  1430. $ix++;
  1431. }
  1432. next;
  1433. }
  1434. elsif ($line =~ /^g(.*)/) {
  1435. my $response = $1;
  1436. unless ($other =~ /g/) {
  1437. error_msg __("No other hunks to goto\n");
  1438. next;
  1439. }
  1440. my $no = $ix > 10 ? $ix - 10 : 0;
  1441. while ($response eq '') {
  1442. $no = display_hunks(\@hunk, $no);
  1443. if ($no < $num) {
  1444. print __("go to which hunk (<ret> to see more)? ");
  1445. } else {
  1446. print __("go to which hunk? ");
  1447. }
  1448. $response = <STDIN>;
  1449. if (!defined $response) {
  1450. $response = '';
  1451. }
  1452. chomp $response;
  1453. }
  1454. if ($response !~ /^\s*\d+\s*$/) {
  1455. error_msg sprintf(__("Invalid number: '%s'\n"),
  1456. $response);
  1457. } elsif (0 < $response && $response <= $num) {
  1458. $ix = $response - 1;
  1459. } else {
  1460. error_msg sprintf(__n("Sorry, only %d hunk available.\n",
  1461. "Sorry, only %d hunks available.\n", $num), $num);
  1462. }
  1463. next;
  1464. }
  1465. elsif ($line =~ /^d/i) {
  1466. while ($ix < $num) {
  1467. if (!defined $hunk[$ix]{USE}) {
  1468. $hunk[$ix]{USE} = 0;
  1469. }
  1470. $ix++;
  1471. }
  1472. next;
  1473. }
  1474. elsif ($line =~ /^q/i) {
  1475. for ($i = 0; $i < $num; $i++) {
  1476. if (!defined $hunk[$i]{USE}) {
  1477. $hunk[$i]{USE} = 0;
  1478. }
  1479. }
  1480. $quit = 1;
  1481. last;
  1482. }
  1483. elsif ($line =~ m|^/(.*)|) {
  1484. my $regex = $1;
  1485. unless ($other =~ m|/|) {
  1486. error_msg __("No other hunks to search\n");
  1487. next;
  1488. }
  1489. if ($regex eq "") {
  1490. print colored $prompt_color, __("search for regex? ");
  1491. $regex = <STDIN>;
  1492. if (defined $regex) {
  1493. chomp $regex;
  1494. }
  1495. }
  1496. my $search_string;
  1497. eval {
  1498. $search_string = qr{$regex}m;
  1499. };
  1500. if ($@) {
  1501. my ($err,$exp) = ($@, $1);
  1502. $err =~ s/ at .*git-add--interactive line \d+, <STDIN> line \d+.*$//;
  1503. error_msg sprintf(__("Malformed search regexp %s: %s\n"), $exp, $err);
  1504. next;
  1505. }
  1506. my $iy = $ix;
  1507. while (1) {
  1508. my $text = join ("", @{$hunk[$iy]{TEXT}});
  1509. last if ($text =~ $search_string);
  1510. $iy++;
  1511. $iy = 0 if ($iy >= $num);
  1512. if ($ix == $iy) {
  1513. error_msg __("No hunk matches the given pattern\n");
  1514. last;
  1515. }
  1516. }
  1517. $ix = $iy;
  1518. next;
  1519. }
  1520. elsif ($line =~ /^K/) {
  1521. if ($other =~ /K/) {
  1522. $ix--;
  1523. }
  1524. else {
  1525. error_msg __("No previous hunk\n");
  1526. }
  1527. next;
  1528. }
  1529. elsif ($line =~ /^J/) {
  1530. if ($other =~ /J/) {
  1531. $ix++;
  1532. }
  1533. else {
  1534. error_msg __("No next hunk\n");
  1535. }
  1536. next;
  1537. }
  1538. elsif ($line =~ /^k/) {
  1539. if ($other =~ /k/) {
  1540. while (1) {
  1541. $ix--;
  1542. last if (!$ix ||
  1543. !defined $hunk[$ix]{USE});
  1544. }
  1545. }
  1546. else {
  1547. error_msg __("No previous hunk\n");
  1548. }
  1549. next;
  1550. }
  1551. elsif ($line =~ /^j/) {
  1552. if ($other !~ /j/) {
  1553. error_msg __("No next hunk\n");
  1554. next;
  1555. }
  1556. }
  1557. elsif ($line =~ /^s/) {
  1558. unless ($other =~ /s/) {
  1559. error_msg __("Sorry, cannot split this hunk\n");
  1560. next;
  1561. }
  1562. my @split = split_hunk($hunk[$ix]{TEXT}, $hunk[$ix]{DISPLAY});
  1563. if (1 < @split) {
  1564. print colored $header_color, sprintf(
  1565. __n("Split into %d hunk.\n",
  1566. "Split into %d hunks.\n",
  1567. scalar(@split)), scalar(@split));
  1568. }
  1569. splice (@hunk, $ix, 1, @split);
  1570. $num = scalar @hunk;
  1571. next;
  1572. }
  1573. elsif ($line =~ /^e/) {
  1574. unless ($other =~ /e/) {
  1575. error_msg __("Sorry, cannot edit this hunk\n");
  1576. next;
  1577. }
  1578. my $newhunk = edit_hunk_loop($head, \@hunk, $ix);
  1579. if (defined $newhunk) {
  1580. splice @hunk, $ix, 1, $newhunk;
  1581. }
  1582. }
  1583. else {
  1584. help_patch_cmd($other);
  1585. next;
  1586. }
  1587. # soft increment
  1588. while (1) {
  1589. $ix++;
  1590. last if ($ix >= $num ||
  1591. !defined $hunk[$ix]{USE});
  1592. }
  1593. }
  1594. }
  1595. @hunk = coalesce_overlapping_hunks(@hunk);
  1596. my $n_lofs = 0;
  1597. my @result = ();
  1598. for (@hunk) {
  1599. if ($_->{USE}) {
  1600. push @result, @{$_->{TEXT}};
  1601. }
  1602. }
  1603. if (@result) {
  1604. my @patch = reassemble_patch($head->{TEXT}, @result);
  1605. my $apply_routine = $patch_mode_flavour{APPLY};
  1606. &$apply_routine(@patch);
  1607. refresh();
  1608. }
  1609. print "\n";
  1610. return $quit;
  1611. }
  1612. sub diff_cmd {
  1613. my @mods = list_modified('index-only');
  1614. @mods = grep { !($_->{BINARY}) } @mods;
  1615. return if (!@mods);
  1616. my (@them) = list_and_choose({ PROMPT => __('Review diff'),
  1617. IMMEDIATE => 1,
  1618. HEADER => $status_head, },
  1619. @mods);
  1620. return if (!@them);
  1621. my $reference = (is_initial_commit()) ? get_empty_tree() : 'HEAD';
  1622. system(qw(git diff -p --cached), $reference, '--',
  1623. map { $_->{VALUE} } @them);
  1624. }
  1625. sub quit_cmd {
  1626. print __("Bye.\n");
  1627. exit(0);
  1628. }
  1629. sub help_cmd {
  1630. # TRANSLATORS: please do not translate the command names
  1631. # 'status', 'update', 'revert', etc.
  1632. print colored $help_color, __ <<'EOF' ;
  1633. status - show paths with changes
  1634. update - add working tree state to the staged set of changes
  1635. revert - revert staged set of changes back to the HEAD version
  1636. patch - pick hunks and update selectively
  1637. diff - view diff between HEAD and index
  1638. add untracked - add contents of untracked files to the staged set of changes
  1639. EOF
  1640. }
  1641. sub process_args {
  1642. return unless @ARGV;
  1643. my $arg = shift @ARGV;
  1644. if ($arg =~ /--patch(?:=(.*))?/) {
  1645. if (defined $1) {
  1646. if ($1 eq 'reset') {
  1647. $patch_mode = 'reset_head';
  1648. $patch_mode_revision = 'HEAD';
  1649. $arg = shift @ARGV or die __("missing --");
  1650. if ($arg ne '--') {
  1651. $patch_mode_revision = $arg;
  1652. $patch_mode = ($arg eq 'HEAD' ?
  1653. 'reset_head' : 'reset_nothead');
  1654. $arg = shift @ARGV or die __("missing --");
  1655. }
  1656. } elsif ($1 eq 'checkout') {
  1657. $arg = shift @ARGV or die __("missing --");
  1658. if ($arg eq '--') {
  1659. $patch_mode = 'checkout_index';
  1660. } else {
  1661. $patch_mode_revision = $arg;
  1662. $patch_mode = ($arg eq 'HEAD' ?
  1663. 'checkout_head' : 'checkout_nothead');
  1664. $arg = shift @ARGV or die __("missing --");
  1665. }
  1666. } elsif ($1 eq 'worktree') {
  1667. $arg = shift @ARGV or die __("missing --");
  1668. if ($arg eq '--') {
  1669. $patch_mode = 'checkout_index';
  1670. } else {
  1671. $patch_mode_revision = $arg;
  1672. $patch_mode = ($arg eq 'HEAD' ?
  1673. 'worktree_head' : 'worktree_nothead');
  1674. $arg = shift @ARGV or die __("missing --");
  1675. }
  1676. } elsif ($1 eq 'stage' or $1 eq 'stash') {
  1677. $patch_mode = $1;
  1678. $arg = shift @ARGV or die __("missing --");
  1679. } else {
  1680. die sprintf(__("unknown --patch mode: %s"), $1);
  1681. }
  1682. } else {
  1683. $patch_mode = 'stage';
  1684. $arg = shift @ARGV or die __("missing --");
  1685. }
  1686. die sprintf(__("invalid argument %s, expecting --"),
  1687. $arg) unless $arg eq "--";
  1688. %patch_mode_flavour = %{$patch_modes{$patch_mode}};
  1689. $patch_mode_only = 1;
  1690. }
  1691. elsif ($arg ne "--") {
  1692. die sprintf(__("invalid argument %s, expecting --"), $arg);
  1693. }
  1694. }
  1695. sub main_loop {
  1696. my @cmd = ([ 'status', \&status_cmd, ],
  1697. [ 'update', \&update_cmd, ],
  1698. [ 'revert', \&revert_cmd, ],
  1699. [ 'add untracked', \&add_untracked_cmd, ],
  1700. [ 'patch', \&patch_update_cmd, ],
  1701. [ 'diff', \&diff_cmd, ],
  1702. [ 'quit', \&quit_cmd, ],
  1703. [ 'help', \&help_cmd, ],
  1704. );
  1705. while (1) {
  1706. my ($it) = list_and_choose({ PROMPT => __('What now'),
  1707. SINGLETON => 1,
  1708. LIST_FLAT => 4,
  1709. HEADER => __('*** Commands ***'),
  1710. ON_EOF => \&quit_cmd,
  1711. IMMEDIATE => 1 }, @cmd);
  1712. if ($it) {
  1713. eval {
  1714. $it->[1]->();
  1715. };
  1716. if ($@) {
  1717. print "$@";
  1718. }
  1719. }
  1720. }
  1721. }
  1722. process_args();
  1723. refresh();
  1724. if ($patch_mode_only) {
  1725. patch_update_cmd();
  1726. }
  1727. else {
  1728. status_cmd();
  1729. main_loop();
  1730. }