builtin/apply: move 'max_change' and 'max_len' into 'struct apply_state'
[git/gitweb.git] / builtin / apply.c
blob9e7d1810e574226b1c9a7ace543079ed244c0ef0
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 enum ws_error_action {
25 nowarn_ws_error,
26 warn_on_ws_error,
27 die_on_ws_error,
28 correct_ws_error
32 enum ws_ignore {
33 ignore_ws_none,
34 ignore_ws_change
37 struct apply_state {
38 const char *prefix;
39 int prefix_length;
41 /* These control what gets looked at and modified */
42 int apply; /* this is not a dry-run */
43 int cached; /* apply to the index only */
44 int check; /* preimage must match working tree, don't actually apply */
45 int check_index; /* preimage must match the indexed version */
46 int update_index; /* check_index && apply */
48 /* These control cosmetic aspect of the output */
49 int diffstat; /* just show a diffstat, and don't actually apply */
50 int numstat; /* just show a numeric diffstat, and don't actually apply */
51 int summary; /* just report creation, deletion, etc, and don't actually apply */
53 /* These boolean parameters control how the apply is done */
54 int allow_overlap;
55 int apply_in_reverse;
56 int apply_with_reject;
57 int apply_verbosely;
58 int no_add;
59 int threeway;
60 int unidiff_zero;
61 int unsafe_paths;
63 /* Other non boolean parameters */
64 const char *fake_ancestor;
65 const char *patch_input_file;
66 int line_termination;
67 struct strbuf root;
68 int p_value;
69 int p_value_known;
70 unsigned int p_context;
72 /* Exclude and include path parameters */
73 struct string_list limit_by_name;
74 int has_include;
77 * For "diff-stat" like behaviour, we keep track of the biggest change
78 * we've seen, and the longest filename. That allows us to do simple
79 * scaling.
81 int max_change;
82 int max_len;
84 /* These control whitespace errors */
85 enum ws_error_action ws_error_action;
86 enum ws_ignore ws_ignore_action;
87 const char *whitespace_option;
88 int whitespace_error;
89 int squelch_whitespace_errors;
90 int applied_after_fixing_ws;
93 static int newfd = -1;
95 static const char * const apply_usage[] = {
96 N_("git apply [<options>] [<patch>...]"),
97 NULL
100 static void parse_whitespace_option(struct apply_state *state, const char *option)
102 if (!option) {
103 state->ws_error_action = warn_on_ws_error;
104 return;
106 if (!strcmp(option, "warn")) {
107 state->ws_error_action = warn_on_ws_error;
108 return;
110 if (!strcmp(option, "nowarn")) {
111 state->ws_error_action = nowarn_ws_error;
112 return;
114 if (!strcmp(option, "error")) {
115 state->ws_error_action = die_on_ws_error;
116 return;
118 if (!strcmp(option, "error-all")) {
119 state->ws_error_action = die_on_ws_error;
120 state->squelch_whitespace_errors = 0;
121 return;
123 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
124 state->ws_error_action = correct_ws_error;
125 return;
127 die(_("unrecognized whitespace option '%s'"), option);
130 static void parse_ignorewhitespace_option(struct apply_state *state,
131 const char *option)
133 if (!option || !strcmp(option, "no") ||
134 !strcmp(option, "false") || !strcmp(option, "never") ||
135 !strcmp(option, "none")) {
136 state->ws_ignore_action = ignore_ws_none;
137 return;
139 if (!strcmp(option, "change")) {
140 state->ws_ignore_action = ignore_ws_change;
141 return;
143 die(_("unrecognized whitespace ignore option '%s'"), option);
146 static void set_default_whitespace_mode(struct apply_state *state)
148 if (!state->whitespace_option && !apply_default_whitespace)
149 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
153 * Various "current state", notably line numbers and what
154 * file (and how) we're patching right now.. The "is_xxxx"
155 * things are flags, where -1 means "don't know yet".
157 static int state_linenr = 1;
160 * This represents one "hunk" from a patch, starting with
161 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
162 * patch text is pointed at by patch, and its byte length
163 * is stored in size. leading and trailing are the number
164 * of context lines.
166 struct fragment {
167 unsigned long leading, trailing;
168 unsigned long oldpos, oldlines;
169 unsigned long newpos, newlines;
171 * 'patch' is usually borrowed from buf in apply_patch(),
172 * but some codepaths store an allocated buffer.
174 const char *patch;
175 unsigned free_patch:1,
176 rejected:1;
177 int size;
178 int linenr;
179 struct fragment *next;
183 * When dealing with a binary patch, we reuse "leading" field
184 * to store the type of the binary hunk, either deflated "delta"
185 * or deflated "literal".
187 #define binary_patch_method leading
188 #define BINARY_DELTA_DEFLATED 1
189 #define BINARY_LITERAL_DEFLATED 2
192 * This represents a "patch" to a file, both metainfo changes
193 * such as creation/deletion, filemode and content changes represented
194 * as a series of fragments.
196 struct patch {
197 char *new_name, *old_name, *def_name;
198 unsigned int old_mode, new_mode;
199 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
200 int rejected;
201 unsigned ws_rule;
202 int lines_added, lines_deleted;
203 int score;
204 unsigned int is_toplevel_relative:1;
205 unsigned int inaccurate_eof:1;
206 unsigned int is_binary:1;
207 unsigned int is_copy:1;
208 unsigned int is_rename:1;
209 unsigned int recount:1;
210 unsigned int conflicted_threeway:1;
211 unsigned int direct_to_threeway:1;
212 struct fragment *fragments;
213 char *result;
214 size_t resultsize;
215 char old_sha1_prefix[41];
216 char new_sha1_prefix[41];
217 struct patch *next;
219 /* three-way fallback result */
220 struct object_id threeway_stage[3];
223 static void free_fragment_list(struct fragment *list)
225 while (list) {
226 struct fragment *next = list->next;
227 if (list->free_patch)
228 free((char *)list->patch);
229 free(list);
230 list = next;
234 static void free_patch(struct patch *patch)
236 free_fragment_list(patch->fragments);
237 free(patch->def_name);
238 free(patch->old_name);
239 free(patch->new_name);
240 free(patch->result);
241 free(patch);
244 static void free_patch_list(struct patch *list)
246 while (list) {
247 struct patch *next = list->next;
248 free_patch(list);
249 list = next;
254 * A line in a file, len-bytes long (includes the terminating LF,
255 * except for an incomplete line at the end if the file ends with
256 * one), and its contents hashes to 'hash'.
258 struct line {
259 size_t len;
260 unsigned hash : 24;
261 unsigned flag : 8;
262 #define LINE_COMMON 1
263 #define LINE_PATCHED 2
267 * This represents a "file", which is an array of "lines".
269 struct image {
270 char *buf;
271 size_t len;
272 size_t nr;
273 size_t alloc;
274 struct line *line_allocated;
275 struct line *line;
279 * Records filenames that have been touched, in order to handle
280 * the case where more than one patches touch the same file.
283 static struct string_list fn_table;
285 static uint32_t hash_line(const char *cp, size_t len)
287 size_t i;
288 uint32_t h;
289 for (i = 0, h = 0; i < len; i++) {
290 if (!isspace(cp[i])) {
291 h = h * 3 + (cp[i] & 0xff);
294 return h;
298 * Compare lines s1 of length n1 and s2 of length n2, ignoring
299 * whitespace difference. Returns 1 if they match, 0 otherwise
301 static int fuzzy_matchlines(const char *s1, size_t n1,
302 const char *s2, size_t n2)
304 const char *last1 = s1 + n1 - 1;
305 const char *last2 = s2 + n2 - 1;
306 int result = 0;
308 /* ignore line endings */
309 while ((*last1 == '\r') || (*last1 == '\n'))
310 last1--;
311 while ((*last2 == '\r') || (*last2 == '\n'))
312 last2--;
314 /* skip leading whitespaces, if both begin with whitespace */
315 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
316 while (isspace(*s1) && (s1 <= last1))
317 s1++;
318 while (isspace(*s2) && (s2 <= last2))
319 s2++;
321 /* early return if both lines are empty */
322 if ((s1 > last1) && (s2 > last2))
323 return 1;
324 while (!result) {
325 result = *s1++ - *s2++;
327 * Skip whitespace inside. We check for whitespace on
328 * both buffers because we don't want "a b" to match
329 * "ab"
331 if (isspace(*s1) && isspace(*s2)) {
332 while (isspace(*s1) && s1 <= last1)
333 s1++;
334 while (isspace(*s2) && s2 <= last2)
335 s2++;
338 * If we reached the end on one side only,
339 * lines don't match
341 if (
342 ((s2 > last2) && (s1 <= last1)) ||
343 ((s1 > last1) && (s2 <= last2)))
344 return 0;
345 if ((s1 > last1) && (s2 > last2))
346 break;
349 return !result;
352 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
354 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
355 img->line_allocated[img->nr].len = len;
356 img->line_allocated[img->nr].hash = hash_line(bol, len);
357 img->line_allocated[img->nr].flag = flag;
358 img->nr++;
362 * "buf" has the file contents to be patched (read from various sources).
363 * attach it to "image" and add line-based index to it.
364 * "image" now owns the "buf".
366 static void prepare_image(struct image *image, char *buf, size_t len,
367 int prepare_linetable)
369 const char *cp, *ep;
371 memset(image, 0, sizeof(*image));
372 image->buf = buf;
373 image->len = len;
375 if (!prepare_linetable)
376 return;
378 ep = image->buf + image->len;
379 cp = image->buf;
380 while (cp < ep) {
381 const char *next;
382 for (next = cp; next < ep && *next != '\n'; next++)
384 if (next < ep)
385 next++;
386 add_line_info(image, cp, next - cp, 0);
387 cp = next;
389 image->line = image->line_allocated;
392 static void clear_image(struct image *image)
394 free(image->buf);
395 free(image->line_allocated);
396 memset(image, 0, sizeof(*image));
399 /* fmt must contain _one_ %s and no other substitution */
400 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
402 struct strbuf sb = STRBUF_INIT;
404 if (patch->old_name && patch->new_name &&
405 strcmp(patch->old_name, patch->new_name)) {
406 quote_c_style(patch->old_name, &sb, NULL, 0);
407 strbuf_addstr(&sb, " => ");
408 quote_c_style(patch->new_name, &sb, NULL, 0);
409 } else {
410 const char *n = patch->new_name;
411 if (!n)
412 n = patch->old_name;
413 quote_c_style(n, &sb, NULL, 0);
415 fprintf(output, fmt, sb.buf);
416 fputc('\n', output);
417 strbuf_release(&sb);
420 #define SLOP (16)
422 static void read_patch_file(struct strbuf *sb, int fd)
424 if (strbuf_read(sb, fd, 0) < 0)
425 die_errno("git apply: failed to read");
428 * Make sure that we have some slop in the buffer
429 * so that we can do speculative "memcmp" etc, and
430 * see to it that it is NUL-filled.
432 strbuf_grow(sb, SLOP);
433 memset(sb->buf + sb->len, 0, SLOP);
436 static unsigned long linelen(const char *buffer, unsigned long size)
438 unsigned long len = 0;
439 while (size--) {
440 len++;
441 if (*buffer++ == '\n')
442 break;
444 return len;
447 static int is_dev_null(const char *str)
449 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
452 #define TERM_SPACE 1
453 #define TERM_TAB 2
455 static int name_terminate(const char *name, int namelen, int c, int terminate)
457 if (c == ' ' && !(terminate & TERM_SPACE))
458 return 0;
459 if (c == '\t' && !(terminate & TERM_TAB))
460 return 0;
462 return 1;
465 /* remove double slashes to make --index work with such filenames */
466 static char *squash_slash(char *name)
468 int i = 0, j = 0;
470 if (!name)
471 return NULL;
473 while (name[i]) {
474 if ((name[j++] = name[i++]) == '/')
475 while (name[i] == '/')
476 i++;
478 name[j] = '\0';
479 return name;
482 static char *find_name_gnu(struct apply_state *state,
483 const char *line,
484 const char *def,
485 int p_value)
487 struct strbuf name = STRBUF_INIT;
488 char *cp;
491 * Proposed "new-style" GNU patch/diff format; see
492 * http://marc.info/?l=git&m=112927316408690&w=2
494 if (unquote_c_style(&name, line, NULL)) {
495 strbuf_release(&name);
496 return NULL;
499 for (cp = name.buf; p_value; p_value--) {
500 cp = strchr(cp, '/');
501 if (!cp) {
502 strbuf_release(&name);
503 return NULL;
505 cp++;
508 strbuf_remove(&name, 0, cp - name.buf);
509 if (state->root.len)
510 strbuf_insert(&name, 0, state->root.buf, state->root.len);
511 return squash_slash(strbuf_detach(&name, NULL));
514 static size_t sane_tz_len(const char *line, size_t len)
516 const char *tz, *p;
518 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
519 return 0;
520 tz = line + len - strlen(" +0500");
522 if (tz[1] != '+' && tz[1] != '-')
523 return 0;
525 for (p = tz + 2; p != line + len; p++)
526 if (!isdigit(*p))
527 return 0;
529 return line + len - tz;
532 static size_t tz_with_colon_len(const char *line, size_t len)
534 const char *tz, *p;
536 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
537 return 0;
538 tz = line + len - strlen(" +08:00");
540 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
541 return 0;
542 p = tz + 2;
543 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
544 !isdigit(*p++) || !isdigit(*p++))
545 return 0;
547 return line + len - tz;
550 static size_t date_len(const char *line, size_t len)
552 const char *date, *p;
554 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
555 return 0;
556 p = date = line + len - strlen("72-02-05");
558 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
559 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
560 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
561 return 0;
563 if (date - line >= strlen("19") &&
564 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
565 date -= strlen("19");
567 return line + len - date;
570 static size_t short_time_len(const char *line, size_t len)
572 const char *time, *p;
574 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
575 return 0;
576 p = time = line + len - strlen(" 07:01:32");
578 /* Permit 1-digit hours? */
579 if (*p++ != ' ' ||
580 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
581 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
582 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
583 return 0;
585 return line + len - time;
588 static size_t fractional_time_len(const char *line, size_t len)
590 const char *p;
591 size_t n;
593 /* Expected format: 19:41:17.620000023 */
594 if (!len || !isdigit(line[len - 1]))
595 return 0;
596 p = line + len - 1;
598 /* Fractional seconds. */
599 while (p > line && isdigit(*p))
600 p--;
601 if (*p != '.')
602 return 0;
604 /* Hours, minutes, and whole seconds. */
605 n = short_time_len(line, p - line);
606 if (!n)
607 return 0;
609 return line + len - p + n;
612 static size_t trailing_spaces_len(const char *line, size_t len)
614 const char *p;
616 /* Expected format: ' ' x (1 or more) */
617 if (!len || line[len - 1] != ' ')
618 return 0;
620 p = line + len;
621 while (p != line) {
622 p--;
623 if (*p != ' ')
624 return line + len - (p + 1);
627 /* All spaces! */
628 return len;
631 static size_t diff_timestamp_len(const char *line, size_t len)
633 const char *end = line + len;
634 size_t n;
637 * Posix: 2010-07-05 19:41:17
638 * GNU: 2010-07-05 19:41:17.620000023 -0500
641 if (!isdigit(end[-1]))
642 return 0;
644 n = sane_tz_len(line, end - line);
645 if (!n)
646 n = tz_with_colon_len(line, end - line);
647 end -= n;
649 n = short_time_len(line, end - line);
650 if (!n)
651 n = fractional_time_len(line, end - line);
652 end -= n;
654 n = date_len(line, end - line);
655 if (!n) /* No date. Too bad. */
656 return 0;
657 end -= n;
659 if (end == line) /* No space before date. */
660 return 0;
661 if (end[-1] == '\t') { /* Success! */
662 end--;
663 return line + len - end;
665 if (end[-1] != ' ') /* No space before date. */
666 return 0;
668 /* Whitespace damage. */
669 end -= trailing_spaces_len(line, end - line);
670 return line + len - end;
673 static char *find_name_common(struct apply_state *state,
674 const char *line,
675 const char *def,
676 int p_value,
677 const char *end,
678 int terminate)
680 int len;
681 const char *start = NULL;
683 if (p_value == 0)
684 start = line;
685 while (line != end) {
686 char c = *line;
688 if (!end && isspace(c)) {
689 if (c == '\n')
690 break;
691 if (name_terminate(start, line-start, c, terminate))
692 break;
694 line++;
695 if (c == '/' && !--p_value)
696 start = line;
698 if (!start)
699 return squash_slash(xstrdup_or_null(def));
700 len = line - start;
701 if (!len)
702 return squash_slash(xstrdup_or_null(def));
705 * Generally we prefer the shorter name, especially
706 * if the other one is just a variation of that with
707 * something else tacked on to the end (ie "file.orig"
708 * or "file~").
710 if (def) {
711 int deflen = strlen(def);
712 if (deflen < len && !strncmp(start, def, deflen))
713 return squash_slash(xstrdup(def));
716 if (state->root.len) {
717 char *ret = xstrfmt("%s%.*s", state->root.buf, len, start);
718 return squash_slash(ret);
721 return squash_slash(xmemdupz(start, len));
724 static char *find_name(struct apply_state *state,
725 const char *line,
726 char *def,
727 int p_value,
728 int terminate)
730 if (*line == '"') {
731 char *name = find_name_gnu(state, line, def, p_value);
732 if (name)
733 return name;
736 return find_name_common(state, line, def, p_value, NULL, terminate);
739 static char *find_name_traditional(struct apply_state *state,
740 const char *line,
741 char *def,
742 int p_value)
744 size_t len;
745 size_t date_len;
747 if (*line == '"') {
748 char *name = find_name_gnu(state, line, def, p_value);
749 if (name)
750 return name;
753 len = strchrnul(line, '\n') - line;
754 date_len = diff_timestamp_len(line, len);
755 if (!date_len)
756 return find_name_common(state, line, def, p_value, NULL, TERM_TAB);
757 len -= date_len;
759 return find_name_common(state, line, def, p_value, line + len, 0);
762 static int count_slashes(const char *cp)
764 int cnt = 0;
765 char ch;
767 while ((ch = *cp++))
768 if (ch == '/')
769 cnt++;
770 return cnt;
774 * Given the string after "--- " or "+++ ", guess the appropriate
775 * p_value for the given patch.
777 static int guess_p_value(struct apply_state *state, const char *nameline)
779 char *name, *cp;
780 int val = -1;
782 if (is_dev_null(nameline))
783 return -1;
784 name = find_name_traditional(state, nameline, NULL, 0);
785 if (!name)
786 return -1;
787 cp = strchr(name, '/');
788 if (!cp)
789 val = 0;
790 else if (state->prefix) {
792 * Does it begin with "a/$our-prefix" and such? Then this is
793 * very likely to apply to our directory.
795 if (!strncmp(name, state->prefix, state->prefix_length))
796 val = count_slashes(state->prefix);
797 else {
798 cp++;
799 if (!strncmp(cp, state->prefix, state->prefix_length))
800 val = count_slashes(state->prefix) + 1;
803 free(name);
804 return val;
808 * Does the ---/+++ line have the POSIX timestamp after the last HT?
809 * GNU diff puts epoch there to signal a creation/deletion event. Is
810 * this such a timestamp?
812 static int has_epoch_timestamp(const char *nameline)
815 * We are only interested in epoch timestamp; any non-zero
816 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
817 * For the same reason, the date must be either 1969-12-31 or
818 * 1970-01-01, and the seconds part must be "00".
820 const char stamp_regexp[] =
821 "^(1969-12-31|1970-01-01)"
823 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
825 "([-+][0-2][0-9]:?[0-5][0-9])\n";
826 const char *timestamp = NULL, *cp, *colon;
827 static regex_t *stamp;
828 regmatch_t m[10];
829 int zoneoffset;
830 int hourminute;
831 int status;
833 for (cp = nameline; *cp != '\n'; cp++) {
834 if (*cp == '\t')
835 timestamp = cp + 1;
837 if (!timestamp)
838 return 0;
839 if (!stamp) {
840 stamp = xmalloc(sizeof(*stamp));
841 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
842 warning(_("Cannot prepare timestamp regexp %s"),
843 stamp_regexp);
844 return 0;
848 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
849 if (status) {
850 if (status != REG_NOMATCH)
851 warning(_("regexec returned %d for input: %s"),
852 status, timestamp);
853 return 0;
856 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
857 if (*colon == ':')
858 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
859 else
860 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
861 if (timestamp[m[3].rm_so] == '-')
862 zoneoffset = -zoneoffset;
865 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
866 * (west of GMT) or 1970-01-01 (east of GMT)
868 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
869 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
870 return 0;
872 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
873 strtol(timestamp + 14, NULL, 10) -
874 zoneoffset);
876 return ((zoneoffset < 0 && hourminute == 1440) ||
877 (0 <= zoneoffset && !hourminute));
881 * Get the name etc info from the ---/+++ lines of a traditional patch header
883 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
884 * files, we can happily check the index for a match, but for creating a
885 * new file we should try to match whatever "patch" does. I have no idea.
887 static void parse_traditional_patch(struct apply_state *state,
888 const char *first,
889 const char *second,
890 struct patch *patch)
892 char *name;
894 first += 4; /* skip "--- " */
895 second += 4; /* skip "+++ " */
896 if (!state->p_value_known) {
897 int p, q;
898 p = guess_p_value(state, first);
899 q = guess_p_value(state, second);
900 if (p < 0) p = q;
901 if (0 <= p && p == q) {
902 state->p_value = p;
903 state->p_value_known = 1;
906 if (is_dev_null(first)) {
907 patch->is_new = 1;
908 patch->is_delete = 0;
909 name = find_name_traditional(state, second, NULL, state->p_value);
910 patch->new_name = name;
911 } else if (is_dev_null(second)) {
912 patch->is_new = 0;
913 patch->is_delete = 1;
914 name = find_name_traditional(state, first, NULL, state->p_value);
915 patch->old_name = name;
916 } else {
917 char *first_name;
918 first_name = find_name_traditional(state, first, NULL, state->p_value);
919 name = find_name_traditional(state, second, first_name, state->p_value);
920 free(first_name);
921 if (has_epoch_timestamp(first)) {
922 patch->is_new = 1;
923 patch->is_delete = 0;
924 patch->new_name = name;
925 } else if (has_epoch_timestamp(second)) {
926 patch->is_new = 0;
927 patch->is_delete = 1;
928 patch->old_name = name;
929 } else {
930 patch->old_name = name;
931 patch->new_name = xstrdup_or_null(name);
934 if (!name)
935 die(_("unable to find filename in patch at line %d"), state_linenr);
938 static int gitdiff_hdrend(struct apply_state *state,
939 const char *line,
940 struct patch *patch)
942 return -1;
946 * We're anal about diff header consistency, to make
947 * sure that we don't end up having strange ambiguous
948 * patches floating around.
950 * As a result, gitdiff_{old|new}name() will check
951 * their names against any previous information, just
952 * to make sure..
954 #define DIFF_OLD_NAME 0
955 #define DIFF_NEW_NAME 1
957 static void gitdiff_verify_name(struct apply_state *state,
958 const char *line,
959 int isnull,
960 char **name,
961 int side)
963 if (!*name && !isnull) {
964 *name = find_name(state, line, NULL, state->p_value, TERM_TAB);
965 return;
968 if (*name) {
969 int len = strlen(*name);
970 char *another;
971 if (isnull)
972 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
973 *name, state_linenr);
974 another = find_name(state, line, NULL, state->p_value, TERM_TAB);
975 if (!another || memcmp(another, *name, len + 1))
976 die((side == DIFF_NEW_NAME) ?
977 _("git apply: bad git-diff - inconsistent new filename on line %d") :
978 _("git apply: bad git-diff - inconsistent old filename on line %d"), state_linenr);
979 free(another);
980 } else {
981 /* expect "/dev/null" */
982 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
983 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr);
987 static int gitdiff_oldname(struct apply_state *state,
988 const char *line,
989 struct patch *patch)
991 gitdiff_verify_name(state, line,
992 patch->is_new, &patch->old_name,
993 DIFF_OLD_NAME);
994 return 0;
997 static int gitdiff_newname(struct apply_state *state,
998 const char *line,
999 struct patch *patch)
1001 gitdiff_verify_name(state, line,
1002 patch->is_delete, &patch->new_name,
1003 DIFF_NEW_NAME);
1004 return 0;
1007 static int gitdiff_oldmode(struct apply_state *state,
1008 const char *line,
1009 struct patch *patch)
1011 patch->old_mode = strtoul(line, NULL, 8);
1012 return 0;
1015 static int gitdiff_newmode(struct apply_state *state,
1016 const char *line,
1017 struct patch *patch)
1019 patch->new_mode = strtoul(line, NULL, 8);
1020 return 0;
1023 static int gitdiff_delete(struct apply_state *state,
1024 const char *line,
1025 struct patch *patch)
1027 patch->is_delete = 1;
1028 free(patch->old_name);
1029 patch->old_name = xstrdup_or_null(patch->def_name);
1030 return gitdiff_oldmode(state, line, patch);
1033 static int gitdiff_newfile(struct apply_state *state,
1034 const char *line,
1035 struct patch *patch)
1037 patch->is_new = 1;
1038 free(patch->new_name);
1039 patch->new_name = xstrdup_or_null(patch->def_name);
1040 return gitdiff_newmode(state, line, patch);
1043 static int gitdiff_copysrc(struct apply_state *state,
1044 const char *line,
1045 struct patch *patch)
1047 patch->is_copy = 1;
1048 free(patch->old_name);
1049 patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1050 return 0;
1053 static int gitdiff_copydst(struct apply_state *state,
1054 const char *line,
1055 struct patch *patch)
1057 patch->is_copy = 1;
1058 free(patch->new_name);
1059 patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1060 return 0;
1063 static int gitdiff_renamesrc(struct apply_state *state,
1064 const char *line,
1065 struct patch *patch)
1067 patch->is_rename = 1;
1068 free(patch->old_name);
1069 patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1070 return 0;
1073 static int gitdiff_renamedst(struct apply_state *state,
1074 const char *line,
1075 struct patch *patch)
1077 patch->is_rename = 1;
1078 free(patch->new_name);
1079 patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1080 return 0;
1083 static int gitdiff_similarity(struct apply_state *state,
1084 const char *line,
1085 struct patch *patch)
1087 unsigned long val = strtoul(line, NULL, 10);
1088 if (val <= 100)
1089 patch->score = val;
1090 return 0;
1093 static int gitdiff_dissimilarity(struct apply_state *state,
1094 const char *line,
1095 struct patch *patch)
1097 unsigned long val = strtoul(line, NULL, 10);
1098 if (val <= 100)
1099 patch->score = val;
1100 return 0;
1103 static int gitdiff_index(struct apply_state *state,
1104 const char *line,
1105 struct patch *patch)
1108 * index line is N hexadecimal, "..", N hexadecimal,
1109 * and optional space with octal mode.
1111 const char *ptr, *eol;
1112 int len;
1114 ptr = strchr(line, '.');
1115 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1116 return 0;
1117 len = ptr - line;
1118 memcpy(patch->old_sha1_prefix, line, len);
1119 patch->old_sha1_prefix[len] = 0;
1121 line = ptr + 2;
1122 ptr = strchr(line, ' ');
1123 eol = strchrnul(line, '\n');
1125 if (!ptr || eol < ptr)
1126 ptr = eol;
1127 len = ptr - line;
1129 if (40 < len)
1130 return 0;
1131 memcpy(patch->new_sha1_prefix, line, len);
1132 patch->new_sha1_prefix[len] = 0;
1133 if (*ptr == ' ')
1134 patch->old_mode = strtoul(ptr+1, NULL, 8);
1135 return 0;
1139 * This is normal for a diff that doesn't change anything: we'll fall through
1140 * into the next diff. Tell the parser to break out.
1142 static int gitdiff_unrecognized(struct apply_state *state,
1143 const char *line,
1144 struct patch *patch)
1146 return -1;
1150 * Skip p_value leading components from "line"; as we do not accept
1151 * absolute paths, return NULL in that case.
1153 static const char *skip_tree_prefix(struct apply_state *state,
1154 const char *line,
1155 int llen)
1157 int nslash;
1158 int i;
1160 if (!state->p_value)
1161 return (llen && line[0] == '/') ? NULL : line;
1163 nslash = state->p_value;
1164 for (i = 0; i < llen; i++) {
1165 int ch = line[i];
1166 if (ch == '/' && --nslash <= 0)
1167 return (i == 0) ? NULL : &line[i + 1];
1169 return NULL;
1173 * This is to extract the same name that appears on "diff --git"
1174 * line. We do not find and return anything if it is a rename
1175 * patch, and it is OK because we will find the name elsewhere.
1176 * We need to reliably find name only when it is mode-change only,
1177 * creation or deletion of an empty file. In any of these cases,
1178 * both sides are the same name under a/ and b/ respectively.
1180 static char *git_header_name(struct apply_state *state,
1181 const char *line,
1182 int llen)
1184 const char *name;
1185 const char *second = NULL;
1186 size_t len, line_len;
1188 line += strlen("diff --git ");
1189 llen -= strlen("diff --git ");
1191 if (*line == '"') {
1192 const char *cp;
1193 struct strbuf first = STRBUF_INIT;
1194 struct strbuf sp = STRBUF_INIT;
1196 if (unquote_c_style(&first, line, &second))
1197 goto free_and_fail1;
1199 /* strip the a/b prefix including trailing slash */
1200 cp = skip_tree_prefix(state, first.buf, first.len);
1201 if (!cp)
1202 goto free_and_fail1;
1203 strbuf_remove(&first, 0, cp - first.buf);
1206 * second points at one past closing dq of name.
1207 * find the second name.
1209 while ((second < line + llen) && isspace(*second))
1210 second++;
1212 if (line + llen <= second)
1213 goto free_and_fail1;
1214 if (*second == '"') {
1215 if (unquote_c_style(&sp, second, NULL))
1216 goto free_and_fail1;
1217 cp = skip_tree_prefix(state, sp.buf, sp.len);
1218 if (!cp)
1219 goto free_and_fail1;
1220 /* They must match, otherwise ignore */
1221 if (strcmp(cp, first.buf))
1222 goto free_and_fail1;
1223 strbuf_release(&sp);
1224 return strbuf_detach(&first, NULL);
1227 /* unquoted second */
1228 cp = skip_tree_prefix(state, second, line + llen - second);
1229 if (!cp)
1230 goto free_and_fail1;
1231 if (line + llen - cp != first.len ||
1232 memcmp(first.buf, cp, first.len))
1233 goto free_and_fail1;
1234 return strbuf_detach(&first, NULL);
1236 free_and_fail1:
1237 strbuf_release(&first);
1238 strbuf_release(&sp);
1239 return NULL;
1242 /* unquoted first name */
1243 name = skip_tree_prefix(state, line, llen);
1244 if (!name)
1245 return NULL;
1248 * since the first name is unquoted, a dq if exists must be
1249 * the beginning of the second name.
1251 for (second = name; second < line + llen; second++) {
1252 if (*second == '"') {
1253 struct strbuf sp = STRBUF_INIT;
1254 const char *np;
1256 if (unquote_c_style(&sp, second, NULL))
1257 goto free_and_fail2;
1259 np = skip_tree_prefix(state, sp.buf, sp.len);
1260 if (!np)
1261 goto free_and_fail2;
1263 len = sp.buf + sp.len - np;
1264 if (len < second - name &&
1265 !strncmp(np, name, len) &&
1266 isspace(name[len])) {
1267 /* Good */
1268 strbuf_remove(&sp, 0, np - sp.buf);
1269 return strbuf_detach(&sp, NULL);
1272 free_and_fail2:
1273 strbuf_release(&sp);
1274 return NULL;
1279 * Accept a name only if it shows up twice, exactly the same
1280 * form.
1282 second = strchr(name, '\n');
1283 if (!second)
1284 return NULL;
1285 line_len = second - name;
1286 for (len = 0 ; ; len++) {
1287 switch (name[len]) {
1288 default:
1289 continue;
1290 case '\n':
1291 return NULL;
1292 case '\t': case ' ':
1294 * Is this the separator between the preimage
1295 * and the postimage pathname? Again, we are
1296 * only interested in the case where there is
1297 * no rename, as this is only to set def_name
1298 * and a rename patch has the names elsewhere
1299 * in an unambiguous form.
1301 if (!name[len + 1])
1302 return NULL; /* no postimage name */
1303 second = skip_tree_prefix(state, name + len + 1,
1304 line_len - (len + 1));
1305 if (!second)
1306 return NULL;
1308 * Does len bytes starting at "name" and "second"
1309 * (that are separated by one HT or SP we just
1310 * found) exactly match?
1312 if (second[len] == '\n' && !strncmp(name, second, len))
1313 return xmemdupz(name, len);
1318 /* Verify that we recognize the lines following a git header */
1319 static int parse_git_header(struct apply_state *state,
1320 const char *line,
1321 int len,
1322 unsigned int size,
1323 struct patch *patch)
1325 unsigned long offset;
1327 /* A git diff has explicit new/delete information, so we don't guess */
1328 patch->is_new = 0;
1329 patch->is_delete = 0;
1332 * Some things may not have the old name in the
1333 * rest of the headers anywhere (pure mode changes,
1334 * or removing or adding empty files), so we get
1335 * the default name from the header.
1337 patch->def_name = git_header_name(state, line, len);
1338 if (patch->def_name && state->root.len) {
1339 char *s = xstrfmt("%s%s", state->root.buf, patch->def_name);
1340 free(patch->def_name);
1341 patch->def_name = s;
1344 line += len;
1345 size -= len;
1346 state_linenr++;
1347 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state_linenr++) {
1348 static const struct opentry {
1349 const char *str;
1350 int (*fn)(struct apply_state *, const char *, struct patch *);
1351 } optable[] = {
1352 { "@@ -", gitdiff_hdrend },
1353 { "--- ", gitdiff_oldname },
1354 { "+++ ", gitdiff_newname },
1355 { "old mode ", gitdiff_oldmode },
1356 { "new mode ", gitdiff_newmode },
1357 { "deleted file mode ", gitdiff_delete },
1358 { "new file mode ", gitdiff_newfile },
1359 { "copy from ", gitdiff_copysrc },
1360 { "copy to ", gitdiff_copydst },
1361 { "rename old ", gitdiff_renamesrc },
1362 { "rename new ", gitdiff_renamedst },
1363 { "rename from ", gitdiff_renamesrc },
1364 { "rename to ", gitdiff_renamedst },
1365 { "similarity index ", gitdiff_similarity },
1366 { "dissimilarity index ", gitdiff_dissimilarity },
1367 { "index ", gitdiff_index },
1368 { "", gitdiff_unrecognized },
1370 int i;
1372 len = linelen(line, size);
1373 if (!len || line[len-1] != '\n')
1374 break;
1375 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1376 const struct opentry *p = optable + i;
1377 int oplen = strlen(p->str);
1378 if (len < oplen || memcmp(p->str, line, oplen))
1379 continue;
1380 if (p->fn(state, line + oplen, patch) < 0)
1381 return offset;
1382 break;
1386 return offset;
1389 static int parse_num(const char *line, unsigned long *p)
1391 char *ptr;
1393 if (!isdigit(*line))
1394 return 0;
1395 *p = strtoul(line, &ptr, 10);
1396 return ptr - line;
1399 static int parse_range(const char *line, int len, int offset, const char *expect,
1400 unsigned long *p1, unsigned long *p2)
1402 int digits, ex;
1404 if (offset < 0 || offset >= len)
1405 return -1;
1406 line += offset;
1407 len -= offset;
1409 digits = parse_num(line, p1);
1410 if (!digits)
1411 return -1;
1413 offset += digits;
1414 line += digits;
1415 len -= digits;
1417 *p2 = 1;
1418 if (*line == ',') {
1419 digits = parse_num(line+1, p2);
1420 if (!digits)
1421 return -1;
1423 offset += digits+1;
1424 line += digits+1;
1425 len -= digits+1;
1428 ex = strlen(expect);
1429 if (ex > len)
1430 return -1;
1431 if (memcmp(line, expect, ex))
1432 return -1;
1434 return offset + ex;
1437 static void recount_diff(const char *line, int size, struct fragment *fragment)
1439 int oldlines = 0, newlines = 0, ret = 0;
1441 if (size < 1) {
1442 warning("recount: ignore empty hunk");
1443 return;
1446 for (;;) {
1447 int len = linelen(line, size);
1448 size -= len;
1449 line += len;
1451 if (size < 1)
1452 break;
1454 switch (*line) {
1455 case ' ': case '\n':
1456 newlines++;
1457 /* fall through */
1458 case '-':
1459 oldlines++;
1460 continue;
1461 case '+':
1462 newlines++;
1463 continue;
1464 case '\\':
1465 continue;
1466 case '@':
1467 ret = size < 3 || !starts_with(line, "@@ ");
1468 break;
1469 case 'd':
1470 ret = size < 5 || !starts_with(line, "diff ");
1471 break;
1472 default:
1473 ret = -1;
1474 break;
1476 if (ret) {
1477 warning(_("recount: unexpected line: %.*s"),
1478 (int)linelen(line, size), line);
1479 return;
1481 break;
1483 fragment->oldlines = oldlines;
1484 fragment->newlines = newlines;
1488 * Parse a unified diff fragment header of the
1489 * form "@@ -a,b +c,d @@"
1491 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1493 int offset;
1495 if (!len || line[len-1] != '\n')
1496 return -1;
1498 /* Figure out the number of lines in a fragment */
1499 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1500 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1502 return offset;
1505 static int find_header(struct apply_state *state,
1506 const char *line,
1507 unsigned long size,
1508 int *hdrsize,
1509 struct patch *patch)
1511 unsigned long offset, len;
1513 patch->is_toplevel_relative = 0;
1514 patch->is_rename = patch->is_copy = 0;
1515 patch->is_new = patch->is_delete = -1;
1516 patch->old_mode = patch->new_mode = 0;
1517 patch->old_name = patch->new_name = NULL;
1518 for (offset = 0; size > 0; offset += len, size -= len, line += len, state_linenr++) {
1519 unsigned long nextlen;
1521 len = linelen(line, size);
1522 if (!len)
1523 break;
1525 /* Testing this early allows us to take a few shortcuts.. */
1526 if (len < 6)
1527 continue;
1530 * Make sure we don't find any unconnected patch fragments.
1531 * That's a sign that we didn't find a header, and that a
1532 * patch has become corrupted/broken up.
1534 if (!memcmp("@@ -", line, 4)) {
1535 struct fragment dummy;
1536 if (parse_fragment_header(line, len, &dummy) < 0)
1537 continue;
1538 die(_("patch fragment without header at line %d: %.*s"),
1539 state_linenr, (int)len-1, line);
1542 if (size < len + 6)
1543 break;
1546 * Git patch? It might not have a real patch, just a rename
1547 * or mode change, so we handle that specially
1549 if (!memcmp("diff --git ", line, 11)) {
1550 int git_hdr_len = parse_git_header(state, line, len, size, patch);
1551 if (git_hdr_len <= len)
1552 continue;
1553 if (!patch->old_name && !patch->new_name) {
1554 if (!patch->def_name)
1555 die(Q_("git diff header lacks filename information when removing "
1556 "%d leading pathname component (line %d)",
1557 "git diff header lacks filename information when removing "
1558 "%d leading pathname components (line %d)",
1559 state->p_value),
1560 state->p_value, state_linenr);
1561 patch->old_name = xstrdup(patch->def_name);
1562 patch->new_name = xstrdup(patch->def_name);
1564 if (!patch->is_delete && !patch->new_name)
1565 die("git diff header lacks filename information "
1566 "(line %d)", state_linenr);
1567 patch->is_toplevel_relative = 1;
1568 *hdrsize = git_hdr_len;
1569 return offset;
1572 /* --- followed by +++ ? */
1573 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1574 continue;
1577 * We only accept unified patches, so we want it to
1578 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1579 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1581 nextlen = linelen(line + len, size - len);
1582 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1583 continue;
1585 /* Ok, we'll consider it a patch */
1586 parse_traditional_patch(state, line, line+len, patch);
1587 *hdrsize = len + nextlen;
1588 state_linenr += 2;
1589 return offset;
1591 return -1;
1594 static void record_ws_error(struct apply_state *state,
1595 unsigned result,
1596 const char *line,
1597 int len,
1598 int linenr)
1600 char *err;
1602 if (!result)
1603 return;
1605 state->whitespace_error++;
1606 if (state->squelch_whitespace_errors &&
1607 state->squelch_whitespace_errors < state->whitespace_error)
1608 return;
1610 err = whitespace_error_string(result);
1611 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1612 state->patch_input_file, linenr, err, len, line);
1613 free(err);
1616 static void check_whitespace(struct apply_state *state,
1617 const char *line,
1618 int len,
1619 unsigned ws_rule)
1621 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1623 record_ws_error(state, result, line + 1, len - 2, state_linenr);
1627 * Parse a unified diff. Note that this really needs to parse each
1628 * fragment separately, since the only way to know the difference
1629 * between a "---" that is part of a patch, and a "---" that starts
1630 * the next patch is to look at the line counts..
1632 static int parse_fragment(struct apply_state *state,
1633 const char *line,
1634 unsigned long size,
1635 struct patch *patch,
1636 struct fragment *fragment)
1638 int added, deleted;
1639 int len = linelen(line, size), offset;
1640 unsigned long oldlines, newlines;
1641 unsigned long leading, trailing;
1643 offset = parse_fragment_header(line, len, fragment);
1644 if (offset < 0)
1645 return -1;
1646 if (offset > 0 && patch->recount)
1647 recount_diff(line + offset, size - offset, fragment);
1648 oldlines = fragment->oldlines;
1649 newlines = fragment->newlines;
1650 leading = 0;
1651 trailing = 0;
1653 /* Parse the thing.. */
1654 line += len;
1655 size -= len;
1656 state_linenr++;
1657 added = deleted = 0;
1658 for (offset = len;
1659 0 < size;
1660 offset += len, size -= len, line += len, state_linenr++) {
1661 if (!oldlines && !newlines)
1662 break;
1663 len = linelen(line, size);
1664 if (!len || line[len-1] != '\n')
1665 return -1;
1666 switch (*line) {
1667 default:
1668 return -1;
1669 case '\n': /* newer GNU diff, an empty context line */
1670 case ' ':
1671 oldlines--;
1672 newlines--;
1673 if (!deleted && !added)
1674 leading++;
1675 trailing++;
1676 if (!state->apply_in_reverse &&
1677 state->ws_error_action == correct_ws_error)
1678 check_whitespace(state, line, len, patch->ws_rule);
1679 break;
1680 case '-':
1681 if (state->apply_in_reverse &&
1682 state->ws_error_action != nowarn_ws_error)
1683 check_whitespace(state, line, len, patch->ws_rule);
1684 deleted++;
1685 oldlines--;
1686 trailing = 0;
1687 break;
1688 case '+':
1689 if (!state->apply_in_reverse &&
1690 state->ws_error_action != nowarn_ws_error)
1691 check_whitespace(state, line, len, patch->ws_rule);
1692 added++;
1693 newlines--;
1694 trailing = 0;
1695 break;
1698 * We allow "\ No newline at end of file". Depending
1699 * on locale settings when the patch was produced we
1700 * don't know what this line looks like. The only
1701 * thing we do know is that it begins with "\ ".
1702 * Checking for 12 is just for sanity check -- any
1703 * l10n of "\ No newline..." is at least that long.
1705 case '\\':
1706 if (len < 12 || memcmp(line, "\\ ", 2))
1707 return -1;
1708 break;
1711 if (oldlines || newlines)
1712 return -1;
1713 if (!deleted && !added)
1714 return -1;
1716 fragment->leading = leading;
1717 fragment->trailing = trailing;
1720 * If a fragment ends with an incomplete line, we failed to include
1721 * it in the above loop because we hit oldlines == newlines == 0
1722 * before seeing it.
1724 if (12 < size && !memcmp(line, "\\ ", 2))
1725 offset += linelen(line, size);
1727 patch->lines_added += added;
1728 patch->lines_deleted += deleted;
1730 if (0 < patch->is_new && oldlines)
1731 return error(_("new file depends on old contents"));
1732 if (0 < patch->is_delete && newlines)
1733 return error(_("deleted file still has contents"));
1734 return offset;
1738 * We have seen "diff --git a/... b/..." header (or a traditional patch
1739 * header). Read hunks that belong to this patch into fragments and hang
1740 * them to the given patch structure.
1742 * The (fragment->patch, fragment->size) pair points into the memory given
1743 * by the caller, not a copy, when we return.
1745 static int parse_single_patch(struct apply_state *state,
1746 const char *line,
1747 unsigned long size,
1748 struct patch *patch)
1750 unsigned long offset = 0;
1751 unsigned long oldlines = 0, newlines = 0, context = 0;
1752 struct fragment **fragp = &patch->fragments;
1754 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1755 struct fragment *fragment;
1756 int len;
1758 fragment = xcalloc(1, sizeof(*fragment));
1759 fragment->linenr = state_linenr;
1760 len = parse_fragment(state, line, size, patch, fragment);
1761 if (len <= 0)
1762 die(_("corrupt patch at line %d"), state_linenr);
1763 fragment->patch = line;
1764 fragment->size = len;
1765 oldlines += fragment->oldlines;
1766 newlines += fragment->newlines;
1767 context += fragment->leading + fragment->trailing;
1769 *fragp = fragment;
1770 fragp = &fragment->next;
1772 offset += len;
1773 line += len;
1774 size -= len;
1778 * If something was removed (i.e. we have old-lines) it cannot
1779 * be creation, and if something was added it cannot be
1780 * deletion. However, the reverse is not true; --unified=0
1781 * patches that only add are not necessarily creation even
1782 * though they do not have any old lines, and ones that only
1783 * delete are not necessarily deletion.
1785 * Unfortunately, a real creation/deletion patch do _not_ have
1786 * any context line by definition, so we cannot safely tell it
1787 * apart with --unified=0 insanity. At least if the patch has
1788 * more than one hunk it is not creation or deletion.
1790 if (patch->is_new < 0 &&
1791 (oldlines || (patch->fragments && patch->fragments->next)))
1792 patch->is_new = 0;
1793 if (patch->is_delete < 0 &&
1794 (newlines || (patch->fragments && patch->fragments->next)))
1795 patch->is_delete = 0;
1797 if (0 < patch->is_new && oldlines)
1798 die(_("new file %s depends on old contents"), patch->new_name);
1799 if (0 < patch->is_delete && newlines)
1800 die(_("deleted file %s still has contents"), patch->old_name);
1801 if (!patch->is_delete && !newlines && context)
1802 fprintf_ln(stderr,
1803 _("** warning: "
1804 "file %s becomes empty but is not deleted"),
1805 patch->new_name);
1807 return offset;
1810 static inline int metadata_changes(struct patch *patch)
1812 return patch->is_rename > 0 ||
1813 patch->is_copy > 0 ||
1814 patch->is_new > 0 ||
1815 patch->is_delete ||
1816 (patch->old_mode && patch->new_mode &&
1817 patch->old_mode != patch->new_mode);
1820 static char *inflate_it(const void *data, unsigned long size,
1821 unsigned long inflated_size)
1823 git_zstream stream;
1824 void *out;
1825 int st;
1827 memset(&stream, 0, sizeof(stream));
1829 stream.next_in = (unsigned char *)data;
1830 stream.avail_in = size;
1831 stream.next_out = out = xmalloc(inflated_size);
1832 stream.avail_out = inflated_size;
1833 git_inflate_init(&stream);
1834 st = git_inflate(&stream, Z_FINISH);
1835 git_inflate_end(&stream);
1836 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1837 free(out);
1838 return NULL;
1840 return out;
1844 * Read a binary hunk and return a new fragment; fragment->patch
1845 * points at an allocated memory that the caller must free, so
1846 * it is marked as "->free_patch = 1".
1848 static struct fragment *parse_binary_hunk(char **buf_p,
1849 unsigned long *sz_p,
1850 int *status_p,
1851 int *used_p)
1854 * Expect a line that begins with binary patch method ("literal"
1855 * or "delta"), followed by the length of data before deflating.
1856 * a sequence of 'length-byte' followed by base-85 encoded data
1857 * should follow, terminated by a newline.
1859 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1860 * and we would limit the patch line to 66 characters,
1861 * so one line can fit up to 13 groups that would decode
1862 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1863 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1865 int llen, used;
1866 unsigned long size = *sz_p;
1867 char *buffer = *buf_p;
1868 int patch_method;
1869 unsigned long origlen;
1870 char *data = NULL;
1871 int hunk_size = 0;
1872 struct fragment *frag;
1874 llen = linelen(buffer, size);
1875 used = llen;
1877 *status_p = 0;
1879 if (starts_with(buffer, "delta ")) {
1880 patch_method = BINARY_DELTA_DEFLATED;
1881 origlen = strtoul(buffer + 6, NULL, 10);
1883 else if (starts_with(buffer, "literal ")) {
1884 patch_method = BINARY_LITERAL_DEFLATED;
1885 origlen = strtoul(buffer + 8, NULL, 10);
1887 else
1888 return NULL;
1890 state_linenr++;
1891 buffer += llen;
1892 while (1) {
1893 int byte_length, max_byte_length, newsize;
1894 llen = linelen(buffer, size);
1895 used += llen;
1896 state_linenr++;
1897 if (llen == 1) {
1898 /* consume the blank line */
1899 buffer++;
1900 size--;
1901 break;
1904 * Minimum line is "A00000\n" which is 7-byte long,
1905 * and the line length must be multiple of 5 plus 2.
1907 if ((llen < 7) || (llen-2) % 5)
1908 goto corrupt;
1909 max_byte_length = (llen - 2) / 5 * 4;
1910 byte_length = *buffer;
1911 if ('A' <= byte_length && byte_length <= 'Z')
1912 byte_length = byte_length - 'A' + 1;
1913 else if ('a' <= byte_length && byte_length <= 'z')
1914 byte_length = byte_length - 'a' + 27;
1915 else
1916 goto corrupt;
1917 /* if the input length was not multiple of 4, we would
1918 * have filler at the end but the filler should never
1919 * exceed 3 bytes
1921 if (max_byte_length < byte_length ||
1922 byte_length <= max_byte_length - 4)
1923 goto corrupt;
1924 newsize = hunk_size + byte_length;
1925 data = xrealloc(data, newsize);
1926 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1927 goto corrupt;
1928 hunk_size = newsize;
1929 buffer += llen;
1930 size -= llen;
1933 frag = xcalloc(1, sizeof(*frag));
1934 frag->patch = inflate_it(data, hunk_size, origlen);
1935 frag->free_patch = 1;
1936 if (!frag->patch)
1937 goto corrupt;
1938 free(data);
1939 frag->size = origlen;
1940 *buf_p = buffer;
1941 *sz_p = size;
1942 *used_p = used;
1943 frag->binary_patch_method = patch_method;
1944 return frag;
1946 corrupt:
1947 free(data);
1948 *status_p = -1;
1949 error(_("corrupt binary patch at line %d: %.*s"),
1950 state_linenr-1, llen-1, buffer);
1951 return NULL;
1955 * Returns:
1956 * -1 in case of error,
1957 * the length of the parsed binary patch otherwise
1959 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1962 * We have read "GIT binary patch\n"; what follows is a line
1963 * that says the patch method (currently, either "literal" or
1964 * "delta") and the length of data before deflating; a
1965 * sequence of 'length-byte' followed by base-85 encoded data
1966 * follows.
1968 * When a binary patch is reversible, there is another binary
1969 * hunk in the same format, starting with patch method (either
1970 * "literal" or "delta") with the length of data, and a sequence
1971 * of length-byte + base-85 encoded data, terminated with another
1972 * empty line. This data, when applied to the postimage, produces
1973 * the preimage.
1975 struct fragment *forward;
1976 struct fragment *reverse;
1977 int status;
1978 int used, used_1;
1980 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1981 if (!forward && !status)
1982 /* there has to be one hunk (forward hunk) */
1983 return error(_("unrecognized binary patch at line %d"), state_linenr-1);
1984 if (status)
1985 /* otherwise we already gave an error message */
1986 return status;
1988 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1989 if (reverse)
1990 used += used_1;
1991 else if (status) {
1993 * Not having reverse hunk is not an error, but having
1994 * a corrupt reverse hunk is.
1996 free((void*) forward->patch);
1997 free(forward);
1998 return status;
2000 forward->next = reverse;
2001 patch->fragments = forward;
2002 patch->is_binary = 1;
2003 return used;
2006 static void prefix_one(struct apply_state *state, char **name)
2008 char *old_name = *name;
2009 if (!old_name)
2010 return;
2011 *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));
2012 free(old_name);
2015 static void prefix_patch(struct apply_state *state, struct patch *p)
2017 if (!state->prefix || p->is_toplevel_relative)
2018 return;
2019 prefix_one(state, &p->new_name);
2020 prefix_one(state, &p->old_name);
2024 * include/exclude
2027 static void add_name_limit(struct apply_state *state,
2028 const char *name,
2029 int exclude)
2031 struct string_list_item *it;
2033 it = string_list_append(&state->limit_by_name, name);
2034 it->util = exclude ? NULL : (void *) 1;
2037 static int use_patch(struct apply_state *state, struct patch *p)
2039 const char *pathname = p->new_name ? p->new_name : p->old_name;
2040 int i;
2042 /* Paths outside are not touched regardless of "--include" */
2043 if (0 < state->prefix_length) {
2044 int pathlen = strlen(pathname);
2045 if (pathlen <= state->prefix_length ||
2046 memcmp(state->prefix, pathname, state->prefix_length))
2047 return 0;
2050 /* See if it matches any of exclude/include rule */
2051 for (i = 0; i < state->limit_by_name.nr; i++) {
2052 struct string_list_item *it = &state->limit_by_name.items[i];
2053 if (!wildmatch(it->string, pathname, 0, NULL))
2054 return (it->util != NULL);
2058 * If we had any include, a path that does not match any rule is
2059 * not used. Otherwise, we saw bunch of exclude rules (or none)
2060 * and such a path is used.
2062 return !state->has_include;
2067 * Read the patch text in "buffer" that extends for "size" bytes; stop
2068 * reading after seeing a single patch (i.e. changes to a single file).
2069 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2070 * Return the number of bytes consumed, so that the caller can call us
2071 * again for the next patch.
2073 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2075 int hdrsize, patchsize;
2076 int offset = find_header(state, buffer, size, &hdrsize, patch);
2078 if (offset < 0)
2079 return offset;
2081 prefix_patch(state, patch);
2083 if (!use_patch(state, patch))
2084 patch->ws_rule = 0;
2085 else
2086 patch->ws_rule = whitespace_rule(patch->new_name
2087 ? patch->new_name
2088 : patch->old_name);
2090 patchsize = parse_single_patch(state,
2091 buffer + offset + hdrsize,
2092 size - offset - hdrsize,
2093 patch);
2095 if (!patchsize) {
2096 static const char git_binary[] = "GIT binary patch\n";
2097 int hd = hdrsize + offset;
2098 unsigned long llen = linelen(buffer + hd, size - hd);
2100 if (llen == sizeof(git_binary) - 1 &&
2101 !memcmp(git_binary, buffer + hd, llen)) {
2102 int used;
2103 state_linenr++;
2104 used = parse_binary(buffer + hd + llen,
2105 size - hd - llen, patch);
2106 if (used < 0)
2107 return -1;
2108 if (used)
2109 patchsize = used + llen;
2110 else
2111 patchsize = 0;
2113 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2114 static const char *binhdr[] = {
2115 "Binary files ",
2116 "Files ",
2117 NULL,
2119 int i;
2120 for (i = 0; binhdr[i]; i++) {
2121 int len = strlen(binhdr[i]);
2122 if (len < size - hd &&
2123 !memcmp(binhdr[i], buffer + hd, len)) {
2124 state_linenr++;
2125 patch->is_binary = 1;
2126 patchsize = llen;
2127 break;
2132 /* Empty patch cannot be applied if it is a text patch
2133 * without metadata change. A binary patch appears
2134 * empty to us here.
2136 if ((state->apply || state->check) &&
2137 (!patch->is_binary && !metadata_changes(patch)))
2138 die(_("patch with only garbage at line %d"), state_linenr);
2141 return offset + hdrsize + patchsize;
2144 #define swap(a,b) myswap((a),(b),sizeof(a))
2146 #define myswap(a, b, size) do { \
2147 unsigned char mytmp[size]; \
2148 memcpy(mytmp, &a, size); \
2149 memcpy(&a, &b, size); \
2150 memcpy(&b, mytmp, size); \
2151 } while (0)
2153 static void reverse_patches(struct patch *p)
2155 for (; p; p = p->next) {
2156 struct fragment *frag = p->fragments;
2158 swap(p->new_name, p->old_name);
2159 swap(p->new_mode, p->old_mode);
2160 swap(p->is_new, p->is_delete);
2161 swap(p->lines_added, p->lines_deleted);
2162 swap(p->old_sha1_prefix, p->new_sha1_prefix);
2164 for (; frag; frag = frag->next) {
2165 swap(frag->newpos, frag->oldpos);
2166 swap(frag->newlines, frag->oldlines);
2171 static const char pluses[] =
2172 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2173 static const char minuses[]=
2174 "----------------------------------------------------------------------";
2176 static void show_stats(struct apply_state *state, struct patch *patch)
2178 struct strbuf qname = STRBUF_INIT;
2179 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2180 int max, add, del;
2182 quote_c_style(cp, &qname, NULL, 0);
2185 * "scale" the filename
2187 max = state->max_len;
2188 if (max > 50)
2189 max = 50;
2191 if (qname.len > max) {
2192 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2193 if (!cp)
2194 cp = qname.buf + qname.len + 3 - max;
2195 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2198 if (patch->is_binary) {
2199 printf(" %-*s | Bin\n", max, qname.buf);
2200 strbuf_release(&qname);
2201 return;
2204 printf(" %-*s |", max, qname.buf);
2205 strbuf_release(&qname);
2208 * scale the add/delete
2210 max = max + state->max_change > 70 ? 70 - max : state->max_change;
2211 add = patch->lines_added;
2212 del = patch->lines_deleted;
2214 if (state->max_change > 0) {
2215 int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2216 add = (add * max + state->max_change / 2) / state->max_change;
2217 del = total - add;
2219 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2220 add, pluses, del, minuses);
2223 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2225 switch (st->st_mode & S_IFMT) {
2226 case S_IFLNK:
2227 if (strbuf_readlink(buf, path, st->st_size) < 0)
2228 return error(_("unable to read symlink %s"), path);
2229 return 0;
2230 case S_IFREG:
2231 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2232 return error(_("unable to open or read %s"), path);
2233 convert_to_git(path, buf->buf, buf->len, buf, 0);
2234 return 0;
2235 default:
2236 return -1;
2241 * Update the preimage, and the common lines in postimage,
2242 * from buffer buf of length len. If postlen is 0 the postimage
2243 * is updated in place, otherwise it's updated on a new buffer
2244 * of length postlen
2247 static void update_pre_post_images(struct image *preimage,
2248 struct image *postimage,
2249 char *buf,
2250 size_t len, size_t postlen)
2252 int i, ctx, reduced;
2253 char *new, *old, *fixed;
2254 struct image fixed_preimage;
2257 * Update the preimage with whitespace fixes. Note that we
2258 * are not losing preimage->buf -- apply_one_fragment() will
2259 * free "oldlines".
2261 prepare_image(&fixed_preimage, buf, len, 1);
2262 assert(postlen
2263 ? fixed_preimage.nr == preimage->nr
2264 : fixed_preimage.nr <= preimage->nr);
2265 for (i = 0; i < fixed_preimage.nr; i++)
2266 fixed_preimage.line[i].flag = preimage->line[i].flag;
2267 free(preimage->line_allocated);
2268 *preimage = fixed_preimage;
2271 * Adjust the common context lines in postimage. This can be
2272 * done in-place when we are shrinking it with whitespace
2273 * fixing, but needs a new buffer when ignoring whitespace or
2274 * expanding leading tabs to spaces.
2276 * We trust the caller to tell us if the update can be done
2277 * in place (postlen==0) or not.
2279 old = postimage->buf;
2280 if (postlen)
2281 new = postimage->buf = xmalloc(postlen);
2282 else
2283 new = old;
2284 fixed = preimage->buf;
2286 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2287 size_t l_len = postimage->line[i].len;
2288 if (!(postimage->line[i].flag & LINE_COMMON)) {
2289 /* an added line -- no counterparts in preimage */
2290 memmove(new, old, l_len);
2291 old += l_len;
2292 new += l_len;
2293 continue;
2296 /* a common context -- skip it in the original postimage */
2297 old += l_len;
2299 /* and find the corresponding one in the fixed preimage */
2300 while (ctx < preimage->nr &&
2301 !(preimage->line[ctx].flag & LINE_COMMON)) {
2302 fixed += preimage->line[ctx].len;
2303 ctx++;
2307 * preimage is expected to run out, if the caller
2308 * fixed addition of trailing blank lines.
2310 if (preimage->nr <= ctx) {
2311 reduced++;
2312 continue;
2315 /* and copy it in, while fixing the line length */
2316 l_len = preimage->line[ctx].len;
2317 memcpy(new, fixed, l_len);
2318 new += l_len;
2319 fixed += l_len;
2320 postimage->line[i].len = l_len;
2321 ctx++;
2324 if (postlen
2325 ? postlen < new - postimage->buf
2326 : postimage->len < new - postimage->buf)
2327 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2328 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));
2330 /* Fix the length of the whole thing */
2331 postimage->len = new - postimage->buf;
2332 postimage->nr -= reduced;
2335 static int line_by_line_fuzzy_match(struct image *img,
2336 struct image *preimage,
2337 struct image *postimage,
2338 unsigned long try,
2339 int try_lno,
2340 int preimage_limit)
2342 int i;
2343 size_t imgoff = 0;
2344 size_t preoff = 0;
2345 size_t postlen = postimage->len;
2346 size_t extra_chars;
2347 char *buf;
2348 char *preimage_eof;
2349 char *preimage_end;
2350 struct strbuf fixed;
2351 char *fixed_buf;
2352 size_t fixed_len;
2354 for (i = 0; i < preimage_limit; i++) {
2355 size_t prelen = preimage->line[i].len;
2356 size_t imglen = img->line[try_lno+i].len;
2358 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2359 preimage->buf + preoff, prelen))
2360 return 0;
2361 if (preimage->line[i].flag & LINE_COMMON)
2362 postlen += imglen - prelen;
2363 imgoff += imglen;
2364 preoff += prelen;
2368 * Ok, the preimage matches with whitespace fuzz.
2370 * imgoff now holds the true length of the target that
2371 * matches the preimage before the end of the file.
2373 * Count the number of characters in the preimage that fall
2374 * beyond the end of the file and make sure that all of them
2375 * are whitespace characters. (This can only happen if
2376 * we are removing blank lines at the end of the file.)
2378 buf = preimage_eof = preimage->buf + preoff;
2379 for ( ; i < preimage->nr; i++)
2380 preoff += preimage->line[i].len;
2381 preimage_end = preimage->buf + preoff;
2382 for ( ; buf < preimage_end; buf++)
2383 if (!isspace(*buf))
2384 return 0;
2387 * Update the preimage and the common postimage context
2388 * lines to use the same whitespace as the target.
2389 * If whitespace is missing in the target (i.e.
2390 * if the preimage extends beyond the end of the file),
2391 * use the whitespace from the preimage.
2393 extra_chars = preimage_end - preimage_eof;
2394 strbuf_init(&fixed, imgoff + extra_chars);
2395 strbuf_add(&fixed, img->buf + try, imgoff);
2396 strbuf_add(&fixed, preimage_eof, extra_chars);
2397 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2398 update_pre_post_images(preimage, postimage,
2399 fixed_buf, fixed_len, postlen);
2400 return 1;
2403 static int match_fragment(struct apply_state *state,
2404 struct image *img,
2405 struct image *preimage,
2406 struct image *postimage,
2407 unsigned long try,
2408 int try_lno,
2409 unsigned ws_rule,
2410 int match_beginning, int match_end)
2412 int i;
2413 char *fixed_buf, *buf, *orig, *target;
2414 struct strbuf fixed;
2415 size_t fixed_len, postlen;
2416 int preimage_limit;
2418 if (preimage->nr + try_lno <= img->nr) {
2420 * The hunk falls within the boundaries of img.
2422 preimage_limit = preimage->nr;
2423 if (match_end && (preimage->nr + try_lno != img->nr))
2424 return 0;
2425 } else if (state->ws_error_action == correct_ws_error &&
2426 (ws_rule & WS_BLANK_AT_EOF)) {
2428 * This hunk extends beyond the end of img, and we are
2429 * removing blank lines at the end of the file. This
2430 * many lines from the beginning of the preimage must
2431 * match with img, and the remainder of the preimage
2432 * must be blank.
2434 preimage_limit = img->nr - try_lno;
2435 } else {
2437 * The hunk extends beyond the end of the img and
2438 * we are not removing blanks at the end, so we
2439 * should reject the hunk at this position.
2441 return 0;
2444 if (match_beginning && try_lno)
2445 return 0;
2447 /* Quick hash check */
2448 for (i = 0; i < preimage_limit; i++)
2449 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2450 (preimage->line[i].hash != img->line[try_lno + i].hash))
2451 return 0;
2453 if (preimage_limit == preimage->nr) {
2455 * Do we have an exact match? If we were told to match
2456 * at the end, size must be exactly at try+fragsize,
2457 * otherwise try+fragsize must be still within the preimage,
2458 * and either case, the old piece should match the preimage
2459 * exactly.
2461 if ((match_end
2462 ? (try + preimage->len == img->len)
2463 : (try + preimage->len <= img->len)) &&
2464 !memcmp(img->buf + try, preimage->buf, preimage->len))
2465 return 1;
2466 } else {
2468 * The preimage extends beyond the end of img, so
2469 * there cannot be an exact match.
2471 * There must be one non-blank context line that match
2472 * a line before the end of img.
2474 char *buf_end;
2476 buf = preimage->buf;
2477 buf_end = buf;
2478 for (i = 0; i < preimage_limit; i++)
2479 buf_end += preimage->line[i].len;
2481 for ( ; buf < buf_end; buf++)
2482 if (!isspace(*buf))
2483 break;
2484 if (buf == buf_end)
2485 return 0;
2489 * No exact match. If we are ignoring whitespace, run a line-by-line
2490 * fuzzy matching. We collect all the line length information because
2491 * we need it to adjust whitespace if we match.
2493 if (state->ws_ignore_action == ignore_ws_change)
2494 return line_by_line_fuzzy_match(img, preimage, postimage,
2495 try, try_lno, preimage_limit);
2497 if (state->ws_error_action != correct_ws_error)
2498 return 0;
2501 * The hunk does not apply byte-by-byte, but the hash says
2502 * it might with whitespace fuzz. We weren't asked to
2503 * ignore whitespace, we were asked to correct whitespace
2504 * errors, so let's try matching after whitespace correction.
2506 * While checking the preimage against the target, whitespace
2507 * errors in both fixed, we count how large the corresponding
2508 * postimage needs to be. The postimage prepared by
2509 * apply_one_fragment() has whitespace errors fixed on added
2510 * lines already, but the common lines were propagated as-is,
2511 * which may become longer when their whitespace errors are
2512 * fixed.
2515 /* First count added lines in postimage */
2516 postlen = 0;
2517 for (i = 0; i < postimage->nr; i++) {
2518 if (!(postimage->line[i].flag & LINE_COMMON))
2519 postlen += postimage->line[i].len;
2523 * The preimage may extend beyond the end of the file,
2524 * but in this loop we will only handle the part of the
2525 * preimage that falls within the file.
2527 strbuf_init(&fixed, preimage->len + 1);
2528 orig = preimage->buf;
2529 target = img->buf + try;
2530 for (i = 0; i < preimage_limit; i++) {
2531 size_t oldlen = preimage->line[i].len;
2532 size_t tgtlen = img->line[try_lno + i].len;
2533 size_t fixstart = fixed.len;
2534 struct strbuf tgtfix;
2535 int match;
2537 /* Try fixing the line in the preimage */
2538 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2540 /* Try fixing the line in the target */
2541 strbuf_init(&tgtfix, tgtlen);
2542 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2545 * If they match, either the preimage was based on
2546 * a version before our tree fixed whitespace breakage,
2547 * or we are lacking a whitespace-fix patch the tree
2548 * the preimage was based on already had (i.e. target
2549 * has whitespace breakage, the preimage doesn't).
2550 * In either case, we are fixing the whitespace breakages
2551 * so we might as well take the fix together with their
2552 * real change.
2554 match = (tgtfix.len == fixed.len - fixstart &&
2555 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2556 fixed.len - fixstart));
2558 /* Add the length if this is common with the postimage */
2559 if (preimage->line[i].flag & LINE_COMMON)
2560 postlen += tgtfix.len;
2562 strbuf_release(&tgtfix);
2563 if (!match)
2564 goto unmatch_exit;
2566 orig += oldlen;
2567 target += tgtlen;
2572 * Now handle the lines in the preimage that falls beyond the
2573 * end of the file (if any). They will only match if they are
2574 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2575 * false).
2577 for ( ; i < preimage->nr; i++) {
2578 size_t fixstart = fixed.len; /* start of the fixed preimage */
2579 size_t oldlen = preimage->line[i].len;
2580 int j;
2582 /* Try fixing the line in the preimage */
2583 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2585 for (j = fixstart; j < fixed.len; j++)
2586 if (!isspace(fixed.buf[j]))
2587 goto unmatch_exit;
2589 orig += oldlen;
2593 * Yes, the preimage is based on an older version that still
2594 * has whitespace breakages unfixed, and fixing them makes the
2595 * hunk match. Update the context lines in the postimage.
2597 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2598 if (postlen < postimage->len)
2599 postlen = 0;
2600 update_pre_post_images(preimage, postimage,
2601 fixed_buf, fixed_len, postlen);
2602 return 1;
2604 unmatch_exit:
2605 strbuf_release(&fixed);
2606 return 0;
2609 static int find_pos(struct apply_state *state,
2610 struct image *img,
2611 struct image *preimage,
2612 struct image *postimage,
2613 int line,
2614 unsigned ws_rule,
2615 int match_beginning, int match_end)
2617 int i;
2618 unsigned long backwards, forwards, try;
2619 int backwards_lno, forwards_lno, try_lno;
2622 * If match_beginning or match_end is specified, there is no
2623 * point starting from a wrong line that will never match and
2624 * wander around and wait for a match at the specified end.
2626 if (match_beginning)
2627 line = 0;
2628 else if (match_end)
2629 line = img->nr - preimage->nr;
2632 * Because the comparison is unsigned, the following test
2633 * will also take care of a negative line number that can
2634 * result when match_end and preimage is larger than the target.
2636 if ((size_t) line > img->nr)
2637 line = img->nr;
2639 try = 0;
2640 for (i = 0; i < line; i++)
2641 try += img->line[i].len;
2644 * There's probably some smart way to do this, but I'll leave
2645 * that to the smart and beautiful people. I'm simple and stupid.
2647 backwards = try;
2648 backwards_lno = line;
2649 forwards = try;
2650 forwards_lno = line;
2651 try_lno = line;
2653 for (i = 0; ; i++) {
2654 if (match_fragment(state, img, preimage, postimage,
2655 try, try_lno, ws_rule,
2656 match_beginning, match_end))
2657 return try_lno;
2659 again:
2660 if (backwards_lno == 0 && forwards_lno == img->nr)
2661 break;
2663 if (i & 1) {
2664 if (backwards_lno == 0) {
2665 i++;
2666 goto again;
2668 backwards_lno--;
2669 backwards -= img->line[backwards_lno].len;
2670 try = backwards;
2671 try_lno = backwards_lno;
2672 } else {
2673 if (forwards_lno == img->nr) {
2674 i++;
2675 goto again;
2677 forwards += img->line[forwards_lno].len;
2678 forwards_lno++;
2679 try = forwards;
2680 try_lno = forwards_lno;
2684 return -1;
2687 static void remove_first_line(struct image *img)
2689 img->buf += img->line[0].len;
2690 img->len -= img->line[0].len;
2691 img->line++;
2692 img->nr--;
2695 static void remove_last_line(struct image *img)
2697 img->len -= img->line[--img->nr].len;
2701 * The change from "preimage" and "postimage" has been found to
2702 * apply at applied_pos (counts in line numbers) in "img".
2703 * Update "img" to remove "preimage" and replace it with "postimage".
2705 static void update_image(struct apply_state *state,
2706 struct image *img,
2707 int applied_pos,
2708 struct image *preimage,
2709 struct image *postimage)
2712 * remove the copy of preimage at offset in img
2713 * and replace it with postimage
2715 int i, nr;
2716 size_t remove_count, insert_count, applied_at = 0;
2717 char *result;
2718 int preimage_limit;
2721 * If we are removing blank lines at the end of img,
2722 * the preimage may extend beyond the end.
2723 * If that is the case, we must be careful only to
2724 * remove the part of the preimage that falls within
2725 * the boundaries of img. Initialize preimage_limit
2726 * to the number of lines in the preimage that falls
2727 * within the boundaries.
2729 preimage_limit = preimage->nr;
2730 if (preimage_limit > img->nr - applied_pos)
2731 preimage_limit = img->nr - applied_pos;
2733 for (i = 0; i < applied_pos; i++)
2734 applied_at += img->line[i].len;
2736 remove_count = 0;
2737 for (i = 0; i < preimage_limit; i++)
2738 remove_count += img->line[applied_pos + i].len;
2739 insert_count = postimage->len;
2741 /* Adjust the contents */
2742 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2743 memcpy(result, img->buf, applied_at);
2744 memcpy(result + applied_at, postimage->buf, postimage->len);
2745 memcpy(result + applied_at + postimage->len,
2746 img->buf + (applied_at + remove_count),
2747 img->len - (applied_at + remove_count));
2748 free(img->buf);
2749 img->buf = result;
2750 img->len += insert_count - remove_count;
2751 result[img->len] = '\0';
2753 /* Adjust the line table */
2754 nr = img->nr + postimage->nr - preimage_limit;
2755 if (preimage_limit < postimage->nr) {
2757 * NOTE: this knows that we never call remove_first_line()
2758 * on anything other than pre/post image.
2760 REALLOC_ARRAY(img->line, nr);
2761 img->line_allocated = img->line;
2763 if (preimage_limit != postimage->nr)
2764 memmove(img->line + applied_pos + postimage->nr,
2765 img->line + applied_pos + preimage_limit,
2766 (img->nr - (applied_pos + preimage_limit)) *
2767 sizeof(*img->line));
2768 memcpy(img->line + applied_pos,
2769 postimage->line,
2770 postimage->nr * sizeof(*img->line));
2771 if (!state->allow_overlap)
2772 for (i = 0; i < postimage->nr; i++)
2773 img->line[applied_pos + i].flag |= LINE_PATCHED;
2774 img->nr = nr;
2778 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2779 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2780 * replace the part of "img" with "postimage" text.
2782 static int apply_one_fragment(struct apply_state *state,
2783 struct image *img, struct fragment *frag,
2784 int inaccurate_eof, unsigned ws_rule,
2785 int nth_fragment)
2787 int match_beginning, match_end;
2788 const char *patch = frag->patch;
2789 int size = frag->size;
2790 char *old, *oldlines;
2791 struct strbuf newlines;
2792 int new_blank_lines_at_end = 0;
2793 int found_new_blank_lines_at_end = 0;
2794 int hunk_linenr = frag->linenr;
2795 unsigned long leading, trailing;
2796 int pos, applied_pos;
2797 struct image preimage;
2798 struct image postimage;
2800 memset(&preimage, 0, sizeof(preimage));
2801 memset(&postimage, 0, sizeof(postimage));
2802 oldlines = xmalloc(size);
2803 strbuf_init(&newlines, size);
2805 old = oldlines;
2806 while (size > 0) {
2807 char first;
2808 int len = linelen(patch, size);
2809 int plen;
2810 int added_blank_line = 0;
2811 int is_blank_context = 0;
2812 size_t start;
2814 if (!len)
2815 break;
2818 * "plen" is how much of the line we should use for
2819 * the actual patch data. Normally we just remove the
2820 * first character on the line, but if the line is
2821 * followed by "\ No newline", then we also remove the
2822 * last one (which is the newline, of course).
2824 plen = len - 1;
2825 if (len < size && patch[len] == '\\')
2826 plen--;
2827 first = *patch;
2828 if (state->apply_in_reverse) {
2829 if (first == '-')
2830 first = '+';
2831 else if (first == '+')
2832 first = '-';
2835 switch (first) {
2836 case '\n':
2837 /* Newer GNU diff, empty context line */
2838 if (plen < 0)
2839 /* ... followed by '\No newline'; nothing */
2840 break;
2841 *old++ = '\n';
2842 strbuf_addch(&newlines, '\n');
2843 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2844 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2845 is_blank_context = 1;
2846 break;
2847 case ' ':
2848 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2849 ws_blank_line(patch + 1, plen, ws_rule))
2850 is_blank_context = 1;
2851 case '-':
2852 memcpy(old, patch + 1, plen);
2853 add_line_info(&preimage, old, plen,
2854 (first == ' ' ? LINE_COMMON : 0));
2855 old += plen;
2856 if (first == '-')
2857 break;
2858 /* Fall-through for ' ' */
2859 case '+':
2860 /* --no-add does not add new lines */
2861 if (first == '+' && state->no_add)
2862 break;
2864 start = newlines.len;
2865 if (first != '+' ||
2866 !state->whitespace_error ||
2867 state->ws_error_action != correct_ws_error) {
2868 strbuf_add(&newlines, patch + 1, plen);
2870 else {
2871 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2873 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2874 (first == '+' ? 0 : LINE_COMMON));
2875 if (first == '+' &&
2876 (ws_rule & WS_BLANK_AT_EOF) &&
2877 ws_blank_line(patch + 1, plen, ws_rule))
2878 added_blank_line = 1;
2879 break;
2880 case '@': case '\\':
2881 /* Ignore it, we already handled it */
2882 break;
2883 default:
2884 if (state->apply_verbosely)
2885 error(_("invalid start of line: '%c'"), first);
2886 applied_pos = -1;
2887 goto out;
2889 if (added_blank_line) {
2890 if (!new_blank_lines_at_end)
2891 found_new_blank_lines_at_end = hunk_linenr;
2892 new_blank_lines_at_end++;
2894 else if (is_blank_context)
2896 else
2897 new_blank_lines_at_end = 0;
2898 patch += len;
2899 size -= len;
2900 hunk_linenr++;
2902 if (inaccurate_eof &&
2903 old > oldlines && old[-1] == '\n' &&
2904 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2905 old--;
2906 strbuf_setlen(&newlines, newlines.len - 1);
2909 leading = frag->leading;
2910 trailing = frag->trailing;
2913 * A hunk to change lines at the beginning would begin with
2914 * @@ -1,L +N,M @@
2915 * but we need to be careful. -U0 that inserts before the second
2916 * line also has this pattern.
2918 * And a hunk to add to an empty file would begin with
2919 * @@ -0,0 +N,M @@
2921 * In other words, a hunk that is (frag->oldpos <= 1) with or
2922 * without leading context must match at the beginning.
2924 match_beginning = (!frag->oldpos ||
2925 (frag->oldpos == 1 && !state->unidiff_zero));
2928 * A hunk without trailing lines must match at the end.
2929 * However, we simply cannot tell if a hunk must match end
2930 * from the lack of trailing lines if the patch was generated
2931 * with unidiff without any context.
2933 match_end = !state->unidiff_zero && !trailing;
2935 pos = frag->newpos ? (frag->newpos - 1) : 0;
2936 preimage.buf = oldlines;
2937 preimage.len = old - oldlines;
2938 postimage.buf = newlines.buf;
2939 postimage.len = newlines.len;
2940 preimage.line = preimage.line_allocated;
2941 postimage.line = postimage.line_allocated;
2943 for (;;) {
2945 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
2946 ws_rule, match_beginning, match_end);
2948 if (applied_pos >= 0)
2949 break;
2951 /* Am I at my context limits? */
2952 if ((leading <= state->p_context) && (trailing <= state->p_context))
2953 break;
2954 if (match_beginning || match_end) {
2955 match_beginning = match_end = 0;
2956 continue;
2960 * Reduce the number of context lines; reduce both
2961 * leading and trailing if they are equal otherwise
2962 * just reduce the larger context.
2964 if (leading >= trailing) {
2965 remove_first_line(&preimage);
2966 remove_first_line(&postimage);
2967 pos--;
2968 leading--;
2970 if (trailing > leading) {
2971 remove_last_line(&preimage);
2972 remove_last_line(&postimage);
2973 trailing--;
2977 if (applied_pos >= 0) {
2978 if (new_blank_lines_at_end &&
2979 preimage.nr + applied_pos >= img->nr &&
2980 (ws_rule & WS_BLANK_AT_EOF) &&
2981 state->ws_error_action != nowarn_ws_error) {
2982 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
2983 found_new_blank_lines_at_end);
2984 if (state->ws_error_action == correct_ws_error) {
2985 while (new_blank_lines_at_end--)
2986 remove_last_line(&postimage);
2989 * We would want to prevent write_out_results()
2990 * from taking place in apply_patch() that follows
2991 * the callchain led us here, which is:
2992 * apply_patch->check_patch_list->check_patch->
2993 * apply_data->apply_fragments->apply_one_fragment
2995 if (state->ws_error_action == die_on_ws_error)
2996 state->apply = 0;
2999 if (state->apply_verbosely && applied_pos != pos) {
3000 int offset = applied_pos - pos;
3001 if (state->apply_in_reverse)
3002 offset = 0 - offset;
3003 fprintf_ln(stderr,
3004 Q_("Hunk #%d succeeded at %d (offset %d line).",
3005 "Hunk #%d succeeded at %d (offset %d lines).",
3006 offset),
3007 nth_fragment, applied_pos + 1, offset);
3011 * Warn if it was necessary to reduce the number
3012 * of context lines.
3014 if ((leading != frag->leading) ||
3015 (trailing != frag->trailing))
3016 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3017 " to apply fragment at %d"),
3018 leading, trailing, applied_pos+1);
3019 update_image(state, img, applied_pos, &preimage, &postimage);
3020 } else {
3021 if (state->apply_verbosely)
3022 error(_("while searching for:\n%.*s"),
3023 (int)(old - oldlines), oldlines);
3026 out:
3027 free(oldlines);
3028 strbuf_release(&newlines);
3029 free(preimage.line_allocated);
3030 free(postimage.line_allocated);
3032 return (applied_pos < 0);
3035 static int apply_binary_fragment(struct apply_state *state,
3036 struct image *img,
3037 struct patch *patch)
3039 struct fragment *fragment = patch->fragments;
3040 unsigned long len;
3041 void *dst;
3043 if (!fragment)
3044 return error(_("missing binary patch data for '%s'"),
3045 patch->new_name ?
3046 patch->new_name :
3047 patch->old_name);
3049 /* Binary patch is irreversible without the optional second hunk */
3050 if (state->apply_in_reverse) {
3051 if (!fragment->next)
3052 return error("cannot reverse-apply a binary patch "
3053 "without the reverse hunk to '%s'",
3054 patch->new_name
3055 ? patch->new_name : patch->old_name);
3056 fragment = fragment->next;
3058 switch (fragment->binary_patch_method) {
3059 case BINARY_DELTA_DEFLATED:
3060 dst = patch_delta(img->buf, img->len, fragment->patch,
3061 fragment->size, &len);
3062 if (!dst)
3063 return -1;
3064 clear_image(img);
3065 img->buf = dst;
3066 img->len = len;
3067 return 0;
3068 case BINARY_LITERAL_DEFLATED:
3069 clear_image(img);
3070 img->len = fragment->size;
3071 img->buf = xmemdupz(fragment->patch, img->len);
3072 return 0;
3074 return -1;
3078 * Replace "img" with the result of applying the binary patch.
3079 * The binary patch data itself in patch->fragment is still kept
3080 * but the preimage prepared by the caller in "img" is freed here
3081 * or in the helper function apply_binary_fragment() this calls.
3083 static int apply_binary(struct apply_state *state,
3084 struct image *img,
3085 struct patch *patch)
3087 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3088 unsigned char sha1[20];
3091 * For safety, we require patch index line to contain
3092 * full 40-byte textual SHA1 for old and new, at least for now.
3094 if (strlen(patch->old_sha1_prefix) != 40 ||
3095 strlen(patch->new_sha1_prefix) != 40 ||
3096 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
3097 get_sha1_hex(patch->new_sha1_prefix, sha1))
3098 return error("cannot apply binary patch to '%s' "
3099 "without full index line", name);
3101 if (patch->old_name) {
3103 * See if the old one matches what the patch
3104 * applies to.
3106 hash_sha1_file(img->buf, img->len, blob_type, sha1);
3107 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
3108 return error("the patch applies to '%s' (%s), "
3109 "which does not match the "
3110 "current contents.",
3111 name, sha1_to_hex(sha1));
3113 else {
3114 /* Otherwise, the old one must be empty. */
3115 if (img->len)
3116 return error("the patch applies to an empty "
3117 "'%s' but it is not empty", name);
3120 get_sha1_hex(patch->new_sha1_prefix, sha1);
3121 if (is_null_sha1(sha1)) {
3122 clear_image(img);
3123 return 0; /* deletion patch */
3126 if (has_sha1_file(sha1)) {
3127 /* We already have the postimage */
3128 enum object_type type;
3129 unsigned long size;
3130 char *result;
3132 result = read_sha1_file(sha1, &type, &size);
3133 if (!result)
3134 return error("the necessary postimage %s for "
3135 "'%s' cannot be read",
3136 patch->new_sha1_prefix, name);
3137 clear_image(img);
3138 img->buf = result;
3139 img->len = size;
3140 } else {
3142 * We have verified buf matches the preimage;
3143 * apply the patch data to it, which is stored
3144 * in the patch->fragments->{patch,size}.
3146 if (apply_binary_fragment(state, img, patch))
3147 return error(_("binary patch does not apply to '%s'"),
3148 name);
3150 /* verify that the result matches */
3151 hash_sha1_file(img->buf, img->len, blob_type, sha1);
3152 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
3153 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3154 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
3157 return 0;
3160 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3162 struct fragment *frag = patch->fragments;
3163 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3164 unsigned ws_rule = patch->ws_rule;
3165 unsigned inaccurate_eof = patch->inaccurate_eof;
3166 int nth = 0;
3168 if (patch->is_binary)
3169 return apply_binary(state, img, patch);
3171 while (frag) {
3172 nth++;
3173 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3174 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3175 if (!state->apply_with_reject)
3176 return -1;
3177 frag->rejected = 1;
3179 frag = frag->next;
3181 return 0;
3184 static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
3186 if (S_ISGITLINK(mode)) {
3187 strbuf_grow(buf, 100);
3188 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
3189 } else {
3190 enum object_type type;
3191 unsigned long sz;
3192 char *result;
3194 result = read_sha1_file(sha1, &type, &sz);
3195 if (!result)
3196 return -1;
3197 /* XXX read_sha1_file NUL-terminates */
3198 strbuf_attach(buf, result, sz, sz + 1);
3200 return 0;
3203 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3205 if (!ce)
3206 return 0;
3207 return read_blob_object(buf, ce->sha1, ce->ce_mode);
3210 static struct patch *in_fn_table(const char *name)
3212 struct string_list_item *item;
3214 if (name == NULL)
3215 return NULL;
3217 item = string_list_lookup(&fn_table, name);
3218 if (item != NULL)
3219 return (struct patch *)item->util;
3221 return NULL;
3225 * item->util in the filename table records the status of the path.
3226 * Usually it points at a patch (whose result records the contents
3227 * of it after applying it), but it could be PATH_WAS_DELETED for a
3228 * path that a previously applied patch has already removed, or
3229 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3231 * The latter is needed to deal with a case where two paths A and B
3232 * are swapped by first renaming A to B and then renaming B to A;
3233 * moving A to B should not be prevented due to presence of B as we
3234 * will remove it in a later patch.
3236 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3237 #define PATH_WAS_DELETED ((struct patch *) -1)
3239 static int to_be_deleted(struct patch *patch)
3241 return patch == PATH_TO_BE_DELETED;
3244 static int was_deleted(struct patch *patch)
3246 return patch == PATH_WAS_DELETED;
3249 static void add_to_fn_table(struct patch *patch)
3251 struct string_list_item *item;
3254 * Always add new_name unless patch is a deletion
3255 * This should cover the cases for normal diffs,
3256 * file creations and copies
3258 if (patch->new_name != NULL) {
3259 item = string_list_insert(&fn_table, patch->new_name);
3260 item->util = patch;
3264 * store a failure on rename/deletion cases because
3265 * later chunks shouldn't patch old names
3267 if ((patch->new_name == NULL) || (patch->is_rename)) {
3268 item = string_list_insert(&fn_table, patch->old_name);
3269 item->util = PATH_WAS_DELETED;
3273 static void prepare_fn_table(struct patch *patch)
3276 * store information about incoming file deletion
3278 while (patch) {
3279 if ((patch->new_name == NULL) || (patch->is_rename)) {
3280 struct string_list_item *item;
3281 item = string_list_insert(&fn_table, patch->old_name);
3282 item->util = PATH_TO_BE_DELETED;
3284 patch = patch->next;
3288 static int checkout_target(struct index_state *istate,
3289 struct cache_entry *ce, struct stat *st)
3291 struct checkout costate;
3293 memset(&costate, 0, sizeof(costate));
3294 costate.base_dir = "";
3295 costate.refresh_cache = 1;
3296 costate.istate = istate;
3297 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3298 return error(_("cannot checkout %s"), ce->name);
3299 return 0;
3302 static struct patch *previous_patch(struct patch *patch, int *gone)
3304 struct patch *previous;
3306 *gone = 0;
3307 if (patch->is_copy || patch->is_rename)
3308 return NULL; /* "git" patches do not depend on the order */
3310 previous = in_fn_table(patch->old_name);
3311 if (!previous)
3312 return NULL;
3314 if (to_be_deleted(previous))
3315 return NULL; /* the deletion hasn't happened yet */
3317 if (was_deleted(previous))
3318 *gone = 1;
3320 return previous;
3323 static int verify_index_match(const struct cache_entry *ce, struct stat *st)
3325 if (S_ISGITLINK(ce->ce_mode)) {
3326 if (!S_ISDIR(st->st_mode))
3327 return -1;
3328 return 0;
3330 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3333 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3335 static int load_patch_target(struct apply_state *state,
3336 struct strbuf *buf,
3337 const struct cache_entry *ce,
3338 struct stat *st,
3339 const char *name,
3340 unsigned expected_mode)
3342 if (state->cached || state->check_index) {
3343 if (read_file_or_gitlink(ce, buf))
3344 return error(_("read of %s failed"), name);
3345 } else if (name) {
3346 if (S_ISGITLINK(expected_mode)) {
3347 if (ce)
3348 return read_file_or_gitlink(ce, buf);
3349 else
3350 return SUBMODULE_PATCH_WITHOUT_INDEX;
3351 } else if (has_symlink_leading_path(name, strlen(name))) {
3352 return error(_("reading from '%s' beyond a symbolic link"), name);
3353 } else {
3354 if (read_old_data(st, name, buf))
3355 return error(_("read of %s failed"), name);
3358 return 0;
3362 * We are about to apply "patch"; populate the "image" with the
3363 * current version we have, from the working tree or from the index,
3364 * depending on the situation e.g. --cached/--index. If we are
3365 * applying a non-git patch that incrementally updates the tree,
3366 * we read from the result of a previous diff.
3368 static int load_preimage(struct apply_state *state,
3369 struct image *image,
3370 struct patch *patch, struct stat *st,
3371 const struct cache_entry *ce)
3373 struct strbuf buf = STRBUF_INIT;
3374 size_t len;
3375 char *img;
3376 struct patch *previous;
3377 int status;
3379 previous = previous_patch(patch, &status);
3380 if (status)
3381 return error(_("path %s has been renamed/deleted"),
3382 patch->old_name);
3383 if (previous) {
3384 /* We have a patched copy in memory; use that. */
3385 strbuf_add(&buf, previous->result, previous->resultsize);
3386 } else {
3387 status = load_patch_target(state, &buf, ce, st,
3388 patch->old_name, patch->old_mode);
3389 if (status < 0)
3390 return status;
3391 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3393 * There is no way to apply subproject
3394 * patch without looking at the index.
3395 * NEEDSWORK: shouldn't this be flagged
3396 * as an error???
3398 free_fragment_list(patch->fragments);
3399 patch->fragments = NULL;
3400 } else if (status) {
3401 return error(_("read of %s failed"), patch->old_name);
3405 img = strbuf_detach(&buf, &len);
3406 prepare_image(image, img, len, !patch->is_binary);
3407 return 0;
3410 static int three_way_merge(struct image *image,
3411 char *path,
3412 const unsigned char *base,
3413 const unsigned char *ours,
3414 const unsigned char *theirs)
3416 mmfile_t base_file, our_file, their_file;
3417 mmbuffer_t result = { NULL };
3418 int status;
3420 read_mmblob(&base_file, base);
3421 read_mmblob(&our_file, ours);
3422 read_mmblob(&their_file, theirs);
3423 status = ll_merge(&result, path,
3424 &base_file, "base",
3425 &our_file, "ours",
3426 &their_file, "theirs", NULL);
3427 free(base_file.ptr);
3428 free(our_file.ptr);
3429 free(their_file.ptr);
3430 if (status < 0 || !result.ptr) {
3431 free(result.ptr);
3432 return -1;
3434 clear_image(image);
3435 image->buf = result.ptr;
3436 image->len = result.size;
3438 return status;
3442 * When directly falling back to add/add three-way merge, we read from
3443 * the current contents of the new_name. In no cases other than that
3444 * this function will be called.
3446 static int load_current(struct apply_state *state,
3447 struct image *image,
3448 struct patch *patch)
3450 struct strbuf buf = STRBUF_INIT;
3451 int status, pos;
3452 size_t len;
3453 char *img;
3454 struct stat st;
3455 struct cache_entry *ce;
3456 char *name = patch->new_name;
3457 unsigned mode = patch->new_mode;
3459 if (!patch->is_new)
3460 die("BUG: patch to %s is not a creation", patch->old_name);
3462 pos = cache_name_pos(name, strlen(name));
3463 if (pos < 0)
3464 return error(_("%s: does not exist in index"), name);
3465 ce = active_cache[pos];
3466 if (lstat(name, &st)) {
3467 if (errno != ENOENT)
3468 return error(_("%s: %s"), name, strerror(errno));
3469 if (checkout_target(&the_index, ce, &st))
3470 return -1;
3472 if (verify_index_match(ce, &st))
3473 return error(_("%s: does not match index"), name);
3475 status = load_patch_target(state, &buf, ce, &st, name, mode);
3476 if (status < 0)
3477 return status;
3478 else if (status)
3479 return -1;
3480 img = strbuf_detach(&buf, &len);
3481 prepare_image(image, img, len, !patch->is_binary);
3482 return 0;
3485 static int try_threeway(struct apply_state *state,
3486 struct image *image,
3487 struct patch *patch,
3488 struct stat *st,
3489 const struct cache_entry *ce)
3491 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3492 struct strbuf buf = STRBUF_INIT;
3493 size_t len;
3494 int status;
3495 char *img;
3496 struct image tmp_image;
3498 /* No point falling back to 3-way merge in these cases */
3499 if (patch->is_delete ||
3500 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3501 return -1;
3503 /* Preimage the patch was prepared for */
3504 if (patch->is_new)
3505 write_sha1_file("", 0, blob_type, pre_sha1);
3506 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3507 read_blob_object(&buf, pre_sha1, patch->old_mode))
3508 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3510 fprintf(stderr, "Falling back to three-way merge...\n");
3512 img = strbuf_detach(&buf, &len);
3513 prepare_image(&tmp_image, img, len, 1);
3514 /* Apply the patch to get the post image */
3515 if (apply_fragments(state, &tmp_image, patch) < 0) {
3516 clear_image(&tmp_image);
3517 return -1;
3519 /* post_sha1[] is theirs */
3520 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3521 clear_image(&tmp_image);
3523 /* our_sha1[] is ours */
3524 if (patch->is_new) {
3525 if (load_current(state, &tmp_image, patch))
3526 return error("cannot read the current contents of '%s'",
3527 patch->new_name);
3528 } else {
3529 if (load_preimage(state, &tmp_image, patch, st, ce))
3530 return error("cannot read the current contents of '%s'",
3531 patch->old_name);
3533 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3534 clear_image(&tmp_image);
3536 /* in-core three-way merge between post and our using pre as base */
3537 status = three_way_merge(image, patch->new_name,
3538 pre_sha1, our_sha1, post_sha1);
3539 if (status < 0) {
3540 fprintf(stderr, "Failed to fall back on three-way merge...\n");
3541 return status;
3544 if (status) {
3545 patch->conflicted_threeway = 1;
3546 if (patch->is_new)
3547 oidclr(&patch->threeway_stage[0]);
3548 else
3549 hashcpy(patch->threeway_stage[0].hash, pre_sha1);
3550 hashcpy(patch->threeway_stage[1].hash, our_sha1);
3551 hashcpy(patch->threeway_stage[2].hash, post_sha1);
3552 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);
3553 } else {
3554 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);
3556 return 0;
3559 static int apply_data(struct apply_state *state, struct patch *patch,
3560 struct stat *st, const struct cache_entry *ce)
3562 struct image image;
3564 if (load_preimage(state, &image, patch, st, ce) < 0)
3565 return -1;
3567 if (patch->direct_to_threeway ||
3568 apply_fragments(state, &image, patch) < 0) {
3569 /* Note: with --reject, apply_fragments() returns 0 */
3570 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0)
3571 return -1;
3573 patch->result = image.buf;
3574 patch->resultsize = image.len;
3575 add_to_fn_table(patch);
3576 free(image.line_allocated);
3578 if (0 < patch->is_delete && patch->resultsize)
3579 return error(_("removal patch leaves file contents"));
3581 return 0;
3585 * If "patch" that we are looking at modifies or deletes what we have,
3586 * we would want it not to lose any local modification we have, either
3587 * in the working tree or in the index.
3589 * This also decides if a non-git patch is a creation patch or a
3590 * modification to an existing empty file. We do not check the state
3591 * of the current tree for a creation patch in this function; the caller
3592 * check_patch() separately makes sure (and errors out otherwise) that
3593 * the path the patch creates does not exist in the current tree.
3595 static int check_preimage(struct apply_state *state,
3596 struct patch *patch,
3597 struct cache_entry **ce,
3598 struct stat *st)
3600 const char *old_name = patch->old_name;
3601 struct patch *previous = NULL;
3602 int stat_ret = 0, status;
3603 unsigned st_mode = 0;
3605 if (!old_name)
3606 return 0;
3608 assert(patch->is_new <= 0);
3609 previous = previous_patch(patch, &status);
3611 if (status)
3612 return error(_("path %s has been renamed/deleted"), old_name);
3613 if (previous) {
3614 st_mode = previous->new_mode;
3615 } else if (!state->cached) {
3616 stat_ret = lstat(old_name, st);
3617 if (stat_ret && errno != ENOENT)
3618 return error(_("%s: %s"), old_name, strerror(errno));
3621 if (state->check_index && !previous) {
3622 int pos = cache_name_pos(old_name, strlen(old_name));
3623 if (pos < 0) {
3624 if (patch->is_new < 0)
3625 goto is_new;
3626 return error(_("%s: does not exist in index"), old_name);
3628 *ce = active_cache[pos];
3629 if (stat_ret < 0) {
3630 if (checkout_target(&the_index, *ce, st))
3631 return -1;
3633 if (!state->cached && verify_index_match(*ce, st))
3634 return error(_("%s: does not match index"), old_name);
3635 if (state->cached)
3636 st_mode = (*ce)->ce_mode;
3637 } else if (stat_ret < 0) {
3638 if (patch->is_new < 0)
3639 goto is_new;
3640 return error(_("%s: %s"), old_name, strerror(errno));
3643 if (!state->cached && !previous)
3644 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3646 if (patch->is_new < 0)
3647 patch->is_new = 0;
3648 if (!patch->old_mode)
3649 patch->old_mode = st_mode;
3650 if ((st_mode ^ patch->old_mode) & S_IFMT)
3651 return error(_("%s: wrong type"), old_name);
3652 if (st_mode != patch->old_mode)
3653 warning(_("%s has type %o, expected %o"),
3654 old_name, st_mode, patch->old_mode);
3655 if (!patch->new_mode && !patch->is_delete)
3656 patch->new_mode = st_mode;
3657 return 0;
3659 is_new:
3660 patch->is_new = 1;
3661 patch->is_delete = 0;
3662 free(patch->old_name);
3663 patch->old_name = NULL;
3664 return 0;
3668 #define EXISTS_IN_INDEX 1
3669 #define EXISTS_IN_WORKTREE 2
3671 static int check_to_create(struct apply_state *state,
3672 const char *new_name,
3673 int ok_if_exists)
3675 struct stat nst;
3677 if (state->check_index &&
3678 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3679 !ok_if_exists)
3680 return EXISTS_IN_INDEX;
3681 if (state->cached)
3682 return 0;
3684 if (!lstat(new_name, &nst)) {
3685 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3686 return 0;
3688 * A leading component of new_name might be a symlink
3689 * that is going to be removed with this patch, but
3690 * still pointing at somewhere that has the path.
3691 * In such a case, path "new_name" does not exist as
3692 * far as git is concerned.
3694 if (has_symlink_leading_path(new_name, strlen(new_name)))
3695 return 0;
3697 return EXISTS_IN_WORKTREE;
3698 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3699 return error("%s: %s", new_name, strerror(errno));
3701 return 0;
3705 * We need to keep track of how symlinks in the preimage are
3706 * manipulated by the patches. A patch to add a/b/c where a/b
3707 * is a symlink should not be allowed to affect the directory
3708 * the symlink points at, but if the same patch removes a/b,
3709 * it is perfectly fine, as the patch removes a/b to make room
3710 * to create a directory a/b so that a/b/c can be created.
3712 static struct string_list symlink_changes;
3713 #define SYMLINK_GOES_AWAY 01
3714 #define SYMLINK_IN_RESULT 02
3716 static uintptr_t register_symlink_changes(const char *path, uintptr_t what)
3718 struct string_list_item *ent;
3720 ent = string_list_lookup(&symlink_changes, path);
3721 if (!ent) {
3722 ent = string_list_insert(&symlink_changes, path);
3723 ent->util = (void *)0;
3725 ent->util = (void *)(what | ((uintptr_t)ent->util));
3726 return (uintptr_t)ent->util;
3729 static uintptr_t check_symlink_changes(const char *path)
3731 struct string_list_item *ent;
3733 ent = string_list_lookup(&symlink_changes, path);
3734 if (!ent)
3735 return 0;
3736 return (uintptr_t)ent->util;
3739 static void prepare_symlink_changes(struct patch *patch)
3741 for ( ; patch; patch = patch->next) {
3742 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3743 (patch->is_rename || patch->is_delete))
3744 /* the symlink at patch->old_name is removed */
3745 register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);
3747 if (patch->new_name && S_ISLNK(patch->new_mode))
3748 /* the symlink at patch->new_name is created or remains */
3749 register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);
3753 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3755 do {
3756 unsigned int change;
3758 while (--name->len && name->buf[name->len] != '/')
3759 ; /* scan backwards */
3760 if (!name->len)
3761 break;
3762 name->buf[name->len] = '\0';
3763 change = check_symlink_changes(name->buf);
3764 if (change & SYMLINK_IN_RESULT)
3765 return 1;
3766 if (change & SYMLINK_GOES_AWAY)
3768 * This cannot be "return 0", because we may
3769 * see a new one created at a higher level.
3771 continue;
3773 /* otherwise, check the preimage */
3774 if (state->check_index) {
3775 struct cache_entry *ce;
3777 ce = cache_file_exists(name->buf, name->len, ignore_case);
3778 if (ce && S_ISLNK(ce->ce_mode))
3779 return 1;
3780 } else {
3781 struct stat st;
3782 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3783 return 1;
3785 } while (1);
3786 return 0;
3789 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3791 int ret;
3792 struct strbuf name = STRBUF_INIT;
3794 assert(*name_ != '\0');
3795 strbuf_addstr(&name, name_);
3796 ret = path_is_beyond_symlink_1(state, &name);
3797 strbuf_release(&name);
3799 return ret;
3802 static void die_on_unsafe_path(struct patch *patch)
3804 const char *old_name = NULL;
3805 const char *new_name = NULL;
3806 if (patch->is_delete)
3807 old_name = patch->old_name;
3808 else if (!patch->is_new && !patch->is_copy)
3809 old_name = patch->old_name;
3810 if (!patch->is_delete)
3811 new_name = patch->new_name;
3813 if (old_name && !verify_path(old_name))
3814 die(_("invalid path '%s'"), old_name);
3815 if (new_name && !verify_path(new_name))
3816 die(_("invalid path '%s'"), new_name);
3820 * Check and apply the patch in-core; leave the result in patch->result
3821 * for the caller to write it out to the final destination.
3823 static int check_patch(struct apply_state *state, struct patch *patch)
3825 struct stat st;
3826 const char *old_name = patch->old_name;
3827 const char *new_name = patch->new_name;
3828 const char *name = old_name ? old_name : new_name;
3829 struct cache_entry *ce = NULL;
3830 struct patch *tpatch;
3831 int ok_if_exists;
3832 int status;
3834 patch->rejected = 1; /* we will drop this after we succeed */
3836 status = check_preimage(state, patch, &ce, &st);
3837 if (status)
3838 return status;
3839 old_name = patch->old_name;
3842 * A type-change diff is always split into a patch to delete
3843 * old, immediately followed by a patch to create new (see
3844 * diff.c::run_diff()); in such a case it is Ok that the entry
3845 * to be deleted by the previous patch is still in the working
3846 * tree and in the index.
3848 * A patch to swap-rename between A and B would first rename A
3849 * to B and then rename B to A. While applying the first one,
3850 * the presence of B should not stop A from getting renamed to
3851 * B; ask to_be_deleted() about the later rename. Removal of
3852 * B and rename from A to B is handled the same way by asking
3853 * was_deleted().
3855 if ((tpatch = in_fn_table(new_name)) &&
3856 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3857 ok_if_exists = 1;
3858 else
3859 ok_if_exists = 0;
3861 if (new_name &&
3862 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3863 int err = check_to_create(state, new_name, ok_if_exists);
3865 if (err && state->threeway) {
3866 patch->direct_to_threeway = 1;
3867 } else switch (err) {
3868 case 0:
3869 break; /* happy */
3870 case EXISTS_IN_INDEX:
3871 return error(_("%s: already exists in index"), new_name);
3872 break;
3873 case EXISTS_IN_WORKTREE:
3874 return error(_("%s: already exists in working directory"),
3875 new_name);
3876 default:
3877 return err;
3880 if (!patch->new_mode) {
3881 if (0 < patch->is_new)
3882 patch->new_mode = S_IFREG | 0644;
3883 else
3884 patch->new_mode = patch->old_mode;
3888 if (new_name && old_name) {
3889 int same = !strcmp(old_name, new_name);
3890 if (!patch->new_mode)
3891 patch->new_mode = patch->old_mode;
3892 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3893 if (same)
3894 return error(_("new mode (%o) of %s does not "
3895 "match old mode (%o)"),
3896 patch->new_mode, new_name,
3897 patch->old_mode);
3898 else
3899 return error(_("new mode (%o) of %s does not "
3900 "match old mode (%o) of %s"),
3901 patch->new_mode, new_name,
3902 patch->old_mode, old_name);
3906 if (!state->unsafe_paths)
3907 die_on_unsafe_path(patch);
3910 * An attempt to read from or delete a path that is beyond a
3911 * symbolic link will be prevented by load_patch_target() that
3912 * is called at the beginning of apply_data() so we do not
3913 * have to worry about a patch marked with "is_delete" bit
3914 * here. We however need to make sure that the patch result
3915 * is not deposited to a path that is beyond a symbolic link
3916 * here.
3918 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
3919 return error(_("affected file '%s' is beyond a symbolic link"),
3920 patch->new_name);
3922 if (apply_data(state, patch, &st, ce) < 0)
3923 return error(_("%s: patch does not apply"), name);
3924 patch->rejected = 0;
3925 return 0;
3928 static int check_patch_list(struct apply_state *state, struct patch *patch)
3930 int err = 0;
3932 prepare_symlink_changes(patch);
3933 prepare_fn_table(patch);
3934 while (patch) {
3935 if (state->apply_verbosely)
3936 say_patch_name(stderr,
3937 _("Checking patch %s..."), patch);
3938 err |= check_patch(state, patch);
3939 patch = patch->next;
3941 return err;
3944 /* This function tries to read the sha1 from the current index */
3945 static int get_current_sha1(const char *path, unsigned char *sha1)
3947 int pos;
3949 if (read_cache() < 0)
3950 return -1;
3951 pos = cache_name_pos(path, strlen(path));
3952 if (pos < 0)
3953 return -1;
3954 hashcpy(sha1, active_cache[pos]->sha1);
3955 return 0;
3958 static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])
3961 * A usable gitlink patch has only one fragment (hunk) that looks like:
3962 * @@ -1 +1 @@
3963 * -Subproject commit <old sha1>
3964 * +Subproject commit <new sha1>
3965 * or
3966 * @@ -1 +0,0 @@
3967 * -Subproject commit <old sha1>
3968 * for a removal patch.
3970 struct fragment *hunk = p->fragments;
3971 static const char heading[] = "-Subproject commit ";
3972 char *preimage;
3974 if (/* does the patch have only one hunk? */
3975 hunk && !hunk->next &&
3976 /* is its preimage one line? */
3977 hunk->oldpos == 1 && hunk->oldlines == 1 &&
3978 /* does preimage begin with the heading? */
3979 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
3980 starts_with(++preimage, heading) &&
3981 /* does it record full SHA-1? */
3982 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&
3983 preimage[sizeof(heading) + 40 - 1] == '\n' &&
3984 /* does the abbreviated name on the index line agree with it? */
3985 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
3986 return 0; /* it all looks fine */
3988 /* we may have full object name on the index line */
3989 return get_sha1_hex(p->old_sha1_prefix, sha1);
3992 /* Build an index that contains the just the files needed for a 3way merge */
3993 static void build_fake_ancestor(struct patch *list, const char *filename)
3995 struct patch *patch;
3996 struct index_state result = { NULL };
3997 static struct lock_file lock;
3999 /* Once we start supporting the reverse patch, it may be
4000 * worth showing the new sha1 prefix, but until then...
4002 for (patch = list; patch; patch = patch->next) {
4003 unsigned char sha1[20];
4004 struct cache_entry *ce;
4005 const char *name;
4007 name = patch->old_name ? patch->old_name : patch->new_name;
4008 if (0 < patch->is_new)
4009 continue;
4011 if (S_ISGITLINK(patch->old_mode)) {
4012 if (!preimage_sha1_in_gitlink_patch(patch, sha1))
4013 ; /* ok, the textual part looks sane */
4014 else
4015 die("sha1 information is lacking or useless for submodule %s",
4016 name);
4017 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {
4018 ; /* ok */
4019 } else if (!patch->lines_added && !patch->lines_deleted) {
4020 /* mode-only change: update the current */
4021 if (get_current_sha1(patch->old_name, sha1))
4022 die("mode change for %s, which is not "
4023 "in current HEAD", name);
4024 } else
4025 die("sha1 information is lacking or useless "
4026 "(%s).", name);
4028 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);
4029 if (!ce)
4030 die(_("make_cache_entry failed for path '%s'"), name);
4031 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
4032 die ("Could not add %s to temporary index", name);
4035 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
4036 if (write_locked_index(&result, &lock, COMMIT_LOCK))
4037 die ("Could not write temporary index to %s", filename);
4039 discard_index(&result);
4042 static void stat_patch_list(struct apply_state *state, struct patch *patch)
4044 int files, adds, dels;
4046 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4047 files++;
4048 adds += patch->lines_added;
4049 dels += patch->lines_deleted;
4050 show_stats(state, patch);
4053 print_stat_summary(stdout, files, adds, dels);
4056 static void numstat_patch_list(struct apply_state *state,
4057 struct patch *patch)
4059 for ( ; patch; patch = patch->next) {
4060 const char *name;
4061 name = patch->new_name ? patch->new_name : patch->old_name;
4062 if (patch->is_binary)
4063 printf("-\t-\t");
4064 else
4065 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4066 write_name_quoted(name, stdout, state->line_termination);
4070 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4072 if (mode)
4073 printf(" %s mode %06o %s\n", newdelete, mode, name);
4074 else
4075 printf(" %s %s\n", newdelete, name);
4078 static void show_mode_change(struct patch *p, int show_name)
4080 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4081 if (show_name)
4082 printf(" mode change %06o => %06o %s\n",
4083 p->old_mode, p->new_mode, p->new_name);
4084 else
4085 printf(" mode change %06o => %06o\n",
4086 p->old_mode, p->new_mode);
4090 static void show_rename_copy(struct patch *p)
4092 const char *renamecopy = p->is_rename ? "rename" : "copy";
4093 const char *old, *new;
4095 /* Find common prefix */
4096 old = p->old_name;
4097 new = p->new_name;
4098 while (1) {
4099 const char *slash_old, *slash_new;
4100 slash_old = strchr(old, '/');
4101 slash_new = strchr(new, '/');
4102 if (!slash_old ||
4103 !slash_new ||
4104 slash_old - old != slash_new - new ||
4105 memcmp(old, new, slash_new - new))
4106 break;
4107 old = slash_old + 1;
4108 new = slash_new + 1;
4110 /* p->old_name thru old is the common prefix, and old and new
4111 * through the end of names are renames
4113 if (old != p->old_name)
4114 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4115 (int)(old - p->old_name), p->old_name,
4116 old, new, p->score);
4117 else
4118 printf(" %s %s => %s (%d%%)\n", renamecopy,
4119 p->old_name, p->new_name, p->score);
4120 show_mode_change(p, 0);
4123 static void summary_patch_list(struct patch *patch)
4125 struct patch *p;
4127 for (p = patch; p; p = p->next) {
4128 if (p->is_new)
4129 show_file_mode_name("create", p->new_mode, p->new_name);
4130 else if (p->is_delete)
4131 show_file_mode_name("delete", p->old_mode, p->old_name);
4132 else {
4133 if (p->is_rename || p->is_copy)
4134 show_rename_copy(p);
4135 else {
4136 if (p->score) {
4137 printf(" rewrite %s (%d%%)\n",
4138 p->new_name, p->score);
4139 show_mode_change(p, 0);
4141 else
4142 show_mode_change(p, 1);
4148 static void patch_stats(struct apply_state *state, struct patch *patch)
4150 int lines = patch->lines_added + patch->lines_deleted;
4152 if (lines > state->max_change)
4153 state->max_change = lines;
4154 if (patch->old_name) {
4155 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4156 if (!len)
4157 len = strlen(patch->old_name);
4158 if (len > state->max_len)
4159 state->max_len = len;
4161 if (patch->new_name) {
4162 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4163 if (!len)
4164 len = strlen(patch->new_name);
4165 if (len > state->max_len)
4166 state->max_len = len;
4170 static void remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4172 if (state->update_index) {
4173 if (remove_file_from_cache(patch->old_name) < 0)
4174 die(_("unable to remove %s from index"), patch->old_name);
4176 if (!state->cached) {
4177 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4178 remove_path(patch->old_name);
4183 static void add_index_file(struct apply_state *state,
4184 const char *path,
4185 unsigned mode,
4186 void *buf,
4187 unsigned long size)
4189 struct stat st;
4190 struct cache_entry *ce;
4191 int namelen = strlen(path);
4192 unsigned ce_size = cache_entry_size(namelen);
4194 if (!state->update_index)
4195 return;
4197 ce = xcalloc(1, ce_size);
4198 memcpy(ce->name, path, namelen);
4199 ce->ce_mode = create_ce_mode(mode);
4200 ce->ce_flags = create_ce_flags(0);
4201 ce->ce_namelen = namelen;
4202 if (S_ISGITLINK(mode)) {
4203 const char *s;
4205 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4206 get_sha1_hex(s, ce->sha1))
4207 die(_("corrupt patch for submodule %s"), path);
4208 } else {
4209 if (!state->cached) {
4210 if (lstat(path, &st) < 0)
4211 die_errno(_("unable to stat newly created file '%s'"),
4212 path);
4213 fill_stat_cache_info(ce, &st);
4215 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
4216 die(_("unable to create backing store for newly created file %s"), path);
4218 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4219 die(_("unable to add cache entry for %s"), path);
4222 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
4224 int fd;
4225 struct strbuf nbuf = STRBUF_INIT;
4227 if (S_ISGITLINK(mode)) {
4228 struct stat st;
4229 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4230 return 0;
4231 return mkdir(path, 0777);
4234 if (has_symlinks && S_ISLNK(mode))
4235 /* Although buf:size is counted string, it also is NUL
4236 * terminated.
4238 return symlink(buf, path);
4240 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4241 if (fd < 0)
4242 return -1;
4244 if (convert_to_working_tree(path, buf, size, &nbuf)) {
4245 size = nbuf.len;
4246 buf = nbuf.buf;
4248 write_or_die(fd, buf, size);
4249 strbuf_release(&nbuf);
4251 if (close(fd) < 0)
4252 die_errno(_("closing file '%s'"), path);
4253 return 0;
4257 * We optimistically assume that the directories exist,
4258 * which is true 99% of the time anyway. If they don't,
4259 * we create them and try again.
4261 static void create_one_file(struct apply_state *state,
4262 char *path,
4263 unsigned mode,
4264 const char *buf,
4265 unsigned long size)
4267 if (state->cached)
4268 return;
4269 if (!try_create_file(path, mode, buf, size))
4270 return;
4272 if (errno == ENOENT) {
4273 if (safe_create_leading_directories(path))
4274 return;
4275 if (!try_create_file(path, mode, buf, size))
4276 return;
4279 if (errno == EEXIST || errno == EACCES) {
4280 /* We may be trying to create a file where a directory
4281 * used to be.
4283 struct stat st;
4284 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4285 errno = EEXIST;
4288 if (errno == EEXIST) {
4289 unsigned int nr = getpid();
4291 for (;;) {
4292 char newpath[PATH_MAX];
4293 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4294 if (!try_create_file(newpath, mode, buf, size)) {
4295 if (!rename(newpath, path))
4296 return;
4297 unlink_or_warn(newpath);
4298 break;
4300 if (errno != EEXIST)
4301 break;
4302 ++nr;
4305 die_errno(_("unable to write file '%s' mode %o"), path, mode);
4308 static void add_conflicted_stages_file(struct apply_state *state,
4309 struct patch *patch)
4311 int stage, namelen;
4312 unsigned ce_size, mode;
4313 struct cache_entry *ce;
4315 if (!state->update_index)
4316 return;
4317 namelen = strlen(patch->new_name);
4318 ce_size = cache_entry_size(namelen);
4319 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4321 remove_file_from_cache(patch->new_name);
4322 for (stage = 1; stage < 4; stage++) {
4323 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4324 continue;
4325 ce = xcalloc(1, ce_size);
4326 memcpy(ce->name, patch->new_name, namelen);
4327 ce->ce_mode = create_ce_mode(mode);
4328 ce->ce_flags = create_ce_flags(stage);
4329 ce->ce_namelen = namelen;
4330 hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);
4331 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4332 die(_("unable to add cache entry for %s"), patch->new_name);
4336 static void create_file(struct apply_state *state, struct patch *patch)
4338 char *path = patch->new_name;
4339 unsigned mode = patch->new_mode;
4340 unsigned long size = patch->resultsize;
4341 char *buf = patch->result;
4343 if (!mode)
4344 mode = S_IFREG | 0644;
4345 create_one_file(state, path, mode, buf, size);
4347 if (patch->conflicted_threeway)
4348 add_conflicted_stages_file(state, patch);
4349 else
4350 add_index_file(state, path, mode, buf, size);
4353 /* phase zero is to remove, phase one is to create */
4354 static void write_out_one_result(struct apply_state *state,
4355 struct patch *patch,
4356 int phase)
4358 if (patch->is_delete > 0) {
4359 if (phase == 0)
4360 remove_file(state, patch, 1);
4361 return;
4363 if (patch->is_new > 0 || patch->is_copy) {
4364 if (phase == 1)
4365 create_file(state, patch);
4366 return;
4369 * Rename or modification boils down to the same
4370 * thing: remove the old, write the new
4372 if (phase == 0)
4373 remove_file(state, patch, patch->is_rename);
4374 if (phase == 1)
4375 create_file(state, patch);
4378 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4380 FILE *rej;
4381 char namebuf[PATH_MAX];
4382 struct fragment *frag;
4383 int cnt = 0;
4384 struct strbuf sb = STRBUF_INIT;
4386 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4387 if (!frag->rejected)
4388 continue;
4389 cnt++;
4392 if (!cnt) {
4393 if (state->apply_verbosely)
4394 say_patch_name(stderr,
4395 _("Applied patch %s cleanly."), patch);
4396 return 0;
4399 /* This should not happen, because a removal patch that leaves
4400 * contents are marked "rejected" at the patch level.
4402 if (!patch->new_name)
4403 die(_("internal error"));
4405 /* Say this even without --verbose */
4406 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4407 "Applying patch %%s with %d rejects...",
4408 cnt),
4409 cnt);
4410 say_patch_name(stderr, sb.buf, patch);
4411 strbuf_release(&sb);
4413 cnt = strlen(patch->new_name);
4414 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4415 cnt = ARRAY_SIZE(namebuf) - 5;
4416 warning(_("truncating .rej filename to %.*s.rej"),
4417 cnt - 1, patch->new_name);
4419 memcpy(namebuf, patch->new_name, cnt);
4420 memcpy(namebuf + cnt, ".rej", 5);
4422 rej = fopen(namebuf, "w");
4423 if (!rej)
4424 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
4426 /* Normal git tools never deal with .rej, so do not pretend
4427 * this is a git patch by saying --git or giving extended
4428 * headers. While at it, maybe please "kompare" that wants
4429 * the trailing TAB and some garbage at the end of line ;-).
4431 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4432 patch->new_name, patch->new_name);
4433 for (cnt = 1, frag = patch->fragments;
4434 frag;
4435 cnt++, frag = frag->next) {
4436 if (!frag->rejected) {
4437 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4438 continue;
4440 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4441 fprintf(rej, "%.*s", frag->size, frag->patch);
4442 if (frag->patch[frag->size-1] != '\n')
4443 fputc('\n', rej);
4445 fclose(rej);
4446 return -1;
4449 static int write_out_results(struct apply_state *state, struct patch *list)
4451 int phase;
4452 int errs = 0;
4453 struct patch *l;
4454 struct string_list cpath = STRING_LIST_INIT_DUP;
4456 for (phase = 0; phase < 2; phase++) {
4457 l = list;
4458 while (l) {
4459 if (l->rejected)
4460 errs = 1;
4461 else {
4462 write_out_one_result(state, l, phase);
4463 if (phase == 1) {
4464 if (write_out_one_reject(state, l))
4465 errs = 1;
4466 if (l->conflicted_threeway) {
4467 string_list_append(&cpath, l->new_name);
4468 errs = 1;
4472 l = l->next;
4476 if (cpath.nr) {
4477 struct string_list_item *item;
4479 string_list_sort(&cpath);
4480 for_each_string_list_item(item, &cpath)
4481 fprintf(stderr, "U %s\n", item->string);
4482 string_list_clear(&cpath, 0);
4484 rerere(0);
4487 return errs;
4490 static struct lock_file lock_file;
4492 #define INACCURATE_EOF (1<<0)
4493 #define RECOUNT (1<<1)
4495 static int apply_patch(struct apply_state *state,
4496 int fd,
4497 const char *filename,
4498 int options)
4500 size_t offset;
4501 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4502 struct patch *list = NULL, **listp = &list;
4503 int skipped_patch = 0;
4505 state->patch_input_file = filename;
4506 read_patch_file(&buf, fd);
4507 offset = 0;
4508 while (offset < buf.len) {
4509 struct patch *patch;
4510 int nr;
4512 patch = xcalloc(1, sizeof(*patch));
4513 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
4514 patch->recount = !!(options & RECOUNT);
4515 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4516 if (nr < 0) {
4517 free_patch(patch);
4518 break;
4520 if (state->apply_in_reverse)
4521 reverse_patches(patch);
4522 if (use_patch(state, patch)) {
4523 patch_stats(state, patch);
4524 *listp = patch;
4525 listp = &patch->next;
4527 else {
4528 if (state->apply_verbosely)
4529 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4530 free_patch(patch);
4531 skipped_patch++;
4533 offset += nr;
4536 if (!list && !skipped_patch)
4537 die(_("unrecognized input"));
4539 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4540 state->apply = 0;
4542 state->update_index = state->check_index && state->apply;
4543 if (state->update_index && newfd < 0)
4544 newfd = hold_locked_index(&lock_file, 1);
4546 if (state->check_index) {
4547 if (read_cache() < 0)
4548 die(_("unable to read index file"));
4551 if ((state->check || state->apply) &&
4552 check_patch_list(state, list) < 0 &&
4553 !state->apply_with_reject)
4554 exit(1);
4556 if (state->apply && write_out_results(state, list)) {
4557 if (state->apply_with_reject)
4558 exit(1);
4559 /* with --3way, we still need to write the index out */
4560 return 1;
4563 if (state->fake_ancestor)
4564 build_fake_ancestor(list, state->fake_ancestor);
4566 if (state->diffstat)
4567 stat_patch_list(state, list);
4569 if (state->numstat)
4570 numstat_patch_list(state, list);
4572 if (state->summary)
4573 summary_patch_list(list);
4575 free_patch_list(list);
4576 strbuf_release(&buf);
4577 string_list_clear(&fn_table, 0);
4578 return 0;
4581 static void git_apply_config(void)
4583 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);
4584 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);
4585 git_config(git_default_config, NULL);
4588 static int option_parse_exclude(const struct option *opt,
4589 const char *arg, int unset)
4591 struct apply_state *state = opt->value;
4592 add_name_limit(state, arg, 1);
4593 return 0;
4596 static int option_parse_include(const struct option *opt,
4597 const char *arg, int unset)
4599 struct apply_state *state = opt->value;
4600 add_name_limit(state, arg, 0);
4601 state->has_include = 1;
4602 return 0;
4605 static int option_parse_p(const struct option *opt,
4606 const char *arg,
4607 int unset)
4609 struct apply_state *state = opt->value;
4610 state->p_value = atoi(arg);
4611 state->p_value_known = 1;
4612 return 0;
4615 static int option_parse_space_change(const struct option *opt,
4616 const char *arg, int unset)
4618 struct apply_state *state = opt->value;
4619 if (unset)
4620 state->ws_ignore_action = ignore_ws_none;
4621 else
4622 state->ws_ignore_action = ignore_ws_change;
4623 return 0;
4626 static int option_parse_whitespace(const struct option *opt,
4627 const char *arg, int unset)
4629 struct apply_state *state = opt->value;
4630 state->whitespace_option = arg;
4631 parse_whitespace_option(state, arg);
4632 return 0;
4635 static int option_parse_directory(const struct option *opt,
4636 const char *arg, int unset)
4638 struct apply_state *state = opt->value;
4639 strbuf_reset(&state->root);
4640 strbuf_addstr(&state->root, arg);
4641 strbuf_complete(&state->root, '/');
4642 return 0;
4645 static void init_apply_state(struct apply_state *state, const char *prefix)
4647 memset(state, 0, sizeof(*state));
4648 state->prefix = prefix;
4649 state->prefix_length = state->prefix ? strlen(state->prefix) : 0;
4650 state->apply = 1;
4651 state->line_termination = '\n';
4652 state->p_value = 1;
4653 state->p_context = UINT_MAX;
4654 state->squelch_whitespace_errors = 5;
4655 state->ws_error_action = warn_on_ws_error;
4656 state->ws_ignore_action = ignore_ws_none;
4657 strbuf_init(&state->root, 0);
4659 git_apply_config();
4660 if (apply_default_whitespace)
4661 parse_whitespace_option(state, apply_default_whitespace);
4662 if (apply_default_ignorewhitespace)
4663 parse_ignorewhitespace_option(state, apply_default_ignorewhitespace);
4666 static void clear_apply_state(struct apply_state *state)
4668 string_list_clear(&state->limit_by_name, 0);
4669 strbuf_release(&state->root);
4672 int cmd_apply(int argc, const char **argv, const char *prefix)
4674 int i;
4675 int errs = 0;
4676 int is_not_gitdir = !startup_info->have_repository;
4677 int force_apply = 0;
4678 int options = 0;
4679 int read_stdin = 1;
4680 struct apply_state state;
4682 struct option builtin_apply_options[] = {
4683 { OPTION_CALLBACK, 0, "exclude", &state, N_("path"),
4684 N_("don't apply changes matching the given path"),
4685 0, option_parse_exclude },
4686 { OPTION_CALLBACK, 0, "include", &state, N_("path"),
4687 N_("apply changes matching the given path"),
4688 0, option_parse_include },
4689 { OPTION_CALLBACK, 'p', NULL, &state, N_("num"),
4690 N_("remove <num> leading slashes from traditional diff paths"),
4691 0, option_parse_p },
4692 OPT_BOOL(0, "no-add", &state.no_add,
4693 N_("ignore additions made by the patch")),
4694 OPT_BOOL(0, "stat", &state.diffstat,
4695 N_("instead of applying the patch, output diffstat for the input")),
4696 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4697 OPT_NOOP_NOARG(0, "binary"),
4698 OPT_BOOL(0, "numstat", &state.numstat,
4699 N_("show number of added and deleted lines in decimal notation")),
4700 OPT_BOOL(0, "summary", &state.summary,
4701 N_("instead of applying the patch, output a summary for the input")),
4702 OPT_BOOL(0, "check", &state.check,
4703 N_("instead of applying the patch, see if the patch is applicable")),
4704 OPT_BOOL(0, "index", &state.check_index,
4705 N_("make sure the patch is applicable to the current index")),
4706 OPT_BOOL(0, "cached", &state.cached,
4707 N_("apply a patch without touching the working tree")),
4708 OPT_BOOL(0, "unsafe-paths", &state.unsafe_paths,
4709 N_("accept a patch that touches outside the working area")),
4710 OPT_BOOL(0, "apply", &force_apply,
4711 N_("also apply the patch (use with --stat/--summary/--check)")),
4712 OPT_BOOL('3', "3way", &state.threeway,
4713 N_( "attempt three-way merge if a patch does not apply")),
4714 OPT_FILENAME(0, "build-fake-ancestor", &state.fake_ancestor,
4715 N_("build a temporary index based on embedded index information")),
4716 /* Think twice before adding "--nul" synonym to this */
4717 OPT_SET_INT('z', NULL, &state.line_termination,
4718 N_("paths are separated with NUL character"), '\0'),
4719 OPT_INTEGER('C', NULL, &state.p_context,
4720 N_("ensure at least <n> lines of context match")),
4721 { OPTION_CALLBACK, 0, "whitespace", &state, N_("action"),
4722 N_("detect new or modified lines that have whitespace errors"),
4723 0, option_parse_whitespace },
4724 { OPTION_CALLBACK, 0, "ignore-space-change", &state, NULL,
4725 N_("ignore changes in whitespace when finding context"),
4726 PARSE_OPT_NOARG, option_parse_space_change },
4727 { OPTION_CALLBACK, 0, "ignore-whitespace", &state, NULL,
4728 N_("ignore changes in whitespace when finding context"),
4729 PARSE_OPT_NOARG, option_parse_space_change },
4730 OPT_BOOL('R', "reverse", &state.apply_in_reverse,
4731 N_("apply the patch in reverse")),
4732 OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,
4733 N_("don't expect at least one line of context")),
4734 OPT_BOOL(0, "reject", &state.apply_with_reject,
4735 N_("leave the rejected hunks in corresponding *.rej files")),
4736 OPT_BOOL(0, "allow-overlap", &state.allow_overlap,
4737 N_("allow overlapping hunks")),
4738 OPT__VERBOSE(&state.apply_verbosely, N_("be verbose")),
4739 OPT_BIT(0, "inaccurate-eof", &options,
4740 N_("tolerate incorrectly detected missing new-line at the end of file"),
4741 INACCURATE_EOF),
4742 OPT_BIT(0, "recount", &options,
4743 N_("do not trust the line counts in the hunk headers"),
4744 RECOUNT),
4745 { OPTION_CALLBACK, 0, "directory", &state, N_("root"),
4746 N_("prepend <root> to all filenames"),
4747 0, option_parse_directory },
4748 OPT_END()
4751 init_apply_state(&state, prefix);
4753 argc = parse_options(argc, argv, state.prefix, builtin_apply_options,
4754 apply_usage, 0);
4756 if (state.apply_with_reject && state.threeway)
4757 die("--reject and --3way cannot be used together.");
4758 if (state.cached && state.threeway)
4759 die("--cached and --3way cannot be used together.");
4760 if (state.threeway) {
4761 if (is_not_gitdir)
4762 die(_("--3way outside a repository"));
4763 state.check_index = 1;
4765 if (state.apply_with_reject)
4766 state.apply = state.apply_verbosely = 1;
4767 if (!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))
4768 state.apply = 0;
4769 if (state.check_index && is_not_gitdir)
4770 die(_("--index outside a repository"));
4771 if (state.cached) {
4772 if (is_not_gitdir)
4773 die(_("--cached outside a repository"));
4774 state.check_index = 1;
4776 if (state.check_index)
4777 state.unsafe_paths = 0;
4779 for (i = 0; i < argc; i++) {
4780 const char *arg = argv[i];
4781 int fd;
4783 if (!strcmp(arg, "-")) {
4784 errs |= apply_patch(&state, 0, "<stdin>", options);
4785 read_stdin = 0;
4786 continue;
4787 } else if (0 < state.prefix_length)
4788 arg = prefix_filename(state.prefix,
4789 state.prefix_length,
4790 arg);
4792 fd = open(arg, O_RDONLY);
4793 if (fd < 0)
4794 die_errno(_("can't open patch '%s'"), arg);
4795 read_stdin = 0;
4796 set_default_whitespace_mode(&state);
4797 errs |= apply_patch(&state, fd, arg, options);
4798 close(fd);
4800 set_default_whitespace_mode(&state);
4801 if (read_stdin)
4802 errs |= apply_patch(&state, 0, "<stdin>", options);
4803 if (state.whitespace_error) {
4804 if (state.squelch_whitespace_errors &&
4805 state.squelch_whitespace_errors < state.whitespace_error) {
4806 int squelched =
4807 state.whitespace_error - state.squelch_whitespace_errors;
4808 warning(Q_("squelched %d whitespace error",
4809 "squelched %d whitespace errors",
4810 squelched),
4811 squelched);
4813 if (state.ws_error_action == die_on_ws_error)
4814 die(Q_("%d line adds whitespace errors.",
4815 "%d lines add whitespace errors.",
4816 state.whitespace_error),
4817 state.whitespace_error);
4818 if (state.applied_after_fixing_ws && state.apply)
4819 warning("%d line%s applied after"
4820 " fixing whitespace errors.",
4821 state.applied_after_fixing_ws,
4822 state.applied_after_fixing_ws == 1 ? "" : "s");
4823 else if (state.whitespace_error)
4824 warning(Q_("%d line adds whitespace errors.",
4825 "%d lines add whitespace errors.",
4826 state.whitespace_error),
4827 state.whitespace_error);
4830 if (state.update_index) {
4831 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
4832 die(_("Unable to write new index file"));
4835 clear_apply_state(&state);
4837 return !!errs;