builtin/apply: move 'p_value_known' global into 'struct apply_state'
[git/debian.git] / builtin / apply.c
blobe1b68d4cb75da74f2d567133534514d19cde9302
1 /*
2 * apply.c
4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
8 */
9 #include "cache.h"
10 #include "lockfile.h"
11 #include "cache-tree.h"
12 #include "quote.h"
13 #include "blob.h"
14 #include "delta.h"
15 #include "builtin.h"
16 #include "string-list.h"
17 #include "dir.h"
18 #include "diff.h"
19 #include "parse-options.h"
20 #include "xdiff-interface.h"
21 #include "ll-merge.h"
22 #include "rerere.h"
24 struct apply_state {
25 const char *prefix;
26 int prefix_length;
28 /* These control what gets looked at and modified */
29 int apply; /* this is not a dry-run */
30 int cached; /* apply to the index only */
31 int check; /* preimage must match working tree, don't actually apply */
32 int check_index; /* preimage must match the indexed version */
33 int update_index; /* check_index && apply */
35 /* These control cosmetic aspect of the output */
36 int diffstat; /* just show a diffstat, and don't actually apply */
37 int numstat; /* just show a numeric diffstat, and don't actually apply */
38 int summary; /* just report creation, deletion, etc, and don't actually apply */
40 /* These boolean parameters control how the apply is done */
41 int allow_overlap;
42 int apply_in_reverse;
43 int apply_with_reject;
44 int apply_verbosely;
45 int no_add;
46 int threeway;
47 int unidiff_zero;
48 int unsafe_paths;
50 /* Other non boolean parameters */
51 const char *fake_ancestor;
52 const char *patch_input_file;
53 int line_termination;
54 int p_value;
55 int p_value_known;
56 unsigned int p_context;
58 /* Exclude and include path parameters */
59 struct string_list limit_by_name;
60 int has_include;
63 static int newfd = -1;
65 static const char * const apply_usage[] = {
66 N_("git apply [<options>] [<patch>...]"),
67 NULL
70 static enum ws_error_action {
71 nowarn_ws_error,
72 warn_on_ws_error,
73 die_on_ws_error,
74 correct_ws_error
75 } ws_error_action = warn_on_ws_error;
76 static int whitespace_error;
77 static int squelch_whitespace_errors = 5;
78 static int applied_after_fixing_ws;
80 static enum ws_ignore {
81 ignore_ws_none,
82 ignore_ws_change
83 } ws_ignore_action = ignore_ws_none;
86 static struct strbuf root = STRBUF_INIT;
88 static void parse_whitespace_option(const char *option)
90 if (!option) {
91 ws_error_action = warn_on_ws_error;
92 return;
94 if (!strcmp(option, "warn")) {
95 ws_error_action = warn_on_ws_error;
96 return;
98 if (!strcmp(option, "nowarn")) {
99 ws_error_action = nowarn_ws_error;
100 return;
102 if (!strcmp(option, "error")) {
103 ws_error_action = die_on_ws_error;
104 return;
106 if (!strcmp(option, "error-all")) {
107 ws_error_action = die_on_ws_error;
108 squelch_whitespace_errors = 0;
109 return;
111 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
112 ws_error_action = correct_ws_error;
113 return;
115 die(_("unrecognized whitespace option '%s'"), option);
118 static void parse_ignorewhitespace_option(const char *option)
120 if (!option || !strcmp(option, "no") ||
121 !strcmp(option, "false") || !strcmp(option, "never") ||
122 !strcmp(option, "none")) {
123 ws_ignore_action = ignore_ws_none;
124 return;
126 if (!strcmp(option, "change")) {
127 ws_ignore_action = ignore_ws_change;
128 return;
130 die(_("unrecognized whitespace ignore option '%s'"), option);
133 static void set_default_whitespace_mode(struct apply_state *state,
134 const char *whitespace_option)
136 if (!whitespace_option && !apply_default_whitespace)
137 ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
141 * For "diff-stat" like behaviour, we keep track of the biggest change
142 * we've seen, and the longest filename. That allows us to do simple
143 * scaling.
145 static int max_change, max_len;
148 * Various "current state", notably line numbers and what
149 * file (and how) we're patching right now.. The "is_xxxx"
150 * things are flags, where -1 means "don't know yet".
152 static int state_linenr = 1;
155 * This represents one "hunk" from a patch, starting with
156 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
157 * patch text is pointed at by patch, and its byte length
158 * is stored in size. leading and trailing are the number
159 * of context lines.
161 struct fragment {
162 unsigned long leading, trailing;
163 unsigned long oldpos, oldlines;
164 unsigned long newpos, newlines;
166 * 'patch' is usually borrowed from buf in apply_patch(),
167 * but some codepaths store an allocated buffer.
169 const char *patch;
170 unsigned free_patch:1,
171 rejected:1;
172 int size;
173 int linenr;
174 struct fragment *next;
178 * When dealing with a binary patch, we reuse "leading" field
179 * to store the type of the binary hunk, either deflated "delta"
180 * or deflated "literal".
182 #define binary_patch_method leading
183 #define BINARY_DELTA_DEFLATED 1
184 #define BINARY_LITERAL_DEFLATED 2
187 * This represents a "patch" to a file, both metainfo changes
188 * such as creation/deletion, filemode and content changes represented
189 * as a series of fragments.
191 struct patch {
192 char *new_name, *old_name, *def_name;
193 unsigned int old_mode, new_mode;
194 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
195 int rejected;
196 unsigned ws_rule;
197 int lines_added, lines_deleted;
198 int score;
199 unsigned int is_toplevel_relative:1;
200 unsigned int inaccurate_eof:1;
201 unsigned int is_binary:1;
202 unsigned int is_copy:1;
203 unsigned int is_rename:1;
204 unsigned int recount:1;
205 unsigned int conflicted_threeway:1;
206 unsigned int direct_to_threeway:1;
207 struct fragment *fragments;
208 char *result;
209 size_t resultsize;
210 char old_sha1_prefix[41];
211 char new_sha1_prefix[41];
212 struct patch *next;
214 /* three-way fallback result */
215 struct object_id threeway_stage[3];
218 static void free_fragment_list(struct fragment *list)
220 while (list) {
221 struct fragment *next = list->next;
222 if (list->free_patch)
223 free((char *)list->patch);
224 free(list);
225 list = next;
229 static void free_patch(struct patch *patch)
231 free_fragment_list(patch->fragments);
232 free(patch->def_name);
233 free(patch->old_name);
234 free(patch->new_name);
235 free(patch->result);
236 free(patch);
239 static void free_patch_list(struct patch *list)
241 while (list) {
242 struct patch *next = list->next;
243 free_patch(list);
244 list = next;
249 * A line in a file, len-bytes long (includes the terminating LF,
250 * except for an incomplete line at the end if the file ends with
251 * one), and its contents hashes to 'hash'.
253 struct line {
254 size_t len;
255 unsigned hash : 24;
256 unsigned flag : 8;
257 #define LINE_COMMON 1
258 #define LINE_PATCHED 2
262 * This represents a "file", which is an array of "lines".
264 struct image {
265 char *buf;
266 size_t len;
267 size_t nr;
268 size_t alloc;
269 struct line *line_allocated;
270 struct line *line;
274 * Records filenames that have been touched, in order to handle
275 * the case where more than one patches touch the same file.
278 static struct string_list fn_table;
280 static uint32_t hash_line(const char *cp, size_t len)
282 size_t i;
283 uint32_t h;
284 for (i = 0, h = 0; i < len; i++) {
285 if (!isspace(cp[i])) {
286 h = h * 3 + (cp[i] & 0xff);
289 return h;
293 * Compare lines s1 of length n1 and s2 of length n2, ignoring
294 * whitespace difference. Returns 1 if they match, 0 otherwise
296 static int fuzzy_matchlines(const char *s1, size_t n1,
297 const char *s2, size_t n2)
299 const char *last1 = s1 + n1 - 1;
300 const char *last2 = s2 + n2 - 1;
301 int result = 0;
303 /* ignore line endings */
304 while ((*last1 == '\r') || (*last1 == '\n'))
305 last1--;
306 while ((*last2 == '\r') || (*last2 == '\n'))
307 last2--;
309 /* skip leading whitespaces, if both begin with whitespace */
310 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
311 while (isspace(*s1) && (s1 <= last1))
312 s1++;
313 while (isspace(*s2) && (s2 <= last2))
314 s2++;
316 /* early return if both lines are empty */
317 if ((s1 > last1) && (s2 > last2))
318 return 1;
319 while (!result) {
320 result = *s1++ - *s2++;
322 * Skip whitespace inside. We check for whitespace on
323 * both buffers because we don't want "a b" to match
324 * "ab"
326 if (isspace(*s1) && isspace(*s2)) {
327 while (isspace(*s1) && s1 <= last1)
328 s1++;
329 while (isspace(*s2) && s2 <= last2)
330 s2++;
333 * If we reached the end on one side only,
334 * lines don't match
336 if (
337 ((s2 > last2) && (s1 <= last1)) ||
338 ((s1 > last1) && (s2 <= last2)))
339 return 0;
340 if ((s1 > last1) && (s2 > last2))
341 break;
344 return !result;
347 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
349 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
350 img->line_allocated[img->nr].len = len;
351 img->line_allocated[img->nr].hash = hash_line(bol, len);
352 img->line_allocated[img->nr].flag = flag;
353 img->nr++;
357 * "buf" has the file contents to be patched (read from various sources).
358 * attach it to "image" and add line-based index to it.
359 * "image" now owns the "buf".
361 static void prepare_image(struct image *image, char *buf, size_t len,
362 int prepare_linetable)
364 const char *cp, *ep;
366 memset(image, 0, sizeof(*image));
367 image->buf = buf;
368 image->len = len;
370 if (!prepare_linetable)
371 return;
373 ep = image->buf + image->len;
374 cp = image->buf;
375 while (cp < ep) {
376 const char *next;
377 for (next = cp; next < ep && *next != '\n'; next++)
379 if (next < ep)
380 next++;
381 add_line_info(image, cp, next - cp, 0);
382 cp = next;
384 image->line = image->line_allocated;
387 static void clear_image(struct image *image)
389 free(image->buf);
390 free(image->line_allocated);
391 memset(image, 0, sizeof(*image));
394 /* fmt must contain _one_ %s and no other substitution */
395 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
397 struct strbuf sb = STRBUF_INIT;
399 if (patch->old_name && patch->new_name &&
400 strcmp(patch->old_name, patch->new_name)) {
401 quote_c_style(patch->old_name, &sb, NULL, 0);
402 strbuf_addstr(&sb, " => ");
403 quote_c_style(patch->new_name, &sb, NULL, 0);
404 } else {
405 const char *n = patch->new_name;
406 if (!n)
407 n = patch->old_name;
408 quote_c_style(n, &sb, NULL, 0);
410 fprintf(output, fmt, sb.buf);
411 fputc('\n', output);
412 strbuf_release(&sb);
415 #define SLOP (16)
417 static void read_patch_file(struct strbuf *sb, int fd)
419 if (strbuf_read(sb, fd, 0) < 0)
420 die_errno("git apply: failed to read");
423 * Make sure that we have some slop in the buffer
424 * so that we can do speculative "memcmp" etc, and
425 * see to it that it is NUL-filled.
427 strbuf_grow(sb, SLOP);
428 memset(sb->buf + sb->len, 0, SLOP);
431 static unsigned long linelen(const char *buffer, unsigned long size)
433 unsigned long len = 0;
434 while (size--) {
435 len++;
436 if (*buffer++ == '\n')
437 break;
439 return len;
442 static int is_dev_null(const char *str)
444 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
447 #define TERM_SPACE 1
448 #define TERM_TAB 2
450 static int name_terminate(const char *name, int namelen, int c, int terminate)
452 if (c == ' ' && !(terminate & TERM_SPACE))
453 return 0;
454 if (c == '\t' && !(terminate & TERM_TAB))
455 return 0;
457 return 1;
460 /* remove double slashes to make --index work with such filenames */
461 static char *squash_slash(char *name)
463 int i = 0, j = 0;
465 if (!name)
466 return NULL;
468 while (name[i]) {
469 if ((name[j++] = name[i++]) == '/')
470 while (name[i] == '/')
471 i++;
473 name[j] = '\0';
474 return name;
477 static char *find_name_gnu(const char *line, const char *def, int p_value)
479 struct strbuf name = STRBUF_INIT;
480 char *cp;
483 * Proposed "new-style" GNU patch/diff format; see
484 * http://marc.info/?l=git&m=112927316408690&w=2
486 if (unquote_c_style(&name, line, NULL)) {
487 strbuf_release(&name);
488 return NULL;
491 for (cp = name.buf; p_value; p_value--) {
492 cp = strchr(cp, '/');
493 if (!cp) {
494 strbuf_release(&name);
495 return NULL;
497 cp++;
500 strbuf_remove(&name, 0, cp - name.buf);
501 if (root.len)
502 strbuf_insert(&name, 0, root.buf, root.len);
503 return squash_slash(strbuf_detach(&name, NULL));
506 static size_t sane_tz_len(const char *line, size_t len)
508 const char *tz, *p;
510 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
511 return 0;
512 tz = line + len - strlen(" +0500");
514 if (tz[1] != '+' && tz[1] != '-')
515 return 0;
517 for (p = tz + 2; p != line + len; p++)
518 if (!isdigit(*p))
519 return 0;
521 return line + len - tz;
524 static size_t tz_with_colon_len(const char *line, size_t len)
526 const char *tz, *p;
528 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
529 return 0;
530 tz = line + len - strlen(" +08:00");
532 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
533 return 0;
534 p = tz + 2;
535 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
536 !isdigit(*p++) || !isdigit(*p++))
537 return 0;
539 return line + len - tz;
542 static size_t date_len(const char *line, size_t len)
544 const char *date, *p;
546 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
547 return 0;
548 p = date = line + len - strlen("72-02-05");
550 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
551 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
552 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
553 return 0;
555 if (date - line >= strlen("19") &&
556 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
557 date -= strlen("19");
559 return line + len - date;
562 static size_t short_time_len(const char *line, size_t len)
564 const char *time, *p;
566 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
567 return 0;
568 p = time = line + len - strlen(" 07:01:32");
570 /* Permit 1-digit hours? */
571 if (*p++ != ' ' ||
572 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
573 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
574 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
575 return 0;
577 return line + len - time;
580 static size_t fractional_time_len(const char *line, size_t len)
582 const char *p;
583 size_t n;
585 /* Expected format: 19:41:17.620000023 */
586 if (!len || !isdigit(line[len - 1]))
587 return 0;
588 p = line + len - 1;
590 /* Fractional seconds. */
591 while (p > line && isdigit(*p))
592 p--;
593 if (*p != '.')
594 return 0;
596 /* Hours, minutes, and whole seconds. */
597 n = short_time_len(line, p - line);
598 if (!n)
599 return 0;
601 return line + len - p + n;
604 static size_t trailing_spaces_len(const char *line, size_t len)
606 const char *p;
608 /* Expected format: ' ' x (1 or more) */
609 if (!len || line[len - 1] != ' ')
610 return 0;
612 p = line + len;
613 while (p != line) {
614 p--;
615 if (*p != ' ')
616 return line + len - (p + 1);
619 /* All spaces! */
620 return len;
623 static size_t diff_timestamp_len(const char *line, size_t len)
625 const char *end = line + len;
626 size_t n;
629 * Posix: 2010-07-05 19:41:17
630 * GNU: 2010-07-05 19:41:17.620000023 -0500
633 if (!isdigit(end[-1]))
634 return 0;
636 n = sane_tz_len(line, end - line);
637 if (!n)
638 n = tz_with_colon_len(line, end - line);
639 end -= n;
641 n = short_time_len(line, end - line);
642 if (!n)
643 n = fractional_time_len(line, end - line);
644 end -= n;
646 n = date_len(line, end - line);
647 if (!n) /* No date. Too bad. */
648 return 0;
649 end -= n;
651 if (end == line) /* No space before date. */
652 return 0;
653 if (end[-1] == '\t') { /* Success! */
654 end--;
655 return line + len - end;
657 if (end[-1] != ' ') /* No space before date. */
658 return 0;
660 /* Whitespace damage. */
661 end -= trailing_spaces_len(line, end - line);
662 return line + len - end;
665 static char *find_name_common(const char *line, const char *def,
666 int p_value, const char *end, int terminate)
668 int len;
669 const char *start = NULL;
671 if (p_value == 0)
672 start = line;
673 while (line != end) {
674 char c = *line;
676 if (!end && isspace(c)) {
677 if (c == '\n')
678 break;
679 if (name_terminate(start, line-start, c, terminate))
680 break;
682 line++;
683 if (c == '/' && !--p_value)
684 start = line;
686 if (!start)
687 return squash_slash(xstrdup_or_null(def));
688 len = line - start;
689 if (!len)
690 return squash_slash(xstrdup_or_null(def));
693 * Generally we prefer the shorter name, especially
694 * if the other one is just a variation of that with
695 * something else tacked on to the end (ie "file.orig"
696 * or "file~").
698 if (def) {
699 int deflen = strlen(def);
700 if (deflen < len && !strncmp(start, def, deflen))
701 return squash_slash(xstrdup(def));
704 if (root.len) {
705 char *ret = xstrfmt("%s%.*s", root.buf, len, start);
706 return squash_slash(ret);
709 return squash_slash(xmemdupz(start, len));
712 static char *find_name(const char *line, char *def, int p_value, int terminate)
714 if (*line == '"') {
715 char *name = find_name_gnu(line, def, p_value);
716 if (name)
717 return name;
720 return find_name_common(line, def, p_value, NULL, terminate);
723 static char *find_name_traditional(const char *line, char *def, int p_value)
725 size_t len;
726 size_t date_len;
728 if (*line == '"') {
729 char *name = find_name_gnu(line, def, p_value);
730 if (name)
731 return name;
734 len = strchrnul(line, '\n') - line;
735 date_len = diff_timestamp_len(line, len);
736 if (!date_len)
737 return find_name_common(line, def, p_value, NULL, TERM_TAB);
738 len -= date_len;
740 return find_name_common(line, def, p_value, line + len, 0);
743 static int count_slashes(const char *cp)
745 int cnt = 0;
746 char ch;
748 while ((ch = *cp++))
749 if (ch == '/')
750 cnt++;
751 return cnt;
755 * Given the string after "--- " or "+++ ", guess the appropriate
756 * p_value for the given patch.
758 static int guess_p_value(struct apply_state *state, const char *nameline)
760 char *name, *cp;
761 int val = -1;
763 if (is_dev_null(nameline))
764 return -1;
765 name = find_name_traditional(nameline, NULL, 0);
766 if (!name)
767 return -1;
768 cp = strchr(name, '/');
769 if (!cp)
770 val = 0;
771 else if (state->prefix) {
773 * Does it begin with "a/$our-prefix" and such? Then this is
774 * very likely to apply to our directory.
776 if (!strncmp(name, state->prefix, state->prefix_length))
777 val = count_slashes(state->prefix);
778 else {
779 cp++;
780 if (!strncmp(cp, state->prefix, state->prefix_length))
781 val = count_slashes(state->prefix) + 1;
784 free(name);
785 return val;
789 * Does the ---/+++ line have the POSIX timestamp after the last HT?
790 * GNU diff puts epoch there to signal a creation/deletion event. Is
791 * this such a timestamp?
793 static int has_epoch_timestamp(const char *nameline)
796 * We are only interested in epoch timestamp; any non-zero
797 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
798 * For the same reason, the date must be either 1969-12-31 or
799 * 1970-01-01, and the seconds part must be "00".
801 const char stamp_regexp[] =
802 "^(1969-12-31|1970-01-01)"
804 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
806 "([-+][0-2][0-9]:?[0-5][0-9])\n";
807 const char *timestamp = NULL, *cp, *colon;
808 static regex_t *stamp;
809 regmatch_t m[10];
810 int zoneoffset;
811 int hourminute;
812 int status;
814 for (cp = nameline; *cp != '\n'; cp++) {
815 if (*cp == '\t')
816 timestamp = cp + 1;
818 if (!timestamp)
819 return 0;
820 if (!stamp) {
821 stamp = xmalloc(sizeof(*stamp));
822 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
823 warning(_("Cannot prepare timestamp regexp %s"),
824 stamp_regexp);
825 return 0;
829 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
830 if (status) {
831 if (status != REG_NOMATCH)
832 warning(_("regexec returned %d for input: %s"),
833 status, timestamp);
834 return 0;
837 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
838 if (*colon == ':')
839 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
840 else
841 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
842 if (timestamp[m[3].rm_so] == '-')
843 zoneoffset = -zoneoffset;
846 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
847 * (west of GMT) or 1970-01-01 (east of GMT)
849 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
850 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
851 return 0;
853 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
854 strtol(timestamp + 14, NULL, 10) -
855 zoneoffset);
857 return ((zoneoffset < 0 && hourminute == 1440) ||
858 (0 <= zoneoffset && !hourminute));
862 * Get the name etc info from the ---/+++ lines of a traditional patch header
864 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
865 * files, we can happily check the index for a match, but for creating a
866 * new file we should try to match whatever "patch" does. I have no idea.
868 static void parse_traditional_patch(struct apply_state *state,
869 const char *first,
870 const char *second,
871 struct patch *patch)
873 char *name;
875 first += 4; /* skip "--- " */
876 second += 4; /* skip "+++ " */
877 if (!state->p_value_known) {
878 int p, q;
879 p = guess_p_value(state, first);
880 q = guess_p_value(state, second);
881 if (p < 0) p = q;
882 if (0 <= p && p == q) {
883 state->p_value = p;
884 state->p_value_known = 1;
887 if (is_dev_null(first)) {
888 patch->is_new = 1;
889 patch->is_delete = 0;
890 name = find_name_traditional(second, NULL, state->p_value);
891 patch->new_name = name;
892 } else if (is_dev_null(second)) {
893 patch->is_new = 0;
894 patch->is_delete = 1;
895 name = find_name_traditional(first, NULL, state->p_value);
896 patch->old_name = name;
897 } else {
898 char *first_name;
899 first_name = find_name_traditional(first, NULL, state->p_value);
900 name = find_name_traditional(second, first_name, state->p_value);
901 free(first_name);
902 if (has_epoch_timestamp(first)) {
903 patch->is_new = 1;
904 patch->is_delete = 0;
905 patch->new_name = name;
906 } else if (has_epoch_timestamp(second)) {
907 patch->is_new = 0;
908 patch->is_delete = 1;
909 patch->old_name = name;
910 } else {
911 patch->old_name = name;
912 patch->new_name = xstrdup_or_null(name);
915 if (!name)
916 die(_("unable to find filename in patch at line %d"), state_linenr);
919 static int gitdiff_hdrend(struct apply_state *state,
920 const char *line,
921 struct patch *patch)
923 return -1;
927 * We're anal about diff header consistency, to make
928 * sure that we don't end up having strange ambiguous
929 * patches floating around.
931 * As a result, gitdiff_{old|new}name() will check
932 * their names against any previous information, just
933 * to make sure..
935 #define DIFF_OLD_NAME 0
936 #define DIFF_NEW_NAME 1
938 static void gitdiff_verify_name(struct apply_state *state,
939 const char *line,
940 int isnull,
941 char **name,
942 int side)
944 if (!*name && !isnull) {
945 *name = find_name(line, NULL, state->p_value, TERM_TAB);
946 return;
949 if (*name) {
950 int len = strlen(*name);
951 char *another;
952 if (isnull)
953 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
954 *name, state_linenr);
955 another = find_name(line, NULL, state->p_value, TERM_TAB);
956 if (!another || memcmp(another, *name, len + 1))
957 die((side == DIFF_NEW_NAME) ?
958 _("git apply: bad git-diff - inconsistent new filename on line %d") :
959 _("git apply: bad git-diff - inconsistent old filename on line %d"), state_linenr);
960 free(another);
961 } else {
962 /* expect "/dev/null" */
963 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
964 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr);
968 static int gitdiff_oldname(struct apply_state *state,
969 const char *line,
970 struct patch *patch)
972 gitdiff_verify_name(state, line,
973 patch->is_new, &patch->old_name,
974 DIFF_OLD_NAME);
975 return 0;
978 static int gitdiff_newname(struct apply_state *state,
979 const char *line,
980 struct patch *patch)
982 gitdiff_verify_name(state, line,
983 patch->is_delete, &patch->new_name,
984 DIFF_NEW_NAME);
985 return 0;
988 static int gitdiff_oldmode(struct apply_state *state,
989 const char *line,
990 struct patch *patch)
992 patch->old_mode = strtoul(line, NULL, 8);
993 return 0;
996 static int gitdiff_newmode(struct apply_state *state,
997 const char *line,
998 struct patch *patch)
1000 patch->new_mode = strtoul(line, NULL, 8);
1001 return 0;
1004 static int gitdiff_delete(struct apply_state *state,
1005 const char *line,
1006 struct patch *patch)
1008 patch->is_delete = 1;
1009 free(patch->old_name);
1010 patch->old_name = xstrdup_or_null(patch->def_name);
1011 return gitdiff_oldmode(state, line, patch);
1014 static int gitdiff_newfile(struct apply_state *state,
1015 const char *line,
1016 struct patch *patch)
1018 patch->is_new = 1;
1019 free(patch->new_name);
1020 patch->new_name = xstrdup_or_null(patch->def_name);
1021 return gitdiff_newmode(state, line, patch);
1024 static int gitdiff_copysrc(struct apply_state *state,
1025 const char *line,
1026 struct patch *patch)
1028 patch->is_copy = 1;
1029 free(patch->old_name);
1030 patch->old_name = find_name(line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1031 return 0;
1034 static int gitdiff_copydst(struct apply_state *state,
1035 const char *line,
1036 struct patch *patch)
1038 patch->is_copy = 1;
1039 free(patch->new_name);
1040 patch->new_name = find_name(line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1041 return 0;
1044 static int gitdiff_renamesrc(struct apply_state *state,
1045 const char *line,
1046 struct patch *patch)
1048 patch->is_rename = 1;
1049 free(patch->old_name);
1050 patch->old_name = find_name(line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1051 return 0;
1054 static int gitdiff_renamedst(struct apply_state *state,
1055 const char *line,
1056 struct patch *patch)
1058 patch->is_rename = 1;
1059 free(patch->new_name);
1060 patch->new_name = find_name(line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1061 return 0;
1064 static int gitdiff_similarity(struct apply_state *state,
1065 const char *line,
1066 struct patch *patch)
1068 unsigned long val = strtoul(line, NULL, 10);
1069 if (val <= 100)
1070 patch->score = val;
1071 return 0;
1074 static int gitdiff_dissimilarity(struct apply_state *state,
1075 const char *line,
1076 struct patch *patch)
1078 unsigned long val = strtoul(line, NULL, 10);
1079 if (val <= 100)
1080 patch->score = val;
1081 return 0;
1084 static int gitdiff_index(struct apply_state *state,
1085 const char *line,
1086 struct patch *patch)
1089 * index line is N hexadecimal, "..", N hexadecimal,
1090 * and optional space with octal mode.
1092 const char *ptr, *eol;
1093 int len;
1095 ptr = strchr(line, '.');
1096 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1097 return 0;
1098 len = ptr - line;
1099 memcpy(patch->old_sha1_prefix, line, len);
1100 patch->old_sha1_prefix[len] = 0;
1102 line = ptr + 2;
1103 ptr = strchr(line, ' ');
1104 eol = strchrnul(line, '\n');
1106 if (!ptr || eol < ptr)
1107 ptr = eol;
1108 len = ptr - line;
1110 if (40 < len)
1111 return 0;
1112 memcpy(patch->new_sha1_prefix, line, len);
1113 patch->new_sha1_prefix[len] = 0;
1114 if (*ptr == ' ')
1115 patch->old_mode = strtoul(ptr+1, NULL, 8);
1116 return 0;
1120 * This is normal for a diff that doesn't change anything: we'll fall through
1121 * into the next diff. Tell the parser to break out.
1123 static int gitdiff_unrecognized(struct apply_state *state,
1124 const char *line,
1125 struct patch *patch)
1127 return -1;
1131 * Skip p_value leading components from "line"; as we do not accept
1132 * absolute paths, return NULL in that case.
1134 static const char *skip_tree_prefix(struct apply_state *state,
1135 const char *line,
1136 int llen)
1138 int nslash;
1139 int i;
1141 if (!state->p_value)
1142 return (llen && line[0] == '/') ? NULL : line;
1144 nslash = state->p_value;
1145 for (i = 0; i < llen; i++) {
1146 int ch = line[i];
1147 if (ch == '/' && --nslash <= 0)
1148 return (i == 0) ? NULL : &line[i + 1];
1150 return NULL;
1154 * This is to extract the same name that appears on "diff --git"
1155 * line. We do not find and return anything if it is a rename
1156 * patch, and it is OK because we will find the name elsewhere.
1157 * We need to reliably find name only when it is mode-change only,
1158 * creation or deletion of an empty file. In any of these cases,
1159 * both sides are the same name under a/ and b/ respectively.
1161 static char *git_header_name(struct apply_state *state,
1162 const char *line,
1163 int llen)
1165 const char *name;
1166 const char *second = NULL;
1167 size_t len, line_len;
1169 line += strlen("diff --git ");
1170 llen -= strlen("diff --git ");
1172 if (*line == '"') {
1173 const char *cp;
1174 struct strbuf first = STRBUF_INIT;
1175 struct strbuf sp = STRBUF_INIT;
1177 if (unquote_c_style(&first, line, &second))
1178 goto free_and_fail1;
1180 /* strip the a/b prefix including trailing slash */
1181 cp = skip_tree_prefix(state, first.buf, first.len);
1182 if (!cp)
1183 goto free_and_fail1;
1184 strbuf_remove(&first, 0, cp - first.buf);
1187 * second points at one past closing dq of name.
1188 * find the second name.
1190 while ((second < line + llen) && isspace(*second))
1191 second++;
1193 if (line + llen <= second)
1194 goto free_and_fail1;
1195 if (*second == '"') {
1196 if (unquote_c_style(&sp, second, NULL))
1197 goto free_and_fail1;
1198 cp = skip_tree_prefix(state, sp.buf, sp.len);
1199 if (!cp)
1200 goto free_and_fail1;
1201 /* They must match, otherwise ignore */
1202 if (strcmp(cp, first.buf))
1203 goto free_and_fail1;
1204 strbuf_release(&sp);
1205 return strbuf_detach(&first, NULL);
1208 /* unquoted second */
1209 cp = skip_tree_prefix(state, second, line + llen - second);
1210 if (!cp)
1211 goto free_and_fail1;
1212 if (line + llen - cp != first.len ||
1213 memcmp(first.buf, cp, first.len))
1214 goto free_and_fail1;
1215 return strbuf_detach(&first, NULL);
1217 free_and_fail1:
1218 strbuf_release(&first);
1219 strbuf_release(&sp);
1220 return NULL;
1223 /* unquoted first name */
1224 name = skip_tree_prefix(state, line, llen);
1225 if (!name)
1226 return NULL;
1229 * since the first name is unquoted, a dq if exists must be
1230 * the beginning of the second name.
1232 for (second = name; second < line + llen; second++) {
1233 if (*second == '"') {
1234 struct strbuf sp = STRBUF_INIT;
1235 const char *np;
1237 if (unquote_c_style(&sp, second, NULL))
1238 goto free_and_fail2;
1240 np = skip_tree_prefix(state, sp.buf, sp.len);
1241 if (!np)
1242 goto free_and_fail2;
1244 len = sp.buf + sp.len - np;
1245 if (len < second - name &&
1246 !strncmp(np, name, len) &&
1247 isspace(name[len])) {
1248 /* Good */
1249 strbuf_remove(&sp, 0, np - sp.buf);
1250 return strbuf_detach(&sp, NULL);
1253 free_and_fail2:
1254 strbuf_release(&sp);
1255 return NULL;
1260 * Accept a name only if it shows up twice, exactly the same
1261 * form.
1263 second = strchr(name, '\n');
1264 if (!second)
1265 return NULL;
1266 line_len = second - name;
1267 for (len = 0 ; ; len++) {
1268 switch (name[len]) {
1269 default:
1270 continue;
1271 case '\n':
1272 return NULL;
1273 case '\t': case ' ':
1275 * Is this the separator between the preimage
1276 * and the postimage pathname? Again, we are
1277 * only interested in the case where there is
1278 * no rename, as this is only to set def_name
1279 * and a rename patch has the names elsewhere
1280 * in an unambiguous form.
1282 if (!name[len + 1])
1283 return NULL; /* no postimage name */
1284 second = skip_tree_prefix(state, name + len + 1,
1285 line_len - (len + 1));
1286 if (!second)
1287 return NULL;
1289 * Does len bytes starting at "name" and "second"
1290 * (that are separated by one HT or SP we just
1291 * found) exactly match?
1293 if (second[len] == '\n' && !strncmp(name, second, len))
1294 return xmemdupz(name, len);
1299 /* Verify that we recognize the lines following a git header */
1300 static int parse_git_header(struct apply_state *state,
1301 const char *line,
1302 int len,
1303 unsigned int size,
1304 struct patch *patch)
1306 unsigned long offset;
1308 /* A git diff has explicit new/delete information, so we don't guess */
1309 patch->is_new = 0;
1310 patch->is_delete = 0;
1313 * Some things may not have the old name in the
1314 * rest of the headers anywhere (pure mode changes,
1315 * or removing or adding empty files), so we get
1316 * the default name from the header.
1318 patch->def_name = git_header_name(state, line, len);
1319 if (patch->def_name && root.len) {
1320 char *s = xstrfmt("%s%s", root.buf, patch->def_name);
1321 free(patch->def_name);
1322 patch->def_name = s;
1325 line += len;
1326 size -= len;
1327 state_linenr++;
1328 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state_linenr++) {
1329 static const struct opentry {
1330 const char *str;
1331 int (*fn)(struct apply_state *, const char *, struct patch *);
1332 } optable[] = {
1333 { "@@ -", gitdiff_hdrend },
1334 { "--- ", gitdiff_oldname },
1335 { "+++ ", gitdiff_newname },
1336 { "old mode ", gitdiff_oldmode },
1337 { "new mode ", gitdiff_newmode },
1338 { "deleted file mode ", gitdiff_delete },
1339 { "new file mode ", gitdiff_newfile },
1340 { "copy from ", gitdiff_copysrc },
1341 { "copy to ", gitdiff_copydst },
1342 { "rename old ", gitdiff_renamesrc },
1343 { "rename new ", gitdiff_renamedst },
1344 { "rename from ", gitdiff_renamesrc },
1345 { "rename to ", gitdiff_renamedst },
1346 { "similarity index ", gitdiff_similarity },
1347 { "dissimilarity index ", gitdiff_dissimilarity },
1348 { "index ", gitdiff_index },
1349 { "", gitdiff_unrecognized },
1351 int i;
1353 len = linelen(line, size);
1354 if (!len || line[len-1] != '\n')
1355 break;
1356 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1357 const struct opentry *p = optable + i;
1358 int oplen = strlen(p->str);
1359 if (len < oplen || memcmp(p->str, line, oplen))
1360 continue;
1361 if (p->fn(state, line + oplen, patch) < 0)
1362 return offset;
1363 break;
1367 return offset;
1370 static int parse_num(const char *line, unsigned long *p)
1372 char *ptr;
1374 if (!isdigit(*line))
1375 return 0;
1376 *p = strtoul(line, &ptr, 10);
1377 return ptr - line;
1380 static int parse_range(const char *line, int len, int offset, const char *expect,
1381 unsigned long *p1, unsigned long *p2)
1383 int digits, ex;
1385 if (offset < 0 || offset >= len)
1386 return -1;
1387 line += offset;
1388 len -= offset;
1390 digits = parse_num(line, p1);
1391 if (!digits)
1392 return -1;
1394 offset += digits;
1395 line += digits;
1396 len -= digits;
1398 *p2 = 1;
1399 if (*line == ',') {
1400 digits = parse_num(line+1, p2);
1401 if (!digits)
1402 return -1;
1404 offset += digits+1;
1405 line += digits+1;
1406 len -= digits+1;
1409 ex = strlen(expect);
1410 if (ex > len)
1411 return -1;
1412 if (memcmp(line, expect, ex))
1413 return -1;
1415 return offset + ex;
1418 static void recount_diff(const char *line, int size, struct fragment *fragment)
1420 int oldlines = 0, newlines = 0, ret = 0;
1422 if (size < 1) {
1423 warning("recount: ignore empty hunk");
1424 return;
1427 for (;;) {
1428 int len = linelen(line, size);
1429 size -= len;
1430 line += len;
1432 if (size < 1)
1433 break;
1435 switch (*line) {
1436 case ' ': case '\n':
1437 newlines++;
1438 /* fall through */
1439 case '-':
1440 oldlines++;
1441 continue;
1442 case '+':
1443 newlines++;
1444 continue;
1445 case '\\':
1446 continue;
1447 case '@':
1448 ret = size < 3 || !starts_with(line, "@@ ");
1449 break;
1450 case 'd':
1451 ret = size < 5 || !starts_with(line, "diff ");
1452 break;
1453 default:
1454 ret = -1;
1455 break;
1457 if (ret) {
1458 warning(_("recount: unexpected line: %.*s"),
1459 (int)linelen(line, size), line);
1460 return;
1462 break;
1464 fragment->oldlines = oldlines;
1465 fragment->newlines = newlines;
1469 * Parse a unified diff fragment header of the
1470 * form "@@ -a,b +c,d @@"
1472 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1474 int offset;
1476 if (!len || line[len-1] != '\n')
1477 return -1;
1479 /* Figure out the number of lines in a fragment */
1480 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1481 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1483 return offset;
1486 static int find_header(struct apply_state *state,
1487 const char *line,
1488 unsigned long size,
1489 int *hdrsize,
1490 struct patch *patch)
1492 unsigned long offset, len;
1494 patch->is_toplevel_relative = 0;
1495 patch->is_rename = patch->is_copy = 0;
1496 patch->is_new = patch->is_delete = -1;
1497 patch->old_mode = patch->new_mode = 0;
1498 patch->old_name = patch->new_name = NULL;
1499 for (offset = 0; size > 0; offset += len, size -= len, line += len, state_linenr++) {
1500 unsigned long nextlen;
1502 len = linelen(line, size);
1503 if (!len)
1504 break;
1506 /* Testing this early allows us to take a few shortcuts.. */
1507 if (len < 6)
1508 continue;
1511 * Make sure we don't find any unconnected patch fragments.
1512 * That's a sign that we didn't find a header, and that a
1513 * patch has become corrupted/broken up.
1515 if (!memcmp("@@ -", line, 4)) {
1516 struct fragment dummy;
1517 if (parse_fragment_header(line, len, &dummy) < 0)
1518 continue;
1519 die(_("patch fragment without header at line %d: %.*s"),
1520 state_linenr, (int)len-1, line);
1523 if (size < len + 6)
1524 break;
1527 * Git patch? It might not have a real patch, just a rename
1528 * or mode change, so we handle that specially
1530 if (!memcmp("diff --git ", line, 11)) {
1531 int git_hdr_len = parse_git_header(state, line, len, size, patch);
1532 if (git_hdr_len <= len)
1533 continue;
1534 if (!patch->old_name && !patch->new_name) {
1535 if (!patch->def_name)
1536 die(Q_("git diff header lacks filename information when removing "
1537 "%d leading pathname component (line %d)",
1538 "git diff header lacks filename information when removing "
1539 "%d leading pathname components (line %d)",
1540 state->p_value),
1541 state->p_value, state_linenr);
1542 patch->old_name = xstrdup(patch->def_name);
1543 patch->new_name = xstrdup(patch->def_name);
1545 if (!patch->is_delete && !patch->new_name)
1546 die("git diff header lacks filename information "
1547 "(line %d)", state_linenr);
1548 patch->is_toplevel_relative = 1;
1549 *hdrsize = git_hdr_len;
1550 return offset;
1553 /* --- followed by +++ ? */
1554 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1555 continue;
1558 * We only accept unified patches, so we want it to
1559 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1560 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1562 nextlen = linelen(line + len, size - len);
1563 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1564 continue;
1566 /* Ok, we'll consider it a patch */
1567 parse_traditional_patch(state, line, line+len, patch);
1568 *hdrsize = len + nextlen;
1569 state_linenr += 2;
1570 return offset;
1572 return -1;
1575 static void record_ws_error(struct apply_state *state,
1576 unsigned result,
1577 const char *line,
1578 int len,
1579 int linenr)
1581 char *err;
1583 if (!result)
1584 return;
1586 whitespace_error++;
1587 if (squelch_whitespace_errors &&
1588 squelch_whitespace_errors < whitespace_error)
1589 return;
1591 err = whitespace_error_string(result);
1592 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1593 state->patch_input_file, linenr, err, len, line);
1594 free(err);
1597 static void check_whitespace(struct apply_state *state,
1598 const char *line,
1599 int len,
1600 unsigned ws_rule)
1602 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1604 record_ws_error(state, result, line + 1, len - 2, state_linenr);
1608 * Parse a unified diff. Note that this really needs to parse each
1609 * fragment separately, since the only way to know the difference
1610 * between a "---" that is part of a patch, and a "---" that starts
1611 * the next patch is to look at the line counts..
1613 static int parse_fragment(struct apply_state *state,
1614 const char *line,
1615 unsigned long size,
1616 struct patch *patch,
1617 struct fragment *fragment)
1619 int added, deleted;
1620 int len = linelen(line, size), offset;
1621 unsigned long oldlines, newlines;
1622 unsigned long leading, trailing;
1624 offset = parse_fragment_header(line, len, fragment);
1625 if (offset < 0)
1626 return -1;
1627 if (offset > 0 && patch->recount)
1628 recount_diff(line + offset, size - offset, fragment);
1629 oldlines = fragment->oldlines;
1630 newlines = fragment->newlines;
1631 leading = 0;
1632 trailing = 0;
1634 /* Parse the thing.. */
1635 line += len;
1636 size -= len;
1637 state_linenr++;
1638 added = deleted = 0;
1639 for (offset = len;
1640 0 < size;
1641 offset += len, size -= len, line += len, state_linenr++) {
1642 if (!oldlines && !newlines)
1643 break;
1644 len = linelen(line, size);
1645 if (!len || line[len-1] != '\n')
1646 return -1;
1647 switch (*line) {
1648 default:
1649 return -1;
1650 case '\n': /* newer GNU diff, an empty context line */
1651 case ' ':
1652 oldlines--;
1653 newlines--;
1654 if (!deleted && !added)
1655 leading++;
1656 trailing++;
1657 if (!state->apply_in_reverse &&
1658 ws_error_action == correct_ws_error)
1659 check_whitespace(state, line, len, patch->ws_rule);
1660 break;
1661 case '-':
1662 if (state->apply_in_reverse &&
1663 ws_error_action != nowarn_ws_error)
1664 check_whitespace(state, line, len, patch->ws_rule);
1665 deleted++;
1666 oldlines--;
1667 trailing = 0;
1668 break;
1669 case '+':
1670 if (!state->apply_in_reverse &&
1671 ws_error_action != nowarn_ws_error)
1672 check_whitespace(state, line, len, patch->ws_rule);
1673 added++;
1674 newlines--;
1675 trailing = 0;
1676 break;
1679 * We allow "\ No newline at end of file". Depending
1680 * on locale settings when the patch was produced we
1681 * don't know what this line looks like. The only
1682 * thing we do know is that it begins with "\ ".
1683 * Checking for 12 is just for sanity check -- any
1684 * l10n of "\ No newline..." is at least that long.
1686 case '\\':
1687 if (len < 12 || memcmp(line, "\\ ", 2))
1688 return -1;
1689 break;
1692 if (oldlines || newlines)
1693 return -1;
1694 if (!deleted && !added)
1695 return -1;
1697 fragment->leading = leading;
1698 fragment->trailing = trailing;
1701 * If a fragment ends with an incomplete line, we failed to include
1702 * it in the above loop because we hit oldlines == newlines == 0
1703 * before seeing it.
1705 if (12 < size && !memcmp(line, "\\ ", 2))
1706 offset += linelen(line, size);
1708 patch->lines_added += added;
1709 patch->lines_deleted += deleted;
1711 if (0 < patch->is_new && oldlines)
1712 return error(_("new file depends on old contents"));
1713 if (0 < patch->is_delete && newlines)
1714 return error(_("deleted file still has contents"));
1715 return offset;
1719 * We have seen "diff --git a/... b/..." header (or a traditional patch
1720 * header). Read hunks that belong to this patch into fragments and hang
1721 * them to the given patch structure.
1723 * The (fragment->patch, fragment->size) pair points into the memory given
1724 * by the caller, not a copy, when we return.
1726 static int parse_single_patch(struct apply_state *state,
1727 const char *line,
1728 unsigned long size,
1729 struct patch *patch)
1731 unsigned long offset = 0;
1732 unsigned long oldlines = 0, newlines = 0, context = 0;
1733 struct fragment **fragp = &patch->fragments;
1735 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1736 struct fragment *fragment;
1737 int len;
1739 fragment = xcalloc(1, sizeof(*fragment));
1740 fragment->linenr = state_linenr;
1741 len = parse_fragment(state, line, size, patch, fragment);
1742 if (len <= 0)
1743 die(_("corrupt patch at line %d"), state_linenr);
1744 fragment->patch = line;
1745 fragment->size = len;
1746 oldlines += fragment->oldlines;
1747 newlines += fragment->newlines;
1748 context += fragment->leading + fragment->trailing;
1750 *fragp = fragment;
1751 fragp = &fragment->next;
1753 offset += len;
1754 line += len;
1755 size -= len;
1759 * If something was removed (i.e. we have old-lines) it cannot
1760 * be creation, and if something was added it cannot be
1761 * deletion. However, the reverse is not true; --unified=0
1762 * patches that only add are not necessarily creation even
1763 * though they do not have any old lines, and ones that only
1764 * delete are not necessarily deletion.
1766 * Unfortunately, a real creation/deletion patch do _not_ have
1767 * any context line by definition, so we cannot safely tell it
1768 * apart with --unified=0 insanity. At least if the patch has
1769 * more than one hunk it is not creation or deletion.
1771 if (patch->is_new < 0 &&
1772 (oldlines || (patch->fragments && patch->fragments->next)))
1773 patch->is_new = 0;
1774 if (patch->is_delete < 0 &&
1775 (newlines || (patch->fragments && patch->fragments->next)))
1776 patch->is_delete = 0;
1778 if (0 < patch->is_new && oldlines)
1779 die(_("new file %s depends on old contents"), patch->new_name);
1780 if (0 < patch->is_delete && newlines)
1781 die(_("deleted file %s still has contents"), patch->old_name);
1782 if (!patch->is_delete && !newlines && context)
1783 fprintf_ln(stderr,
1784 _("** warning: "
1785 "file %s becomes empty but is not deleted"),
1786 patch->new_name);
1788 return offset;
1791 static inline int metadata_changes(struct patch *patch)
1793 return patch->is_rename > 0 ||
1794 patch->is_copy > 0 ||
1795 patch->is_new > 0 ||
1796 patch->is_delete ||
1797 (patch->old_mode && patch->new_mode &&
1798 patch->old_mode != patch->new_mode);
1801 static char *inflate_it(const void *data, unsigned long size,
1802 unsigned long inflated_size)
1804 git_zstream stream;
1805 void *out;
1806 int st;
1808 memset(&stream, 0, sizeof(stream));
1810 stream.next_in = (unsigned char *)data;
1811 stream.avail_in = size;
1812 stream.next_out = out = xmalloc(inflated_size);
1813 stream.avail_out = inflated_size;
1814 git_inflate_init(&stream);
1815 st = git_inflate(&stream, Z_FINISH);
1816 git_inflate_end(&stream);
1817 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1818 free(out);
1819 return NULL;
1821 return out;
1825 * Read a binary hunk and return a new fragment; fragment->patch
1826 * points at an allocated memory that the caller must free, so
1827 * it is marked as "->free_patch = 1".
1829 static struct fragment *parse_binary_hunk(char **buf_p,
1830 unsigned long *sz_p,
1831 int *status_p,
1832 int *used_p)
1835 * Expect a line that begins with binary patch method ("literal"
1836 * or "delta"), followed by the length of data before deflating.
1837 * a sequence of 'length-byte' followed by base-85 encoded data
1838 * should follow, terminated by a newline.
1840 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1841 * and we would limit the patch line to 66 characters,
1842 * so one line can fit up to 13 groups that would decode
1843 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1844 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1846 int llen, used;
1847 unsigned long size = *sz_p;
1848 char *buffer = *buf_p;
1849 int patch_method;
1850 unsigned long origlen;
1851 char *data = NULL;
1852 int hunk_size = 0;
1853 struct fragment *frag;
1855 llen = linelen(buffer, size);
1856 used = llen;
1858 *status_p = 0;
1860 if (starts_with(buffer, "delta ")) {
1861 patch_method = BINARY_DELTA_DEFLATED;
1862 origlen = strtoul(buffer + 6, NULL, 10);
1864 else if (starts_with(buffer, "literal ")) {
1865 patch_method = BINARY_LITERAL_DEFLATED;
1866 origlen = strtoul(buffer + 8, NULL, 10);
1868 else
1869 return NULL;
1871 state_linenr++;
1872 buffer += llen;
1873 while (1) {
1874 int byte_length, max_byte_length, newsize;
1875 llen = linelen(buffer, size);
1876 used += llen;
1877 state_linenr++;
1878 if (llen == 1) {
1879 /* consume the blank line */
1880 buffer++;
1881 size--;
1882 break;
1885 * Minimum line is "A00000\n" which is 7-byte long,
1886 * and the line length must be multiple of 5 plus 2.
1888 if ((llen < 7) || (llen-2) % 5)
1889 goto corrupt;
1890 max_byte_length = (llen - 2) / 5 * 4;
1891 byte_length = *buffer;
1892 if ('A' <= byte_length && byte_length <= 'Z')
1893 byte_length = byte_length - 'A' + 1;
1894 else if ('a' <= byte_length && byte_length <= 'z')
1895 byte_length = byte_length - 'a' + 27;
1896 else
1897 goto corrupt;
1898 /* if the input length was not multiple of 4, we would
1899 * have filler at the end but the filler should never
1900 * exceed 3 bytes
1902 if (max_byte_length < byte_length ||
1903 byte_length <= max_byte_length - 4)
1904 goto corrupt;
1905 newsize = hunk_size + byte_length;
1906 data = xrealloc(data, newsize);
1907 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1908 goto corrupt;
1909 hunk_size = newsize;
1910 buffer += llen;
1911 size -= llen;
1914 frag = xcalloc(1, sizeof(*frag));
1915 frag->patch = inflate_it(data, hunk_size, origlen);
1916 frag->free_patch = 1;
1917 if (!frag->patch)
1918 goto corrupt;
1919 free(data);
1920 frag->size = origlen;
1921 *buf_p = buffer;
1922 *sz_p = size;
1923 *used_p = used;
1924 frag->binary_patch_method = patch_method;
1925 return frag;
1927 corrupt:
1928 free(data);
1929 *status_p = -1;
1930 error(_("corrupt binary patch at line %d: %.*s"),
1931 state_linenr-1, llen-1, buffer);
1932 return NULL;
1936 * Returns:
1937 * -1 in case of error,
1938 * the length of the parsed binary patch otherwise
1940 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1943 * We have read "GIT binary patch\n"; what follows is a line
1944 * that says the patch method (currently, either "literal" or
1945 * "delta") and the length of data before deflating; a
1946 * sequence of 'length-byte' followed by base-85 encoded data
1947 * follows.
1949 * When a binary patch is reversible, there is another binary
1950 * hunk in the same format, starting with patch method (either
1951 * "literal" or "delta") with the length of data, and a sequence
1952 * of length-byte + base-85 encoded data, terminated with another
1953 * empty line. This data, when applied to the postimage, produces
1954 * the preimage.
1956 struct fragment *forward;
1957 struct fragment *reverse;
1958 int status;
1959 int used, used_1;
1961 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1962 if (!forward && !status)
1963 /* there has to be one hunk (forward hunk) */
1964 return error(_("unrecognized binary patch at line %d"), state_linenr-1);
1965 if (status)
1966 /* otherwise we already gave an error message */
1967 return status;
1969 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1970 if (reverse)
1971 used += used_1;
1972 else if (status) {
1974 * Not having reverse hunk is not an error, but having
1975 * a corrupt reverse hunk is.
1977 free((void*) forward->patch);
1978 free(forward);
1979 return status;
1981 forward->next = reverse;
1982 patch->fragments = forward;
1983 patch->is_binary = 1;
1984 return used;
1987 static void prefix_one(struct apply_state *state, char **name)
1989 char *old_name = *name;
1990 if (!old_name)
1991 return;
1992 *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));
1993 free(old_name);
1996 static void prefix_patch(struct apply_state *state, struct patch *p)
1998 if (!state->prefix || p->is_toplevel_relative)
1999 return;
2000 prefix_one(state, &p->new_name);
2001 prefix_one(state, &p->old_name);
2005 * include/exclude
2008 static void add_name_limit(struct apply_state *state,
2009 const char *name,
2010 int exclude)
2012 struct string_list_item *it;
2014 it = string_list_append(&state->limit_by_name, name);
2015 it->util = exclude ? NULL : (void *) 1;
2018 static int use_patch(struct apply_state *state, struct patch *p)
2020 const char *pathname = p->new_name ? p->new_name : p->old_name;
2021 int i;
2023 /* Paths outside are not touched regardless of "--include" */
2024 if (0 < state->prefix_length) {
2025 int pathlen = strlen(pathname);
2026 if (pathlen <= state->prefix_length ||
2027 memcmp(state->prefix, pathname, state->prefix_length))
2028 return 0;
2031 /* See if it matches any of exclude/include rule */
2032 for (i = 0; i < state->limit_by_name.nr; i++) {
2033 struct string_list_item *it = &state->limit_by_name.items[i];
2034 if (!wildmatch(it->string, pathname, 0, NULL))
2035 return (it->util != NULL);
2039 * If we had any include, a path that does not match any rule is
2040 * not used. Otherwise, we saw bunch of exclude rules (or none)
2041 * and such a path is used.
2043 return !state->has_include;
2048 * Read the patch text in "buffer" that extends for "size" bytes; stop
2049 * reading after seeing a single patch (i.e. changes to a single file).
2050 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2051 * Return the number of bytes consumed, so that the caller can call us
2052 * again for the next patch.
2054 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2056 int hdrsize, patchsize;
2057 int offset = find_header(state, buffer, size, &hdrsize, patch);
2059 if (offset < 0)
2060 return offset;
2062 prefix_patch(state, patch);
2064 if (!use_patch(state, patch))
2065 patch->ws_rule = 0;
2066 else
2067 patch->ws_rule = whitespace_rule(patch->new_name
2068 ? patch->new_name
2069 : patch->old_name);
2071 patchsize = parse_single_patch(state,
2072 buffer + offset + hdrsize,
2073 size - offset - hdrsize,
2074 patch);
2076 if (!patchsize) {
2077 static const char git_binary[] = "GIT binary patch\n";
2078 int hd = hdrsize + offset;
2079 unsigned long llen = linelen(buffer + hd, size - hd);
2081 if (llen == sizeof(git_binary) - 1 &&
2082 !memcmp(git_binary, buffer + hd, llen)) {
2083 int used;
2084 state_linenr++;
2085 used = parse_binary(buffer + hd + llen,
2086 size - hd - llen, patch);
2087 if (used < 0)
2088 return -1;
2089 if (used)
2090 patchsize = used + llen;
2091 else
2092 patchsize = 0;
2094 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2095 static const char *binhdr[] = {
2096 "Binary files ",
2097 "Files ",
2098 NULL,
2100 int i;
2101 for (i = 0; binhdr[i]; i++) {
2102 int len = strlen(binhdr[i]);
2103 if (len < size - hd &&
2104 !memcmp(binhdr[i], buffer + hd, len)) {
2105 state_linenr++;
2106 patch->is_binary = 1;
2107 patchsize = llen;
2108 break;
2113 /* Empty patch cannot be applied if it is a text patch
2114 * without metadata change. A binary patch appears
2115 * empty to us here.
2117 if ((state->apply || state->check) &&
2118 (!patch->is_binary && !metadata_changes(patch)))
2119 die(_("patch with only garbage at line %d"), state_linenr);
2122 return offset + hdrsize + patchsize;
2125 #define swap(a,b) myswap((a),(b),sizeof(a))
2127 #define myswap(a, b, size) do { \
2128 unsigned char mytmp[size]; \
2129 memcpy(mytmp, &a, size); \
2130 memcpy(&a, &b, size); \
2131 memcpy(&b, mytmp, size); \
2132 } while (0)
2134 static void reverse_patches(struct patch *p)
2136 for (; p; p = p->next) {
2137 struct fragment *frag = p->fragments;
2139 swap(p->new_name, p->old_name);
2140 swap(p->new_mode, p->old_mode);
2141 swap(p->is_new, p->is_delete);
2142 swap(p->lines_added, p->lines_deleted);
2143 swap(p->old_sha1_prefix, p->new_sha1_prefix);
2145 for (; frag; frag = frag->next) {
2146 swap(frag->newpos, frag->oldpos);
2147 swap(frag->newlines, frag->oldlines);
2152 static const char pluses[] =
2153 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2154 static const char minuses[]=
2155 "----------------------------------------------------------------------";
2157 static void show_stats(struct patch *patch)
2159 struct strbuf qname = STRBUF_INIT;
2160 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2161 int max, add, del;
2163 quote_c_style(cp, &qname, NULL, 0);
2166 * "scale" the filename
2168 max = max_len;
2169 if (max > 50)
2170 max = 50;
2172 if (qname.len > max) {
2173 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2174 if (!cp)
2175 cp = qname.buf + qname.len + 3 - max;
2176 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2179 if (patch->is_binary) {
2180 printf(" %-*s | Bin\n", max, qname.buf);
2181 strbuf_release(&qname);
2182 return;
2185 printf(" %-*s |", max, qname.buf);
2186 strbuf_release(&qname);
2189 * scale the add/delete
2191 max = max + max_change > 70 ? 70 - max : max_change;
2192 add = patch->lines_added;
2193 del = patch->lines_deleted;
2195 if (max_change > 0) {
2196 int total = ((add + del) * max + max_change / 2) / max_change;
2197 add = (add * max + max_change / 2) / max_change;
2198 del = total - add;
2200 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2201 add, pluses, del, minuses);
2204 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2206 switch (st->st_mode & S_IFMT) {
2207 case S_IFLNK:
2208 if (strbuf_readlink(buf, path, st->st_size) < 0)
2209 return error(_("unable to read symlink %s"), path);
2210 return 0;
2211 case S_IFREG:
2212 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2213 return error(_("unable to open or read %s"), path);
2214 convert_to_git(path, buf->buf, buf->len, buf, 0);
2215 return 0;
2216 default:
2217 return -1;
2222 * Update the preimage, and the common lines in postimage,
2223 * from buffer buf of length len. If postlen is 0 the postimage
2224 * is updated in place, otherwise it's updated on a new buffer
2225 * of length postlen
2228 static void update_pre_post_images(struct image *preimage,
2229 struct image *postimage,
2230 char *buf,
2231 size_t len, size_t postlen)
2233 int i, ctx, reduced;
2234 char *new, *old, *fixed;
2235 struct image fixed_preimage;
2238 * Update the preimage with whitespace fixes. Note that we
2239 * are not losing preimage->buf -- apply_one_fragment() will
2240 * free "oldlines".
2242 prepare_image(&fixed_preimage, buf, len, 1);
2243 assert(postlen
2244 ? fixed_preimage.nr == preimage->nr
2245 : fixed_preimage.nr <= preimage->nr);
2246 for (i = 0; i < fixed_preimage.nr; i++)
2247 fixed_preimage.line[i].flag = preimage->line[i].flag;
2248 free(preimage->line_allocated);
2249 *preimage = fixed_preimage;
2252 * Adjust the common context lines in postimage. This can be
2253 * done in-place when we are shrinking it with whitespace
2254 * fixing, but needs a new buffer when ignoring whitespace or
2255 * expanding leading tabs to spaces.
2257 * We trust the caller to tell us if the update can be done
2258 * in place (postlen==0) or not.
2260 old = postimage->buf;
2261 if (postlen)
2262 new = postimage->buf = xmalloc(postlen);
2263 else
2264 new = old;
2265 fixed = preimage->buf;
2267 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2268 size_t l_len = postimage->line[i].len;
2269 if (!(postimage->line[i].flag & LINE_COMMON)) {
2270 /* an added line -- no counterparts in preimage */
2271 memmove(new, old, l_len);
2272 old += l_len;
2273 new += l_len;
2274 continue;
2277 /* a common context -- skip it in the original postimage */
2278 old += l_len;
2280 /* and find the corresponding one in the fixed preimage */
2281 while (ctx < preimage->nr &&
2282 !(preimage->line[ctx].flag & LINE_COMMON)) {
2283 fixed += preimage->line[ctx].len;
2284 ctx++;
2288 * preimage is expected to run out, if the caller
2289 * fixed addition of trailing blank lines.
2291 if (preimage->nr <= ctx) {
2292 reduced++;
2293 continue;
2296 /* and copy it in, while fixing the line length */
2297 l_len = preimage->line[ctx].len;
2298 memcpy(new, fixed, l_len);
2299 new += l_len;
2300 fixed += l_len;
2301 postimage->line[i].len = l_len;
2302 ctx++;
2305 if (postlen
2306 ? postlen < new - postimage->buf
2307 : postimage->len < new - postimage->buf)
2308 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2309 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));
2311 /* Fix the length of the whole thing */
2312 postimage->len = new - postimage->buf;
2313 postimage->nr -= reduced;
2316 static int line_by_line_fuzzy_match(struct image *img,
2317 struct image *preimage,
2318 struct image *postimage,
2319 unsigned long try,
2320 int try_lno,
2321 int preimage_limit)
2323 int i;
2324 size_t imgoff = 0;
2325 size_t preoff = 0;
2326 size_t postlen = postimage->len;
2327 size_t extra_chars;
2328 char *buf;
2329 char *preimage_eof;
2330 char *preimage_end;
2331 struct strbuf fixed;
2332 char *fixed_buf;
2333 size_t fixed_len;
2335 for (i = 0; i < preimage_limit; i++) {
2336 size_t prelen = preimage->line[i].len;
2337 size_t imglen = img->line[try_lno+i].len;
2339 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2340 preimage->buf + preoff, prelen))
2341 return 0;
2342 if (preimage->line[i].flag & LINE_COMMON)
2343 postlen += imglen - prelen;
2344 imgoff += imglen;
2345 preoff += prelen;
2349 * Ok, the preimage matches with whitespace fuzz.
2351 * imgoff now holds the true length of the target that
2352 * matches the preimage before the end of the file.
2354 * Count the number of characters in the preimage that fall
2355 * beyond the end of the file and make sure that all of them
2356 * are whitespace characters. (This can only happen if
2357 * we are removing blank lines at the end of the file.)
2359 buf = preimage_eof = preimage->buf + preoff;
2360 for ( ; i < preimage->nr; i++)
2361 preoff += preimage->line[i].len;
2362 preimage_end = preimage->buf + preoff;
2363 for ( ; buf < preimage_end; buf++)
2364 if (!isspace(*buf))
2365 return 0;
2368 * Update the preimage and the common postimage context
2369 * lines to use the same whitespace as the target.
2370 * If whitespace is missing in the target (i.e.
2371 * if the preimage extends beyond the end of the file),
2372 * use the whitespace from the preimage.
2374 extra_chars = preimage_end - preimage_eof;
2375 strbuf_init(&fixed, imgoff + extra_chars);
2376 strbuf_add(&fixed, img->buf + try, imgoff);
2377 strbuf_add(&fixed, preimage_eof, extra_chars);
2378 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2379 update_pre_post_images(preimage, postimage,
2380 fixed_buf, fixed_len, postlen);
2381 return 1;
2384 static int match_fragment(struct image *img,
2385 struct image *preimage,
2386 struct image *postimage,
2387 unsigned long try,
2388 int try_lno,
2389 unsigned ws_rule,
2390 int match_beginning, int match_end)
2392 int i;
2393 char *fixed_buf, *buf, *orig, *target;
2394 struct strbuf fixed;
2395 size_t fixed_len, postlen;
2396 int preimage_limit;
2398 if (preimage->nr + try_lno <= img->nr) {
2400 * The hunk falls within the boundaries of img.
2402 preimage_limit = preimage->nr;
2403 if (match_end && (preimage->nr + try_lno != img->nr))
2404 return 0;
2405 } else if (ws_error_action == correct_ws_error &&
2406 (ws_rule & WS_BLANK_AT_EOF)) {
2408 * This hunk extends beyond the end of img, and we are
2409 * removing blank lines at the end of the file. This
2410 * many lines from the beginning of the preimage must
2411 * match with img, and the remainder of the preimage
2412 * must be blank.
2414 preimage_limit = img->nr - try_lno;
2415 } else {
2417 * The hunk extends beyond the end of the img and
2418 * we are not removing blanks at the end, so we
2419 * should reject the hunk at this position.
2421 return 0;
2424 if (match_beginning && try_lno)
2425 return 0;
2427 /* Quick hash check */
2428 for (i = 0; i < preimage_limit; i++)
2429 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2430 (preimage->line[i].hash != img->line[try_lno + i].hash))
2431 return 0;
2433 if (preimage_limit == preimage->nr) {
2435 * Do we have an exact match? If we were told to match
2436 * at the end, size must be exactly at try+fragsize,
2437 * otherwise try+fragsize must be still within the preimage,
2438 * and either case, the old piece should match the preimage
2439 * exactly.
2441 if ((match_end
2442 ? (try + preimage->len == img->len)
2443 : (try + preimage->len <= img->len)) &&
2444 !memcmp(img->buf + try, preimage->buf, preimage->len))
2445 return 1;
2446 } else {
2448 * The preimage extends beyond the end of img, so
2449 * there cannot be an exact match.
2451 * There must be one non-blank context line that match
2452 * a line before the end of img.
2454 char *buf_end;
2456 buf = preimage->buf;
2457 buf_end = buf;
2458 for (i = 0; i < preimage_limit; i++)
2459 buf_end += preimage->line[i].len;
2461 for ( ; buf < buf_end; buf++)
2462 if (!isspace(*buf))
2463 break;
2464 if (buf == buf_end)
2465 return 0;
2469 * No exact match. If we are ignoring whitespace, run a line-by-line
2470 * fuzzy matching. We collect all the line length information because
2471 * we need it to adjust whitespace if we match.
2473 if (ws_ignore_action == ignore_ws_change)
2474 return line_by_line_fuzzy_match(img, preimage, postimage,
2475 try, try_lno, preimage_limit);
2477 if (ws_error_action != correct_ws_error)
2478 return 0;
2481 * The hunk does not apply byte-by-byte, but the hash says
2482 * it might with whitespace fuzz. We weren't asked to
2483 * ignore whitespace, we were asked to correct whitespace
2484 * errors, so let's try matching after whitespace correction.
2486 * While checking the preimage against the target, whitespace
2487 * errors in both fixed, we count how large the corresponding
2488 * postimage needs to be. The postimage prepared by
2489 * apply_one_fragment() has whitespace errors fixed on added
2490 * lines already, but the common lines were propagated as-is,
2491 * which may become longer when their whitespace errors are
2492 * fixed.
2495 /* First count added lines in postimage */
2496 postlen = 0;
2497 for (i = 0; i < postimage->nr; i++) {
2498 if (!(postimage->line[i].flag & LINE_COMMON))
2499 postlen += postimage->line[i].len;
2503 * The preimage may extend beyond the end of the file,
2504 * but in this loop we will only handle the part of the
2505 * preimage that falls within the file.
2507 strbuf_init(&fixed, preimage->len + 1);
2508 orig = preimage->buf;
2509 target = img->buf + try;
2510 for (i = 0; i < preimage_limit; i++) {
2511 size_t oldlen = preimage->line[i].len;
2512 size_t tgtlen = img->line[try_lno + i].len;
2513 size_t fixstart = fixed.len;
2514 struct strbuf tgtfix;
2515 int match;
2517 /* Try fixing the line in the preimage */
2518 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2520 /* Try fixing the line in the target */
2521 strbuf_init(&tgtfix, tgtlen);
2522 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2525 * If they match, either the preimage was based on
2526 * a version before our tree fixed whitespace breakage,
2527 * or we are lacking a whitespace-fix patch the tree
2528 * the preimage was based on already had (i.e. target
2529 * has whitespace breakage, the preimage doesn't).
2530 * In either case, we are fixing the whitespace breakages
2531 * so we might as well take the fix together with their
2532 * real change.
2534 match = (tgtfix.len == fixed.len - fixstart &&
2535 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2536 fixed.len - fixstart));
2538 /* Add the length if this is common with the postimage */
2539 if (preimage->line[i].flag & LINE_COMMON)
2540 postlen += tgtfix.len;
2542 strbuf_release(&tgtfix);
2543 if (!match)
2544 goto unmatch_exit;
2546 orig += oldlen;
2547 target += tgtlen;
2552 * Now handle the lines in the preimage that falls beyond the
2553 * end of the file (if any). They will only match if they are
2554 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2555 * false).
2557 for ( ; i < preimage->nr; i++) {
2558 size_t fixstart = fixed.len; /* start of the fixed preimage */
2559 size_t oldlen = preimage->line[i].len;
2560 int j;
2562 /* Try fixing the line in the preimage */
2563 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2565 for (j = fixstart; j < fixed.len; j++)
2566 if (!isspace(fixed.buf[j]))
2567 goto unmatch_exit;
2569 orig += oldlen;
2573 * Yes, the preimage is based on an older version that still
2574 * has whitespace breakages unfixed, and fixing them makes the
2575 * hunk match. Update the context lines in the postimage.
2577 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2578 if (postlen < postimage->len)
2579 postlen = 0;
2580 update_pre_post_images(preimage, postimage,
2581 fixed_buf, fixed_len, postlen);
2582 return 1;
2584 unmatch_exit:
2585 strbuf_release(&fixed);
2586 return 0;
2589 static int find_pos(struct image *img,
2590 struct image *preimage,
2591 struct image *postimage,
2592 int line,
2593 unsigned ws_rule,
2594 int match_beginning, int match_end)
2596 int i;
2597 unsigned long backwards, forwards, try;
2598 int backwards_lno, forwards_lno, try_lno;
2601 * If match_beginning or match_end is specified, there is no
2602 * point starting from a wrong line that will never match and
2603 * wander around and wait for a match at the specified end.
2605 if (match_beginning)
2606 line = 0;
2607 else if (match_end)
2608 line = img->nr - preimage->nr;
2611 * Because the comparison is unsigned, the following test
2612 * will also take care of a negative line number that can
2613 * result when match_end and preimage is larger than the target.
2615 if ((size_t) line > img->nr)
2616 line = img->nr;
2618 try = 0;
2619 for (i = 0; i < line; i++)
2620 try += img->line[i].len;
2623 * There's probably some smart way to do this, but I'll leave
2624 * that to the smart and beautiful people. I'm simple and stupid.
2626 backwards = try;
2627 backwards_lno = line;
2628 forwards = try;
2629 forwards_lno = line;
2630 try_lno = line;
2632 for (i = 0; ; i++) {
2633 if (match_fragment(img, preimage, postimage,
2634 try, try_lno, ws_rule,
2635 match_beginning, match_end))
2636 return try_lno;
2638 again:
2639 if (backwards_lno == 0 && forwards_lno == img->nr)
2640 break;
2642 if (i & 1) {
2643 if (backwards_lno == 0) {
2644 i++;
2645 goto again;
2647 backwards_lno--;
2648 backwards -= img->line[backwards_lno].len;
2649 try = backwards;
2650 try_lno = backwards_lno;
2651 } else {
2652 if (forwards_lno == img->nr) {
2653 i++;
2654 goto again;
2656 forwards += img->line[forwards_lno].len;
2657 forwards_lno++;
2658 try = forwards;
2659 try_lno = forwards_lno;
2663 return -1;
2666 static void remove_first_line(struct image *img)
2668 img->buf += img->line[0].len;
2669 img->len -= img->line[0].len;
2670 img->line++;
2671 img->nr--;
2674 static void remove_last_line(struct image *img)
2676 img->len -= img->line[--img->nr].len;
2680 * The change from "preimage" and "postimage" has been found to
2681 * apply at applied_pos (counts in line numbers) in "img".
2682 * Update "img" to remove "preimage" and replace it with "postimage".
2684 static void update_image(struct apply_state *state,
2685 struct image *img,
2686 int applied_pos,
2687 struct image *preimage,
2688 struct image *postimage)
2691 * remove the copy of preimage at offset in img
2692 * and replace it with postimage
2694 int i, nr;
2695 size_t remove_count, insert_count, applied_at = 0;
2696 char *result;
2697 int preimage_limit;
2700 * If we are removing blank lines at the end of img,
2701 * the preimage may extend beyond the end.
2702 * If that is the case, we must be careful only to
2703 * remove the part of the preimage that falls within
2704 * the boundaries of img. Initialize preimage_limit
2705 * to the number of lines in the preimage that falls
2706 * within the boundaries.
2708 preimage_limit = preimage->nr;
2709 if (preimage_limit > img->nr - applied_pos)
2710 preimage_limit = img->nr - applied_pos;
2712 for (i = 0; i < applied_pos; i++)
2713 applied_at += img->line[i].len;
2715 remove_count = 0;
2716 for (i = 0; i < preimage_limit; i++)
2717 remove_count += img->line[applied_pos + i].len;
2718 insert_count = postimage->len;
2720 /* Adjust the contents */
2721 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2722 memcpy(result, img->buf, applied_at);
2723 memcpy(result + applied_at, postimage->buf, postimage->len);
2724 memcpy(result + applied_at + postimage->len,
2725 img->buf + (applied_at + remove_count),
2726 img->len - (applied_at + remove_count));
2727 free(img->buf);
2728 img->buf = result;
2729 img->len += insert_count - remove_count;
2730 result[img->len] = '\0';
2732 /* Adjust the line table */
2733 nr = img->nr + postimage->nr - preimage_limit;
2734 if (preimage_limit < postimage->nr) {
2736 * NOTE: this knows that we never call remove_first_line()
2737 * on anything other than pre/post image.
2739 REALLOC_ARRAY(img->line, nr);
2740 img->line_allocated = img->line;
2742 if (preimage_limit != postimage->nr)
2743 memmove(img->line + applied_pos + postimage->nr,
2744 img->line + applied_pos + preimage_limit,
2745 (img->nr - (applied_pos + preimage_limit)) *
2746 sizeof(*img->line));
2747 memcpy(img->line + applied_pos,
2748 postimage->line,
2749 postimage->nr * sizeof(*img->line));
2750 if (!state->allow_overlap)
2751 for (i = 0; i < postimage->nr; i++)
2752 img->line[applied_pos + i].flag |= LINE_PATCHED;
2753 img->nr = nr;
2757 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2758 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2759 * replace the part of "img" with "postimage" text.
2761 static int apply_one_fragment(struct apply_state *state,
2762 struct image *img, struct fragment *frag,
2763 int inaccurate_eof, unsigned ws_rule,
2764 int nth_fragment)
2766 int match_beginning, match_end;
2767 const char *patch = frag->patch;
2768 int size = frag->size;
2769 char *old, *oldlines;
2770 struct strbuf newlines;
2771 int new_blank_lines_at_end = 0;
2772 int found_new_blank_lines_at_end = 0;
2773 int hunk_linenr = frag->linenr;
2774 unsigned long leading, trailing;
2775 int pos, applied_pos;
2776 struct image preimage;
2777 struct image postimage;
2779 memset(&preimage, 0, sizeof(preimage));
2780 memset(&postimage, 0, sizeof(postimage));
2781 oldlines = xmalloc(size);
2782 strbuf_init(&newlines, size);
2784 old = oldlines;
2785 while (size > 0) {
2786 char first;
2787 int len = linelen(patch, size);
2788 int plen;
2789 int added_blank_line = 0;
2790 int is_blank_context = 0;
2791 size_t start;
2793 if (!len)
2794 break;
2797 * "plen" is how much of the line we should use for
2798 * the actual patch data. Normally we just remove the
2799 * first character on the line, but if the line is
2800 * followed by "\ No newline", then we also remove the
2801 * last one (which is the newline, of course).
2803 plen = len - 1;
2804 if (len < size && patch[len] == '\\')
2805 plen--;
2806 first = *patch;
2807 if (state->apply_in_reverse) {
2808 if (first == '-')
2809 first = '+';
2810 else if (first == '+')
2811 first = '-';
2814 switch (first) {
2815 case '\n':
2816 /* Newer GNU diff, empty context line */
2817 if (plen < 0)
2818 /* ... followed by '\No newline'; nothing */
2819 break;
2820 *old++ = '\n';
2821 strbuf_addch(&newlines, '\n');
2822 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2823 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2824 is_blank_context = 1;
2825 break;
2826 case ' ':
2827 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2828 ws_blank_line(patch + 1, plen, ws_rule))
2829 is_blank_context = 1;
2830 case '-':
2831 memcpy(old, patch + 1, plen);
2832 add_line_info(&preimage, old, plen,
2833 (first == ' ' ? LINE_COMMON : 0));
2834 old += plen;
2835 if (first == '-')
2836 break;
2837 /* Fall-through for ' ' */
2838 case '+':
2839 /* --no-add does not add new lines */
2840 if (first == '+' && state->no_add)
2841 break;
2843 start = newlines.len;
2844 if (first != '+' ||
2845 !whitespace_error ||
2846 ws_error_action != correct_ws_error) {
2847 strbuf_add(&newlines, patch + 1, plen);
2849 else {
2850 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2852 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2853 (first == '+' ? 0 : LINE_COMMON));
2854 if (first == '+' &&
2855 (ws_rule & WS_BLANK_AT_EOF) &&
2856 ws_blank_line(patch + 1, plen, ws_rule))
2857 added_blank_line = 1;
2858 break;
2859 case '@': case '\\':
2860 /* Ignore it, we already handled it */
2861 break;
2862 default:
2863 if (state->apply_verbosely)
2864 error(_("invalid start of line: '%c'"), first);
2865 applied_pos = -1;
2866 goto out;
2868 if (added_blank_line) {
2869 if (!new_blank_lines_at_end)
2870 found_new_blank_lines_at_end = hunk_linenr;
2871 new_blank_lines_at_end++;
2873 else if (is_blank_context)
2875 else
2876 new_blank_lines_at_end = 0;
2877 patch += len;
2878 size -= len;
2879 hunk_linenr++;
2881 if (inaccurate_eof &&
2882 old > oldlines && old[-1] == '\n' &&
2883 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2884 old--;
2885 strbuf_setlen(&newlines, newlines.len - 1);
2888 leading = frag->leading;
2889 trailing = frag->trailing;
2892 * A hunk to change lines at the beginning would begin with
2893 * @@ -1,L +N,M @@
2894 * but we need to be careful. -U0 that inserts before the second
2895 * line also has this pattern.
2897 * And a hunk to add to an empty file would begin with
2898 * @@ -0,0 +N,M @@
2900 * In other words, a hunk that is (frag->oldpos <= 1) with or
2901 * without leading context must match at the beginning.
2903 match_beginning = (!frag->oldpos ||
2904 (frag->oldpos == 1 && !state->unidiff_zero));
2907 * A hunk without trailing lines must match at the end.
2908 * However, we simply cannot tell if a hunk must match end
2909 * from the lack of trailing lines if the patch was generated
2910 * with unidiff without any context.
2912 match_end = !state->unidiff_zero && !trailing;
2914 pos = frag->newpos ? (frag->newpos - 1) : 0;
2915 preimage.buf = oldlines;
2916 preimage.len = old - oldlines;
2917 postimage.buf = newlines.buf;
2918 postimage.len = newlines.len;
2919 preimage.line = preimage.line_allocated;
2920 postimage.line = postimage.line_allocated;
2922 for (;;) {
2924 applied_pos = find_pos(img, &preimage, &postimage, pos,
2925 ws_rule, match_beginning, match_end);
2927 if (applied_pos >= 0)
2928 break;
2930 /* Am I at my context limits? */
2931 if ((leading <= state->p_context) && (trailing <= state->p_context))
2932 break;
2933 if (match_beginning || match_end) {
2934 match_beginning = match_end = 0;
2935 continue;
2939 * Reduce the number of context lines; reduce both
2940 * leading and trailing if they are equal otherwise
2941 * just reduce the larger context.
2943 if (leading >= trailing) {
2944 remove_first_line(&preimage);
2945 remove_first_line(&postimage);
2946 pos--;
2947 leading--;
2949 if (trailing > leading) {
2950 remove_last_line(&preimage);
2951 remove_last_line(&postimage);
2952 trailing--;
2956 if (applied_pos >= 0) {
2957 if (new_blank_lines_at_end &&
2958 preimage.nr + applied_pos >= img->nr &&
2959 (ws_rule & WS_BLANK_AT_EOF) &&
2960 ws_error_action != nowarn_ws_error) {
2961 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
2962 found_new_blank_lines_at_end);
2963 if (ws_error_action == correct_ws_error) {
2964 while (new_blank_lines_at_end--)
2965 remove_last_line(&postimage);
2968 * We would want to prevent write_out_results()
2969 * from taking place in apply_patch() that follows
2970 * the callchain led us here, which is:
2971 * apply_patch->check_patch_list->check_patch->
2972 * apply_data->apply_fragments->apply_one_fragment
2974 if (ws_error_action == die_on_ws_error)
2975 state->apply = 0;
2978 if (state->apply_verbosely && applied_pos != pos) {
2979 int offset = applied_pos - pos;
2980 if (state->apply_in_reverse)
2981 offset = 0 - offset;
2982 fprintf_ln(stderr,
2983 Q_("Hunk #%d succeeded at %d (offset %d line).",
2984 "Hunk #%d succeeded at %d (offset %d lines).",
2985 offset),
2986 nth_fragment, applied_pos + 1, offset);
2990 * Warn if it was necessary to reduce the number
2991 * of context lines.
2993 if ((leading != frag->leading) ||
2994 (trailing != frag->trailing))
2995 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2996 " to apply fragment at %d"),
2997 leading, trailing, applied_pos+1);
2998 update_image(state, img, applied_pos, &preimage, &postimage);
2999 } else {
3000 if (state->apply_verbosely)
3001 error(_("while searching for:\n%.*s"),
3002 (int)(old - oldlines), oldlines);
3005 out:
3006 free(oldlines);
3007 strbuf_release(&newlines);
3008 free(preimage.line_allocated);
3009 free(postimage.line_allocated);
3011 return (applied_pos < 0);
3014 static int apply_binary_fragment(struct apply_state *state,
3015 struct image *img,
3016 struct patch *patch)
3018 struct fragment *fragment = patch->fragments;
3019 unsigned long len;
3020 void *dst;
3022 if (!fragment)
3023 return error(_("missing binary patch data for '%s'"),
3024 patch->new_name ?
3025 patch->new_name :
3026 patch->old_name);
3028 /* Binary patch is irreversible without the optional second hunk */
3029 if (state->apply_in_reverse) {
3030 if (!fragment->next)
3031 return error("cannot reverse-apply a binary patch "
3032 "without the reverse hunk to '%s'",
3033 patch->new_name
3034 ? patch->new_name : patch->old_name);
3035 fragment = fragment->next;
3037 switch (fragment->binary_patch_method) {
3038 case BINARY_DELTA_DEFLATED:
3039 dst = patch_delta(img->buf, img->len, fragment->patch,
3040 fragment->size, &len);
3041 if (!dst)
3042 return -1;
3043 clear_image(img);
3044 img->buf = dst;
3045 img->len = len;
3046 return 0;
3047 case BINARY_LITERAL_DEFLATED:
3048 clear_image(img);
3049 img->len = fragment->size;
3050 img->buf = xmemdupz(fragment->patch, img->len);
3051 return 0;
3053 return -1;
3057 * Replace "img" with the result of applying the binary patch.
3058 * The binary patch data itself in patch->fragment is still kept
3059 * but the preimage prepared by the caller in "img" is freed here
3060 * or in the helper function apply_binary_fragment() this calls.
3062 static int apply_binary(struct apply_state *state,
3063 struct image *img,
3064 struct patch *patch)
3066 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3067 unsigned char sha1[20];
3070 * For safety, we require patch index line to contain
3071 * full 40-byte textual SHA1 for old and new, at least for now.
3073 if (strlen(patch->old_sha1_prefix) != 40 ||
3074 strlen(patch->new_sha1_prefix) != 40 ||
3075 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
3076 get_sha1_hex(patch->new_sha1_prefix, sha1))
3077 return error("cannot apply binary patch to '%s' "
3078 "without full index line", name);
3080 if (patch->old_name) {
3082 * See if the old one matches what the patch
3083 * applies to.
3085 hash_sha1_file(img->buf, img->len, blob_type, sha1);
3086 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
3087 return error("the patch applies to '%s' (%s), "
3088 "which does not match the "
3089 "current contents.",
3090 name, sha1_to_hex(sha1));
3092 else {
3093 /* Otherwise, the old one must be empty. */
3094 if (img->len)
3095 return error("the patch applies to an empty "
3096 "'%s' but it is not empty", name);
3099 get_sha1_hex(patch->new_sha1_prefix, sha1);
3100 if (is_null_sha1(sha1)) {
3101 clear_image(img);
3102 return 0; /* deletion patch */
3105 if (has_sha1_file(sha1)) {
3106 /* We already have the postimage */
3107 enum object_type type;
3108 unsigned long size;
3109 char *result;
3111 result = read_sha1_file(sha1, &type, &size);
3112 if (!result)
3113 return error("the necessary postimage %s for "
3114 "'%s' cannot be read",
3115 patch->new_sha1_prefix, name);
3116 clear_image(img);
3117 img->buf = result;
3118 img->len = size;
3119 } else {
3121 * We have verified buf matches the preimage;
3122 * apply the patch data to it, which is stored
3123 * in the patch->fragments->{patch,size}.
3125 if (apply_binary_fragment(state, img, patch))
3126 return error(_("binary patch does not apply to '%s'"),
3127 name);
3129 /* verify that the result matches */
3130 hash_sha1_file(img->buf, img->len, blob_type, sha1);
3131 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
3132 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3133 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
3136 return 0;
3139 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3141 struct fragment *frag = patch->fragments;
3142 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3143 unsigned ws_rule = patch->ws_rule;
3144 unsigned inaccurate_eof = patch->inaccurate_eof;
3145 int nth = 0;
3147 if (patch->is_binary)
3148 return apply_binary(state, img, patch);
3150 while (frag) {
3151 nth++;
3152 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3153 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3154 if (!state->apply_with_reject)
3155 return -1;
3156 frag->rejected = 1;
3158 frag = frag->next;
3160 return 0;
3163 static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
3165 if (S_ISGITLINK(mode)) {
3166 strbuf_grow(buf, 100);
3167 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
3168 } else {
3169 enum object_type type;
3170 unsigned long sz;
3171 char *result;
3173 result = read_sha1_file(sha1, &type, &sz);
3174 if (!result)
3175 return -1;
3176 /* XXX read_sha1_file NUL-terminates */
3177 strbuf_attach(buf, result, sz, sz + 1);
3179 return 0;
3182 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3184 if (!ce)
3185 return 0;
3186 return read_blob_object(buf, ce->sha1, ce->ce_mode);
3189 static struct patch *in_fn_table(const char *name)
3191 struct string_list_item *item;
3193 if (name == NULL)
3194 return NULL;
3196 item = string_list_lookup(&fn_table, name);
3197 if (item != NULL)
3198 return (struct patch *)item->util;
3200 return NULL;
3204 * item->util in the filename table records the status of the path.
3205 * Usually it points at a patch (whose result records the contents
3206 * of it after applying it), but it could be PATH_WAS_DELETED for a
3207 * path that a previously applied patch has already removed, or
3208 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3210 * The latter is needed to deal with a case where two paths A and B
3211 * are swapped by first renaming A to B and then renaming B to A;
3212 * moving A to B should not be prevented due to presence of B as we
3213 * will remove it in a later patch.
3215 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3216 #define PATH_WAS_DELETED ((struct patch *) -1)
3218 static int to_be_deleted(struct patch *patch)
3220 return patch == PATH_TO_BE_DELETED;
3223 static int was_deleted(struct patch *patch)
3225 return patch == PATH_WAS_DELETED;
3228 static void add_to_fn_table(struct patch *patch)
3230 struct string_list_item *item;
3233 * Always add new_name unless patch is a deletion
3234 * This should cover the cases for normal diffs,
3235 * file creations and copies
3237 if (patch->new_name != NULL) {
3238 item = string_list_insert(&fn_table, patch->new_name);
3239 item->util = patch;
3243 * store a failure on rename/deletion cases because
3244 * later chunks shouldn't patch old names
3246 if ((patch->new_name == NULL) || (patch->is_rename)) {
3247 item = string_list_insert(&fn_table, patch->old_name);
3248 item->util = PATH_WAS_DELETED;
3252 static void prepare_fn_table(struct patch *patch)
3255 * store information about incoming file deletion
3257 while (patch) {
3258 if ((patch->new_name == NULL) || (patch->is_rename)) {
3259 struct string_list_item *item;
3260 item = string_list_insert(&fn_table, patch->old_name);
3261 item->util = PATH_TO_BE_DELETED;
3263 patch = patch->next;
3267 static int checkout_target(struct index_state *istate,
3268 struct cache_entry *ce, struct stat *st)
3270 struct checkout costate;
3272 memset(&costate, 0, sizeof(costate));
3273 costate.base_dir = "";
3274 costate.refresh_cache = 1;
3275 costate.istate = istate;
3276 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3277 return error(_("cannot checkout %s"), ce->name);
3278 return 0;
3281 static struct patch *previous_patch(struct patch *patch, int *gone)
3283 struct patch *previous;
3285 *gone = 0;
3286 if (patch->is_copy || patch->is_rename)
3287 return NULL; /* "git" patches do not depend on the order */
3289 previous = in_fn_table(patch->old_name);
3290 if (!previous)
3291 return NULL;
3293 if (to_be_deleted(previous))
3294 return NULL; /* the deletion hasn't happened yet */
3296 if (was_deleted(previous))
3297 *gone = 1;
3299 return previous;
3302 static int verify_index_match(const struct cache_entry *ce, struct stat *st)
3304 if (S_ISGITLINK(ce->ce_mode)) {
3305 if (!S_ISDIR(st->st_mode))
3306 return -1;
3307 return 0;
3309 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3312 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3314 static int load_patch_target(struct apply_state *state,
3315 struct strbuf *buf,
3316 const struct cache_entry *ce,
3317 struct stat *st,
3318 const char *name,
3319 unsigned expected_mode)
3321 if (state->cached || state->check_index) {
3322 if (read_file_or_gitlink(ce, buf))
3323 return error(_("read of %s failed"), name);
3324 } else if (name) {
3325 if (S_ISGITLINK(expected_mode)) {
3326 if (ce)
3327 return read_file_or_gitlink(ce, buf);
3328 else
3329 return SUBMODULE_PATCH_WITHOUT_INDEX;
3330 } else if (has_symlink_leading_path(name, strlen(name))) {
3331 return error(_("reading from '%s' beyond a symbolic link"), name);
3332 } else {
3333 if (read_old_data(st, name, buf))
3334 return error(_("read of %s failed"), name);
3337 return 0;
3341 * We are about to apply "patch"; populate the "image" with the
3342 * current version we have, from the working tree or from the index,
3343 * depending on the situation e.g. --cached/--index. If we are
3344 * applying a non-git patch that incrementally updates the tree,
3345 * we read from the result of a previous diff.
3347 static int load_preimage(struct apply_state *state,
3348 struct image *image,
3349 struct patch *patch, struct stat *st,
3350 const struct cache_entry *ce)
3352 struct strbuf buf = STRBUF_INIT;
3353 size_t len;
3354 char *img;
3355 struct patch *previous;
3356 int status;
3358 previous = previous_patch(patch, &status);
3359 if (status)
3360 return error(_("path %s has been renamed/deleted"),
3361 patch->old_name);
3362 if (previous) {
3363 /* We have a patched copy in memory; use that. */
3364 strbuf_add(&buf, previous->result, previous->resultsize);
3365 } else {
3366 status = load_patch_target(state, &buf, ce, st,
3367 patch->old_name, patch->old_mode);
3368 if (status < 0)
3369 return status;
3370 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3372 * There is no way to apply subproject
3373 * patch without looking at the index.
3374 * NEEDSWORK: shouldn't this be flagged
3375 * as an error???
3377 free_fragment_list(patch->fragments);
3378 patch->fragments = NULL;
3379 } else if (status) {
3380 return error(_("read of %s failed"), patch->old_name);
3384 img = strbuf_detach(&buf, &len);
3385 prepare_image(image, img, len, !patch->is_binary);
3386 return 0;
3389 static int three_way_merge(struct image *image,
3390 char *path,
3391 const unsigned char *base,
3392 const unsigned char *ours,
3393 const unsigned char *theirs)
3395 mmfile_t base_file, our_file, their_file;
3396 mmbuffer_t result = { NULL };
3397 int status;
3399 read_mmblob(&base_file, base);
3400 read_mmblob(&our_file, ours);
3401 read_mmblob(&their_file, theirs);
3402 status = ll_merge(&result, path,
3403 &base_file, "base",
3404 &our_file, "ours",
3405 &their_file, "theirs", NULL);
3406 free(base_file.ptr);
3407 free(our_file.ptr);
3408 free(their_file.ptr);
3409 if (status < 0 || !result.ptr) {
3410 free(result.ptr);
3411 return -1;
3413 clear_image(image);
3414 image->buf = result.ptr;
3415 image->len = result.size;
3417 return status;
3421 * When directly falling back to add/add three-way merge, we read from
3422 * the current contents of the new_name. In no cases other than that
3423 * this function will be called.
3425 static int load_current(struct apply_state *state,
3426 struct image *image,
3427 struct patch *patch)
3429 struct strbuf buf = STRBUF_INIT;
3430 int status, pos;
3431 size_t len;
3432 char *img;
3433 struct stat st;
3434 struct cache_entry *ce;
3435 char *name = patch->new_name;
3436 unsigned mode = patch->new_mode;
3438 if (!patch->is_new)
3439 die("BUG: patch to %s is not a creation", patch->old_name);
3441 pos = cache_name_pos(name, strlen(name));
3442 if (pos < 0)
3443 return error(_("%s: does not exist in index"), name);
3444 ce = active_cache[pos];
3445 if (lstat(name, &st)) {
3446 if (errno != ENOENT)
3447 return error(_("%s: %s"), name, strerror(errno));
3448 if (checkout_target(&the_index, ce, &st))
3449 return -1;
3451 if (verify_index_match(ce, &st))
3452 return error(_("%s: does not match index"), name);
3454 status = load_patch_target(state, &buf, ce, &st, name, mode);
3455 if (status < 0)
3456 return status;
3457 else if (status)
3458 return -1;
3459 img = strbuf_detach(&buf, &len);
3460 prepare_image(image, img, len, !patch->is_binary);
3461 return 0;
3464 static int try_threeway(struct apply_state *state,
3465 struct image *image,
3466 struct patch *patch,
3467 struct stat *st,
3468 const struct cache_entry *ce)
3470 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3471 struct strbuf buf = STRBUF_INIT;
3472 size_t len;
3473 int status;
3474 char *img;
3475 struct image tmp_image;
3477 /* No point falling back to 3-way merge in these cases */
3478 if (patch->is_delete ||
3479 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3480 return -1;
3482 /* Preimage the patch was prepared for */
3483 if (patch->is_new)
3484 write_sha1_file("", 0, blob_type, pre_sha1);
3485 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3486 read_blob_object(&buf, pre_sha1, patch->old_mode))
3487 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3489 fprintf(stderr, "Falling back to three-way merge...\n");
3491 img = strbuf_detach(&buf, &len);
3492 prepare_image(&tmp_image, img, len, 1);
3493 /* Apply the patch to get the post image */
3494 if (apply_fragments(state, &tmp_image, patch) < 0) {
3495 clear_image(&tmp_image);
3496 return -1;
3498 /* post_sha1[] is theirs */
3499 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3500 clear_image(&tmp_image);
3502 /* our_sha1[] is ours */
3503 if (patch->is_new) {
3504 if (load_current(state, &tmp_image, patch))
3505 return error("cannot read the current contents of '%s'",
3506 patch->new_name);
3507 } else {
3508 if (load_preimage(state, &tmp_image, patch, st, ce))
3509 return error("cannot read the current contents of '%s'",
3510 patch->old_name);
3512 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3513 clear_image(&tmp_image);
3515 /* in-core three-way merge between post and our using pre as base */
3516 status = three_way_merge(image, patch->new_name,
3517 pre_sha1, our_sha1, post_sha1);
3518 if (status < 0) {
3519 fprintf(stderr, "Failed to fall back on three-way merge...\n");
3520 return status;
3523 if (status) {
3524 patch->conflicted_threeway = 1;
3525 if (patch->is_new)
3526 oidclr(&patch->threeway_stage[0]);
3527 else
3528 hashcpy(patch->threeway_stage[0].hash, pre_sha1);
3529 hashcpy(patch->threeway_stage[1].hash, our_sha1);
3530 hashcpy(patch->threeway_stage[2].hash, post_sha1);
3531 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);
3532 } else {
3533 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);
3535 return 0;
3538 static int apply_data(struct apply_state *state, struct patch *patch,
3539 struct stat *st, const struct cache_entry *ce)
3541 struct image image;
3543 if (load_preimage(state, &image, patch, st, ce) < 0)
3544 return -1;
3546 if (patch->direct_to_threeway ||
3547 apply_fragments(state, &image, patch) < 0) {
3548 /* Note: with --reject, apply_fragments() returns 0 */
3549 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0)
3550 return -1;
3552 patch->result = image.buf;
3553 patch->resultsize = image.len;
3554 add_to_fn_table(patch);
3555 free(image.line_allocated);
3557 if (0 < patch->is_delete && patch->resultsize)
3558 return error(_("removal patch leaves file contents"));
3560 return 0;
3564 * If "patch" that we are looking at modifies or deletes what we have,
3565 * we would want it not to lose any local modification we have, either
3566 * in the working tree or in the index.
3568 * This also decides if a non-git patch is a creation patch or a
3569 * modification to an existing empty file. We do not check the state
3570 * of the current tree for a creation patch in this function; the caller
3571 * check_patch() separately makes sure (and errors out otherwise) that
3572 * the path the patch creates does not exist in the current tree.
3574 static int check_preimage(struct apply_state *state,
3575 struct patch *patch,
3576 struct cache_entry **ce,
3577 struct stat *st)
3579 const char *old_name = patch->old_name;
3580 struct patch *previous = NULL;
3581 int stat_ret = 0, status;
3582 unsigned st_mode = 0;
3584 if (!old_name)
3585 return 0;
3587 assert(patch->is_new <= 0);
3588 previous = previous_patch(patch, &status);
3590 if (status)
3591 return error(_("path %s has been renamed/deleted"), old_name);
3592 if (previous) {
3593 st_mode = previous->new_mode;
3594 } else if (!state->cached) {
3595 stat_ret = lstat(old_name, st);
3596 if (stat_ret && errno != ENOENT)
3597 return error(_("%s: %s"), old_name, strerror(errno));
3600 if (state->check_index && !previous) {
3601 int pos = cache_name_pos(old_name, strlen(old_name));
3602 if (pos < 0) {
3603 if (patch->is_new < 0)
3604 goto is_new;
3605 return error(_("%s: does not exist in index"), old_name);
3607 *ce = active_cache[pos];
3608 if (stat_ret < 0) {
3609 if (checkout_target(&the_index, *ce, st))
3610 return -1;
3612 if (!state->cached && verify_index_match(*ce, st))
3613 return error(_("%s: does not match index"), old_name);
3614 if (state->cached)
3615 st_mode = (*ce)->ce_mode;
3616 } else if (stat_ret < 0) {
3617 if (patch->is_new < 0)
3618 goto is_new;
3619 return error(_("%s: %s"), old_name, strerror(errno));
3622 if (!state->cached && !previous)
3623 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3625 if (patch->is_new < 0)
3626 patch->is_new = 0;
3627 if (!patch->old_mode)
3628 patch->old_mode = st_mode;
3629 if ((st_mode ^ patch->old_mode) & S_IFMT)
3630 return error(_("%s: wrong type"), old_name);
3631 if (st_mode != patch->old_mode)
3632 warning(_("%s has type %o, expected %o"),
3633 old_name, st_mode, patch->old_mode);
3634 if (!patch->new_mode && !patch->is_delete)
3635 patch->new_mode = st_mode;
3636 return 0;
3638 is_new:
3639 patch->is_new = 1;
3640 patch->is_delete = 0;
3641 free(patch->old_name);
3642 patch->old_name = NULL;
3643 return 0;
3647 #define EXISTS_IN_INDEX 1
3648 #define EXISTS_IN_WORKTREE 2
3650 static int check_to_create(struct apply_state *state,
3651 const char *new_name,
3652 int ok_if_exists)
3654 struct stat nst;
3656 if (state->check_index &&
3657 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3658 !ok_if_exists)
3659 return EXISTS_IN_INDEX;
3660 if (state->cached)
3661 return 0;
3663 if (!lstat(new_name, &nst)) {
3664 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3665 return 0;
3667 * A leading component of new_name might be a symlink
3668 * that is going to be removed with this patch, but
3669 * still pointing at somewhere that has the path.
3670 * In such a case, path "new_name" does not exist as
3671 * far as git is concerned.
3673 if (has_symlink_leading_path(new_name, strlen(new_name)))
3674 return 0;
3676 return EXISTS_IN_WORKTREE;
3677 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3678 return error("%s: %s", new_name, strerror(errno));
3680 return 0;
3684 * We need to keep track of how symlinks in the preimage are
3685 * manipulated by the patches. A patch to add a/b/c where a/b
3686 * is a symlink should not be allowed to affect the directory
3687 * the symlink points at, but if the same patch removes a/b,
3688 * it is perfectly fine, as the patch removes a/b to make room
3689 * to create a directory a/b so that a/b/c can be created.
3691 static struct string_list symlink_changes;
3692 #define SYMLINK_GOES_AWAY 01
3693 #define SYMLINK_IN_RESULT 02
3695 static uintptr_t register_symlink_changes(const char *path, uintptr_t what)
3697 struct string_list_item *ent;
3699 ent = string_list_lookup(&symlink_changes, path);
3700 if (!ent) {
3701 ent = string_list_insert(&symlink_changes, path);
3702 ent->util = (void *)0;
3704 ent->util = (void *)(what | ((uintptr_t)ent->util));
3705 return (uintptr_t)ent->util;
3708 static uintptr_t check_symlink_changes(const char *path)
3710 struct string_list_item *ent;
3712 ent = string_list_lookup(&symlink_changes, path);
3713 if (!ent)
3714 return 0;
3715 return (uintptr_t)ent->util;
3718 static void prepare_symlink_changes(struct patch *patch)
3720 for ( ; patch; patch = patch->next) {
3721 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3722 (patch->is_rename || patch->is_delete))
3723 /* the symlink at patch->old_name is removed */
3724 register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);
3726 if (patch->new_name && S_ISLNK(patch->new_mode))
3727 /* the symlink at patch->new_name is created or remains */
3728 register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);
3732 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3734 do {
3735 unsigned int change;
3737 while (--name->len && name->buf[name->len] != '/')
3738 ; /* scan backwards */
3739 if (!name->len)
3740 break;
3741 name->buf[name->len] = '\0';
3742 change = check_symlink_changes(name->buf);
3743 if (change & SYMLINK_IN_RESULT)
3744 return 1;
3745 if (change & SYMLINK_GOES_AWAY)
3747 * This cannot be "return 0", because we may
3748 * see a new one created at a higher level.
3750 continue;
3752 /* otherwise, check the preimage */
3753 if (state->check_index) {
3754 struct cache_entry *ce;
3756 ce = cache_file_exists(name->buf, name->len, ignore_case);
3757 if (ce && S_ISLNK(ce->ce_mode))
3758 return 1;
3759 } else {
3760 struct stat st;
3761 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3762 return 1;
3764 } while (1);
3765 return 0;
3768 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3770 int ret;
3771 struct strbuf name = STRBUF_INIT;
3773 assert(*name_ != '\0');
3774 strbuf_addstr(&name, name_);
3775 ret = path_is_beyond_symlink_1(state, &name);
3776 strbuf_release(&name);
3778 return ret;
3781 static void die_on_unsafe_path(struct patch *patch)
3783 const char *old_name = NULL;
3784 const char *new_name = NULL;
3785 if (patch->is_delete)
3786 old_name = patch->old_name;
3787 else if (!patch->is_new && !patch->is_copy)
3788 old_name = patch->old_name;
3789 if (!patch->is_delete)
3790 new_name = patch->new_name;
3792 if (old_name && !verify_path(old_name))
3793 die(_("invalid path '%s'"), old_name);
3794 if (new_name && !verify_path(new_name))
3795 die(_("invalid path '%s'"), new_name);
3799 * Check and apply the patch in-core; leave the result in patch->result
3800 * for the caller to write it out to the final destination.
3802 static int check_patch(struct apply_state *state, struct patch *patch)
3804 struct stat st;
3805 const char *old_name = patch->old_name;
3806 const char *new_name = patch->new_name;
3807 const char *name = old_name ? old_name : new_name;
3808 struct cache_entry *ce = NULL;
3809 struct patch *tpatch;
3810 int ok_if_exists;
3811 int status;
3813 patch->rejected = 1; /* we will drop this after we succeed */
3815 status = check_preimage(state, patch, &ce, &st);
3816 if (status)
3817 return status;
3818 old_name = patch->old_name;
3821 * A type-change diff is always split into a patch to delete
3822 * old, immediately followed by a patch to create new (see
3823 * diff.c::run_diff()); in such a case it is Ok that the entry
3824 * to be deleted by the previous patch is still in the working
3825 * tree and in the index.
3827 * A patch to swap-rename between A and B would first rename A
3828 * to B and then rename B to A. While applying the first one,
3829 * the presence of B should not stop A from getting renamed to
3830 * B; ask to_be_deleted() about the later rename. Removal of
3831 * B and rename from A to B is handled the same way by asking
3832 * was_deleted().
3834 if ((tpatch = in_fn_table(new_name)) &&
3835 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3836 ok_if_exists = 1;
3837 else
3838 ok_if_exists = 0;
3840 if (new_name &&
3841 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3842 int err = check_to_create(state, new_name, ok_if_exists);
3844 if (err && state->threeway) {
3845 patch->direct_to_threeway = 1;
3846 } else switch (err) {
3847 case 0:
3848 break; /* happy */
3849 case EXISTS_IN_INDEX:
3850 return error(_("%s: already exists in index"), new_name);
3851 break;
3852 case EXISTS_IN_WORKTREE:
3853 return error(_("%s: already exists in working directory"),
3854 new_name);
3855 default:
3856 return err;
3859 if (!patch->new_mode) {
3860 if (0 < patch->is_new)
3861 patch->new_mode = S_IFREG | 0644;
3862 else
3863 patch->new_mode = patch->old_mode;
3867 if (new_name && old_name) {
3868 int same = !strcmp(old_name, new_name);
3869 if (!patch->new_mode)
3870 patch->new_mode = patch->old_mode;
3871 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3872 if (same)
3873 return error(_("new mode (%o) of %s does not "
3874 "match old mode (%o)"),
3875 patch->new_mode, new_name,
3876 patch->old_mode);
3877 else
3878 return error(_("new mode (%o) of %s does not "
3879 "match old mode (%o) of %s"),
3880 patch->new_mode, new_name,
3881 patch->old_mode, old_name);
3885 if (!state->unsafe_paths)
3886 die_on_unsafe_path(patch);
3889 * An attempt to read from or delete a path that is beyond a
3890 * symbolic link will be prevented by load_patch_target() that
3891 * is called at the beginning of apply_data() so we do not
3892 * have to worry about a patch marked with "is_delete" bit
3893 * here. We however need to make sure that the patch result
3894 * is not deposited to a path that is beyond a symbolic link
3895 * here.
3897 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
3898 return error(_("affected file '%s' is beyond a symbolic link"),
3899 patch->new_name);
3901 if (apply_data(state, patch, &st, ce) < 0)
3902 return error(_("%s: patch does not apply"), name);
3903 patch->rejected = 0;
3904 return 0;
3907 static int check_patch_list(struct apply_state *state, struct patch *patch)
3909 int err = 0;
3911 prepare_symlink_changes(patch);
3912 prepare_fn_table(patch);
3913 while (patch) {
3914 if (state->apply_verbosely)
3915 say_patch_name(stderr,
3916 _("Checking patch %s..."), patch);
3917 err |= check_patch(state, patch);
3918 patch = patch->next;
3920 return err;
3923 /* This function tries to read the sha1 from the current index */
3924 static int get_current_sha1(const char *path, unsigned char *sha1)
3926 int pos;
3928 if (read_cache() < 0)
3929 return -1;
3930 pos = cache_name_pos(path, strlen(path));
3931 if (pos < 0)
3932 return -1;
3933 hashcpy(sha1, active_cache[pos]->sha1);
3934 return 0;
3937 static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])
3940 * A usable gitlink patch has only one fragment (hunk) that looks like:
3941 * @@ -1 +1 @@
3942 * -Subproject commit <old sha1>
3943 * +Subproject commit <new sha1>
3944 * or
3945 * @@ -1 +0,0 @@
3946 * -Subproject commit <old sha1>
3947 * for a removal patch.
3949 struct fragment *hunk = p->fragments;
3950 static const char heading[] = "-Subproject commit ";
3951 char *preimage;
3953 if (/* does the patch have only one hunk? */
3954 hunk && !hunk->next &&
3955 /* is its preimage one line? */
3956 hunk->oldpos == 1 && hunk->oldlines == 1 &&
3957 /* does preimage begin with the heading? */
3958 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
3959 starts_with(++preimage, heading) &&
3960 /* does it record full SHA-1? */
3961 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&
3962 preimage[sizeof(heading) + 40 - 1] == '\n' &&
3963 /* does the abbreviated name on the index line agree with it? */
3964 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
3965 return 0; /* it all looks fine */
3967 /* we may have full object name on the index line */
3968 return get_sha1_hex(p->old_sha1_prefix, sha1);
3971 /* Build an index that contains the just the files needed for a 3way merge */
3972 static void build_fake_ancestor(struct patch *list, const char *filename)
3974 struct patch *patch;
3975 struct index_state result = { NULL };
3976 static struct lock_file lock;
3978 /* Once we start supporting the reverse patch, it may be
3979 * worth showing the new sha1 prefix, but until then...
3981 for (patch = list; patch; patch = patch->next) {
3982 unsigned char sha1[20];
3983 struct cache_entry *ce;
3984 const char *name;
3986 name = patch->old_name ? patch->old_name : patch->new_name;
3987 if (0 < patch->is_new)
3988 continue;
3990 if (S_ISGITLINK(patch->old_mode)) {
3991 if (!preimage_sha1_in_gitlink_patch(patch, sha1))
3992 ; /* ok, the textual part looks sane */
3993 else
3994 die("sha1 information is lacking or useless for submodule %s",
3995 name);
3996 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {
3997 ; /* ok */
3998 } else if (!patch->lines_added && !patch->lines_deleted) {
3999 /* mode-only change: update the current */
4000 if (get_current_sha1(patch->old_name, sha1))
4001 die("mode change for %s, which is not "
4002 "in current HEAD", name);
4003 } else
4004 die("sha1 information is lacking or useless "
4005 "(%s).", name);
4007 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);
4008 if (!ce)
4009 die(_("make_cache_entry failed for path '%s'"), name);
4010 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
4011 die ("Could not add %s to temporary index", name);
4014 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
4015 if (write_locked_index(&result, &lock, COMMIT_LOCK))
4016 die ("Could not write temporary index to %s", filename);
4018 discard_index(&result);
4021 static void stat_patch_list(struct patch *patch)
4023 int files, adds, dels;
4025 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4026 files++;
4027 adds += patch->lines_added;
4028 dels += patch->lines_deleted;
4029 show_stats(patch);
4032 print_stat_summary(stdout, files, adds, dels);
4035 static void numstat_patch_list(struct apply_state *state,
4036 struct patch *patch)
4038 for ( ; patch; patch = patch->next) {
4039 const char *name;
4040 name = patch->new_name ? patch->new_name : patch->old_name;
4041 if (patch->is_binary)
4042 printf("-\t-\t");
4043 else
4044 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4045 write_name_quoted(name, stdout, state->line_termination);
4049 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4051 if (mode)
4052 printf(" %s mode %06o %s\n", newdelete, mode, name);
4053 else
4054 printf(" %s %s\n", newdelete, name);
4057 static void show_mode_change(struct patch *p, int show_name)
4059 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4060 if (show_name)
4061 printf(" mode change %06o => %06o %s\n",
4062 p->old_mode, p->new_mode, p->new_name);
4063 else
4064 printf(" mode change %06o => %06o\n",
4065 p->old_mode, p->new_mode);
4069 static void show_rename_copy(struct patch *p)
4071 const char *renamecopy = p->is_rename ? "rename" : "copy";
4072 const char *old, *new;
4074 /* Find common prefix */
4075 old = p->old_name;
4076 new = p->new_name;
4077 while (1) {
4078 const char *slash_old, *slash_new;
4079 slash_old = strchr(old, '/');
4080 slash_new = strchr(new, '/');
4081 if (!slash_old ||
4082 !slash_new ||
4083 slash_old - old != slash_new - new ||
4084 memcmp(old, new, slash_new - new))
4085 break;
4086 old = slash_old + 1;
4087 new = slash_new + 1;
4089 /* p->old_name thru old is the common prefix, and old and new
4090 * through the end of names are renames
4092 if (old != p->old_name)
4093 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4094 (int)(old - p->old_name), p->old_name,
4095 old, new, p->score);
4096 else
4097 printf(" %s %s => %s (%d%%)\n", renamecopy,
4098 p->old_name, p->new_name, p->score);
4099 show_mode_change(p, 0);
4102 static void summary_patch_list(struct patch *patch)
4104 struct patch *p;
4106 for (p = patch; p; p = p->next) {
4107 if (p->is_new)
4108 show_file_mode_name("create", p->new_mode, p->new_name);
4109 else if (p->is_delete)
4110 show_file_mode_name("delete", p->old_mode, p->old_name);
4111 else {
4112 if (p->is_rename || p->is_copy)
4113 show_rename_copy(p);
4114 else {
4115 if (p->score) {
4116 printf(" rewrite %s (%d%%)\n",
4117 p->new_name, p->score);
4118 show_mode_change(p, 0);
4120 else
4121 show_mode_change(p, 1);
4127 static void patch_stats(struct patch *patch)
4129 int lines = patch->lines_added + patch->lines_deleted;
4131 if (lines > max_change)
4132 max_change = lines;
4133 if (patch->old_name) {
4134 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4135 if (!len)
4136 len = strlen(patch->old_name);
4137 if (len > max_len)
4138 max_len = len;
4140 if (patch->new_name) {
4141 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4142 if (!len)
4143 len = strlen(patch->new_name);
4144 if (len > max_len)
4145 max_len = len;
4149 static void remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4151 if (state->update_index) {
4152 if (remove_file_from_cache(patch->old_name) < 0)
4153 die(_("unable to remove %s from index"), patch->old_name);
4155 if (!state->cached) {
4156 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4157 remove_path(patch->old_name);
4162 static void add_index_file(struct apply_state *state,
4163 const char *path,
4164 unsigned mode,
4165 void *buf,
4166 unsigned long size)
4168 struct stat st;
4169 struct cache_entry *ce;
4170 int namelen = strlen(path);
4171 unsigned ce_size = cache_entry_size(namelen);
4173 if (!state->update_index)
4174 return;
4176 ce = xcalloc(1, ce_size);
4177 memcpy(ce->name, path, namelen);
4178 ce->ce_mode = create_ce_mode(mode);
4179 ce->ce_flags = create_ce_flags(0);
4180 ce->ce_namelen = namelen;
4181 if (S_ISGITLINK(mode)) {
4182 const char *s;
4184 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4185 get_sha1_hex(s, ce->sha1))
4186 die(_("corrupt patch for submodule %s"), path);
4187 } else {
4188 if (!state->cached) {
4189 if (lstat(path, &st) < 0)
4190 die_errno(_("unable to stat newly created file '%s'"),
4191 path);
4192 fill_stat_cache_info(ce, &st);
4194 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
4195 die(_("unable to create backing store for newly created file %s"), path);
4197 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4198 die(_("unable to add cache entry for %s"), path);
4201 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
4203 int fd;
4204 struct strbuf nbuf = STRBUF_INIT;
4206 if (S_ISGITLINK(mode)) {
4207 struct stat st;
4208 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4209 return 0;
4210 return mkdir(path, 0777);
4213 if (has_symlinks && S_ISLNK(mode))
4214 /* Although buf:size is counted string, it also is NUL
4215 * terminated.
4217 return symlink(buf, path);
4219 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4220 if (fd < 0)
4221 return -1;
4223 if (convert_to_working_tree(path, buf, size, &nbuf)) {
4224 size = nbuf.len;
4225 buf = nbuf.buf;
4227 write_or_die(fd, buf, size);
4228 strbuf_release(&nbuf);
4230 if (close(fd) < 0)
4231 die_errno(_("closing file '%s'"), path);
4232 return 0;
4236 * We optimistically assume that the directories exist,
4237 * which is true 99% of the time anyway. If they don't,
4238 * we create them and try again.
4240 static void create_one_file(struct apply_state *state,
4241 char *path,
4242 unsigned mode,
4243 const char *buf,
4244 unsigned long size)
4246 if (state->cached)
4247 return;
4248 if (!try_create_file(path, mode, buf, size))
4249 return;
4251 if (errno == ENOENT) {
4252 if (safe_create_leading_directories(path))
4253 return;
4254 if (!try_create_file(path, mode, buf, size))
4255 return;
4258 if (errno == EEXIST || errno == EACCES) {
4259 /* We may be trying to create a file where a directory
4260 * used to be.
4262 struct stat st;
4263 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4264 errno = EEXIST;
4267 if (errno == EEXIST) {
4268 unsigned int nr = getpid();
4270 for (;;) {
4271 char newpath[PATH_MAX];
4272 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4273 if (!try_create_file(newpath, mode, buf, size)) {
4274 if (!rename(newpath, path))
4275 return;
4276 unlink_or_warn(newpath);
4277 break;
4279 if (errno != EEXIST)
4280 break;
4281 ++nr;
4284 die_errno(_("unable to write file '%s' mode %o"), path, mode);
4287 static void add_conflicted_stages_file(struct apply_state *state,
4288 struct patch *patch)
4290 int stage, namelen;
4291 unsigned ce_size, mode;
4292 struct cache_entry *ce;
4294 if (!state->update_index)
4295 return;
4296 namelen = strlen(patch->new_name);
4297 ce_size = cache_entry_size(namelen);
4298 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4300 remove_file_from_cache(patch->new_name);
4301 for (stage = 1; stage < 4; stage++) {
4302 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4303 continue;
4304 ce = xcalloc(1, ce_size);
4305 memcpy(ce->name, patch->new_name, namelen);
4306 ce->ce_mode = create_ce_mode(mode);
4307 ce->ce_flags = create_ce_flags(stage);
4308 ce->ce_namelen = namelen;
4309 hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);
4310 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4311 die(_("unable to add cache entry for %s"), patch->new_name);
4315 static void create_file(struct apply_state *state, struct patch *patch)
4317 char *path = patch->new_name;
4318 unsigned mode = patch->new_mode;
4319 unsigned long size = patch->resultsize;
4320 char *buf = patch->result;
4322 if (!mode)
4323 mode = S_IFREG | 0644;
4324 create_one_file(state, path, mode, buf, size);
4326 if (patch->conflicted_threeway)
4327 add_conflicted_stages_file(state, patch);
4328 else
4329 add_index_file(state, path, mode, buf, size);
4332 /* phase zero is to remove, phase one is to create */
4333 static void write_out_one_result(struct apply_state *state,
4334 struct patch *patch,
4335 int phase)
4337 if (patch->is_delete > 0) {
4338 if (phase == 0)
4339 remove_file(state, patch, 1);
4340 return;
4342 if (patch->is_new > 0 || patch->is_copy) {
4343 if (phase == 1)
4344 create_file(state, patch);
4345 return;
4348 * Rename or modification boils down to the same
4349 * thing: remove the old, write the new
4351 if (phase == 0)
4352 remove_file(state, patch, patch->is_rename);
4353 if (phase == 1)
4354 create_file(state, patch);
4357 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4359 FILE *rej;
4360 char namebuf[PATH_MAX];
4361 struct fragment *frag;
4362 int cnt = 0;
4363 struct strbuf sb = STRBUF_INIT;
4365 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4366 if (!frag->rejected)
4367 continue;
4368 cnt++;
4371 if (!cnt) {
4372 if (state->apply_verbosely)
4373 say_patch_name(stderr,
4374 _("Applied patch %s cleanly."), patch);
4375 return 0;
4378 /* This should not happen, because a removal patch that leaves
4379 * contents are marked "rejected" at the patch level.
4381 if (!patch->new_name)
4382 die(_("internal error"));
4384 /* Say this even without --verbose */
4385 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4386 "Applying patch %%s with %d rejects...",
4387 cnt),
4388 cnt);
4389 say_patch_name(stderr, sb.buf, patch);
4390 strbuf_release(&sb);
4392 cnt = strlen(patch->new_name);
4393 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4394 cnt = ARRAY_SIZE(namebuf) - 5;
4395 warning(_("truncating .rej filename to %.*s.rej"),
4396 cnt - 1, patch->new_name);
4398 memcpy(namebuf, patch->new_name, cnt);
4399 memcpy(namebuf + cnt, ".rej", 5);
4401 rej = fopen(namebuf, "w");
4402 if (!rej)
4403 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
4405 /* Normal git tools never deal with .rej, so do not pretend
4406 * this is a git patch by saying --git or giving extended
4407 * headers. While at it, maybe please "kompare" that wants
4408 * the trailing TAB and some garbage at the end of line ;-).
4410 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4411 patch->new_name, patch->new_name);
4412 for (cnt = 1, frag = patch->fragments;
4413 frag;
4414 cnt++, frag = frag->next) {
4415 if (!frag->rejected) {
4416 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4417 continue;
4419 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4420 fprintf(rej, "%.*s", frag->size, frag->patch);
4421 if (frag->patch[frag->size-1] != '\n')
4422 fputc('\n', rej);
4424 fclose(rej);
4425 return -1;
4428 static int write_out_results(struct apply_state *state, struct patch *list)
4430 int phase;
4431 int errs = 0;
4432 struct patch *l;
4433 struct string_list cpath = STRING_LIST_INIT_DUP;
4435 for (phase = 0; phase < 2; phase++) {
4436 l = list;
4437 while (l) {
4438 if (l->rejected)
4439 errs = 1;
4440 else {
4441 write_out_one_result(state, l, phase);
4442 if (phase == 1) {
4443 if (write_out_one_reject(state, l))
4444 errs = 1;
4445 if (l->conflicted_threeway) {
4446 string_list_append(&cpath, l->new_name);
4447 errs = 1;
4451 l = l->next;
4455 if (cpath.nr) {
4456 struct string_list_item *item;
4458 string_list_sort(&cpath);
4459 for_each_string_list_item(item, &cpath)
4460 fprintf(stderr, "U %s\n", item->string);
4461 string_list_clear(&cpath, 0);
4463 rerere(0);
4466 return errs;
4469 static struct lock_file lock_file;
4471 #define INACCURATE_EOF (1<<0)
4472 #define RECOUNT (1<<1)
4474 static int apply_patch(struct apply_state *state,
4475 int fd,
4476 const char *filename,
4477 int options)
4479 size_t offset;
4480 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4481 struct patch *list = NULL, **listp = &list;
4482 int skipped_patch = 0;
4484 state->patch_input_file = filename;
4485 read_patch_file(&buf, fd);
4486 offset = 0;
4487 while (offset < buf.len) {
4488 struct patch *patch;
4489 int nr;
4491 patch = xcalloc(1, sizeof(*patch));
4492 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
4493 patch->recount = !!(options & RECOUNT);
4494 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4495 if (nr < 0) {
4496 free_patch(patch);
4497 break;
4499 if (state->apply_in_reverse)
4500 reverse_patches(patch);
4501 if (use_patch(state, patch)) {
4502 patch_stats(patch);
4503 *listp = patch;
4504 listp = &patch->next;
4506 else {
4507 if (state->apply_verbosely)
4508 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4509 free_patch(patch);
4510 skipped_patch++;
4512 offset += nr;
4515 if (!list && !skipped_patch)
4516 die(_("unrecognized input"));
4518 if (whitespace_error && (ws_error_action == die_on_ws_error))
4519 state->apply = 0;
4521 state->update_index = state->check_index && state->apply;
4522 if (state->update_index && newfd < 0)
4523 newfd = hold_locked_index(&lock_file, 1);
4525 if (state->check_index) {
4526 if (read_cache() < 0)
4527 die(_("unable to read index file"));
4530 if ((state->check || state->apply) &&
4531 check_patch_list(state, list) < 0 &&
4532 !state->apply_with_reject)
4533 exit(1);
4535 if (state->apply && write_out_results(state, list)) {
4536 if (state->apply_with_reject)
4537 exit(1);
4538 /* with --3way, we still need to write the index out */
4539 return 1;
4542 if (state->fake_ancestor)
4543 build_fake_ancestor(list, state->fake_ancestor);
4545 if (state->diffstat)
4546 stat_patch_list(list);
4548 if (state->numstat)
4549 numstat_patch_list(state, list);
4551 if (state->summary)
4552 summary_patch_list(list);
4554 free_patch_list(list);
4555 strbuf_release(&buf);
4556 string_list_clear(&fn_table, 0);
4557 return 0;
4560 static void git_apply_config(void)
4562 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);
4563 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);
4564 git_config(git_default_config, NULL);
4567 static int option_parse_exclude(const struct option *opt,
4568 const char *arg, int unset)
4570 struct apply_state *state = opt->value;
4571 add_name_limit(state, arg, 1);
4572 return 0;
4575 static int option_parse_include(const struct option *opt,
4576 const char *arg, int unset)
4578 struct apply_state *state = opt->value;
4579 add_name_limit(state, arg, 0);
4580 state->has_include = 1;
4581 return 0;
4584 static int option_parse_p(const struct option *opt,
4585 const char *arg,
4586 int unset)
4588 struct apply_state *state = opt->value;
4589 state->p_value = atoi(arg);
4590 state->p_value_known = 1;
4591 return 0;
4594 static int option_parse_space_change(const struct option *opt,
4595 const char *arg, int unset)
4597 if (unset)
4598 ws_ignore_action = ignore_ws_none;
4599 else
4600 ws_ignore_action = ignore_ws_change;
4601 return 0;
4604 static int option_parse_whitespace(const struct option *opt,
4605 const char *arg, int unset)
4607 const char **whitespace_option = opt->value;
4609 *whitespace_option = arg;
4610 parse_whitespace_option(arg);
4611 return 0;
4614 static int option_parse_directory(const struct option *opt,
4615 const char *arg, int unset)
4617 strbuf_reset(&root);
4618 strbuf_addstr(&root, arg);
4619 strbuf_complete(&root, '/');
4620 return 0;
4623 static void init_apply_state(struct apply_state *state, const char *prefix)
4625 memset(state, 0, sizeof(*state));
4626 state->prefix = prefix;
4627 state->prefix_length = state->prefix ? strlen(state->prefix) : 0;
4628 state->apply = 1;
4629 state->line_termination = '\n';
4630 state->p_value = 1;
4631 state->p_context = UINT_MAX;
4633 git_apply_config();
4634 if (apply_default_whitespace)
4635 parse_whitespace_option(apply_default_whitespace);
4636 if (apply_default_ignorewhitespace)
4637 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4640 static void clear_apply_state(struct apply_state *state)
4642 string_list_clear(&state->limit_by_name, 0);
4645 int cmd_apply(int argc, const char **argv, const char *prefix)
4647 int i;
4648 int errs = 0;
4649 int is_not_gitdir = !startup_info->have_repository;
4650 int force_apply = 0;
4651 int options = 0;
4652 int read_stdin = 1;
4653 struct apply_state state;
4655 const char *whitespace_option = NULL;
4657 struct option builtin_apply_options[] = {
4658 { OPTION_CALLBACK, 0, "exclude", &state, N_("path"),
4659 N_("don't apply changes matching the given path"),
4660 0, option_parse_exclude },
4661 { OPTION_CALLBACK, 0, "include", &state, N_("path"),
4662 N_("apply changes matching the given path"),
4663 0, option_parse_include },
4664 { OPTION_CALLBACK, 'p', NULL, &state, N_("num"),
4665 N_("remove <num> leading slashes from traditional diff paths"),
4666 0, option_parse_p },
4667 OPT_BOOL(0, "no-add", &state.no_add,
4668 N_("ignore additions made by the patch")),
4669 OPT_BOOL(0, "stat", &state.diffstat,
4670 N_("instead of applying the patch, output diffstat for the input")),
4671 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4672 OPT_NOOP_NOARG(0, "binary"),
4673 OPT_BOOL(0, "numstat", &state.numstat,
4674 N_("show number of added and deleted lines in decimal notation")),
4675 OPT_BOOL(0, "summary", &state.summary,
4676 N_("instead of applying the patch, output a summary for the input")),
4677 OPT_BOOL(0, "check", &state.check,
4678 N_("instead of applying the patch, see if the patch is applicable")),
4679 OPT_BOOL(0, "index", &state.check_index,
4680 N_("make sure the patch is applicable to the current index")),
4681 OPT_BOOL(0, "cached", &state.cached,
4682 N_("apply a patch without touching the working tree")),
4683 OPT_BOOL(0, "unsafe-paths", &state.unsafe_paths,
4684 N_("accept a patch that touches outside the working area")),
4685 OPT_BOOL(0, "apply", &force_apply,
4686 N_("also apply the patch (use with --stat/--summary/--check)")),
4687 OPT_BOOL('3', "3way", &state.threeway,
4688 N_( "attempt three-way merge if a patch does not apply")),
4689 OPT_FILENAME(0, "build-fake-ancestor", &state.fake_ancestor,
4690 N_("build a temporary index based on embedded index information")),
4691 /* Think twice before adding "--nul" synonym to this */
4692 OPT_SET_INT('z', NULL, &state.line_termination,
4693 N_("paths are separated with NUL character"), '\0'),
4694 OPT_INTEGER('C', NULL, &state.p_context,
4695 N_("ensure at least <n> lines of context match")),
4696 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),
4697 N_("detect new or modified lines that have whitespace errors"),
4698 0, option_parse_whitespace },
4699 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4700 N_("ignore changes in whitespace when finding context"),
4701 PARSE_OPT_NOARG, option_parse_space_change },
4702 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4703 N_("ignore changes in whitespace when finding context"),
4704 PARSE_OPT_NOARG, option_parse_space_change },
4705 OPT_BOOL('R', "reverse", &state.apply_in_reverse,
4706 N_("apply the patch in reverse")),
4707 OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,
4708 N_("don't expect at least one line of context")),
4709 OPT_BOOL(0, "reject", &state.apply_with_reject,
4710 N_("leave the rejected hunks in corresponding *.rej files")),
4711 OPT_BOOL(0, "allow-overlap", &state.allow_overlap,
4712 N_("allow overlapping hunks")),
4713 OPT__VERBOSE(&state.apply_verbosely, N_("be verbose")),
4714 OPT_BIT(0, "inaccurate-eof", &options,
4715 N_("tolerate incorrectly detected missing new-line at the end of file"),
4716 INACCURATE_EOF),
4717 OPT_BIT(0, "recount", &options,
4718 N_("do not trust the line counts in the hunk headers"),
4719 RECOUNT),
4720 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),
4721 N_("prepend <root> to all filenames"),
4722 0, option_parse_directory },
4723 OPT_END()
4726 init_apply_state(&state, prefix);
4728 argc = parse_options(argc, argv, state.prefix, builtin_apply_options,
4729 apply_usage, 0);
4731 if (state.apply_with_reject && state.threeway)
4732 die("--reject and --3way cannot be used together.");
4733 if (state.cached && state.threeway)
4734 die("--cached and --3way cannot be used together.");
4735 if (state.threeway) {
4736 if (is_not_gitdir)
4737 die(_("--3way outside a repository"));
4738 state.check_index = 1;
4740 if (state.apply_with_reject)
4741 state.apply = state.apply_verbosely = 1;
4742 if (!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))
4743 state.apply = 0;
4744 if (state.check_index && is_not_gitdir)
4745 die(_("--index outside a repository"));
4746 if (state.cached) {
4747 if (is_not_gitdir)
4748 die(_("--cached outside a repository"));
4749 state.check_index = 1;
4751 if (state.check_index)
4752 state.unsafe_paths = 0;
4754 for (i = 0; i < argc; i++) {
4755 const char *arg = argv[i];
4756 int fd;
4758 if (!strcmp(arg, "-")) {
4759 errs |= apply_patch(&state, 0, "<stdin>", options);
4760 read_stdin = 0;
4761 continue;
4762 } else if (0 < state.prefix_length)
4763 arg = prefix_filename(state.prefix,
4764 state.prefix_length,
4765 arg);
4767 fd = open(arg, O_RDONLY);
4768 if (fd < 0)
4769 die_errno(_("can't open patch '%s'"), arg);
4770 read_stdin = 0;
4771 set_default_whitespace_mode(&state, whitespace_option);
4772 errs |= apply_patch(&state, fd, arg, options);
4773 close(fd);
4775 set_default_whitespace_mode(&state, whitespace_option);
4776 if (read_stdin)
4777 errs |= apply_patch(&state, 0, "<stdin>", options);
4778 if (whitespace_error) {
4779 if (squelch_whitespace_errors &&
4780 squelch_whitespace_errors < whitespace_error) {
4781 int squelched =
4782 whitespace_error - squelch_whitespace_errors;
4783 warning(Q_("squelched %d whitespace error",
4784 "squelched %d whitespace errors",
4785 squelched),
4786 squelched);
4788 if (ws_error_action == die_on_ws_error)
4789 die(Q_("%d line adds whitespace errors.",
4790 "%d lines add whitespace errors.",
4791 whitespace_error),
4792 whitespace_error);
4793 if (applied_after_fixing_ws && state.apply)
4794 warning("%d line%s applied after"
4795 " fixing whitespace errors.",
4796 applied_after_fixing_ws,
4797 applied_after_fixing_ws == 1 ? "" : "s");
4798 else if (whitespace_error)
4799 warning(Q_("%d line adds whitespace errors.",
4800 "%d lines add whitespace errors.",
4801 whitespace_error),
4802 whitespace_error);
4805 if (state.update_index) {
4806 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
4807 die(_("Unable to write new index file"));
4810 clear_apply_state(&state);
4812 return !!errs;