git
/
add-patch.c
1819 строк · 51.9 Кб
1#define USE_THE_REPOSITORY_VARIABLE
2
3#include "git-compat-util.h"
4#include "add-interactive.h"
5#include "advice.h"
6#include "editor.h"
7#include "environment.h"
8#include "gettext.h"
9#include "object-name.h"
10#include "pager.h"
11#include "read-cache-ll.h"
12#include "repository.h"
13#include "strbuf.h"
14#include "sigchain.h"
15#include "run-command.h"
16#include "strvec.h"
17#include "pathspec.h"
18#include "color.h"
19#include "compat/terminal.h"
20#include "prompt.h"
21
22enum prompt_mode_type {
23PROMPT_MODE_CHANGE = 0, PROMPT_DELETION, PROMPT_ADDITION, PROMPT_HUNK,
24PROMPT_MODE_MAX, /* must be last */
25};
26
27struct patch_mode {
28/*
29* The magic constant 4 is chosen such that all patch modes
30* provide enough space for three command-line arguments followed by a
31* trailing `NULL`.
32*/
33const char *diff_cmd[4], *apply_args[4], *apply_check_args[4];
34unsigned is_reverse:1, index_only:1, apply_for_checkout:1;
35const char *prompt_mode[PROMPT_MODE_MAX];
36const char *edit_hunk_hint, *help_patch_text;
37};
38
39static struct patch_mode patch_mode_add = {
40.diff_cmd = { "diff-files", NULL },
41.apply_args = { "--cached", NULL },
42.apply_check_args = { "--cached", NULL },
43.prompt_mode = {
44N_("Stage mode change [y,n,q,a,d%s,?]? "),
45N_("Stage deletion [y,n,q,a,d%s,?]? "),
46N_("Stage addition [y,n,q,a,d%s,?]? "),
47N_("Stage this hunk [y,n,q,a,d%s,?]? ")
48},
49.edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
50"will immediately be marked for staging."),
51.help_patch_text =
52N_("y - stage this hunk\n"
53"n - do not stage this hunk\n"
54"q - quit; do not stage this hunk or any of the remaining "
55"ones\n"
56"a - stage this hunk and all later hunks in the file\n"
57"d - do not stage this hunk or any of the later hunks in "
58"the file\n")
59};
60
61static struct patch_mode patch_mode_stash = {
62.diff_cmd = { "diff-index", "HEAD", NULL },
63.apply_args = { "--cached", NULL },
64.apply_check_args = { "--cached", NULL },
65.prompt_mode = {
66N_("Stash mode change [y,n,q,a,d%s,?]? "),
67N_("Stash deletion [y,n,q,a,d%s,?]? "),
68N_("Stash addition [y,n,q,a,d%s,?]? "),
69N_("Stash this hunk [y,n,q,a,d%s,?]? "),
70},
71.edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
72"will immediately be marked for stashing."),
73.help_patch_text =
74N_("y - stash this hunk\n"
75"n - do not stash this hunk\n"
76"q - quit; do not stash this hunk or any of the remaining "
77"ones\n"
78"a - stash this hunk and all later hunks in the file\n"
79"d - do not stash this hunk or any of the later hunks in "
80"the file\n"),
81};
82
83static struct patch_mode patch_mode_reset_head = {
84.diff_cmd = { "diff-index", "--cached", NULL },
85.apply_args = { "-R", "--cached", NULL },
86.apply_check_args = { "-R", "--cached", NULL },
87.is_reverse = 1,
88.index_only = 1,
89.prompt_mode = {
90N_("Unstage mode change [y,n,q,a,d%s,?]? "),
91N_("Unstage deletion [y,n,q,a,d%s,?]? "),
92N_("Unstage addition [y,n,q,a,d%s,?]? "),
93N_("Unstage this hunk [y,n,q,a,d%s,?]? "),
94},
95.edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
96"will immediately be marked for unstaging."),
97.help_patch_text =
98N_("y - unstage this hunk\n"
99"n - do not unstage this hunk\n"
100"q - quit; do not unstage this hunk or any of the remaining "
101"ones\n"
102"a - unstage this hunk and all later hunks in the file\n"
103"d - do not unstage this hunk or any of the later hunks in "
104"the file\n"),
105};
106
107static struct patch_mode patch_mode_reset_nothead = {
108.diff_cmd = { "diff-index", "-R", "--cached", NULL },
109.apply_args = { "--cached", NULL },
110.apply_check_args = { "--cached", NULL },
111.index_only = 1,
112.prompt_mode = {
113N_("Apply mode change to index [y,n,q,a,d%s,?]? "),
114N_("Apply deletion to index [y,n,q,a,d%s,?]? "),
115N_("Apply addition to index [y,n,q,a,d%s,?]? "),
116N_("Apply this hunk to index [y,n,q,a,d%s,?]? "),
117},
118.edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
119"will immediately be marked for applying."),
120.help_patch_text =
121N_("y - apply this hunk to index\n"
122"n - do not apply this hunk to index\n"
123"q - quit; do not apply this hunk or any of the remaining "
124"ones\n"
125"a - apply this hunk and all later hunks in the file\n"
126"d - do not apply this hunk or any of the later hunks in "
127"the file\n"),
128};
129
130static struct patch_mode patch_mode_checkout_index = {
131.diff_cmd = { "diff-files", NULL },
132.apply_args = { "-R", NULL },
133.apply_check_args = { "-R", NULL },
134.is_reverse = 1,
135.prompt_mode = {
136N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
137N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
138N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
139N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
140},
141.edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
142"will immediately be marked for discarding."),
143.help_patch_text =
144N_("y - discard this hunk from worktree\n"
145"n - do not discard this hunk from worktree\n"
146"q - quit; do not discard this hunk or any of the remaining "
147"ones\n"
148"a - discard this hunk and all later hunks in the file\n"
149"d - do not discard this hunk or any of the later hunks in "
150"the file\n"),
151};
152
153static struct patch_mode patch_mode_checkout_head = {
154.diff_cmd = { "diff-index", NULL },
155.apply_for_checkout = 1,
156.apply_check_args = { "-R", NULL },
157.is_reverse = 1,
158.prompt_mode = {
159N_("Discard mode change from index and worktree [y,n,q,a,d%s,?]? "),
160N_("Discard deletion from index and worktree [y,n,q,a,d%s,?]? "),
161N_("Discard addition from index and worktree [y,n,q,a,d%s,?]? "),
162N_("Discard this hunk from index and worktree [y,n,q,a,d%s,?]? "),
163},
164.edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
165"will immediately be marked for discarding."),
166.help_patch_text =
167N_("y - discard this hunk from index and worktree\n"
168"n - do not discard this hunk from index and worktree\n"
169"q - quit; do not discard this hunk or any of the remaining "
170"ones\n"
171"a - discard this hunk and all later hunks in the file\n"
172"d - do not discard this hunk or any of the later hunks in "
173"the file\n"),
174};
175
176static struct patch_mode patch_mode_checkout_nothead = {
177.diff_cmd = { "diff-index", "-R", NULL },
178.apply_for_checkout = 1,
179.apply_check_args = { NULL },
180.prompt_mode = {
181N_("Apply mode change to index and worktree [y,n,q,a,d%s,?]? "),
182N_("Apply deletion to index and worktree [y,n,q,a,d%s,?]? "),
183N_("Apply addition to index and worktree [y,n,q,a,d%s,?]? "),
184N_("Apply this hunk to index and worktree [y,n,q,a,d%s,?]? "),
185},
186.edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
187"will immediately be marked for applying."),
188.help_patch_text =
189N_("y - apply this hunk to index and worktree\n"
190"n - do not apply this hunk to index and worktree\n"
191"q - quit; do not apply this hunk or any of the remaining "
192"ones\n"
193"a - apply this hunk and all later hunks in the file\n"
194"d - do not apply this hunk or any of the later hunks in "
195"the file\n"),
196};
197
198static struct patch_mode patch_mode_worktree_head = {
199.diff_cmd = { "diff-index", NULL },
200.apply_args = { "-R", NULL },
201.apply_check_args = { "-R", NULL },
202.is_reverse = 1,
203.prompt_mode = {
204N_("Discard mode change from worktree [y,n,q,a,d%s,?]? "),
205N_("Discard deletion from worktree [y,n,q,a,d%s,?]? "),
206N_("Discard addition from worktree [y,n,q,a,d%s,?]? "),
207N_("Discard this hunk from worktree [y,n,q,a,d%s,?]? "),
208},
209.edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
210"will immediately be marked for discarding."),
211.help_patch_text =
212N_("y - discard this hunk from worktree\n"
213"n - do not discard this hunk from worktree\n"
214"q - quit; do not discard this hunk or any of the remaining "
215"ones\n"
216"a - discard this hunk and all later hunks in the file\n"
217"d - do not discard this hunk or any of the later hunks in "
218"the file\n"),
219};
220
221static struct patch_mode patch_mode_worktree_nothead = {
222.diff_cmd = { "diff-index", "-R", NULL },
223.apply_args = { NULL },
224.apply_check_args = { NULL },
225.prompt_mode = {
226N_("Apply mode change to worktree [y,n,q,a,d%s,?]? "),
227N_("Apply deletion to worktree [y,n,q,a,d%s,?]? "),
228N_("Apply addition to worktree [y,n,q,a,d%s,?]? "),
229N_("Apply this hunk to worktree [y,n,q,a,d%s,?]? "),
230},
231.edit_hunk_hint = N_("If the patch applies cleanly, the edited hunk "
232"will immediately be marked for applying."),
233.help_patch_text =
234N_("y - apply this hunk to worktree\n"
235"n - do not apply this hunk to worktree\n"
236"q - quit; do not apply this hunk or any of the remaining "
237"ones\n"
238"a - apply this hunk and all later hunks in the file\n"
239"d - do not apply this hunk or any of the later hunks in "
240"the file\n"),
241};
242
243struct hunk_header {
244unsigned long old_offset, old_count, new_offset, new_count;
245/*
246* Start/end offsets to the extra text after the second `@@` in the
247* hunk header, e.g. the function signature. This is expected to
248* include the newline.
249*/
250size_t extra_start, extra_end, colored_extra_start, colored_extra_end;
251unsigned suppress_colored_line_range:1;
252};
253
254struct hunk {
255size_t start, end, colored_start, colored_end, splittable_into;
256ssize_t delta;
257enum { UNDECIDED_HUNK = 0, SKIP_HUNK, USE_HUNK } use;
258struct hunk_header header;
259};
260
261struct add_p_state {
262struct add_i_state s;
263struct strbuf answer, buf;
264
265/* parsed diff */
266struct strbuf plain, colored;
267struct file_diff {
268struct hunk head;
269struct hunk *hunk;
270size_t hunk_nr, hunk_alloc;
271unsigned deleted:1, added:1, mode_change:1,binary:1;
272} *file_diff;
273size_t file_diff_nr;
274
275/* patch mode */
276struct patch_mode *mode;
277const char *revision;
278};
279
280static void add_p_state_clear(struct add_p_state *s)
281{
282size_t i;
283
284strbuf_release(&s->answer);
285strbuf_release(&s->buf);
286strbuf_release(&s->plain);
287strbuf_release(&s->colored);
288for (i = 0; i < s->file_diff_nr; i++)
289free(s->file_diff[i].hunk);
290free(s->file_diff);
291clear_add_i_state(&s->s);
292}
293
294__attribute__((format (printf, 2, 3)))
295static void err(struct add_p_state *s, const char *fmt, ...)
296{
297va_list args;
298
299va_start(args, fmt);
300fputs(s->s.error_color, stdout);
301vprintf(fmt, args);
302puts(s->s.reset_color);
303va_end(args);
304}
305
306LAST_ARG_MUST_BE_NULL
307static void setup_child_process(struct add_p_state *s,
308struct child_process *cp, ...)
309{
310va_list ap;
311const char *arg;
312
313va_start(ap, cp);
314while ((arg = va_arg(ap, const char *)))
315strvec_push(&cp->args, arg);
316va_end(ap);
317
318cp->git_cmd = 1;
319strvec_pushf(&cp->env,
320INDEX_ENVIRONMENT "=%s", s->s.r->index_file);
321}
322
323static int parse_range(const char **p,
324unsigned long *offset, unsigned long *count)
325{
326char *pend;
327
328*offset = strtoul(*p, &pend, 10);
329if (pend == *p)
330return -1;
331if (*pend != ',') {
332*count = 1;
333*p = pend;
334return 0;
335}
336*count = strtoul(pend + 1, (char **)p, 10);
337return *p == pend + 1 ? -1 : 0;
338}
339
340static int parse_hunk_header(struct add_p_state *s, struct hunk *hunk)
341{
342struct hunk_header *header = &hunk->header;
343const char *line = s->plain.buf + hunk->start, *p = line;
344char *eol = memchr(p, '\n', s->plain.len - hunk->start);
345
346if (!eol)
347eol = s->plain.buf + s->plain.len;
348
349if (!skip_prefix(p, "@@ -", &p) ||
350parse_range(&p, &header->old_offset, &header->old_count) < 0 ||
351!skip_prefix(p, " +", &p) ||
352parse_range(&p, &header->new_offset, &header->new_count) < 0 ||
353!skip_prefix(p, " @@", &p))
354return error(_("could not parse hunk header '%.*s'"),
355(int)(eol - line), line);
356
357hunk->start = eol - s->plain.buf + (*eol == '\n');
358header->extra_start = p - s->plain.buf;
359header->extra_end = hunk->start;
360
361if (!s->colored.len) {
362header->colored_extra_start = header->colored_extra_end = 0;
363return 0;
364}
365
366/* Now find the extra text in the colored diff */
367line = s->colored.buf + hunk->colored_start;
368eol = memchr(line, '\n', s->colored.len - hunk->colored_start);
369if (!eol)
370eol = s->colored.buf + s->colored.len;
371p = memmem(line, eol - line, "@@ -", 4);
372if (p && (p = memmem(p + 4, eol - p - 4, " @@", 3))) {
373header->colored_extra_start = p + 3 - s->colored.buf;
374} else {
375/* could not parse colored hunk header, leave as-is */
376header->colored_extra_start = hunk->colored_start;
377header->suppress_colored_line_range = 1;
378}
379hunk->colored_start = eol - s->colored.buf + (*eol == '\n');
380header->colored_extra_end = hunk->colored_start;
381
382return 0;
383}
384
385static int is_octal(const char *p, size_t len)
386{
387if (!len)
388return 0;
389
390while (len--)
391if (*p < '0' || *(p++) > '7')
392return 0;
393return 1;
394}
395
396static void complete_file(char marker, struct hunk *hunk)
397{
398if (marker == '-' || marker == '+')
399/*
400* Last hunk ended in non-context line (i.e. it
401* appended lines to the file, so there are no
402* trailing context lines).
403*/
404hunk->splittable_into++;
405}
406
407/* Empty context lines may omit the leading ' ' */
408static int normalize_marker(const char *p)
409{
410return p[0] == '\n' || (p[0] == '\r' && p[1] == '\n') ? ' ' : p[0];
411}
412
413static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
414{
415struct strvec args = STRVEC_INIT;
416const char *diff_algorithm = s->s.interactive_diff_algorithm;
417struct strbuf *plain = &s->plain, *colored = NULL;
418struct child_process cp = CHILD_PROCESS_INIT;
419char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
420size_t file_diff_alloc = 0, i, color_arg_index;
421struct file_diff *file_diff = NULL;
422struct hunk *hunk = NULL;
423int res;
424
425strvec_pushv(&args, s->mode->diff_cmd);
426if (diff_algorithm)
427strvec_pushf(&args, "--diff-algorithm=%s", diff_algorithm);
428if (s->revision) {
429struct object_id oid;
430strvec_push(&args,
431/* could be on an unborn branch */
432!strcmp("HEAD", s->revision) &&
433repo_get_oid(the_repository, "HEAD", &oid) ?
434empty_tree_oid_hex(the_repository->hash_algo) : s->revision);
435}
436color_arg_index = args.nr;
437/* Use `--no-color` explicitly, just in case `diff.color = always`. */
438strvec_pushl(&args, "--no-color", "--ignore-submodules=dirty", "-p",
439"--", NULL);
440for (i = 0; i < ps->nr; i++)
441strvec_push(&args, ps->items[i].original);
442
443setup_child_process(s, &cp, NULL);
444strvec_pushv(&cp.args, args.v);
445res = capture_command(&cp, plain, 0);
446if (res) {
447strvec_clear(&args);
448return error(_("could not parse diff"));
449}
450if (!plain->len) {
451strvec_clear(&args);
452return 0;
453}
454strbuf_complete_line(plain);
455
456if (want_color_fd(1, -1)) {
457struct child_process colored_cp = CHILD_PROCESS_INIT;
458const char *diff_filter = s->s.interactive_diff_filter;
459
460setup_child_process(s, &colored_cp, NULL);
461xsnprintf((char *)args.v[color_arg_index], 8, "--color");
462strvec_pushv(&colored_cp.args, args.v);
463colored = &s->colored;
464res = capture_command(&colored_cp, colored, 0);
465strvec_clear(&args);
466if (res)
467return error(_("could not parse colored diff"));
468
469if (diff_filter) {
470struct child_process filter_cp = CHILD_PROCESS_INIT;
471
472setup_child_process(s, &filter_cp,
473diff_filter, NULL);
474filter_cp.git_cmd = 0;
475filter_cp.use_shell = 1;
476strbuf_reset(&s->buf);
477if (pipe_command(&filter_cp,
478colored->buf, colored->len,
479&s->buf, colored->len,
480NULL, 0) < 0)
481return error(_("failed to run '%s'"),
482diff_filter);
483strbuf_swap(colored, &s->buf);
484}
485
486strbuf_complete_line(colored);
487colored_p = colored->buf;
488colored_pend = colored_p + colored->len;
489}
490strvec_clear(&args);
491
492/* parse files and hunks */
493p = plain->buf;
494pend = p + plain->len;
495while (p != pend) {
496char *eol = memchr(p, '\n', pend - p);
497const char *deleted = NULL, *mode_change = NULL;
498char ch = normalize_marker(p);
499
500if (!eol)
501eol = pend;
502
503if (starts_with(p, "diff ") ||
504starts_with(p, "* Unmerged path ")) {
505complete_file(marker, hunk);
506ALLOC_GROW_BY(s->file_diff, s->file_diff_nr, 1,
507file_diff_alloc);
508file_diff = s->file_diff + s->file_diff_nr - 1;
509hunk = &file_diff->head;
510hunk->start = p - plain->buf;
511if (colored_p)
512hunk->colored_start = colored_p - colored->buf;
513marker = '\0';
514} else if (p == plain->buf)
515BUG("diff starts with unexpected line:\n"
516"%.*s\n", (int)(eol - p), p);
517else if (file_diff->deleted)
518; /* keep the rest of the file in a single "hunk" */
519else if (starts_with(p, "@@ ") ||
520(hunk == &file_diff->head &&
521(skip_prefix(p, "deleted file", &deleted)))) {
522if (marker == '-' || marker == '+')
523/*
524* Should not happen; previous hunk did not end
525* in a context line? Handle it anyway.
526*/
527hunk->splittable_into++;
528
529ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
530file_diff->hunk_alloc);
531hunk = file_diff->hunk + file_diff->hunk_nr - 1;
532
533hunk->start = p - plain->buf;
534if (colored)
535hunk->colored_start = colored_p - colored->buf;
536
537if (deleted)
538file_diff->deleted = 1;
539else if (parse_hunk_header(s, hunk) < 0)
540return -1;
541
542/*
543* Start counting into how many hunks this one can be
544* split
545*/
546marker = ch;
547} else if (hunk == &file_diff->head &&
548starts_with(p, "new file")) {
549file_diff->added = 1;
550} else if (hunk == &file_diff->head &&
551skip_prefix(p, "old mode ", &mode_change) &&
552is_octal(mode_change, eol - mode_change)) {
553if (file_diff->mode_change)
554BUG("double mode change?\n\n%.*s",
555(int)(eol - plain->buf), plain->buf);
556if (file_diff->hunk_nr)
557BUG("mode change in the middle?\n\n%.*s",
558(int)(eol - plain->buf), plain->buf);
559
560/*
561* Do *not* change `hunk`: the mode change pseudo-hunk
562* is _part of_ the header "hunk".
563*/
564file_diff->mode_change = 1;
565ALLOC_GROW_BY(file_diff->hunk, file_diff->hunk_nr, 1,
566file_diff->hunk_alloc);
567file_diff->hunk->start = p - plain->buf;
568if (colored_p)
569file_diff->hunk->colored_start =
570colored_p - colored->buf;
571} else if (hunk == &file_diff->head &&
572skip_prefix(p, "new mode ", &mode_change) &&
573is_octal(mode_change, eol - mode_change)) {
574
575/*
576* Extend the "mode change" pseudo-hunk to include also
577* the "new mode" line.
578*/
579if (!file_diff->mode_change)
580BUG("'new mode' without 'old mode'?\n\n%.*s",
581(int)(eol - plain->buf), plain->buf);
582if (file_diff->hunk_nr != 1)
583BUG("mode change in the middle?\n\n%.*s",
584(int)(eol - plain->buf), plain->buf);
585if (p - plain->buf != file_diff->hunk->end)
586BUG("'new mode' does not immediately follow "
587"'old mode'?\n\n%.*s",
588(int)(eol - plain->buf), plain->buf);
589} else if (hunk == &file_diff->head &&
590starts_with(p, "Binary files "))
591file_diff->binary = 1;
592
593if (!!file_diff->deleted + !!file_diff->added +
594!!file_diff->mode_change > 1)
595BUG("diff can only contain delete *or* add *or* a "
596"mode change?!?\n%.*s",
597(int)(eol - (plain->buf + file_diff->head.start)),
598plain->buf + file_diff->head.start);
599
600if ((marker == '-' || marker == '+') && ch == ' ')
601hunk->splittable_into++;
602if (marker && ch != '\\')
603marker = ch;
604
605p = eol == pend ? pend : eol + 1;
606hunk->end = p - plain->buf;
607
608if (colored) {
609char *colored_eol = memchr(colored_p, '\n',
610colored_pend - colored_p);
611if (colored_eol)
612colored_p = colored_eol + 1;
613else if (p != pend)
614/* non-colored has more lines? */
615goto mismatched_output;
616else if (colored_p == colored_pend)
617/* last line has no matching colored one? */
618goto mismatched_output;
619else
620colored_p = colored_pend;
621
622hunk->colored_end = colored_p - colored->buf;
623}
624
625if (mode_change) {
626if (file_diff->hunk_nr != 1)
627BUG("mode change in hunk #%d???",
628(int)file_diff->hunk_nr);
629/* Adjust the end of the "mode change" pseudo-hunk */
630file_diff->hunk->end = hunk->end;
631if (colored)
632file_diff->hunk->colored_end = hunk->colored_end;
633}
634}
635complete_file(marker, hunk);
636
637/* non-colored shorter than colored? */
638if (colored_p != colored_pend) {
639mismatched_output:
640error(_("mismatched output from interactive.diffFilter"));
641advise(_("Your filter must maintain a one-to-one correspondence\n"
642"between its input and output lines."));
643return -1;
644}
645
646return 0;
647}
648
649static size_t find_next_line(struct strbuf *sb, size_t offset)
650{
651char *eol;
652
653if (offset >= sb->len)
654BUG("looking for next line beyond buffer (%d >= %d)\n%s",
655(int)offset, (int)sb->len, sb->buf);
656
657eol = memchr(sb->buf + offset, '\n', sb->len - offset);
658if (!eol)
659return sb->len;
660return eol - sb->buf + 1;
661}
662
663static void render_hunk(struct add_p_state *s, struct hunk *hunk,
664ssize_t delta, int colored, struct strbuf *out)
665{
666struct hunk_header *header = &hunk->header;
667
668if (hunk->header.old_offset != 0 || hunk->header.new_offset != 0) {
669/*
670* Generate the hunk header dynamically, except for special
671* hunks (such as the diff header).
672*/
673const char *p;
674size_t len;
675unsigned long old_offset = header->old_offset;
676unsigned long new_offset = header->new_offset;
677
678if (!colored) {
679p = s->plain.buf + header->extra_start;
680len = header->extra_end - header->extra_start;
681} else if (header->suppress_colored_line_range) {
682strbuf_add(out,
683s->colored.buf + header->colored_extra_start,
684header->colored_extra_end -
685header->colored_extra_start);
686
687strbuf_add(out, s->colored.buf + hunk->colored_start,
688hunk->colored_end - hunk->colored_start);
689return;
690} else {
691strbuf_addstr(out, s->s.fraginfo_color);
692p = s->colored.buf + header->colored_extra_start;
693len = header->colored_extra_end
694- header->colored_extra_start;
695}
696
697if (s->mode->is_reverse)
698old_offset -= delta;
699else
700new_offset += delta;
701
702strbuf_addf(out, "@@ -%lu", old_offset);
703if (header->old_count != 1)
704strbuf_addf(out, ",%lu", header->old_count);
705strbuf_addf(out, " +%lu", new_offset);
706if (header->new_count != 1)
707strbuf_addf(out, ",%lu", header->new_count);
708strbuf_addstr(out, " @@");
709
710if (len)
711strbuf_add(out, p, len);
712else if (colored)
713strbuf_addf(out, "%s\n", s->s.reset_color);
714else
715strbuf_addch(out, '\n');
716}
717
718if (colored)
719strbuf_add(out, s->colored.buf + hunk->colored_start,
720hunk->colored_end - hunk->colored_start);
721else
722strbuf_add(out, s->plain.buf + hunk->start,
723hunk->end - hunk->start);
724}
725
726static void render_diff_header(struct add_p_state *s,
727struct file_diff *file_diff, int colored,
728struct strbuf *out)
729{
730/*
731* If there was a mode change, the first hunk is a pseudo hunk that
732* corresponds to the mode line in the header. If the user did not want
733* to stage that "hunk", we actually have to cut it out from the header.
734*/
735int skip_mode_change =
736file_diff->mode_change && file_diff->hunk->use != USE_HUNK;
737struct hunk *head = &file_diff->head, *first = file_diff->hunk;
738
739if (!skip_mode_change) {
740render_hunk(s, head, 0, colored, out);
741return;
742}
743
744if (colored) {
745const char *p = s->colored.buf;
746
747strbuf_add(out, p + head->colored_start,
748first->colored_start - head->colored_start);
749strbuf_add(out, p + first->colored_end,
750head->colored_end - first->colored_end);
751} else {
752const char *p = s->plain.buf;
753
754strbuf_add(out, p + head->start, first->start - head->start);
755strbuf_add(out, p + first->end, head->end - first->end);
756}
757}
758
759/* Coalesce hunks again that were split */
760static int merge_hunks(struct add_p_state *s, struct file_diff *file_diff,
761size_t *hunk_index, int use_all, struct hunk *merged)
762{
763size_t i = *hunk_index, delta;
764struct hunk *hunk = file_diff->hunk + i;
765/* `header` corresponds to the merged hunk */
766struct hunk_header *header = &merged->header, *next;
767
768if (!use_all && hunk->use != USE_HUNK)
769return 0;
770
771*merged = *hunk;
772/* We simply skip the colored part (if any) when merging hunks */
773merged->colored_start = merged->colored_end = 0;
774
775for (; i + 1 < file_diff->hunk_nr; i++) {
776hunk++;
777next = &hunk->header;
778
779/*
780* Stop merging hunks when:
781*
782* - the hunk is not selected for use, or
783* - the hunk does not overlap with the already-merged hunk(s)
784*/
785if ((!use_all && hunk->use != USE_HUNK) ||
786header->new_offset >= next->new_offset + merged->delta ||
787header->new_offset + header->new_count
788< next->new_offset + merged->delta)
789break;
790
791/*
792* If the hunks were not edited, and overlap, we can simply
793* extend the line range.
794*/
795if (merged->start < hunk->start && merged->end > hunk->start) {
796merged->end = hunk->end;
797merged->colored_end = hunk->colored_end;
798delta = 0;
799} else {
800const char *plain = s->plain.buf;
801size_t overlapping_line_count = header->new_offset
802+ header->new_count - merged->delta
803- next->new_offset;
804size_t overlap_end = hunk->start;
805size_t overlap_start = overlap_end;
806size_t overlap_next, len, j;
807
808/*
809* One of the hunks was edited: the modified hunk was
810* appended to the strbuf `s->plain`.
811*
812* Let's ensure that at least the last context line of
813* the first hunk overlaps with the corresponding line
814* of the second hunk, and then merge.
815*/
816for (j = 0; j < overlapping_line_count; j++) {
817overlap_next = find_next_line(&s->plain,
818overlap_end);
819
820if (overlap_next > hunk->end)
821BUG("failed to find %d context lines "
822"in:\n%.*s",
823(int)overlapping_line_count,
824(int)(hunk->end - hunk->start),
825plain + hunk->start);
826
827if (normalize_marker(&plain[overlap_end]) != ' ')
828return error(_("expected context line "
829"#%d in\n%.*s"),
830(int)(j + 1),
831(int)(hunk->end
832- hunk->start),
833plain + hunk->start);
834
835overlap_start = overlap_end;
836overlap_end = overlap_next;
837}
838len = overlap_end - overlap_start;
839
840if (len > merged->end - merged->start ||
841memcmp(plain + merged->end - len,
842plain + overlap_start, len))
843return error(_("hunks do not overlap:\n%.*s\n"
844"\tdoes not end with:\n%.*s"),
845(int)(merged->end - merged->start),
846plain + merged->start,
847(int)len, plain + overlap_start);
848
849/*
850* Since the start-end ranges are not adjacent, we
851* cannot simply take the union of the ranges. To
852* address that, we temporarily append the union of the
853* lines to the `plain` strbuf.
854*/
855if (merged->end != s->plain.len) {
856size_t start = s->plain.len;
857
858strbuf_add(&s->plain, plain + merged->start,
859merged->end - merged->start);
860plain = s->plain.buf;
861merged->start = start;
862merged->end = s->plain.len;
863}
864
865strbuf_add(&s->plain,
866plain + overlap_end,
867hunk->end - overlap_end);
868merged->end = s->plain.len;
869merged->splittable_into += hunk->splittable_into;
870delta = merged->delta;
871merged->delta += hunk->delta;
872}
873
874header->old_count = next->old_offset + next->old_count
875- header->old_offset;
876header->new_count = next->new_offset + delta
877+ next->new_count - header->new_offset;
878}
879
880if (i == *hunk_index)
881return 0;
882
883*hunk_index = i;
884return 1;
885}
886
887static void reassemble_patch(struct add_p_state *s,
888struct file_diff *file_diff, int use_all,
889struct strbuf *out)
890{
891struct hunk *hunk;
892size_t save_len = s->plain.len, i;
893ssize_t delta = 0;
894
895render_diff_header(s, file_diff, 0, out);
896
897for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
898struct hunk merged = { 0 };
899
900hunk = file_diff->hunk + i;
901if (!use_all && hunk->use != USE_HUNK)
902delta += hunk->header.old_count
903- hunk->header.new_count;
904else {
905/* merge overlapping hunks into a temporary hunk */
906if (merge_hunks(s, file_diff, &i, use_all, &merged))
907hunk = &merged;
908
909render_hunk(s, hunk, delta, 0, out);
910
911/*
912* In case `merge_hunks()` used `plain` as a scratch
913* pad (this happens when an edited hunk had to be
914* coalesced with another hunk).
915*/
916strbuf_setlen(&s->plain, save_len);
917
918delta += hunk->delta;
919}
920}
921}
922
923static int split_hunk(struct add_p_state *s, struct file_diff *file_diff,
924size_t hunk_index)
925{
926int colored = !!s->colored.len, first = 1;
927struct hunk *hunk = file_diff->hunk + hunk_index;
928size_t splittable_into;
929size_t end, colored_end, current, colored_current = 0, context_line_count;
930struct hunk_header remaining, *header;
931char marker, ch;
932
933if (hunk_index >= file_diff->hunk_nr)
934BUG("invalid hunk index: %d (must be >= 0 and < %d)",
935(int)hunk_index, (int)file_diff->hunk_nr);
936
937if (hunk->splittable_into < 2)
938return 0;
939splittable_into = hunk->splittable_into;
940
941end = hunk->end;
942colored_end = hunk->colored_end;
943
944remaining = hunk->header;
945
946file_diff->hunk_nr += splittable_into - 1;
947ALLOC_GROW(file_diff->hunk, file_diff->hunk_nr, file_diff->hunk_alloc);
948if (hunk_index + splittable_into < file_diff->hunk_nr)
949memmove(file_diff->hunk + hunk_index + splittable_into,
950file_diff->hunk + hunk_index + 1,
951(file_diff->hunk_nr - hunk_index - splittable_into)
952* sizeof(*hunk));
953hunk = file_diff->hunk + hunk_index;
954hunk->splittable_into = 1;
955memset(hunk + 1, 0, (splittable_into - 1) * sizeof(*hunk));
956
957header = &hunk->header;
958header->old_count = header->new_count = 0;
959
960current = hunk->start;
961if (colored)
962colored_current = hunk->colored_start;
963marker = '\0';
964context_line_count = 0;
965
966while (splittable_into > 1) {
967ch = normalize_marker(&s->plain.buf[current]);
968
969if (!ch)
970BUG("buffer overrun while splitting hunks");
971
972/*
973* Is this the first context line after a chain of +/- lines?
974* Then record the start of the next split hunk.
975*/
976if ((marker == '-' || marker == '+') && ch == ' ') {
977first = 0;
978hunk[1].start = current;
979if (colored)
980hunk[1].colored_start = colored_current;
981context_line_count = 0;
982}
983
984/*
985* Was the previous line a +/- one? Alternatively, is this the
986* first line (and not a +/- one)?
987*
988* Then just increment the appropriate counter and continue
989* with the next line.
990*/
991if (marker != ' ' || (ch != '-' && ch != '+')) {
992next_hunk_line:
993/* Comment lines are attached to the previous line */
994if (ch == '\\')
995ch = marker ? marker : ' ';
996
997/* current hunk not done yet */
998if (ch == ' ')
999context_line_count++;
1000else if (ch == '-')
1001header->old_count++;
1002else if (ch == '+')
1003header->new_count++;
1004else
1005BUG("unhandled diff marker: '%c'", ch);
1006marker = ch;
1007current = find_next_line(&s->plain, current);
1008if (colored)
1009colored_current =
1010find_next_line(&s->colored,
1011colored_current);
1012continue;
1013}
1014
1015/*
1016* We got us the start of a new hunk!
1017*
1018* This is a context line, so it is shared with the previous
1019* hunk, if any.
1020*/
1021
1022if (first) {
1023if (header->old_count || header->new_count)
1024BUG("counts are off: %d/%d",
1025(int)header->old_count,
1026(int)header->new_count);
1027
1028header->old_count = context_line_count;
1029header->new_count = context_line_count;
1030context_line_count = 0;
1031first = 0;
1032goto next_hunk_line;
1033}
1034
1035remaining.old_offset += header->old_count;
1036remaining.old_count -= header->old_count;
1037remaining.new_offset += header->new_count;
1038remaining.new_count -= header->new_count;
1039
1040/* initialize next hunk header's offsets */
1041hunk[1].header.old_offset =
1042header->old_offset + header->old_count;
1043hunk[1].header.new_offset =
1044header->new_offset + header->new_count;
1045
1046/* add one split hunk */
1047header->old_count += context_line_count;
1048header->new_count += context_line_count;
1049
1050hunk->end = current;
1051if (colored)
1052hunk->colored_end = colored_current;
1053
1054hunk++;
1055hunk->splittable_into = 1;
1056hunk->use = hunk[-1].use;
1057header = &hunk->header;
1058
1059header->old_count = header->new_count = context_line_count;
1060context_line_count = 0;
1061
1062splittable_into--;
1063marker = ch;
1064}
1065
1066/* last hunk simply gets the rest */
1067if (header->old_offset != remaining.old_offset)
1068BUG("miscounted old_offset: %lu != %lu",
1069header->old_offset, remaining.old_offset);
1070if (header->new_offset != remaining.new_offset)
1071BUG("miscounted new_offset: %lu != %lu",
1072header->new_offset, remaining.new_offset);
1073header->old_count = remaining.old_count;
1074header->new_count = remaining.new_count;
1075hunk->end = end;
1076if (colored)
1077hunk->colored_end = colored_end;
1078
1079return 0;
1080}
1081
1082static void recolor_hunk(struct add_p_state *s, struct hunk *hunk)
1083{
1084const char *plain = s->plain.buf;
1085size_t current, eol, next;
1086
1087if (!s->colored.len)
1088return;
1089
1090hunk->colored_start = s->colored.len;
1091for (current = hunk->start; current < hunk->end; ) {
1092for (eol = current; eol < hunk->end; eol++)
1093if (plain[eol] == '\n')
1094break;
1095next = eol + (eol < hunk->end);
1096if (eol > current && plain[eol - 1] == '\r')
1097eol--;
1098
1099strbuf_addstr(&s->colored,
1100plain[current] == '-' ?
1101s->s.file_old_color :
1102plain[current] == '+' ?
1103s->s.file_new_color :
1104s->s.context_color);
1105strbuf_add(&s->colored, plain + current, eol - current);
1106strbuf_addstr(&s->colored, s->s.reset_color);
1107if (next > eol)
1108strbuf_add(&s->colored, plain + eol, next - eol);
1109current = next;
1110}
1111hunk->colored_end = s->colored.len;
1112}
1113
1114static int edit_hunk_manually(struct add_p_state *s, struct hunk *hunk)
1115{
1116size_t i;
1117
1118strbuf_reset(&s->buf);
1119strbuf_commented_addf(&s->buf, comment_line_str,
1120_("Manual hunk edit mode -- see bottom for "
1121"a quick guide.\n"));
1122render_hunk(s, hunk, 0, 0, &s->buf);
1123strbuf_commented_addf(&s->buf, comment_line_str,
1124_("---\n"
1125"To remove '%c' lines, make them ' ' lines "
1126"(context).\n"
1127"To remove '%c' lines, delete them.\n"
1128"Lines starting with %s will be removed.\n"),
1129s->mode->is_reverse ? '+' : '-',
1130s->mode->is_reverse ? '-' : '+',
1131comment_line_str);
1132strbuf_commented_addf(&s->buf, comment_line_str, "%s",
1133_(s->mode->edit_hunk_hint));
1134/*
1135* TRANSLATORS: 'it' refers to the patch mentioned in the previous
1136* messages.
1137*/
1138strbuf_commented_addf(&s->buf, comment_line_str,
1139_("If it does not apply cleanly, you will be "
1140"given an opportunity to\n"
1141"edit again. If all lines of the hunk are "
1142"removed, then the edit is\n"
1143"aborted and the hunk is left unchanged.\n"));
1144
1145if (strbuf_edit_interactively(the_repository, &s->buf,
1146"addp-hunk-edit.diff", NULL) < 0)
1147return -1;
1148
1149/* strip out commented lines */
1150hunk->start = s->plain.len;
1151for (i = 0; i < s->buf.len; ) {
1152size_t next = find_next_line(&s->buf, i);
1153
1154if (!starts_with(s->buf.buf + i, comment_line_str))
1155strbuf_add(&s->plain, s->buf.buf + i, next - i);
1156i = next;
1157}
1158
1159hunk->end = s->plain.len;
1160if (hunk->end == hunk->start)
1161/* The user aborted editing by deleting everything */
1162return 0;
1163
1164recolor_hunk(s, hunk);
1165
1166/*
1167* If the hunk header is intact, parse it, otherwise simply use the
1168* hunk header prior to editing (which will adjust `hunk->start` to
1169* skip the hunk header).
1170*/
1171if (s->plain.buf[hunk->start] == '@' &&
1172parse_hunk_header(s, hunk) < 0)
1173return error(_("could not parse hunk header"));
1174
1175return 1;
1176}
1177
1178static ssize_t recount_edited_hunk(struct add_p_state *s, struct hunk *hunk,
1179size_t orig_old_count, size_t orig_new_count)
1180{
1181struct hunk_header *header = &hunk->header;
1182size_t i;
1183
1184header->old_count = header->new_count = 0;
1185for (i = hunk->start; i < hunk->end; ) {
1186switch(normalize_marker(&s->plain.buf[i])) {
1187case '-':
1188header->old_count++;
1189break;
1190case '+':
1191header->new_count++;
1192break;
1193case ' ':
1194header->old_count++;
1195header->new_count++;
1196break;
1197}
1198
1199i = find_next_line(&s->plain, i);
1200}
1201
1202return orig_old_count - orig_new_count
1203- header->old_count + header->new_count;
1204}
1205
1206static int run_apply_check(struct add_p_state *s,
1207struct file_diff *file_diff)
1208{
1209struct child_process cp = CHILD_PROCESS_INIT;
1210
1211strbuf_reset(&s->buf);
1212reassemble_patch(s, file_diff, 1, &s->buf);
1213
1214setup_child_process(s, &cp,
1215"apply", "--check", NULL);
1216strvec_pushv(&cp.args, s->mode->apply_check_args);
1217if (pipe_command(&cp, s->buf.buf, s->buf.len, NULL, 0, NULL, 0))
1218return error(_("'git apply --cached' failed"));
1219
1220return 0;
1221}
1222
1223static int read_single_character(struct add_p_state *s)
1224{
1225if (s->s.use_single_key) {
1226int res = read_key_without_echo(&s->answer);
1227printf("%s\n", res == EOF ? "" : s->answer.buf);
1228return res;
1229}
1230
1231if (git_read_line_interactively(&s->answer) == EOF)
1232return EOF;
1233return 0;
1234}
1235
1236static int prompt_yesno(struct add_p_state *s, const char *prompt)
1237{
1238for (;;) {
1239color_fprintf(stdout, s->s.prompt_color, "%s", _(prompt));
1240fflush(stdout);
1241if (read_single_character(s) == EOF)
1242return -1;
1243/* do not limit to 1-byte input to allow 'no' etc. */
1244switch (tolower(s->answer.buf[0])) {
1245case 'n': return 0;
1246case 'y': return 1;
1247}
1248}
1249}
1250
1251static int edit_hunk_loop(struct add_p_state *s,
1252struct file_diff *file_diff, struct hunk *hunk)
1253{
1254size_t plain_len = s->plain.len, colored_len = s->colored.len;
1255struct hunk backup;
1256
1257backup = *hunk;
1258
1259for (;;) {
1260int res = edit_hunk_manually(s, hunk);
1261if (res == 0) {
1262/* abandoned */
1263*hunk = backup;
1264return -1;
1265}
1266
1267if (res > 0) {
1268hunk->delta +=
1269recount_edited_hunk(s, hunk,
1270backup.header.old_count,
1271backup.header.new_count);
1272if (!run_apply_check(s, file_diff))
1273return 0;
1274}
1275
1276/* Drop edits (they were appended to s->plain) */
1277strbuf_setlen(&s->plain, plain_len);
1278strbuf_setlen(&s->colored, colored_len);
1279*hunk = backup;
1280
1281/*
1282* TRANSLATORS: do not translate [y/n]
1283* The program will only accept that input at this point.
1284* Consider translating (saying "no" discards!) as
1285* (saying "n" for "no" discards!) if the translation
1286* of the word "no" does not start with n.
1287*/
1288res = prompt_yesno(s, _("Your edited hunk does not apply. "
1289"Edit again (saying \"no\" discards!) "
1290"[y/n]? "));
1291if (res < 1)
1292return -1;
1293}
1294}
1295
1296static int apply_for_checkout(struct add_p_state *s, struct strbuf *diff,
1297int is_reverse)
1298{
1299const char *reverse = is_reverse ? "-R" : NULL;
1300struct child_process check_index = CHILD_PROCESS_INIT;
1301struct child_process check_worktree = CHILD_PROCESS_INIT;
1302struct child_process apply_index = CHILD_PROCESS_INIT;
1303struct child_process apply_worktree = CHILD_PROCESS_INIT;
1304int applies_index, applies_worktree;
1305
1306setup_child_process(s, &check_index,
1307"apply", "--cached", "--check", reverse, NULL);
1308applies_index = !pipe_command(&check_index, diff->buf, diff->len,
1309NULL, 0, NULL, 0);
1310
1311setup_child_process(s, &check_worktree,
1312"apply", "--check", reverse, NULL);
1313applies_worktree = !pipe_command(&check_worktree, diff->buf, diff->len,
1314NULL, 0, NULL, 0);
1315
1316if (applies_worktree && applies_index) {
1317setup_child_process(s, &apply_index,
1318"apply", "--cached", reverse, NULL);
1319pipe_command(&apply_index, diff->buf, diff->len,
1320NULL, 0, NULL, 0);
1321
1322setup_child_process(s, &apply_worktree,
1323"apply", reverse, NULL);
1324pipe_command(&apply_worktree, diff->buf, diff->len,
1325NULL, 0, NULL, 0);
1326
1327return 1;
1328}
1329
1330if (!applies_index) {
1331err(s, _("The selected hunks do not apply to the index!"));
1332if (prompt_yesno(s, _("Apply them to the worktree "
1333"anyway? ")) > 0) {
1334setup_child_process(s, &apply_worktree,
1335"apply", reverse, NULL);
1336return pipe_command(&apply_worktree, diff->buf,
1337diff->len, NULL, 0, NULL, 0);
1338}
1339err(s, _("Nothing was applied.\n"));
1340} else
1341/* As a last resort, show the diff to the user */
1342fwrite(diff->buf, diff->len, 1, stdout);
1343
1344return 0;
1345}
1346
1347#define SUMMARY_HEADER_WIDTH 20
1348#define SUMMARY_LINE_WIDTH 80
1349static void summarize_hunk(struct add_p_state *s, struct hunk *hunk,
1350struct strbuf *out)
1351{
1352struct hunk_header *header = &hunk->header;
1353struct strbuf *plain = &s->plain;
1354size_t len = out->len, i;
1355
1356strbuf_addf(out, " -%lu,%lu +%lu,%lu ",
1357header->old_offset, header->old_count,
1358header->new_offset, header->new_count);
1359if (out->len - len < SUMMARY_HEADER_WIDTH)
1360strbuf_addchars(out, ' ',
1361SUMMARY_HEADER_WIDTH + len - out->len);
1362for (i = hunk->start; i < hunk->end; i = find_next_line(plain, i))
1363if (plain->buf[i] != ' ')
1364break;
1365if (i < hunk->end)
1366strbuf_add(out, plain->buf + i, find_next_line(plain, i) - i);
1367if (out->len - len > SUMMARY_LINE_WIDTH)
1368strbuf_setlen(out, len + SUMMARY_LINE_WIDTH);
1369strbuf_complete_line(out);
1370}
1371
1372#define DISPLAY_HUNKS_LINES 20
1373static size_t display_hunks(struct add_p_state *s,
1374struct file_diff *file_diff, size_t start_index)
1375{
1376size_t end_index = start_index + DISPLAY_HUNKS_LINES;
1377
1378if (end_index > file_diff->hunk_nr)
1379end_index = file_diff->hunk_nr;
1380
1381while (start_index < end_index) {
1382struct hunk *hunk = file_diff->hunk + start_index++;
1383
1384strbuf_reset(&s->buf);
1385strbuf_addf(&s->buf, "%c%2d: ", hunk->use == USE_HUNK ? '+'
1386: hunk->use == SKIP_HUNK ? '-' : ' ',
1387(int)start_index);
1388summarize_hunk(s, hunk, &s->buf);
1389fputs(s->buf.buf, stdout);
1390}
1391
1392return end_index;
1393}
1394
1395static const char help_patch_remainder[] =
1396N_("j - leave this hunk undecided, see next undecided hunk\n"
1397"J - leave this hunk undecided, see next hunk\n"
1398"k - leave this hunk undecided, see previous undecided hunk\n"
1399"K - leave this hunk undecided, see previous hunk\n"
1400"g - select a hunk to go to\n"
1401"/ - search for a hunk matching the given regex\n"
1402"s - split the current hunk into smaller hunks\n"
1403"e - manually edit the current hunk\n"
1404"p - print the current hunk, 'P' to use the pager\n"
1405"? - print help\n");
1406
1407static int patch_update_file(struct add_p_state *s,
1408struct file_diff *file_diff)
1409{
1410size_t hunk_index = 0;
1411ssize_t i, undecided_previous, undecided_next, rendered_hunk_index = -1;
1412struct hunk *hunk;
1413char ch;
1414struct child_process cp = CHILD_PROCESS_INIT;
1415int colored = !!s->colored.len, quit = 0, use_pager = 0;
1416enum prompt_mode_type prompt_mode_type;
1417enum {
1418ALLOW_GOTO_PREVIOUS_HUNK = 1 << 0,
1419ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK = 1 << 1,
1420ALLOW_GOTO_NEXT_HUNK = 1 << 2,
1421ALLOW_GOTO_NEXT_UNDECIDED_HUNK = 1 << 3,
1422ALLOW_SEARCH_AND_GOTO = 1 << 4,
1423ALLOW_SPLIT = 1 << 5,
1424ALLOW_EDIT = 1 << 6
1425} permitted = 0;
1426
1427/* Empty added files have no hunks */
1428if (!file_diff->hunk_nr && !file_diff->added)
1429return 0;
1430
1431strbuf_reset(&s->buf);
1432render_diff_header(s, file_diff, colored, &s->buf);
1433fputs(s->buf.buf, stdout);
1434for (;;) {
1435if (hunk_index >= file_diff->hunk_nr)
1436hunk_index = 0;
1437hunk = file_diff->hunk_nr
1438? file_diff->hunk + hunk_index
1439: &file_diff->head;
1440undecided_previous = -1;
1441undecided_next = -1;
1442
1443if (file_diff->hunk_nr) {
1444for (i = hunk_index - 1; i >= 0; i--)
1445if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1446undecided_previous = i;
1447break;
1448}
1449
1450for (i = hunk_index + 1; i < file_diff->hunk_nr; i++)
1451if (file_diff->hunk[i].use == UNDECIDED_HUNK) {
1452undecided_next = i;
1453break;
1454}
1455}
1456
1457/* Everything decided? */
1458if (undecided_previous < 0 && undecided_next < 0 &&
1459hunk->use != UNDECIDED_HUNK)
1460break;
1461
1462strbuf_reset(&s->buf);
1463if (file_diff->hunk_nr) {
1464if (rendered_hunk_index != hunk_index) {
1465if (use_pager) {
1466setup_pager();
1467sigchain_push(SIGPIPE, SIG_IGN);
1468}
1469render_hunk(s, hunk, 0, colored, &s->buf);
1470fputs(s->buf.buf, stdout);
1471rendered_hunk_index = hunk_index;
1472if (use_pager) {
1473sigchain_pop(SIGPIPE);
1474wait_for_pager();
1475use_pager = 0;
1476}
1477}
1478
1479strbuf_reset(&s->buf);
1480if (undecided_previous >= 0) {
1481permitted |= ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK;
1482strbuf_addstr(&s->buf, ",k");
1483}
1484if (hunk_index) {
1485permitted |= ALLOW_GOTO_PREVIOUS_HUNK;
1486strbuf_addstr(&s->buf, ",K");
1487}
1488if (undecided_next >= 0) {
1489permitted |= ALLOW_GOTO_NEXT_UNDECIDED_HUNK;
1490strbuf_addstr(&s->buf, ",j");
1491}
1492if (hunk_index + 1 < file_diff->hunk_nr) {
1493permitted |= ALLOW_GOTO_NEXT_HUNK;
1494strbuf_addstr(&s->buf, ",J");
1495}
1496if (file_diff->hunk_nr > 1) {
1497permitted |= ALLOW_SEARCH_AND_GOTO;
1498strbuf_addstr(&s->buf, ",g,/");
1499}
1500if (hunk->splittable_into > 1) {
1501permitted |= ALLOW_SPLIT;
1502strbuf_addstr(&s->buf, ",s");
1503}
1504if (hunk_index + 1 > file_diff->mode_change &&
1505!file_diff->deleted) {
1506permitted |= ALLOW_EDIT;
1507strbuf_addstr(&s->buf, ",e");
1508}
1509strbuf_addstr(&s->buf, ",p");
1510}
1511if (file_diff->deleted)
1512prompt_mode_type = PROMPT_DELETION;
1513else if (file_diff->added)
1514prompt_mode_type = PROMPT_ADDITION;
1515else if (file_diff->mode_change && !hunk_index)
1516prompt_mode_type = PROMPT_MODE_CHANGE;
1517else
1518prompt_mode_type = PROMPT_HUNK;
1519
1520printf("%s(%"PRIuMAX"/%"PRIuMAX") ", s->s.prompt_color,
1521(uintmax_t)hunk_index + 1,
1522(uintmax_t)(file_diff->hunk_nr
1523? file_diff->hunk_nr
1524: 1));
1525printf(_(s->mode->prompt_mode[prompt_mode_type]),
1526s->buf.buf);
1527if (*s->s.reset_color)
1528fputs(s->s.reset_color, stdout);
1529fflush(stdout);
1530if (read_single_character(s) == EOF)
1531break;
1532
1533if (!s->answer.len)
1534continue;
1535ch = tolower(s->answer.buf[0]);
1536
1537/* 'g' takes a hunk number and '/' takes a regexp */
1538if (s->answer.len != 1 && (ch != 'g' && ch != '/')) {
1539err(s, _("Only one letter is expected, got '%s'"), s->answer.buf);
1540continue;
1541}
1542if (ch == 'y') {
1543hunk->use = USE_HUNK;
1544soft_increment:
1545hunk_index = undecided_next < 0 ?
1546file_diff->hunk_nr : undecided_next;
1547} else if (ch == 'n') {
1548hunk->use = SKIP_HUNK;
1549goto soft_increment;
1550} else if (ch == 'a') {
1551if (file_diff->hunk_nr) {
1552for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1553hunk = file_diff->hunk + hunk_index;
1554if (hunk->use == UNDECIDED_HUNK)
1555hunk->use = USE_HUNK;
1556}
1557} else if (hunk->use == UNDECIDED_HUNK) {
1558hunk->use = USE_HUNK;
1559}
1560} else if (ch == 'd' || ch == 'q') {
1561if (file_diff->hunk_nr) {
1562for (; hunk_index < file_diff->hunk_nr; hunk_index++) {
1563hunk = file_diff->hunk + hunk_index;
1564if (hunk->use == UNDECIDED_HUNK)
1565hunk->use = SKIP_HUNK;
1566}
1567} else if (hunk->use == UNDECIDED_HUNK) {
1568hunk->use = SKIP_HUNK;
1569}
1570if (ch == 'q') {
1571quit = 1;
1572break;
1573}
1574} else if (s->answer.buf[0] == 'K') {
1575if (permitted & ALLOW_GOTO_PREVIOUS_HUNK)
1576hunk_index--;
1577else
1578err(s, _("No previous hunk"));
1579} else if (s->answer.buf[0] == 'J') {
1580if (permitted & ALLOW_GOTO_NEXT_HUNK)
1581hunk_index++;
1582else
1583err(s, _("No next hunk"));
1584} else if (s->answer.buf[0] == 'k') {
1585if (permitted & ALLOW_GOTO_PREVIOUS_UNDECIDED_HUNK)
1586hunk_index = undecided_previous;
1587else
1588err(s, _("No previous hunk"));
1589} else if (s->answer.buf[0] == 'j') {
1590if (permitted & ALLOW_GOTO_NEXT_UNDECIDED_HUNK)
1591hunk_index = undecided_next;
1592else
1593err(s, _("No next hunk"));
1594} else if (s->answer.buf[0] == 'g') {
1595char *pend;
1596unsigned long response;
1597
1598if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1599err(s, _("No other hunks to goto"));
1600continue;
1601}
1602strbuf_remove(&s->answer, 0, 1);
1603strbuf_trim(&s->answer);
1604i = hunk_index - DISPLAY_HUNKS_LINES / 2;
1605if (i < (int)file_diff->mode_change)
1606i = file_diff->mode_change;
1607while (s->answer.len == 0) {
1608i = display_hunks(s, file_diff, i);
1609printf("%s", i < file_diff->hunk_nr ?
1610_("go to which hunk (<ret> to see "
1611"more)? ") : _("go to which hunk? "));
1612fflush(stdout);
1613if (strbuf_getline(&s->answer,
1614stdin) == EOF)
1615break;
1616strbuf_trim_trailing_newline(&s->answer);
1617}
1618
1619strbuf_trim(&s->answer);
1620response = strtoul(s->answer.buf, &pend, 10);
1621if (*pend || pend == s->answer.buf)
1622err(s, _("Invalid number: '%s'"),
1623s->answer.buf);
1624else if (0 < response && response <= file_diff->hunk_nr)
1625hunk_index = response - 1;
1626else
1627err(s, Q_("Sorry, only %d hunk available.",
1628"Sorry, only %d hunks available.",
1629file_diff->hunk_nr),
1630(int)file_diff->hunk_nr);
1631} else if (s->answer.buf[0] == '/') {
1632regex_t regex;
1633int ret;
1634
1635if (!(permitted & ALLOW_SEARCH_AND_GOTO)) {
1636err(s, _("No other hunks to search"));
1637continue;
1638}
1639strbuf_remove(&s->answer, 0, 1);
1640strbuf_trim_trailing_newline(&s->answer);
1641if (s->answer.len == 0) {
1642printf("%s", _("search for regex? "));
1643fflush(stdout);
1644if (strbuf_getline(&s->answer,
1645stdin) == EOF)
1646break;
1647strbuf_trim_trailing_newline(&s->answer);
1648if (s->answer.len == 0)
1649continue;
1650}
1651ret = regcomp(®ex, s->answer.buf,
1652REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
1653if (ret) {
1654char errbuf[1024];
1655
1656regerror(ret, ®ex, errbuf, sizeof(errbuf));
1657err(s, _("Malformed search regexp %s: %s"),
1658s->answer.buf, errbuf);
1659continue;
1660}
1661i = hunk_index;
1662for (;;) {
1663/* render the hunk into a scratch buffer */
1664render_hunk(s, file_diff->hunk + i, 0, 0,
1665&s->buf);
1666if (regexec(®ex, s->buf.buf, 0, NULL, 0)
1667!= REG_NOMATCH)
1668break;
1669i++;
1670if (i == file_diff->hunk_nr)
1671i = 0;
1672if (i != hunk_index)
1673continue;
1674err(s, _("No hunk matches the given pattern"));
1675break;
1676}
1677regfree(®ex);
1678hunk_index = i;
1679} else if (s->answer.buf[0] == 's') {
1680size_t splittable_into = hunk->splittable_into;
1681if (!(permitted & ALLOW_SPLIT)) {
1682err(s, _("Sorry, cannot split this hunk"));
1683} else if (!split_hunk(s, file_diff,
1684hunk - file_diff->hunk)) {
1685color_fprintf_ln(stdout, s->s.header_color,
1686_("Split into %d hunks."),
1687(int)splittable_into);
1688rendered_hunk_index = -1;
1689}
1690} else if (s->answer.buf[0] == 'e') {
1691if (!(permitted & ALLOW_EDIT))
1692err(s, _("Sorry, cannot edit this hunk"));
1693else if (edit_hunk_loop(s, file_diff, hunk) >= 0) {
1694hunk->use = USE_HUNK;
1695goto soft_increment;
1696}
1697} else if (ch == 'p') {
1698rendered_hunk_index = -1;
1699use_pager = (s->answer.buf[0] == 'P') ? 1 : 0;
1700} else if (s->answer.buf[0] == '?') {
1701const char *p = _(help_patch_remainder), *eol = p;
1702
1703color_fprintf(stdout, s->s.help_color, "%s",
1704_(s->mode->help_patch_text));
1705
1706/*
1707* Show only those lines of the remainder that are
1708* actually applicable with the current hunk.
1709*/
1710for (; *p; p = eol + (*eol == '\n')) {
1711eol = strchrnul(p, '\n');
1712
1713/*
1714* `s->buf` still contains the part of the
1715* commands shown in the prompt that are not
1716* always available.
1717*/
1718if (*p != '?' && !strchr(s->buf.buf, *p))
1719continue;
1720
1721color_fprintf_ln(stdout, s->s.help_color,
1722"%.*s", (int)(eol - p), p);
1723}
1724} else {
1725err(s, _("Unknown command '%s' (use '?' for help)"),
1726s->answer.buf);
1727}
1728}
1729
1730/* Any hunk to be used? */
1731for (i = 0; i < file_diff->hunk_nr; i++)
1732if (file_diff->hunk[i].use == USE_HUNK)
1733break;
1734
1735if (i < file_diff->hunk_nr ||
1736(!file_diff->hunk_nr && file_diff->head.use == USE_HUNK)) {
1737/* At least one hunk selected: apply */
1738strbuf_reset(&s->buf);
1739reassemble_patch(s, file_diff, 0, &s->buf);
1740
1741discard_index(s->s.r->index);
1742if (s->mode->apply_for_checkout)
1743apply_for_checkout(s, &s->buf,
1744s->mode->is_reverse);
1745else {
1746setup_child_process(s, &cp, "apply", NULL);
1747strvec_pushv(&cp.args, s->mode->apply_args);
1748if (pipe_command(&cp, s->buf.buf, s->buf.len,
1749NULL, 0, NULL, 0))
1750error(_("'git apply' failed"));
1751}
1752if (repo_read_index(s->s.r) >= 0)
1753repo_refresh_and_write_index(s->s.r, REFRESH_QUIET, 0,
17541, NULL, NULL, NULL);
1755}
1756
1757putchar('\n');
1758return quit;
1759}
1760
1761int run_add_p(struct repository *r, enum add_p_mode mode,
1762const char *revision, const struct pathspec *ps)
1763{
1764struct add_p_state s = {
1765{ r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1766};
1767size_t i, binary_count = 0;
1768
1769init_add_i_state(&s.s, r);
1770
1771if (mode == ADD_P_STASH)
1772s.mode = &patch_mode_stash;
1773else if (mode == ADD_P_RESET) {
1774if (!revision || !strcmp(revision, "HEAD"))
1775s.mode = &patch_mode_reset_head;
1776else
1777s.mode = &patch_mode_reset_nothead;
1778} else if (mode == ADD_P_CHECKOUT) {
1779if (!revision)
1780s.mode = &patch_mode_checkout_index;
1781else if (!strcmp(revision, "HEAD"))
1782s.mode = &patch_mode_checkout_head;
1783else
1784s.mode = &patch_mode_checkout_nothead;
1785} else if (mode == ADD_P_WORKTREE) {
1786if (!revision)
1787s.mode = &patch_mode_checkout_index;
1788else if (!strcmp(revision, "HEAD"))
1789s.mode = &patch_mode_worktree_head;
1790else
1791s.mode = &patch_mode_worktree_nothead;
1792} else
1793s.mode = &patch_mode_add;
1794s.revision = revision;
1795
1796discard_index(r->index);
1797if (repo_read_index(r) < 0 ||
1798(!s.mode->index_only &&
1799repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1800NULL, NULL, NULL) < 0) ||
1801parse_diff(&s, ps) < 0) {
1802add_p_state_clear(&s);
1803return -1;
1804}
1805
1806for (i = 0; i < s.file_diff_nr; i++)
1807if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
1808binary_count++;
1809else if (patch_update_file(&s, s.file_diff + i))
1810break;
1811
1812if (s.file_diff_nr == 0)
1813err(&s, _("No changes."));
1814else if (binary_count == s.file_diff_nr)
1815err(&s, _("Only binary files changed."));
1816
1817add_p_state_clear(&s);
1818return 0;
1819}
1820