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