apply: document buffer ownership rules across functions
[git.git] / builtin / apply.c
blobf27f80ed76cd17370b2477ff6223abbd7b67c7d9
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 "cache-tree.h"
11 #include "quote.h"
12 #include "blob.h"
13 #include "delta.h"
14 #include "builtin.h"
15 #include "string-list.h"
16 #include "dir.h"
17 #include "parse-options.h"
20 * --check turns on checking that the working tree matches the
21 * files that are being modified, but doesn't apply the patch
22 * --stat does just a diffstat, and doesn't actually apply
23 * --numstat does numeric diffstat, and doesn't actually apply
24 * --index-info shows the old and new index info for paths if available.
25 * --index updates the cache as well.
26 * --cached updates only the cache without ever touching the working tree.
28 static const char *prefix;
29 static int prefix_length = -1;
30 static int newfd = -1;
32 static int unidiff_zero;
33 static int p_value = 1;
34 static int p_value_known;
35 static int check_index;
36 static int update_index;
37 static int cached;
38 static int diffstat;
39 static int numstat;
40 static int summary;
41 static int check;
42 static int apply = 1;
43 static int apply_in_reverse;
44 static int apply_with_reject;
45 static int apply_verbosely;
46 static int allow_overlap;
47 static int no_add;
48 static const char *fake_ancestor;
49 static int line_termination = '\n';
50 static unsigned int p_context = UINT_MAX;
51 static const char * const apply_usage[] = {
52 "git apply [options] [<patch>...]",
53 NULL
56 static enum ws_error_action {
57 nowarn_ws_error,
58 warn_on_ws_error,
59 die_on_ws_error,
60 correct_ws_error
61 } ws_error_action = warn_on_ws_error;
62 static int whitespace_error;
63 static int squelch_whitespace_errors = 5;
64 static int applied_after_fixing_ws;
66 static enum ws_ignore {
67 ignore_ws_none,
68 ignore_ws_change
69 } ws_ignore_action = ignore_ws_none;
72 static const char *patch_input_file;
73 static const char *root;
74 static int root_len;
75 static int read_stdin = 1;
76 static int options;
78 static void parse_whitespace_option(const char *option)
80 if (!option) {
81 ws_error_action = warn_on_ws_error;
82 return;
84 if (!strcmp(option, "warn")) {
85 ws_error_action = warn_on_ws_error;
86 return;
88 if (!strcmp(option, "nowarn")) {
89 ws_error_action = nowarn_ws_error;
90 return;
92 if (!strcmp(option, "error")) {
93 ws_error_action = die_on_ws_error;
94 return;
96 if (!strcmp(option, "error-all")) {
97 ws_error_action = die_on_ws_error;
98 squelch_whitespace_errors = 0;
99 return;
101 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
102 ws_error_action = correct_ws_error;
103 return;
105 die("unrecognized whitespace option '%s'", option);
108 static void parse_ignorewhitespace_option(const char *option)
110 if (!option || !strcmp(option, "no") ||
111 !strcmp(option, "false") || !strcmp(option, "never") ||
112 !strcmp(option, "none")) {
113 ws_ignore_action = ignore_ws_none;
114 return;
116 if (!strcmp(option, "change")) {
117 ws_ignore_action = ignore_ws_change;
118 return;
120 die("unrecognized whitespace ignore option '%s'", option);
123 static void set_default_whitespace_mode(const char *whitespace_option)
125 if (!whitespace_option && !apply_default_whitespace)
126 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
130 * For "diff-stat" like behaviour, we keep track of the biggest change
131 * we've seen, and the longest filename. That allows us to do simple
132 * scaling.
134 static int max_change, max_len;
137 * Various "current state", notably line numbers and what
138 * file (and how) we're patching right now.. The "is_xxxx"
139 * things are flags, where -1 means "don't know yet".
141 static int linenr = 1;
144 * This represents one "hunk" from a patch, starting with
145 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
146 * patch text is pointed at by patch, and its byte length
147 * is stored in size. leading and trailing are the number
148 * of context lines.
150 struct fragment {
151 unsigned long leading, trailing;
152 unsigned long oldpos, oldlines;
153 unsigned long newpos, newlines;
155 * 'patch' is usually borrowed from buf in apply_patch(),
156 * but some codepaths store an allocated buffer.
158 const char *patch;
159 unsigned free_patch:1,
160 rejected:1;
161 int size;
162 int linenr;
163 struct fragment *next;
167 * When dealing with a binary patch, we reuse "leading" field
168 * to store the type of the binary hunk, either deflated "delta"
169 * or deflated "literal".
171 #define binary_patch_method leading
172 #define BINARY_DELTA_DEFLATED 1
173 #define BINARY_LITERAL_DEFLATED 2
176 * This represents a "patch" to a file, both metainfo changes
177 * such as creation/deletion, filemode and content changes represented
178 * as a series of fragments.
180 struct patch {
181 char *new_name, *old_name, *def_name;
182 unsigned int old_mode, new_mode;
183 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
184 int rejected;
185 unsigned ws_rule;
186 unsigned long deflate_origlen;
187 int lines_added, lines_deleted;
188 int score;
189 unsigned int is_toplevel_relative:1;
190 unsigned int inaccurate_eof:1;
191 unsigned int is_binary:1;
192 unsigned int is_copy:1;
193 unsigned int is_rename:1;
194 unsigned int recount:1;
195 struct fragment *fragments;
196 char *result;
197 size_t resultsize;
198 char old_sha1_prefix[41];
199 char new_sha1_prefix[41];
200 struct patch *next;
203 static void free_fragment_list(struct fragment *list)
205 while (list) {
206 struct fragment *next = list->next;
207 if (list->free_patch)
208 free((char *)list->patch);
209 free(list);
210 list = next;
214 static void free_patch(struct patch *patch)
216 free_fragment_list(patch->fragments);
217 free(patch->def_name);
218 free(patch->old_name);
219 free(patch->new_name);
220 free(patch->result);
221 free(patch);
224 static void free_patch_list(struct patch *list)
226 while (list) {
227 struct patch *next = list->next;
228 free_patch(list);
229 list = next;
234 * A line in a file, len-bytes long (includes the terminating LF,
235 * except for an incomplete line at the end if the file ends with
236 * one), and its contents hashes to 'hash'.
238 struct line {
239 size_t len;
240 unsigned hash : 24;
241 unsigned flag : 8;
242 #define LINE_COMMON 1
243 #define LINE_PATCHED 2
247 * This represents a "file", which is an array of "lines".
249 struct image {
250 char *buf;
251 size_t len;
252 size_t nr;
253 size_t alloc;
254 struct line *line_allocated;
255 struct line *line;
259 * Records filenames that have been touched, in order to handle
260 * the case where more than one patches touch the same file.
263 static struct string_list fn_table;
265 static uint32_t hash_line(const char *cp, size_t len)
267 size_t i;
268 uint32_t h;
269 for (i = 0, h = 0; i < len; i++) {
270 if (!isspace(cp[i])) {
271 h = h * 3 + (cp[i] & 0xff);
274 return h;
278 * Compare lines s1 of length n1 and s2 of length n2, ignoring
279 * whitespace difference. Returns 1 if they match, 0 otherwise
281 static int fuzzy_matchlines(const char *s1, size_t n1,
282 const char *s2, size_t n2)
284 const char *last1 = s1 + n1 - 1;
285 const char *last2 = s2 + n2 - 1;
286 int result = 0;
288 /* ignore line endings */
289 while ((*last1 == '\r') || (*last1 == '\n'))
290 last1--;
291 while ((*last2 == '\r') || (*last2 == '\n'))
292 last2--;
294 /* skip leading whitespace */
295 while (isspace(*s1) && (s1 <= last1))
296 s1++;
297 while (isspace(*s2) && (s2 <= last2))
298 s2++;
299 /* early return if both lines are empty */
300 if ((s1 > last1) && (s2 > last2))
301 return 1;
302 while (!result) {
303 result = *s1++ - *s2++;
305 * Skip whitespace inside. We check for whitespace on
306 * both buffers because we don't want "a b" to match
307 * "ab"
309 if (isspace(*s1) && isspace(*s2)) {
310 while (isspace(*s1) && s1 <= last1)
311 s1++;
312 while (isspace(*s2) && s2 <= last2)
313 s2++;
316 * If we reached the end on one side only,
317 * lines don't match
319 if (
320 ((s2 > last2) && (s1 <= last1)) ||
321 ((s1 > last1) && (s2 <= last2)))
322 return 0;
323 if ((s1 > last1) && (s2 > last2))
324 break;
327 return !result;
330 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
332 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
333 img->line_allocated[img->nr].len = len;
334 img->line_allocated[img->nr].hash = hash_line(bol, len);
335 img->line_allocated[img->nr].flag = flag;
336 img->nr++;
340 * "buf" has the file contents to be patched (read from various sources).
341 * attach it to "image" and add line-based index to it.
342 * "image" now owns the "buf".
344 static void prepare_image(struct image *image, char *buf, size_t len,
345 int prepare_linetable)
347 const char *cp, *ep;
349 memset(image, 0, sizeof(*image));
350 image->buf = buf;
351 image->len = len;
353 if (!prepare_linetable)
354 return;
356 ep = image->buf + image->len;
357 cp = image->buf;
358 while (cp < ep) {
359 const char *next;
360 for (next = cp; next < ep && *next != '\n'; next++)
362 if (next < ep)
363 next++;
364 add_line_info(image, cp, next - cp, 0);
365 cp = next;
367 image->line = image->line_allocated;
370 static void clear_image(struct image *image)
372 free(image->buf);
373 image->buf = NULL;
374 image->len = 0;
377 static void say_patch_name(FILE *output, const char *pre,
378 struct patch *patch, const char *post)
380 fputs(pre, output);
381 if (patch->old_name && patch->new_name &&
382 strcmp(patch->old_name, patch->new_name)) {
383 quote_c_style(patch->old_name, NULL, output, 0);
384 fputs(" => ", output);
385 quote_c_style(patch->new_name, NULL, output, 0);
386 } else {
387 const char *n = patch->new_name;
388 if (!n)
389 n = patch->old_name;
390 quote_c_style(n, NULL, output, 0);
392 fputs(post, output);
395 #define SLOP (16)
397 static void read_patch_file(struct strbuf *sb, int fd)
399 if (strbuf_read(sb, fd, 0) < 0)
400 die_errno("git apply: failed to read");
403 * Make sure that we have some slop in the buffer
404 * so that we can do speculative "memcmp" etc, and
405 * see to it that it is NUL-filled.
407 strbuf_grow(sb, SLOP);
408 memset(sb->buf + sb->len, 0, SLOP);
411 static unsigned long linelen(const char *buffer, unsigned long size)
413 unsigned long len = 0;
414 while (size--) {
415 len++;
416 if (*buffer++ == '\n')
417 break;
419 return len;
422 static int is_dev_null(const char *str)
424 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
427 #define TERM_SPACE 1
428 #define TERM_TAB 2
430 static int name_terminate(const char *name, int namelen, int c, int terminate)
432 if (c == ' ' && !(terminate & TERM_SPACE))
433 return 0;
434 if (c == '\t' && !(terminate & TERM_TAB))
435 return 0;
437 return 1;
440 /* remove double slashes to make --index work with such filenames */
441 static char *squash_slash(char *name)
443 int i = 0, j = 0;
445 if (!name)
446 return NULL;
448 while (name[i]) {
449 if ((name[j++] = name[i++]) == '/')
450 while (name[i] == '/')
451 i++;
453 name[j] = '\0';
454 return name;
457 static char *find_name_gnu(const char *line, const char *def, int p_value)
459 struct strbuf name = STRBUF_INIT;
460 char *cp;
463 * Proposed "new-style" GNU patch/diff format; see
464 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
466 if (unquote_c_style(&name, line, NULL)) {
467 strbuf_release(&name);
468 return NULL;
471 for (cp = name.buf; p_value; p_value--) {
472 cp = strchr(cp, '/');
473 if (!cp) {
474 strbuf_release(&name);
475 return NULL;
477 cp++;
480 strbuf_remove(&name, 0, cp - name.buf);
481 if (root)
482 strbuf_insert(&name, 0, root, root_len);
483 return squash_slash(strbuf_detach(&name, NULL));
486 static size_t sane_tz_len(const char *line, size_t len)
488 const char *tz, *p;
490 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
491 return 0;
492 tz = line + len - strlen(" +0500");
494 if (tz[1] != '+' && tz[1] != '-')
495 return 0;
497 for (p = tz + 2; p != line + len; p++)
498 if (!isdigit(*p))
499 return 0;
501 return line + len - tz;
504 static size_t tz_with_colon_len(const char *line, size_t len)
506 const char *tz, *p;
508 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
509 return 0;
510 tz = line + len - strlen(" +08:00");
512 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
513 return 0;
514 p = tz + 2;
515 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
516 !isdigit(*p++) || !isdigit(*p++))
517 return 0;
519 return line + len - tz;
522 static size_t date_len(const char *line, size_t len)
524 const char *date, *p;
526 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
527 return 0;
528 p = date = line + len - strlen("72-02-05");
530 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
531 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
532 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
533 return 0;
535 if (date - line >= strlen("19") &&
536 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
537 date -= strlen("19");
539 return line + len - date;
542 static size_t short_time_len(const char *line, size_t len)
544 const char *time, *p;
546 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
547 return 0;
548 p = time = line + len - strlen(" 07:01:32");
550 /* Permit 1-digit hours? */
551 if (*p++ != ' ' ||
552 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
553 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
554 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
555 return 0;
557 return line + len - time;
560 static size_t fractional_time_len(const char *line, size_t len)
562 const char *p;
563 size_t n;
565 /* Expected format: 19:41:17.620000023 */
566 if (!len || !isdigit(line[len - 1]))
567 return 0;
568 p = line + len - 1;
570 /* Fractional seconds. */
571 while (p > line && isdigit(*p))
572 p--;
573 if (*p != '.')
574 return 0;
576 /* Hours, minutes, and whole seconds. */
577 n = short_time_len(line, p - line);
578 if (!n)
579 return 0;
581 return line + len - p + n;
584 static size_t trailing_spaces_len(const char *line, size_t len)
586 const char *p;
588 /* Expected format: ' ' x (1 or more) */
589 if (!len || line[len - 1] != ' ')
590 return 0;
592 p = line + len;
593 while (p != line) {
594 p--;
595 if (*p != ' ')
596 return line + len - (p + 1);
599 /* All spaces! */
600 return len;
603 static size_t diff_timestamp_len(const char *line, size_t len)
605 const char *end = line + len;
606 size_t n;
609 * Posix: 2010-07-05 19:41:17
610 * GNU: 2010-07-05 19:41:17.620000023 -0500
613 if (!isdigit(end[-1]))
614 return 0;
616 n = sane_tz_len(line, end - line);
617 if (!n)
618 n = tz_with_colon_len(line, end - line);
619 end -= n;
621 n = short_time_len(line, end - line);
622 if (!n)
623 n = fractional_time_len(line, end - line);
624 end -= n;
626 n = date_len(line, end - line);
627 if (!n) /* No date. Too bad. */
628 return 0;
629 end -= n;
631 if (end == line) /* No space before date. */
632 return 0;
633 if (end[-1] == '\t') { /* Success! */
634 end--;
635 return line + len - end;
637 if (end[-1] != ' ') /* No space before date. */
638 return 0;
640 /* Whitespace damage. */
641 end -= trailing_spaces_len(line, end - line);
642 return line + len - end;
645 static char *null_strdup(const char *s)
647 return s ? xstrdup(s) : NULL;
650 static char *find_name_common(const char *line, const char *def,
651 int p_value, const char *end, int terminate)
653 int len;
654 const char *start = NULL;
656 if (p_value == 0)
657 start = line;
658 while (line != end) {
659 char c = *line;
661 if (!end && isspace(c)) {
662 if (c == '\n')
663 break;
664 if (name_terminate(start, line-start, c, terminate))
665 break;
667 line++;
668 if (c == '/' && !--p_value)
669 start = line;
671 if (!start)
672 return squash_slash(null_strdup(def));
673 len = line - start;
674 if (!len)
675 return squash_slash(null_strdup(def));
678 * Generally we prefer the shorter name, especially
679 * if the other one is just a variation of that with
680 * something else tacked on to the end (ie "file.orig"
681 * or "file~").
683 if (def) {
684 int deflen = strlen(def);
685 if (deflen < len && !strncmp(start, def, deflen))
686 return squash_slash(xstrdup(def));
689 if (root) {
690 char *ret = xmalloc(root_len + len + 1);
691 strcpy(ret, root);
692 memcpy(ret + root_len, start, len);
693 ret[root_len + len] = '\0';
694 return squash_slash(ret);
697 return squash_slash(xmemdupz(start, len));
700 static char *find_name(const char *line, char *def, int p_value, int terminate)
702 if (*line == '"') {
703 char *name = find_name_gnu(line, def, p_value);
704 if (name)
705 return name;
708 return find_name_common(line, def, p_value, NULL, terminate);
711 static char *find_name_traditional(const char *line, char *def, int p_value)
713 size_t len = strlen(line);
714 size_t date_len;
716 if (*line == '"') {
717 char *name = find_name_gnu(line, def, p_value);
718 if (name)
719 return name;
722 len = strchrnul(line, '\n') - line;
723 date_len = diff_timestamp_len(line, len);
724 if (!date_len)
725 return find_name_common(line, def, p_value, NULL, TERM_TAB);
726 len -= date_len;
728 return find_name_common(line, def, p_value, line + len, 0);
731 static int count_slashes(const char *cp)
733 int cnt = 0;
734 char ch;
736 while ((ch = *cp++))
737 if (ch == '/')
738 cnt++;
739 return cnt;
743 * Given the string after "--- " or "+++ ", guess the appropriate
744 * p_value for the given patch.
746 static int guess_p_value(const char *nameline)
748 char *name, *cp;
749 int val = -1;
751 if (is_dev_null(nameline))
752 return -1;
753 name = find_name_traditional(nameline, NULL, 0);
754 if (!name)
755 return -1;
756 cp = strchr(name, '/');
757 if (!cp)
758 val = 0;
759 else if (prefix) {
761 * Does it begin with "a/$our-prefix" and such? Then this is
762 * very likely to apply to our directory.
764 if (!strncmp(name, prefix, prefix_length))
765 val = count_slashes(prefix);
766 else {
767 cp++;
768 if (!strncmp(cp, prefix, prefix_length))
769 val = count_slashes(prefix) + 1;
772 free(name);
773 return val;
777 * Does the ---/+++ line has the POSIX timestamp after the last HT?
778 * GNU diff puts epoch there to signal a creation/deletion event. Is
779 * this such a timestamp?
781 static int has_epoch_timestamp(const char *nameline)
784 * We are only interested in epoch timestamp; any non-zero
785 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
786 * For the same reason, the date must be either 1969-12-31 or
787 * 1970-01-01, and the seconds part must be "00".
789 const char stamp_regexp[] =
790 "^(1969-12-31|1970-01-01)"
792 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
794 "([-+][0-2][0-9]:?[0-5][0-9])\n";
795 const char *timestamp = NULL, *cp, *colon;
796 static regex_t *stamp;
797 regmatch_t m[10];
798 int zoneoffset;
799 int hourminute;
800 int status;
802 for (cp = nameline; *cp != '\n'; cp++) {
803 if (*cp == '\t')
804 timestamp = cp + 1;
806 if (!timestamp)
807 return 0;
808 if (!stamp) {
809 stamp = xmalloc(sizeof(*stamp));
810 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
811 warning("Cannot prepare timestamp regexp %s",
812 stamp_regexp);
813 return 0;
817 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
818 if (status) {
819 if (status != REG_NOMATCH)
820 warning("regexec returned %d for input: %s",
821 status, timestamp);
822 return 0;
825 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
826 if (*colon == ':')
827 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
828 else
829 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
830 if (timestamp[m[3].rm_so] == '-')
831 zoneoffset = -zoneoffset;
834 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
835 * (west of GMT) or 1970-01-01 (east of GMT)
837 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
838 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
839 return 0;
841 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
842 strtol(timestamp + 14, NULL, 10) -
843 zoneoffset);
845 return ((zoneoffset < 0 && hourminute == 1440) ||
846 (0 <= zoneoffset && !hourminute));
850 * Get the name etc info from the ---/+++ lines of a traditional patch header
852 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
853 * files, we can happily check the index for a match, but for creating a
854 * new file we should try to match whatever "patch" does. I have no idea.
856 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
858 char *name;
860 first += 4; /* skip "--- " */
861 second += 4; /* skip "+++ " */
862 if (!p_value_known) {
863 int p, q;
864 p = guess_p_value(first);
865 q = guess_p_value(second);
866 if (p < 0) p = q;
867 if (0 <= p && p == q) {
868 p_value = p;
869 p_value_known = 1;
872 if (is_dev_null(first)) {
873 patch->is_new = 1;
874 patch->is_delete = 0;
875 name = find_name_traditional(second, NULL, p_value);
876 patch->new_name = name;
877 } else if (is_dev_null(second)) {
878 patch->is_new = 0;
879 patch->is_delete = 1;
880 name = find_name_traditional(first, NULL, p_value);
881 patch->old_name = name;
882 } else {
883 char *first_name;
884 first_name = find_name_traditional(first, NULL, p_value);
885 name = find_name_traditional(second, first_name, p_value);
886 free(first_name);
887 if (has_epoch_timestamp(first)) {
888 patch->is_new = 1;
889 patch->is_delete = 0;
890 patch->new_name = name;
891 } else if (has_epoch_timestamp(second)) {
892 patch->is_new = 0;
893 patch->is_delete = 1;
894 patch->old_name = name;
895 } else {
896 patch->old_name = name;
897 patch->new_name = xstrdup(name);
900 if (!name)
901 die("unable to find filename in patch at line %d", linenr);
904 static int gitdiff_hdrend(const char *line, struct patch *patch)
906 return -1;
910 * We're anal about diff header consistency, to make
911 * sure that we don't end up having strange ambiguous
912 * patches floating around.
914 * As a result, gitdiff_{old|new}name() will check
915 * their names against any previous information, just
916 * to make sure..
918 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
920 if (!orig_name && !isnull)
921 return find_name(line, NULL, p_value, TERM_TAB);
923 if (orig_name) {
924 int len;
925 const char *name;
926 char *another;
927 name = orig_name;
928 len = strlen(name);
929 if (isnull)
930 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
931 another = find_name(line, NULL, p_value, TERM_TAB);
932 if (!another || memcmp(another, name, len + 1))
933 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
934 free(another);
935 return orig_name;
937 else {
938 /* expect "/dev/null" */
939 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
940 die("git apply: bad git-diff - expected /dev/null on line %d", linenr);
941 return NULL;
945 static int gitdiff_oldname(const char *line, struct patch *patch)
947 char *orig = patch->old_name;
948 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
949 if (orig != patch->old_name)
950 free(orig);
951 return 0;
954 static int gitdiff_newname(const char *line, struct patch *patch)
956 char *orig = patch->new_name;
957 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
958 if (orig != patch->new_name)
959 free(orig);
960 return 0;
963 static int gitdiff_oldmode(const char *line, struct patch *patch)
965 patch->old_mode = strtoul(line, NULL, 8);
966 return 0;
969 static int gitdiff_newmode(const char *line, struct patch *patch)
971 patch->new_mode = strtoul(line, NULL, 8);
972 return 0;
975 static int gitdiff_delete(const char *line, struct patch *patch)
977 patch->is_delete = 1;
978 free(patch->old_name);
979 patch->old_name = null_strdup(patch->def_name);
980 return gitdiff_oldmode(line, patch);
983 static int gitdiff_newfile(const char *line, struct patch *patch)
985 patch->is_new = 1;
986 free(patch->new_name);
987 patch->new_name = null_strdup(patch->def_name);
988 return gitdiff_newmode(line, patch);
991 static int gitdiff_copysrc(const char *line, struct patch *patch)
993 patch->is_copy = 1;
994 free(patch->old_name);
995 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
996 return 0;
999 static int gitdiff_copydst(const char *line, struct patch *patch)
1001 patch->is_copy = 1;
1002 free(patch->new_name);
1003 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1004 return 0;
1007 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1009 patch->is_rename = 1;
1010 free(patch->old_name);
1011 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1012 return 0;
1015 static int gitdiff_renamedst(const char *line, struct patch *patch)
1017 patch->is_rename = 1;
1018 free(patch->new_name);
1019 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1020 return 0;
1023 static int gitdiff_similarity(const char *line, struct patch *patch)
1025 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1026 patch->score = 0;
1027 return 0;
1030 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1032 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1033 patch->score = 0;
1034 return 0;
1037 static int gitdiff_index(const char *line, struct patch *patch)
1040 * index line is N hexadecimal, "..", N hexadecimal,
1041 * and optional space with octal mode.
1043 const char *ptr, *eol;
1044 int len;
1046 ptr = strchr(line, '.');
1047 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1048 return 0;
1049 len = ptr - line;
1050 memcpy(patch->old_sha1_prefix, line, len);
1051 patch->old_sha1_prefix[len] = 0;
1053 line = ptr + 2;
1054 ptr = strchr(line, ' ');
1055 eol = strchr(line, '\n');
1057 if (!ptr || eol < ptr)
1058 ptr = eol;
1059 len = ptr - line;
1061 if (40 < len)
1062 return 0;
1063 memcpy(patch->new_sha1_prefix, line, len);
1064 patch->new_sha1_prefix[len] = 0;
1065 if (*ptr == ' ')
1066 patch->old_mode = strtoul(ptr+1, NULL, 8);
1067 return 0;
1071 * This is normal for a diff that doesn't change anything: we'll fall through
1072 * into the next diff. Tell the parser to break out.
1074 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1076 return -1;
1079 static const char *stop_at_slash(const char *line, int llen)
1081 int nslash = p_value;
1082 int i;
1084 for (i = 0; i < llen; i++) {
1085 int ch = line[i];
1086 if (ch == '/' && --nslash <= 0)
1087 return &line[i];
1089 return NULL;
1093 * This is to extract the same name that appears on "diff --git"
1094 * line. We do not find and return anything if it is a rename
1095 * patch, and it is OK because we will find the name elsewhere.
1096 * We need to reliably find name only when it is mode-change only,
1097 * creation or deletion of an empty file. In any of these cases,
1098 * both sides are the same name under a/ and b/ respectively.
1100 static char *git_header_name(const char *line, int llen)
1102 const char *name;
1103 const char *second = NULL;
1104 size_t len, line_len;
1106 line += strlen("diff --git ");
1107 llen -= strlen("diff --git ");
1109 if (*line == '"') {
1110 const char *cp;
1111 struct strbuf first = STRBUF_INIT;
1112 struct strbuf sp = STRBUF_INIT;
1114 if (unquote_c_style(&first, line, &second))
1115 goto free_and_fail1;
1117 /* advance to the first slash */
1118 cp = stop_at_slash(first.buf, first.len);
1119 /* we do not accept absolute paths */
1120 if (!cp || cp == first.buf)
1121 goto free_and_fail1;
1122 strbuf_remove(&first, 0, cp + 1 - first.buf);
1125 * second points at one past closing dq of name.
1126 * find the second name.
1128 while ((second < line + llen) && isspace(*second))
1129 second++;
1131 if (line + llen <= second)
1132 goto free_and_fail1;
1133 if (*second == '"') {
1134 if (unquote_c_style(&sp, second, NULL))
1135 goto free_and_fail1;
1136 cp = stop_at_slash(sp.buf, sp.len);
1137 if (!cp || cp == sp.buf)
1138 goto free_and_fail1;
1139 /* They must match, otherwise ignore */
1140 if (strcmp(cp + 1, first.buf))
1141 goto free_and_fail1;
1142 strbuf_release(&sp);
1143 return strbuf_detach(&first, NULL);
1146 /* unquoted second */
1147 cp = stop_at_slash(second, line + llen - second);
1148 if (!cp || cp == second)
1149 goto free_and_fail1;
1150 cp++;
1151 if (line + llen - cp != first.len + 1 ||
1152 memcmp(first.buf, cp, first.len))
1153 goto free_and_fail1;
1154 return strbuf_detach(&first, NULL);
1156 free_and_fail1:
1157 strbuf_release(&first);
1158 strbuf_release(&sp);
1159 return NULL;
1162 /* unquoted first name */
1163 name = stop_at_slash(line, llen);
1164 if (!name || name == line)
1165 return NULL;
1166 name++;
1169 * since the first name is unquoted, a dq if exists must be
1170 * the beginning of the second name.
1172 for (second = name; second < line + llen; second++) {
1173 if (*second == '"') {
1174 struct strbuf sp = STRBUF_INIT;
1175 const char *np;
1177 if (unquote_c_style(&sp, second, NULL))
1178 goto free_and_fail2;
1180 np = stop_at_slash(sp.buf, sp.len);
1181 if (!np || np == sp.buf)
1182 goto free_and_fail2;
1183 np++;
1185 len = sp.buf + sp.len - np;
1186 if (len < second - name &&
1187 !strncmp(np, name, len) &&
1188 isspace(name[len])) {
1189 /* Good */
1190 strbuf_remove(&sp, 0, np - sp.buf);
1191 return strbuf_detach(&sp, NULL);
1194 free_and_fail2:
1195 strbuf_release(&sp);
1196 return NULL;
1201 * Accept a name only if it shows up twice, exactly the same
1202 * form.
1204 second = strchr(name, '\n');
1205 if (!second)
1206 return NULL;
1207 line_len = second - name;
1208 for (len = 0 ; ; len++) {
1209 switch (name[len]) {
1210 default:
1211 continue;
1212 case '\n':
1213 return NULL;
1214 case '\t': case ' ':
1215 second = stop_at_slash(name + len, line_len - len);
1216 if (!second)
1217 return NULL;
1218 second++;
1219 if (second[len] == '\n' && !strncmp(name, second, len)) {
1220 return xmemdupz(name, len);
1226 /* Verify that we recognize the lines following a git header */
1227 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1229 unsigned long offset;
1231 /* A git diff has explicit new/delete information, so we don't guess */
1232 patch->is_new = 0;
1233 patch->is_delete = 0;
1236 * Some things may not have the old name in the
1237 * rest of the headers anywhere (pure mode changes,
1238 * or removing or adding empty files), so we get
1239 * the default name from the header.
1241 patch->def_name = git_header_name(line, len);
1242 if (patch->def_name && root) {
1243 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1244 strcpy(s, root);
1245 strcpy(s + root_len, patch->def_name);
1246 free(patch->def_name);
1247 patch->def_name = s;
1250 line += len;
1251 size -= len;
1252 linenr++;
1253 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1254 static const struct opentry {
1255 const char *str;
1256 int (*fn)(const char *, struct patch *);
1257 } optable[] = {
1258 { "@@ -", gitdiff_hdrend },
1259 { "--- ", gitdiff_oldname },
1260 { "+++ ", gitdiff_newname },
1261 { "old mode ", gitdiff_oldmode },
1262 { "new mode ", gitdiff_newmode },
1263 { "deleted file mode ", gitdiff_delete },
1264 { "new file mode ", gitdiff_newfile },
1265 { "copy from ", gitdiff_copysrc },
1266 { "copy to ", gitdiff_copydst },
1267 { "rename old ", gitdiff_renamesrc },
1268 { "rename new ", gitdiff_renamedst },
1269 { "rename from ", gitdiff_renamesrc },
1270 { "rename to ", gitdiff_renamedst },
1271 { "similarity index ", gitdiff_similarity },
1272 { "dissimilarity index ", gitdiff_dissimilarity },
1273 { "index ", gitdiff_index },
1274 { "", gitdiff_unrecognized },
1276 int i;
1278 len = linelen(line, size);
1279 if (!len || line[len-1] != '\n')
1280 break;
1281 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1282 const struct opentry *p = optable + i;
1283 int oplen = strlen(p->str);
1284 if (len < oplen || memcmp(p->str, line, oplen))
1285 continue;
1286 if (p->fn(line + oplen, patch) < 0)
1287 return offset;
1288 break;
1292 return offset;
1295 static int parse_num(const char *line, unsigned long *p)
1297 char *ptr;
1299 if (!isdigit(*line))
1300 return 0;
1301 *p = strtoul(line, &ptr, 10);
1302 return ptr - line;
1305 static int parse_range(const char *line, int len, int offset, const char *expect,
1306 unsigned long *p1, unsigned long *p2)
1308 int digits, ex;
1310 if (offset < 0 || offset >= len)
1311 return -1;
1312 line += offset;
1313 len -= offset;
1315 digits = parse_num(line, p1);
1316 if (!digits)
1317 return -1;
1319 offset += digits;
1320 line += digits;
1321 len -= digits;
1323 *p2 = 1;
1324 if (*line == ',') {
1325 digits = parse_num(line+1, p2);
1326 if (!digits)
1327 return -1;
1329 offset += digits+1;
1330 line += digits+1;
1331 len -= digits+1;
1334 ex = strlen(expect);
1335 if (ex > len)
1336 return -1;
1337 if (memcmp(line, expect, ex))
1338 return -1;
1340 return offset + ex;
1343 static void recount_diff(const char *line, int size, struct fragment *fragment)
1345 int oldlines = 0, newlines = 0, ret = 0;
1347 if (size < 1) {
1348 warning("recount: ignore empty hunk");
1349 return;
1352 for (;;) {
1353 int len = linelen(line, size);
1354 size -= len;
1355 line += len;
1357 if (size < 1)
1358 break;
1360 switch (*line) {
1361 case ' ': case '\n':
1362 newlines++;
1363 /* fall through */
1364 case '-':
1365 oldlines++;
1366 continue;
1367 case '+':
1368 newlines++;
1369 continue;
1370 case '\\':
1371 continue;
1372 case '@':
1373 ret = size < 3 || prefixcmp(line, "@@ ");
1374 break;
1375 case 'd':
1376 ret = size < 5 || prefixcmp(line, "diff ");
1377 break;
1378 default:
1379 ret = -1;
1380 break;
1382 if (ret) {
1383 warning("recount: unexpected line: %.*s",
1384 (int)linelen(line, size), line);
1385 return;
1387 break;
1389 fragment->oldlines = oldlines;
1390 fragment->newlines = newlines;
1394 * Parse a unified diff fragment header of the
1395 * form "@@ -a,b +c,d @@"
1397 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1399 int offset;
1401 if (!len || line[len-1] != '\n')
1402 return -1;
1404 /* Figure out the number of lines in a fragment */
1405 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1406 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1408 return offset;
1411 static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)
1413 unsigned long offset, len;
1415 patch->is_toplevel_relative = 0;
1416 patch->is_rename = patch->is_copy = 0;
1417 patch->is_new = patch->is_delete = -1;
1418 patch->old_mode = patch->new_mode = 0;
1419 patch->old_name = patch->new_name = NULL;
1420 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1421 unsigned long nextlen;
1423 len = linelen(line, size);
1424 if (!len)
1425 break;
1427 /* Testing this early allows us to take a few shortcuts.. */
1428 if (len < 6)
1429 continue;
1432 * Make sure we don't find any unconnected patch fragments.
1433 * That's a sign that we didn't find a header, and that a
1434 * patch has become corrupted/broken up.
1436 if (!memcmp("@@ -", line, 4)) {
1437 struct fragment dummy;
1438 if (parse_fragment_header(line, len, &dummy) < 0)
1439 continue;
1440 die("patch fragment without header at line %d: %.*s",
1441 linenr, (int)len-1, line);
1444 if (size < len + 6)
1445 break;
1448 * Git patch? It might not have a real patch, just a rename
1449 * or mode change, so we handle that specially
1451 if (!memcmp("diff --git ", line, 11)) {
1452 int git_hdr_len = parse_git_header(line, len, size, patch);
1453 if (git_hdr_len <= len)
1454 continue;
1455 if (!patch->old_name && !patch->new_name) {
1456 if (!patch->def_name)
1457 die("git diff header lacks filename information when removing "
1458 "%d leading pathname components (line %d)" , p_value, linenr);
1459 patch->old_name = xstrdup(patch->def_name);
1460 patch->new_name = xstrdup(patch->def_name);
1462 if (!patch->is_delete && !patch->new_name)
1463 die("git diff header lacks filename information "
1464 "(line %d)", linenr);
1465 patch->is_toplevel_relative = 1;
1466 *hdrsize = git_hdr_len;
1467 return offset;
1470 /* --- followed by +++ ? */
1471 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1472 continue;
1475 * We only accept unified patches, so we want it to
1476 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1477 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1479 nextlen = linelen(line + len, size - len);
1480 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1481 continue;
1483 /* Ok, we'll consider it a patch */
1484 parse_traditional_patch(line, line+len, patch);
1485 *hdrsize = len + nextlen;
1486 linenr += 2;
1487 return offset;
1489 return -1;
1492 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1494 char *err;
1496 if (!result)
1497 return;
1499 whitespace_error++;
1500 if (squelch_whitespace_errors &&
1501 squelch_whitespace_errors < whitespace_error)
1502 return;
1504 err = whitespace_error_string(result);
1505 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1506 patch_input_file, linenr, err, len, line);
1507 free(err);
1510 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1512 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1514 record_ws_error(result, line + 1, len - 2, linenr);
1518 * Parse a unified diff. Note that this really needs to parse each
1519 * fragment separately, since the only way to know the difference
1520 * between a "---" that is part of a patch, and a "---" that starts
1521 * the next patch is to look at the line counts..
1523 static int parse_fragment(const char *line, unsigned long size,
1524 struct patch *patch, struct fragment *fragment)
1526 int added, deleted;
1527 int len = linelen(line, size), offset;
1528 unsigned long oldlines, newlines;
1529 unsigned long leading, trailing;
1531 offset = parse_fragment_header(line, len, fragment);
1532 if (offset < 0)
1533 return -1;
1534 if (offset > 0 && patch->recount)
1535 recount_diff(line + offset, size - offset, fragment);
1536 oldlines = fragment->oldlines;
1537 newlines = fragment->newlines;
1538 leading = 0;
1539 trailing = 0;
1541 /* Parse the thing.. */
1542 line += len;
1543 size -= len;
1544 linenr++;
1545 added = deleted = 0;
1546 for (offset = len;
1547 0 < size;
1548 offset += len, size -= len, line += len, linenr++) {
1549 if (!oldlines && !newlines)
1550 break;
1551 len = linelen(line, size);
1552 if (!len || line[len-1] != '\n')
1553 return -1;
1554 switch (*line) {
1555 default:
1556 return -1;
1557 case '\n': /* newer GNU diff, an empty context line */
1558 case ' ':
1559 oldlines--;
1560 newlines--;
1561 if (!deleted && !added)
1562 leading++;
1563 trailing++;
1564 break;
1565 case '-':
1566 if (apply_in_reverse &&
1567 ws_error_action != nowarn_ws_error)
1568 check_whitespace(line, len, patch->ws_rule);
1569 deleted++;
1570 oldlines--;
1571 trailing = 0;
1572 break;
1573 case '+':
1574 if (!apply_in_reverse &&
1575 ws_error_action != nowarn_ws_error)
1576 check_whitespace(line, len, patch->ws_rule);
1577 added++;
1578 newlines--;
1579 trailing = 0;
1580 break;
1583 * We allow "\ No newline at end of file". Depending
1584 * on locale settings when the patch was produced we
1585 * don't know what this line looks like. The only
1586 * thing we do know is that it begins with "\ ".
1587 * Checking for 12 is just for sanity check -- any
1588 * l10n of "\ No newline..." is at least that long.
1590 case '\\':
1591 if (len < 12 || memcmp(line, "\\ ", 2))
1592 return -1;
1593 break;
1596 if (oldlines || newlines)
1597 return -1;
1598 fragment->leading = leading;
1599 fragment->trailing = trailing;
1602 * If a fragment ends with an incomplete line, we failed to include
1603 * it in the above loop because we hit oldlines == newlines == 0
1604 * before seeing it.
1606 if (12 < size && !memcmp(line, "\\ ", 2))
1607 offset += linelen(line, size);
1609 patch->lines_added += added;
1610 patch->lines_deleted += deleted;
1612 if (0 < patch->is_new && oldlines)
1613 return error("new file depends on old contents");
1614 if (0 < patch->is_delete && newlines)
1615 return error("deleted file still has contents");
1616 return offset;
1620 * We have seen "diff --git a/... b/..." header (or a traditional patch
1621 * header). Read hunks that belong to this patch into fragments and hang
1622 * them to the given patch structure.
1624 * The (fragment->patch, fragment->size) pair points into the memory given
1625 * by the caller, not a copy, when we return.
1627 static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)
1629 unsigned long offset = 0;
1630 unsigned long oldlines = 0, newlines = 0, context = 0;
1631 struct fragment **fragp = &patch->fragments;
1633 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1634 struct fragment *fragment;
1635 int len;
1637 fragment = xcalloc(1, sizeof(*fragment));
1638 fragment->linenr = linenr;
1639 len = parse_fragment(line, size, patch, fragment);
1640 if (len <= 0)
1641 die("corrupt patch at line %d", linenr);
1642 fragment->patch = line;
1643 fragment->size = len;
1644 oldlines += fragment->oldlines;
1645 newlines += fragment->newlines;
1646 context += fragment->leading + fragment->trailing;
1648 *fragp = fragment;
1649 fragp = &fragment->next;
1651 offset += len;
1652 line += len;
1653 size -= len;
1657 * If something was removed (i.e. we have old-lines) it cannot
1658 * be creation, and if something was added it cannot be
1659 * deletion. However, the reverse is not true; --unified=0
1660 * patches that only add are not necessarily creation even
1661 * though they do not have any old lines, and ones that only
1662 * delete are not necessarily deletion.
1664 * Unfortunately, a real creation/deletion patch do _not_ have
1665 * any context line by definition, so we cannot safely tell it
1666 * apart with --unified=0 insanity. At least if the patch has
1667 * more than one hunk it is not creation or deletion.
1669 if (patch->is_new < 0 &&
1670 (oldlines || (patch->fragments && patch->fragments->next)))
1671 patch->is_new = 0;
1672 if (patch->is_delete < 0 &&
1673 (newlines || (patch->fragments && patch->fragments->next)))
1674 patch->is_delete = 0;
1676 if (0 < patch->is_new && oldlines)
1677 die("new file %s depends on old contents", patch->new_name);
1678 if (0 < patch->is_delete && newlines)
1679 die("deleted file %s still has contents", patch->old_name);
1680 if (!patch->is_delete && !newlines && context)
1681 fprintf(stderr, "** warning: file %s becomes empty but "
1682 "is not deleted\n", patch->new_name);
1684 return offset;
1687 static inline int metadata_changes(struct patch *patch)
1689 return patch->is_rename > 0 ||
1690 patch->is_copy > 0 ||
1691 patch->is_new > 0 ||
1692 patch->is_delete ||
1693 (patch->old_mode && patch->new_mode &&
1694 patch->old_mode != patch->new_mode);
1697 static char *inflate_it(const void *data, unsigned long size,
1698 unsigned long inflated_size)
1700 git_zstream stream;
1701 void *out;
1702 int st;
1704 memset(&stream, 0, sizeof(stream));
1706 stream.next_in = (unsigned char *)data;
1707 stream.avail_in = size;
1708 stream.next_out = out = xmalloc(inflated_size);
1709 stream.avail_out = inflated_size;
1710 git_inflate_init(&stream);
1711 st = git_inflate(&stream, Z_FINISH);
1712 git_inflate_end(&stream);
1713 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1714 free(out);
1715 return NULL;
1717 return out;
1721 * Read a binary hunk and return a new fragment; fragment->patch
1722 * points at an allocated memory that the caller must free, so
1723 * it is marked as "->free_patch = 1".
1725 static struct fragment *parse_binary_hunk(char **buf_p,
1726 unsigned long *sz_p,
1727 int *status_p,
1728 int *used_p)
1731 * Expect a line that begins with binary patch method ("literal"
1732 * or "delta"), followed by the length of data before deflating.
1733 * a sequence of 'length-byte' followed by base-85 encoded data
1734 * should follow, terminated by a newline.
1736 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1737 * and we would limit the patch line to 66 characters,
1738 * so one line can fit up to 13 groups that would decode
1739 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1740 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1742 int llen, used;
1743 unsigned long size = *sz_p;
1744 char *buffer = *buf_p;
1745 int patch_method;
1746 unsigned long origlen;
1747 char *data = NULL;
1748 int hunk_size = 0;
1749 struct fragment *frag;
1751 llen = linelen(buffer, size);
1752 used = llen;
1754 *status_p = 0;
1756 if (!prefixcmp(buffer, "delta ")) {
1757 patch_method = BINARY_DELTA_DEFLATED;
1758 origlen = strtoul(buffer + 6, NULL, 10);
1760 else if (!prefixcmp(buffer, "literal ")) {
1761 patch_method = BINARY_LITERAL_DEFLATED;
1762 origlen = strtoul(buffer + 8, NULL, 10);
1764 else
1765 return NULL;
1767 linenr++;
1768 buffer += llen;
1769 while (1) {
1770 int byte_length, max_byte_length, newsize;
1771 llen = linelen(buffer, size);
1772 used += llen;
1773 linenr++;
1774 if (llen == 1) {
1775 /* consume the blank line */
1776 buffer++;
1777 size--;
1778 break;
1781 * Minimum line is "A00000\n" which is 7-byte long,
1782 * and the line length must be multiple of 5 plus 2.
1784 if ((llen < 7) || (llen-2) % 5)
1785 goto corrupt;
1786 max_byte_length = (llen - 2) / 5 * 4;
1787 byte_length = *buffer;
1788 if ('A' <= byte_length && byte_length <= 'Z')
1789 byte_length = byte_length - 'A' + 1;
1790 else if ('a' <= byte_length && byte_length <= 'z')
1791 byte_length = byte_length - 'a' + 27;
1792 else
1793 goto corrupt;
1794 /* if the input length was not multiple of 4, we would
1795 * have filler at the end but the filler should never
1796 * exceed 3 bytes
1798 if (max_byte_length < byte_length ||
1799 byte_length <= max_byte_length - 4)
1800 goto corrupt;
1801 newsize = hunk_size + byte_length;
1802 data = xrealloc(data, newsize);
1803 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1804 goto corrupt;
1805 hunk_size = newsize;
1806 buffer += llen;
1807 size -= llen;
1810 frag = xcalloc(1, sizeof(*frag));
1811 frag->patch = inflate_it(data, hunk_size, origlen);
1812 frag->free_patch = 1;
1813 if (!frag->patch)
1814 goto corrupt;
1815 free(data);
1816 frag->size = origlen;
1817 *buf_p = buffer;
1818 *sz_p = size;
1819 *used_p = used;
1820 frag->binary_patch_method = patch_method;
1821 return frag;
1823 corrupt:
1824 free(data);
1825 *status_p = -1;
1826 error("corrupt binary patch at line %d: %.*s",
1827 linenr-1, llen-1, buffer);
1828 return NULL;
1831 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1834 * We have read "GIT binary patch\n"; what follows is a line
1835 * that says the patch method (currently, either "literal" or
1836 * "delta") and the length of data before deflating; a
1837 * sequence of 'length-byte' followed by base-85 encoded data
1838 * follows.
1840 * When a binary patch is reversible, there is another binary
1841 * hunk in the same format, starting with patch method (either
1842 * "literal" or "delta") with the length of data, and a sequence
1843 * of length-byte + base-85 encoded data, terminated with another
1844 * empty line. This data, when applied to the postimage, produces
1845 * the preimage.
1847 struct fragment *forward;
1848 struct fragment *reverse;
1849 int status;
1850 int used, used_1;
1852 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1853 if (!forward && !status)
1854 /* there has to be one hunk (forward hunk) */
1855 return error("unrecognized binary patch at line %d", linenr-1);
1856 if (status)
1857 /* otherwise we already gave an error message */
1858 return status;
1860 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1861 if (reverse)
1862 used += used_1;
1863 else if (status) {
1865 * Not having reverse hunk is not an error, but having
1866 * a corrupt reverse hunk is.
1868 free((void*) forward->patch);
1869 free(forward);
1870 return status;
1872 forward->next = reverse;
1873 patch->fragments = forward;
1874 patch->is_binary = 1;
1875 return used;
1879 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1880 * reading after seeing a single patch (i.e. changes to a single file).
1881 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1882 * Return the number of bytes consumed, so that the caller can call us
1883 * again for the next patch.
1885 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1887 int hdrsize, patchsize;
1888 int offset = find_header(buffer, size, &hdrsize, patch);
1890 if (offset < 0)
1891 return offset;
1893 patch->ws_rule = whitespace_rule(patch->new_name
1894 ? patch->new_name
1895 : patch->old_name);
1897 patchsize = parse_single_patch(buffer + offset + hdrsize,
1898 size - offset - hdrsize, patch);
1900 if (!patchsize) {
1901 static const char *binhdr[] = {
1902 "Binary files ",
1903 "Files ",
1904 NULL,
1906 static const char git_binary[] = "GIT binary patch\n";
1907 int i;
1908 int hd = hdrsize + offset;
1909 unsigned long llen = linelen(buffer + hd, size - hd);
1911 if (llen == sizeof(git_binary) - 1 &&
1912 !memcmp(git_binary, buffer + hd, llen)) {
1913 int used;
1914 linenr++;
1915 used = parse_binary(buffer + hd + llen,
1916 size - hd - llen, patch);
1917 if (used)
1918 patchsize = used + llen;
1919 else
1920 patchsize = 0;
1922 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1923 for (i = 0; binhdr[i]; i++) {
1924 int len = strlen(binhdr[i]);
1925 if (len < size - hd &&
1926 !memcmp(binhdr[i], buffer + hd, len)) {
1927 linenr++;
1928 patch->is_binary = 1;
1929 patchsize = llen;
1930 break;
1935 /* Empty patch cannot be applied if it is a text patch
1936 * without metadata change. A binary patch appears
1937 * empty to us here.
1939 if ((apply || check) &&
1940 (!patch->is_binary && !metadata_changes(patch)))
1941 die("patch with only garbage at line %d", linenr);
1944 return offset + hdrsize + patchsize;
1947 #define swap(a,b) myswap((a),(b),sizeof(a))
1949 #define myswap(a, b, size) do { \
1950 unsigned char mytmp[size]; \
1951 memcpy(mytmp, &a, size); \
1952 memcpy(&a, &b, size); \
1953 memcpy(&b, mytmp, size); \
1954 } while (0)
1956 static void reverse_patches(struct patch *p)
1958 for (; p; p = p->next) {
1959 struct fragment *frag = p->fragments;
1961 swap(p->new_name, p->old_name);
1962 swap(p->new_mode, p->old_mode);
1963 swap(p->is_new, p->is_delete);
1964 swap(p->lines_added, p->lines_deleted);
1965 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1967 for (; frag; frag = frag->next) {
1968 swap(frag->newpos, frag->oldpos);
1969 swap(frag->newlines, frag->oldlines);
1974 static const char pluses[] =
1975 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1976 static const char minuses[]=
1977 "----------------------------------------------------------------------";
1979 static void show_stats(struct patch *patch)
1981 struct strbuf qname = STRBUF_INIT;
1982 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1983 int max, add, del;
1985 quote_c_style(cp, &qname, NULL, 0);
1988 * "scale" the filename
1990 max = max_len;
1991 if (max > 50)
1992 max = 50;
1994 if (qname.len > max) {
1995 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1996 if (!cp)
1997 cp = qname.buf + qname.len + 3 - max;
1998 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2001 if (patch->is_binary) {
2002 printf(" %-*s | Bin\n", max, qname.buf);
2003 strbuf_release(&qname);
2004 return;
2007 printf(" %-*s |", max, qname.buf);
2008 strbuf_release(&qname);
2011 * scale the add/delete
2013 max = max + max_change > 70 ? 70 - max : max_change;
2014 add = patch->lines_added;
2015 del = patch->lines_deleted;
2017 if (max_change > 0) {
2018 int total = ((add + del) * max + max_change / 2) / max_change;
2019 add = (add * max + max_change / 2) / max_change;
2020 del = total - add;
2022 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2023 add, pluses, del, minuses);
2026 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2028 switch (st->st_mode & S_IFMT) {
2029 case S_IFLNK:
2030 if (strbuf_readlink(buf, path, st->st_size) < 0)
2031 return error("unable to read symlink %s", path);
2032 return 0;
2033 case S_IFREG:
2034 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2035 return error("unable to open or read %s", path);
2036 convert_to_git(path, buf->buf, buf->len, buf, 0);
2037 return 0;
2038 default:
2039 return -1;
2044 * Update the preimage, and the common lines in postimage,
2045 * from buffer buf of length len. If postlen is 0 the postimage
2046 * is updated in place, otherwise it's updated on a new buffer
2047 * of length postlen
2050 static void update_pre_post_images(struct image *preimage,
2051 struct image *postimage,
2052 char *buf,
2053 size_t len, size_t postlen)
2055 int i, ctx;
2056 char *new, *old, *fixed;
2057 struct image fixed_preimage;
2060 * Update the preimage with whitespace fixes. Note that we
2061 * are not losing preimage->buf -- apply_one_fragment() will
2062 * free "oldlines".
2064 prepare_image(&fixed_preimage, buf, len, 1);
2065 assert(fixed_preimage.nr == preimage->nr);
2066 for (i = 0; i < preimage->nr; i++)
2067 fixed_preimage.line[i].flag = preimage->line[i].flag;
2068 free(preimage->line_allocated);
2069 *preimage = fixed_preimage;
2072 * Adjust the common context lines in postimage. This can be
2073 * done in-place when we are just doing whitespace fixing,
2074 * which does not make the string grow, but needs a new buffer
2075 * when ignoring whitespace causes the update, since in this case
2076 * we could have e.g. tabs converted to multiple spaces.
2077 * We trust the caller to tell us if the update can be done
2078 * in place (postlen==0) or not.
2080 old = postimage->buf;
2081 if (postlen)
2082 new = postimage->buf = xmalloc(postlen);
2083 else
2084 new = old;
2085 fixed = preimage->buf;
2086 for (i = ctx = 0; i < postimage->nr; i++) {
2087 size_t len = postimage->line[i].len;
2088 if (!(postimage->line[i].flag & LINE_COMMON)) {
2089 /* an added line -- no counterparts in preimage */
2090 memmove(new, old, len);
2091 old += len;
2092 new += len;
2093 continue;
2096 /* a common context -- skip it in the original postimage */
2097 old += len;
2099 /* and find the corresponding one in the fixed preimage */
2100 while (ctx < preimage->nr &&
2101 !(preimage->line[ctx].flag & LINE_COMMON)) {
2102 fixed += preimage->line[ctx].len;
2103 ctx++;
2105 if (preimage->nr <= ctx)
2106 die("oops");
2108 /* and copy it in, while fixing the line length */
2109 len = preimage->line[ctx].len;
2110 memcpy(new, fixed, len);
2111 new += len;
2112 fixed += len;
2113 postimage->line[i].len = len;
2114 ctx++;
2117 /* Fix the length of the whole thing */
2118 postimage->len = new - postimage->buf;
2121 static int match_fragment(struct image *img,
2122 struct image *preimage,
2123 struct image *postimage,
2124 unsigned long try,
2125 int try_lno,
2126 unsigned ws_rule,
2127 int match_beginning, int match_end)
2129 int i;
2130 char *fixed_buf, *buf, *orig, *target;
2131 struct strbuf fixed;
2132 size_t fixed_len;
2133 int preimage_limit;
2135 if (preimage->nr + try_lno <= img->nr) {
2137 * The hunk falls within the boundaries of img.
2139 preimage_limit = preimage->nr;
2140 if (match_end && (preimage->nr + try_lno != img->nr))
2141 return 0;
2142 } else if (ws_error_action == correct_ws_error &&
2143 (ws_rule & WS_BLANK_AT_EOF)) {
2145 * This hunk extends beyond the end of img, and we are
2146 * removing blank lines at the end of the file. This
2147 * many lines from the beginning of the preimage must
2148 * match with img, and the remainder of the preimage
2149 * must be blank.
2151 preimage_limit = img->nr - try_lno;
2152 } else {
2154 * The hunk extends beyond the end of the img and
2155 * we are not removing blanks at the end, so we
2156 * should reject the hunk at this position.
2158 return 0;
2161 if (match_beginning && try_lno)
2162 return 0;
2164 /* Quick hash check */
2165 for (i = 0; i < preimage_limit; i++)
2166 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2167 (preimage->line[i].hash != img->line[try_lno + i].hash))
2168 return 0;
2170 if (preimage_limit == preimage->nr) {
2172 * Do we have an exact match? If we were told to match
2173 * at the end, size must be exactly at try+fragsize,
2174 * otherwise try+fragsize must be still within the preimage,
2175 * and either case, the old piece should match the preimage
2176 * exactly.
2178 if ((match_end
2179 ? (try + preimage->len == img->len)
2180 : (try + preimage->len <= img->len)) &&
2181 !memcmp(img->buf + try, preimage->buf, preimage->len))
2182 return 1;
2183 } else {
2185 * The preimage extends beyond the end of img, so
2186 * there cannot be an exact match.
2188 * There must be one non-blank context line that match
2189 * a line before the end of img.
2191 char *buf_end;
2193 buf = preimage->buf;
2194 buf_end = buf;
2195 for (i = 0; i < preimage_limit; i++)
2196 buf_end += preimage->line[i].len;
2198 for ( ; buf < buf_end; buf++)
2199 if (!isspace(*buf))
2200 break;
2201 if (buf == buf_end)
2202 return 0;
2206 * No exact match. If we are ignoring whitespace, run a line-by-line
2207 * fuzzy matching. We collect all the line length information because
2208 * we need it to adjust whitespace if we match.
2210 if (ws_ignore_action == ignore_ws_change) {
2211 size_t imgoff = 0;
2212 size_t preoff = 0;
2213 size_t postlen = postimage->len;
2214 size_t extra_chars;
2215 char *preimage_eof;
2216 char *preimage_end;
2217 for (i = 0; i < preimage_limit; i++) {
2218 size_t prelen = preimage->line[i].len;
2219 size_t imglen = img->line[try_lno+i].len;
2221 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2222 preimage->buf + preoff, prelen))
2223 return 0;
2224 if (preimage->line[i].flag & LINE_COMMON)
2225 postlen += imglen - prelen;
2226 imgoff += imglen;
2227 preoff += prelen;
2231 * Ok, the preimage matches with whitespace fuzz.
2233 * imgoff now holds the true length of the target that
2234 * matches the preimage before the end of the file.
2236 * Count the number of characters in the preimage that fall
2237 * beyond the end of the file and make sure that all of them
2238 * are whitespace characters. (This can only happen if
2239 * we are removing blank lines at the end of the file.)
2241 buf = preimage_eof = preimage->buf + preoff;
2242 for ( ; i < preimage->nr; i++)
2243 preoff += preimage->line[i].len;
2244 preimage_end = preimage->buf + preoff;
2245 for ( ; buf < preimage_end; buf++)
2246 if (!isspace(*buf))
2247 return 0;
2250 * Update the preimage and the common postimage context
2251 * lines to use the same whitespace as the target.
2252 * If whitespace is missing in the target (i.e.
2253 * if the preimage extends beyond the end of the file),
2254 * use the whitespace from the preimage.
2256 extra_chars = preimage_end - preimage_eof;
2257 strbuf_init(&fixed, imgoff + extra_chars);
2258 strbuf_add(&fixed, img->buf + try, imgoff);
2259 strbuf_add(&fixed, preimage_eof, extra_chars);
2260 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2261 update_pre_post_images(preimage, postimage,
2262 fixed_buf, fixed_len, postlen);
2263 return 1;
2266 if (ws_error_action != correct_ws_error)
2267 return 0;
2270 * The hunk does not apply byte-by-byte, but the hash says
2271 * it might with whitespace fuzz. We haven't been asked to
2272 * ignore whitespace, we were asked to correct whitespace
2273 * errors, so let's try matching after whitespace correction.
2275 * The preimage may extend beyond the end of the file,
2276 * but in this loop we will only handle the part of the
2277 * preimage that falls within the file.
2279 strbuf_init(&fixed, preimage->len + 1);
2280 orig = preimage->buf;
2281 target = img->buf + try;
2282 for (i = 0; i < preimage_limit; i++) {
2283 size_t oldlen = preimage->line[i].len;
2284 size_t tgtlen = img->line[try_lno + i].len;
2285 size_t fixstart = fixed.len;
2286 struct strbuf tgtfix;
2287 int match;
2289 /* Try fixing the line in the preimage */
2290 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2292 /* Try fixing the line in the target */
2293 strbuf_init(&tgtfix, tgtlen);
2294 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2297 * If they match, either the preimage was based on
2298 * a version before our tree fixed whitespace breakage,
2299 * or we are lacking a whitespace-fix patch the tree
2300 * the preimage was based on already had (i.e. target
2301 * has whitespace breakage, the preimage doesn't).
2302 * In either case, we are fixing the whitespace breakages
2303 * so we might as well take the fix together with their
2304 * real change.
2306 match = (tgtfix.len == fixed.len - fixstart &&
2307 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2308 fixed.len - fixstart));
2310 strbuf_release(&tgtfix);
2311 if (!match)
2312 goto unmatch_exit;
2314 orig += oldlen;
2315 target += tgtlen;
2320 * Now handle the lines in the preimage that falls beyond the
2321 * end of the file (if any). They will only match if they are
2322 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2323 * false).
2325 for ( ; i < preimage->nr; i++) {
2326 size_t fixstart = fixed.len; /* start of the fixed preimage */
2327 size_t oldlen = preimage->line[i].len;
2328 int j;
2330 /* Try fixing the line in the preimage */
2331 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2333 for (j = fixstart; j < fixed.len; j++)
2334 if (!isspace(fixed.buf[j]))
2335 goto unmatch_exit;
2337 orig += oldlen;
2341 * Yes, the preimage is based on an older version that still
2342 * has whitespace breakages unfixed, and fixing them makes the
2343 * hunk match. Update the context lines in the postimage.
2345 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2346 update_pre_post_images(preimage, postimage,
2347 fixed_buf, fixed_len, 0);
2348 return 1;
2350 unmatch_exit:
2351 strbuf_release(&fixed);
2352 return 0;
2355 static int find_pos(struct image *img,
2356 struct image *preimage,
2357 struct image *postimage,
2358 int line,
2359 unsigned ws_rule,
2360 int match_beginning, int match_end)
2362 int i;
2363 unsigned long backwards, forwards, try;
2364 int backwards_lno, forwards_lno, try_lno;
2367 * If match_beginning or match_end is specified, there is no
2368 * point starting from a wrong line that will never match and
2369 * wander around and wait for a match at the specified end.
2371 if (match_beginning)
2372 line = 0;
2373 else if (match_end)
2374 line = img->nr - preimage->nr;
2377 * Because the comparison is unsigned, the following test
2378 * will also take care of a negative line number that can
2379 * result when match_end and preimage is larger than the target.
2381 if ((size_t) line > img->nr)
2382 line = img->nr;
2384 try = 0;
2385 for (i = 0; i < line; i++)
2386 try += img->line[i].len;
2389 * There's probably some smart way to do this, but I'll leave
2390 * that to the smart and beautiful people. I'm simple and stupid.
2392 backwards = try;
2393 backwards_lno = line;
2394 forwards = try;
2395 forwards_lno = line;
2396 try_lno = line;
2398 for (i = 0; ; i++) {
2399 if (match_fragment(img, preimage, postimage,
2400 try, try_lno, ws_rule,
2401 match_beginning, match_end))
2402 return try_lno;
2404 again:
2405 if (backwards_lno == 0 && forwards_lno == img->nr)
2406 break;
2408 if (i & 1) {
2409 if (backwards_lno == 0) {
2410 i++;
2411 goto again;
2413 backwards_lno--;
2414 backwards -= img->line[backwards_lno].len;
2415 try = backwards;
2416 try_lno = backwards_lno;
2417 } else {
2418 if (forwards_lno == img->nr) {
2419 i++;
2420 goto again;
2422 forwards += img->line[forwards_lno].len;
2423 forwards_lno++;
2424 try = forwards;
2425 try_lno = forwards_lno;
2429 return -1;
2432 static void remove_first_line(struct image *img)
2434 img->buf += img->line[0].len;
2435 img->len -= img->line[0].len;
2436 img->line++;
2437 img->nr--;
2440 static void remove_last_line(struct image *img)
2442 img->len -= img->line[--img->nr].len;
2446 * The change from "preimage" and "postimage" has been found to
2447 * apply at applied_pos (counts in line numbers) in "img".
2448 * Update "img" to remove "preimage" and replace it with "postimage".
2450 static void update_image(struct image *img,
2451 int applied_pos,
2452 struct image *preimage,
2453 struct image *postimage)
2456 * remove the copy of preimage at offset in img
2457 * and replace it with postimage
2459 int i, nr;
2460 size_t remove_count, insert_count, applied_at = 0;
2461 char *result;
2462 int preimage_limit;
2465 * If we are removing blank lines at the end of img,
2466 * the preimage may extend beyond the end.
2467 * If that is the case, we must be careful only to
2468 * remove the part of the preimage that falls within
2469 * the boundaries of img. Initialize preimage_limit
2470 * to the number of lines in the preimage that falls
2471 * within the boundaries.
2473 preimage_limit = preimage->nr;
2474 if (preimage_limit > img->nr - applied_pos)
2475 preimage_limit = img->nr - applied_pos;
2477 for (i = 0; i < applied_pos; i++)
2478 applied_at += img->line[i].len;
2480 remove_count = 0;
2481 for (i = 0; i < preimage_limit; i++)
2482 remove_count += img->line[applied_pos + i].len;
2483 insert_count = postimage->len;
2485 /* Adjust the contents */
2486 result = xmalloc(img->len + insert_count - remove_count + 1);
2487 memcpy(result, img->buf, applied_at);
2488 memcpy(result + applied_at, postimage->buf, postimage->len);
2489 memcpy(result + applied_at + postimage->len,
2490 img->buf + (applied_at + remove_count),
2491 img->len - (applied_at + remove_count));
2492 free(img->buf);
2493 img->buf = result;
2494 img->len += insert_count - remove_count;
2495 result[img->len] = '\0';
2497 /* Adjust the line table */
2498 nr = img->nr + postimage->nr - preimage_limit;
2499 if (preimage_limit < postimage->nr) {
2501 * NOTE: this knows that we never call remove_first_line()
2502 * on anything other than pre/post image.
2504 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2505 img->line_allocated = img->line;
2507 if (preimage_limit != postimage->nr)
2508 memmove(img->line + applied_pos + postimage->nr,
2509 img->line + applied_pos + preimage_limit,
2510 (img->nr - (applied_pos + preimage_limit)) *
2511 sizeof(*img->line));
2512 memcpy(img->line + applied_pos,
2513 postimage->line,
2514 postimage->nr * sizeof(*img->line));
2515 if (!allow_overlap)
2516 for (i = 0; i < postimage->nr; i++)
2517 img->line[applied_pos + i].flag |= LINE_PATCHED;
2518 img->nr = nr;
2522 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2523 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2524 * replace the part of "img" with "postimage" text.
2526 static int apply_one_fragment(struct image *img, struct fragment *frag,
2527 int inaccurate_eof, unsigned ws_rule,
2528 int nth_fragment)
2530 int match_beginning, match_end;
2531 const char *patch = frag->patch;
2532 int size = frag->size;
2533 char *old, *oldlines;
2534 struct strbuf newlines;
2535 int new_blank_lines_at_end = 0;
2536 int found_new_blank_lines_at_end = 0;
2537 int hunk_linenr = frag->linenr;
2538 unsigned long leading, trailing;
2539 int pos, applied_pos;
2540 struct image preimage;
2541 struct image postimage;
2543 memset(&preimage, 0, sizeof(preimage));
2544 memset(&postimage, 0, sizeof(postimage));
2545 oldlines = xmalloc(size);
2546 strbuf_init(&newlines, size);
2548 old = oldlines;
2549 while (size > 0) {
2550 char first;
2551 int len = linelen(patch, size);
2552 int plen;
2553 int added_blank_line = 0;
2554 int is_blank_context = 0;
2555 size_t start;
2557 if (!len)
2558 break;
2561 * "plen" is how much of the line we should use for
2562 * the actual patch data. Normally we just remove the
2563 * first character on the line, but if the line is
2564 * followed by "\ No newline", then we also remove the
2565 * last one (which is the newline, of course).
2567 plen = len - 1;
2568 if (len < size && patch[len] == '\\')
2569 plen--;
2570 first = *patch;
2571 if (apply_in_reverse) {
2572 if (first == '-')
2573 first = '+';
2574 else if (first == '+')
2575 first = '-';
2578 switch (first) {
2579 case '\n':
2580 /* Newer GNU diff, empty context line */
2581 if (plen < 0)
2582 /* ... followed by '\No newline'; nothing */
2583 break;
2584 *old++ = '\n';
2585 strbuf_addch(&newlines, '\n');
2586 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2587 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2588 is_blank_context = 1;
2589 break;
2590 case ' ':
2591 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2592 ws_blank_line(patch + 1, plen, ws_rule))
2593 is_blank_context = 1;
2594 case '-':
2595 memcpy(old, patch + 1, plen);
2596 add_line_info(&preimage, old, plen,
2597 (first == ' ' ? LINE_COMMON : 0));
2598 old += plen;
2599 if (first == '-')
2600 break;
2601 /* Fall-through for ' ' */
2602 case '+':
2603 /* --no-add does not add new lines */
2604 if (first == '+' && no_add)
2605 break;
2607 start = newlines.len;
2608 if (first != '+' ||
2609 !whitespace_error ||
2610 ws_error_action != correct_ws_error) {
2611 strbuf_add(&newlines, patch + 1, plen);
2613 else {
2614 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2616 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2617 (first == '+' ? 0 : LINE_COMMON));
2618 if (first == '+' &&
2619 (ws_rule & WS_BLANK_AT_EOF) &&
2620 ws_blank_line(patch + 1, plen, ws_rule))
2621 added_blank_line = 1;
2622 break;
2623 case '@': case '\\':
2624 /* Ignore it, we already handled it */
2625 break;
2626 default:
2627 if (apply_verbosely)
2628 error("invalid start of line: '%c'", first);
2629 return -1;
2631 if (added_blank_line) {
2632 if (!new_blank_lines_at_end)
2633 found_new_blank_lines_at_end = hunk_linenr;
2634 new_blank_lines_at_end++;
2636 else if (is_blank_context)
2638 else
2639 new_blank_lines_at_end = 0;
2640 patch += len;
2641 size -= len;
2642 hunk_linenr++;
2644 if (inaccurate_eof &&
2645 old > oldlines && old[-1] == '\n' &&
2646 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2647 old--;
2648 strbuf_setlen(&newlines, newlines.len - 1);
2651 leading = frag->leading;
2652 trailing = frag->trailing;
2655 * A hunk to change lines at the beginning would begin with
2656 * @@ -1,L +N,M @@
2657 * but we need to be careful. -U0 that inserts before the second
2658 * line also has this pattern.
2660 * And a hunk to add to an empty file would begin with
2661 * @@ -0,0 +N,M @@
2663 * In other words, a hunk that is (frag->oldpos <= 1) with or
2664 * without leading context must match at the beginning.
2666 match_beginning = (!frag->oldpos ||
2667 (frag->oldpos == 1 && !unidiff_zero));
2670 * A hunk without trailing lines must match at the end.
2671 * However, we simply cannot tell if a hunk must match end
2672 * from the lack of trailing lines if the patch was generated
2673 * with unidiff without any context.
2675 match_end = !unidiff_zero && !trailing;
2677 pos = frag->newpos ? (frag->newpos - 1) : 0;
2678 preimage.buf = oldlines;
2679 preimage.len = old - oldlines;
2680 postimage.buf = newlines.buf;
2681 postimage.len = newlines.len;
2682 preimage.line = preimage.line_allocated;
2683 postimage.line = postimage.line_allocated;
2685 for (;;) {
2687 applied_pos = find_pos(img, &preimage, &postimage, pos,
2688 ws_rule, match_beginning, match_end);
2690 if (applied_pos >= 0)
2691 break;
2693 /* Am I at my context limits? */
2694 if ((leading <= p_context) && (trailing <= p_context))
2695 break;
2696 if (match_beginning || match_end) {
2697 match_beginning = match_end = 0;
2698 continue;
2702 * Reduce the number of context lines; reduce both
2703 * leading and trailing if they are equal otherwise
2704 * just reduce the larger context.
2706 if (leading >= trailing) {
2707 remove_first_line(&preimage);
2708 remove_first_line(&postimage);
2709 pos--;
2710 leading--;
2712 if (trailing > leading) {
2713 remove_last_line(&preimage);
2714 remove_last_line(&postimage);
2715 trailing--;
2719 if (applied_pos >= 0) {
2720 if (new_blank_lines_at_end &&
2721 preimage.nr + applied_pos >= img->nr &&
2722 (ws_rule & WS_BLANK_AT_EOF) &&
2723 ws_error_action != nowarn_ws_error) {
2724 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2725 found_new_blank_lines_at_end);
2726 if (ws_error_action == correct_ws_error) {
2727 while (new_blank_lines_at_end--)
2728 remove_last_line(&postimage);
2731 * We would want to prevent write_out_results()
2732 * from taking place in apply_patch() that follows
2733 * the callchain led us here, which is:
2734 * apply_patch->check_patch_list->check_patch->
2735 * apply_data->apply_fragments->apply_one_fragment
2737 if (ws_error_action == die_on_ws_error)
2738 apply = 0;
2741 if (apply_verbosely && applied_pos != pos) {
2742 int offset = applied_pos - pos;
2743 if (apply_in_reverse)
2744 offset = 0 - offset;
2745 fprintf(stderr,
2746 "Hunk #%d succeeded at %d (offset %d lines).\n",
2747 nth_fragment, applied_pos + 1, offset);
2751 * Warn if it was necessary to reduce the number
2752 * of context lines.
2754 if ((leading != frag->leading) ||
2755 (trailing != frag->trailing))
2756 fprintf(stderr, "Context reduced to (%ld/%ld)"
2757 " to apply fragment at %d\n",
2758 leading, trailing, applied_pos+1);
2759 update_image(img, applied_pos, &preimage, &postimage);
2760 } else {
2761 if (apply_verbosely)
2762 error("while searching for:\n%.*s",
2763 (int)(old - oldlines), oldlines);
2766 free(oldlines);
2767 strbuf_release(&newlines);
2768 free(preimage.line_allocated);
2769 free(postimage.line_allocated);
2771 return (applied_pos < 0);
2774 static int apply_binary_fragment(struct image *img, struct patch *patch)
2776 struct fragment *fragment = patch->fragments;
2777 unsigned long len;
2778 void *dst;
2780 if (!fragment)
2781 return error("missing binary patch data for '%s'",
2782 patch->new_name ?
2783 patch->new_name :
2784 patch->old_name);
2786 /* Binary patch is irreversible without the optional second hunk */
2787 if (apply_in_reverse) {
2788 if (!fragment->next)
2789 return error("cannot reverse-apply a binary patch "
2790 "without the reverse hunk to '%s'",
2791 patch->new_name
2792 ? patch->new_name : patch->old_name);
2793 fragment = fragment->next;
2795 switch (fragment->binary_patch_method) {
2796 case BINARY_DELTA_DEFLATED:
2797 dst = patch_delta(img->buf, img->len, fragment->patch,
2798 fragment->size, &len);
2799 if (!dst)
2800 return -1;
2801 clear_image(img);
2802 img->buf = dst;
2803 img->len = len;
2804 return 0;
2805 case BINARY_LITERAL_DEFLATED:
2806 clear_image(img);
2807 img->len = fragment->size;
2808 img->buf = xmalloc(img->len+1);
2809 memcpy(img->buf, fragment->patch, img->len);
2810 img->buf[img->len] = '\0';
2811 return 0;
2813 return -1;
2817 * Replace "img" with the result of applying the binary patch.
2818 * The binary patch data itself in patch->fragment is still kept
2819 * but the preimage prepared by the caller in "img" is freed here
2820 * or in the helper function apply_binary_fragment() this calls.
2822 static int apply_binary(struct image *img, struct patch *patch)
2824 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2825 unsigned char sha1[20];
2828 * For safety, we require patch index line to contain
2829 * full 40-byte textual SHA1 for old and new, at least for now.
2831 if (strlen(patch->old_sha1_prefix) != 40 ||
2832 strlen(patch->new_sha1_prefix) != 40 ||
2833 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2834 get_sha1_hex(patch->new_sha1_prefix, sha1))
2835 return error("cannot apply binary patch to '%s' "
2836 "without full index line", name);
2838 if (patch->old_name) {
2840 * See if the old one matches what the patch
2841 * applies to.
2843 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2844 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2845 return error("the patch applies to '%s' (%s), "
2846 "which does not match the "
2847 "current contents.",
2848 name, sha1_to_hex(sha1));
2850 else {
2851 /* Otherwise, the old one must be empty. */
2852 if (img->len)
2853 return error("the patch applies to an empty "
2854 "'%s' but it is not empty", name);
2857 get_sha1_hex(patch->new_sha1_prefix, sha1);
2858 if (is_null_sha1(sha1)) {
2859 clear_image(img);
2860 return 0; /* deletion patch */
2863 if (has_sha1_file(sha1)) {
2864 /* We already have the postimage */
2865 enum object_type type;
2866 unsigned long size;
2867 char *result;
2869 result = read_sha1_file(sha1, &type, &size);
2870 if (!result)
2871 return error("the necessary postimage %s for "
2872 "'%s' cannot be read",
2873 patch->new_sha1_prefix, name);
2874 clear_image(img);
2875 img->buf = result;
2876 img->len = size;
2877 } else {
2879 * We have verified buf matches the preimage;
2880 * apply the patch data to it, which is stored
2881 * in the patch->fragments->{patch,size}.
2883 if (apply_binary_fragment(img, patch))
2884 return error("binary patch does not apply to '%s'",
2885 name);
2887 /* verify that the result matches */
2888 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2889 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2890 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2891 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2894 return 0;
2897 static int apply_fragments(struct image *img, struct patch *patch)
2899 struct fragment *frag = patch->fragments;
2900 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2901 unsigned ws_rule = patch->ws_rule;
2902 unsigned inaccurate_eof = patch->inaccurate_eof;
2903 int nth = 0;
2905 if (patch->is_binary)
2906 return apply_binary(img, patch);
2908 while (frag) {
2909 nth++;
2910 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
2911 error("patch failed: %s:%ld", name, frag->oldpos);
2912 if (!apply_with_reject)
2913 return -1;
2914 frag->rejected = 1;
2916 frag = frag->next;
2918 return 0;
2921 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2923 if (!ce)
2924 return 0;
2926 if (S_ISGITLINK(ce->ce_mode)) {
2927 strbuf_grow(buf, 100);
2928 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2929 } else {
2930 enum object_type type;
2931 unsigned long sz;
2932 char *result;
2934 result = read_sha1_file(ce->sha1, &type, &sz);
2935 if (!result)
2936 return -1;
2937 /* XXX read_sha1_file NUL-terminates */
2938 strbuf_attach(buf, result, sz, sz + 1);
2940 return 0;
2943 static struct patch *in_fn_table(const char *name)
2945 struct string_list_item *item;
2947 if (name == NULL)
2948 return NULL;
2950 item = string_list_lookup(&fn_table, name);
2951 if (item != NULL)
2952 return (struct patch *)item->util;
2954 return NULL;
2958 * item->util in the filename table records the status of the path.
2959 * Usually it points at a patch (whose result records the contents
2960 * of it after applying it), but it could be PATH_WAS_DELETED for a
2961 * path that a previously applied patch has already removed.
2963 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2964 #define PATH_WAS_DELETED ((struct patch *) -1)
2966 static int to_be_deleted(struct patch *patch)
2968 return patch == PATH_TO_BE_DELETED;
2971 static int was_deleted(struct patch *patch)
2973 return patch == PATH_WAS_DELETED;
2976 static void add_to_fn_table(struct patch *patch)
2978 struct string_list_item *item;
2981 * Always add new_name unless patch is a deletion
2982 * This should cover the cases for normal diffs,
2983 * file creations and copies
2985 if (patch->new_name != NULL) {
2986 item = string_list_insert(&fn_table, patch->new_name);
2987 item->util = patch;
2991 * store a failure on rename/deletion cases because
2992 * later chunks shouldn't patch old names
2994 if ((patch->new_name == NULL) || (patch->is_rename)) {
2995 item = string_list_insert(&fn_table, patch->old_name);
2996 item->util = PATH_WAS_DELETED;
3000 static void prepare_fn_table(struct patch *patch)
3003 * store information about incoming file deletion
3005 while (patch) {
3006 if ((patch->new_name == NULL) || (patch->is_rename)) {
3007 struct string_list_item *item;
3008 item = string_list_insert(&fn_table, patch->old_name);
3009 item->util = PATH_TO_BE_DELETED;
3011 patch = patch->next;
3015 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
3017 struct strbuf buf = STRBUF_INIT;
3018 struct image image;
3019 size_t len;
3020 char *img;
3021 struct patch *tpatch;
3023 if (!(patch->is_copy || patch->is_rename) &&
3024 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
3025 if (was_deleted(tpatch)) {
3026 return error("patch %s has been renamed/deleted",
3027 patch->old_name);
3029 /* We have a patched copy in memory; use that. */
3030 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
3031 } else if (cached) {
3032 if (read_file_or_gitlink(ce, &buf))
3033 return error("read of %s failed", patch->old_name);
3034 } else if (patch->old_name) {
3035 if (S_ISGITLINK(patch->old_mode)) {
3036 if (ce) {
3037 read_file_or_gitlink(ce, &buf);
3038 } else {
3040 * There is no way to apply subproject
3041 * patch without looking at the index.
3042 * NEEDSWORK: shouldn't this be flagged
3043 * as an error???
3045 free_fragment_list(patch->fragments);
3046 patch->fragments = NULL;
3048 } else {
3049 if (read_old_data(st, patch->old_name, &buf))
3050 return error("read of %s failed", patch->old_name);
3054 img = strbuf_detach(&buf, &len);
3055 prepare_image(&image, img, len, !patch->is_binary);
3057 if (apply_fragments(&image, patch) < 0)
3058 return -1; /* note with --reject this succeeds. */
3059 patch->result = image.buf;
3060 patch->resultsize = image.len;
3061 add_to_fn_table(patch);
3062 free(image.line_allocated);
3064 if (0 < patch->is_delete && patch->resultsize)
3065 return error("removal patch leaves file contents");
3067 return 0;
3070 static int check_to_create_blob(const char *new_name, int ok_if_exists)
3072 struct stat nst;
3073 if (!lstat(new_name, &nst)) {
3074 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3075 return 0;
3077 * A leading component of new_name might be a symlink
3078 * that is going to be removed with this patch, but
3079 * still pointing at somewhere that has the path.
3080 * In such a case, path "new_name" does not exist as
3081 * far as git is concerned.
3083 if (has_symlink_leading_path(new_name, strlen(new_name)))
3084 return 0;
3086 return error("%s: already exists in working directory", new_name);
3088 else if ((errno != ENOENT) && (errno != ENOTDIR))
3089 return error("%s: %s", new_name, strerror(errno));
3090 return 0;
3093 static int verify_index_match(struct cache_entry *ce, struct stat *st)
3095 if (S_ISGITLINK(ce->ce_mode)) {
3096 if (!S_ISDIR(st->st_mode))
3097 return -1;
3098 return 0;
3100 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3103 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3105 const char *old_name = patch->old_name;
3106 struct patch *tpatch = NULL;
3107 int stat_ret = 0;
3108 unsigned st_mode = 0;
3111 * Make sure that we do not have local modifications from the
3112 * index when we are looking at the index. Also make sure
3113 * we have the preimage file to be patched in the work tree,
3114 * unless --cached, which tells git to apply only in the index.
3116 if (!old_name)
3117 return 0;
3119 assert(patch->is_new <= 0);
3121 if (!(patch->is_copy || patch->is_rename) &&
3122 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3123 if (was_deleted(tpatch))
3124 return error("%s: has been deleted/renamed", old_name);
3125 st_mode = tpatch->new_mode;
3126 } else if (!cached) {
3127 stat_ret = lstat(old_name, st);
3128 if (stat_ret && errno != ENOENT)
3129 return error("%s: %s", old_name, strerror(errno));
3132 if (to_be_deleted(tpatch))
3133 tpatch = NULL;
3135 if (check_index && !tpatch) {
3136 int pos = cache_name_pos(old_name, strlen(old_name));
3137 if (pos < 0) {
3138 if (patch->is_new < 0)
3139 goto is_new;
3140 return error("%s: does not exist in index", old_name);
3142 *ce = active_cache[pos];
3143 if (stat_ret < 0) {
3144 struct checkout costate;
3145 /* checkout */
3146 memset(&costate, 0, sizeof(costate));
3147 costate.base_dir = "";
3148 costate.refresh_cache = 1;
3149 if (checkout_entry(*ce, &costate, NULL) ||
3150 lstat(old_name, st))
3151 return -1;
3153 if (!cached && verify_index_match(*ce, st))
3154 return error("%s: does not match index", old_name);
3155 if (cached)
3156 st_mode = (*ce)->ce_mode;
3157 } else if (stat_ret < 0) {
3158 if (patch->is_new < 0)
3159 goto is_new;
3160 return error("%s: %s", old_name, strerror(errno));
3163 if (!cached && !tpatch)
3164 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3166 if (patch->is_new < 0)
3167 patch->is_new = 0;
3168 if (!patch->old_mode)
3169 patch->old_mode = st_mode;
3170 if ((st_mode ^ patch->old_mode) & S_IFMT)
3171 return error("%s: wrong type", old_name);
3172 if (st_mode != patch->old_mode)
3173 warning("%s has type %o, expected %o",
3174 old_name, st_mode, patch->old_mode);
3175 if (!patch->new_mode && !patch->is_delete)
3176 patch->new_mode = st_mode;
3177 return 0;
3179 is_new:
3180 patch->is_new = 1;
3181 patch->is_delete = 0;
3182 free(patch->old_name);
3183 patch->old_name = NULL;
3184 return 0;
3188 * Check and apply the patch in-core; leave the result in patch->result
3189 * for the caller to write it out to the final destination.
3191 static int check_patch(struct patch *patch)
3193 struct stat st;
3194 const char *old_name = patch->old_name;
3195 const char *new_name = patch->new_name;
3196 const char *name = old_name ? old_name : new_name;
3197 struct cache_entry *ce = NULL;
3198 struct patch *tpatch;
3199 int ok_if_exists;
3200 int status;
3202 patch->rejected = 1; /* we will drop this after we succeed */
3204 status = check_preimage(patch, &ce, &st);
3205 if (status)
3206 return status;
3207 old_name = patch->old_name;
3209 if ((tpatch = in_fn_table(new_name)) &&
3210 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3212 * A type-change diff is always split into a patch to
3213 * delete old, immediately followed by a patch to
3214 * create new (see diff.c::run_diff()); in such a case
3215 * it is Ok that the entry to be deleted by the
3216 * previous patch is still in the working tree and in
3217 * the index.
3219 ok_if_exists = 1;
3220 else
3221 ok_if_exists = 0;
3223 if (new_name &&
3224 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3225 if (check_index &&
3226 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3227 !ok_if_exists)
3228 return error("%s: already exists in index", new_name);
3229 if (!cached) {
3230 int err = check_to_create_blob(new_name, ok_if_exists);
3231 if (err)
3232 return err;
3234 if (!patch->new_mode) {
3235 if (0 < patch->is_new)
3236 patch->new_mode = S_IFREG | 0644;
3237 else
3238 patch->new_mode = patch->old_mode;
3242 if (new_name && old_name) {
3243 int same = !strcmp(old_name, new_name);
3244 if (!patch->new_mode)
3245 patch->new_mode = patch->old_mode;
3246 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3247 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3248 patch->new_mode, new_name, patch->old_mode,
3249 same ? "" : " of ", same ? "" : old_name);
3252 if (apply_data(patch, &st, ce) < 0)
3253 return error("%s: patch does not apply", name);
3254 patch->rejected = 0;
3255 return 0;
3258 static int check_patch_list(struct patch *patch)
3260 int err = 0;
3262 prepare_fn_table(patch);
3263 while (patch) {
3264 if (apply_verbosely)
3265 say_patch_name(stderr,
3266 "Checking patch ", patch, "...\n");
3267 err |= check_patch(patch);
3268 patch = patch->next;
3270 return err;
3273 /* This function tries to read the sha1 from the current index */
3274 static int get_current_sha1(const char *path, unsigned char *sha1)
3276 int pos;
3278 if (read_cache() < 0)
3279 return -1;
3280 pos = cache_name_pos(path, strlen(path));
3281 if (pos < 0)
3282 return -1;
3283 hashcpy(sha1, active_cache[pos]->sha1);
3284 return 0;
3287 /* Build an index that contains the just the files needed for a 3way merge */
3288 static void build_fake_ancestor(struct patch *list, const char *filename)
3290 struct patch *patch;
3291 struct index_state result = { NULL };
3292 int fd;
3294 /* Once we start supporting the reverse patch, it may be
3295 * worth showing the new sha1 prefix, but until then...
3297 for (patch = list; patch; patch = patch->next) {
3298 const unsigned char *sha1_ptr;
3299 unsigned char sha1[20];
3300 struct cache_entry *ce;
3301 const char *name;
3303 name = patch->old_name ? patch->old_name : patch->new_name;
3304 if (0 < patch->is_new)
3305 continue;
3306 else if (get_sha1(patch->old_sha1_prefix, sha1))
3307 /* git diff has no index line for mode/type changes */
3308 if (!patch->lines_added && !patch->lines_deleted) {
3309 if (get_current_sha1(patch->old_name, sha1))
3310 die("mode change for %s, which is not "
3311 "in current HEAD", name);
3312 sha1_ptr = sha1;
3313 } else
3314 die("sha1 information is lacking or useless "
3315 "(%s).", name);
3316 else
3317 sha1_ptr = sha1;
3319 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3320 if (!ce)
3321 die("make_cache_entry failed for path '%s'", name);
3322 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3323 die ("Could not add %s to temporary index", name);
3326 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3327 if (fd < 0 || write_index(&result, fd) || close(fd))
3328 die ("Could not write temporary index to %s", filename);
3330 discard_index(&result);
3333 static void stat_patch_list(struct patch *patch)
3335 int files, adds, dels;
3337 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3338 files++;
3339 adds += patch->lines_added;
3340 dels += patch->lines_deleted;
3341 show_stats(patch);
3344 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3347 static void numstat_patch_list(struct patch *patch)
3349 for ( ; patch; patch = patch->next) {
3350 const char *name;
3351 name = patch->new_name ? patch->new_name : patch->old_name;
3352 if (patch->is_binary)
3353 printf("-\t-\t");
3354 else
3355 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3356 write_name_quoted(name, stdout, line_termination);
3360 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3362 if (mode)
3363 printf(" %s mode %06o %s\n", newdelete, mode, name);
3364 else
3365 printf(" %s %s\n", newdelete, name);
3368 static void show_mode_change(struct patch *p, int show_name)
3370 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3371 if (show_name)
3372 printf(" mode change %06o => %06o %s\n",
3373 p->old_mode, p->new_mode, p->new_name);
3374 else
3375 printf(" mode change %06o => %06o\n",
3376 p->old_mode, p->new_mode);
3380 static void show_rename_copy(struct patch *p)
3382 const char *renamecopy = p->is_rename ? "rename" : "copy";
3383 const char *old, *new;
3385 /* Find common prefix */
3386 old = p->old_name;
3387 new = p->new_name;
3388 while (1) {
3389 const char *slash_old, *slash_new;
3390 slash_old = strchr(old, '/');
3391 slash_new = strchr(new, '/');
3392 if (!slash_old ||
3393 !slash_new ||
3394 slash_old - old != slash_new - new ||
3395 memcmp(old, new, slash_new - new))
3396 break;
3397 old = slash_old + 1;
3398 new = slash_new + 1;
3400 /* p->old_name thru old is the common prefix, and old and new
3401 * through the end of names are renames
3403 if (old != p->old_name)
3404 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3405 (int)(old - p->old_name), p->old_name,
3406 old, new, p->score);
3407 else
3408 printf(" %s %s => %s (%d%%)\n", renamecopy,
3409 p->old_name, p->new_name, p->score);
3410 show_mode_change(p, 0);
3413 static void summary_patch_list(struct patch *patch)
3415 struct patch *p;
3417 for (p = patch; p; p = p->next) {
3418 if (p->is_new)
3419 show_file_mode_name("create", p->new_mode, p->new_name);
3420 else if (p->is_delete)
3421 show_file_mode_name("delete", p->old_mode, p->old_name);
3422 else {
3423 if (p->is_rename || p->is_copy)
3424 show_rename_copy(p);
3425 else {
3426 if (p->score) {
3427 printf(" rewrite %s (%d%%)\n",
3428 p->new_name, p->score);
3429 show_mode_change(p, 0);
3431 else
3432 show_mode_change(p, 1);
3438 static void patch_stats(struct patch *patch)
3440 int lines = patch->lines_added + patch->lines_deleted;
3442 if (lines > max_change)
3443 max_change = lines;
3444 if (patch->old_name) {
3445 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3446 if (!len)
3447 len = strlen(patch->old_name);
3448 if (len > max_len)
3449 max_len = len;
3451 if (patch->new_name) {
3452 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3453 if (!len)
3454 len = strlen(patch->new_name);
3455 if (len > max_len)
3456 max_len = len;
3460 static void remove_file(struct patch *patch, int rmdir_empty)
3462 if (update_index) {
3463 if (remove_file_from_cache(patch->old_name) < 0)
3464 die("unable to remove %s from index", patch->old_name);
3466 if (!cached) {
3467 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3468 remove_path(patch->old_name);
3473 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3475 struct stat st;
3476 struct cache_entry *ce;
3477 int namelen = strlen(path);
3478 unsigned ce_size = cache_entry_size(namelen);
3480 if (!update_index)
3481 return;
3483 ce = xcalloc(1, ce_size);
3484 memcpy(ce->name, path, namelen);
3485 ce->ce_mode = create_ce_mode(mode);
3486 ce->ce_flags = namelen;
3487 if (S_ISGITLINK(mode)) {
3488 const char *s = buf;
3490 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3491 die("corrupt patch for subproject %s", path);
3492 } else {
3493 if (!cached) {
3494 if (lstat(path, &st) < 0)
3495 die_errno("unable to stat newly created file '%s'",
3496 path);
3497 fill_stat_cache_info(ce, &st);
3499 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3500 die("unable to create backing store for newly created file %s", path);
3502 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3503 die("unable to add cache entry for %s", path);
3506 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3508 int fd;
3509 struct strbuf nbuf = STRBUF_INIT;
3511 if (S_ISGITLINK(mode)) {
3512 struct stat st;
3513 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3514 return 0;
3515 return mkdir(path, 0777);
3518 if (has_symlinks && S_ISLNK(mode))
3519 /* Although buf:size is counted string, it also is NUL
3520 * terminated.
3522 return symlink(buf, path);
3524 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3525 if (fd < 0)
3526 return -1;
3528 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3529 size = nbuf.len;
3530 buf = nbuf.buf;
3532 write_or_die(fd, buf, size);
3533 strbuf_release(&nbuf);
3535 if (close(fd) < 0)
3536 die_errno("closing file '%s'", path);
3537 return 0;
3541 * We optimistically assume that the directories exist,
3542 * which is true 99% of the time anyway. If they don't,
3543 * we create them and try again.
3545 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3547 if (cached)
3548 return;
3549 if (!try_create_file(path, mode, buf, size))
3550 return;
3552 if (errno == ENOENT) {
3553 if (safe_create_leading_directories(path))
3554 return;
3555 if (!try_create_file(path, mode, buf, size))
3556 return;
3559 if (errno == EEXIST || errno == EACCES) {
3560 /* We may be trying to create a file where a directory
3561 * used to be.
3563 struct stat st;
3564 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3565 errno = EEXIST;
3568 if (errno == EEXIST) {
3569 unsigned int nr = getpid();
3571 for (;;) {
3572 char newpath[PATH_MAX];
3573 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3574 if (!try_create_file(newpath, mode, buf, size)) {
3575 if (!rename(newpath, path))
3576 return;
3577 unlink_or_warn(newpath);
3578 break;
3580 if (errno != EEXIST)
3581 break;
3582 ++nr;
3585 die_errno("unable to write file '%s' mode %o", path, mode);
3588 static void create_file(struct patch *patch)
3590 char *path = patch->new_name;
3591 unsigned mode = patch->new_mode;
3592 unsigned long size = patch->resultsize;
3593 char *buf = patch->result;
3595 if (!mode)
3596 mode = S_IFREG | 0644;
3597 create_one_file(path, mode, buf, size);
3598 add_index_file(path, mode, buf, size);
3601 /* phase zero is to remove, phase one is to create */
3602 static void write_out_one_result(struct patch *patch, int phase)
3604 if (patch->is_delete > 0) {
3605 if (phase == 0)
3606 remove_file(patch, 1);
3607 return;
3609 if (patch->is_new > 0 || patch->is_copy) {
3610 if (phase == 1)
3611 create_file(patch);
3612 return;
3615 * Rename or modification boils down to the same
3616 * thing: remove the old, write the new
3618 if (phase == 0)
3619 remove_file(patch, patch->is_rename);
3620 if (phase == 1)
3621 create_file(patch);
3624 static int write_out_one_reject(struct patch *patch)
3626 FILE *rej;
3627 char namebuf[PATH_MAX];
3628 struct fragment *frag;
3629 int cnt = 0;
3631 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3632 if (!frag->rejected)
3633 continue;
3634 cnt++;
3637 if (!cnt) {
3638 if (apply_verbosely)
3639 say_patch_name(stderr,
3640 "Applied patch ", patch, " cleanly.\n");
3641 return 0;
3644 /* This should not happen, because a removal patch that leaves
3645 * contents are marked "rejected" at the patch level.
3647 if (!patch->new_name)
3648 die("internal error");
3650 /* Say this even without --verbose */
3651 say_patch_name(stderr, "Applying patch ", patch, " with");
3652 fprintf(stderr, " %d rejects...\n", cnt);
3654 cnt = strlen(patch->new_name);
3655 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3656 cnt = ARRAY_SIZE(namebuf) - 5;
3657 warning("truncating .rej filename to %.*s.rej",
3658 cnt - 1, patch->new_name);
3660 memcpy(namebuf, patch->new_name, cnt);
3661 memcpy(namebuf + cnt, ".rej", 5);
3663 rej = fopen(namebuf, "w");
3664 if (!rej)
3665 return error("cannot open %s: %s", namebuf, strerror(errno));
3667 /* Normal git tools never deal with .rej, so do not pretend
3668 * this is a git patch by saying --git nor give extended
3669 * headers. While at it, maybe please "kompare" that wants
3670 * the trailing TAB and some garbage at the end of line ;-).
3672 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3673 patch->new_name, patch->new_name);
3674 for (cnt = 1, frag = patch->fragments;
3675 frag;
3676 cnt++, frag = frag->next) {
3677 if (!frag->rejected) {
3678 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
3679 continue;
3681 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
3682 fprintf(rej, "%.*s", frag->size, frag->patch);
3683 if (frag->patch[frag->size-1] != '\n')
3684 fputc('\n', rej);
3686 fclose(rej);
3687 return -1;
3690 static int write_out_results(struct patch *list)
3692 int phase;
3693 int errs = 0;
3694 struct patch *l;
3696 for (phase = 0; phase < 2; phase++) {
3697 l = list;
3698 while (l) {
3699 if (l->rejected)
3700 errs = 1;
3701 else {
3702 write_out_one_result(l, phase);
3703 if (phase == 1 && write_out_one_reject(l))
3704 errs = 1;
3706 l = l->next;
3709 return errs;
3712 static struct lock_file lock_file;
3714 static struct string_list limit_by_name;
3715 static int has_include;
3716 static void add_name_limit(const char *name, int exclude)
3718 struct string_list_item *it;
3720 it = string_list_append(&limit_by_name, name);
3721 it->util = exclude ? NULL : (void *) 1;
3724 static int use_patch(struct patch *p)
3726 const char *pathname = p->new_name ? p->new_name : p->old_name;
3727 int i;
3729 /* Paths outside are not touched regardless of "--include" */
3730 if (0 < prefix_length) {
3731 int pathlen = strlen(pathname);
3732 if (pathlen <= prefix_length ||
3733 memcmp(prefix, pathname, prefix_length))
3734 return 0;
3737 /* See if it matches any of exclude/include rule */
3738 for (i = 0; i < limit_by_name.nr; i++) {
3739 struct string_list_item *it = &limit_by_name.items[i];
3740 if (!fnmatch(it->string, pathname, 0))
3741 return (it->util != NULL);
3745 * If we had any include, a path that does not match any rule is
3746 * not used. Otherwise, we saw bunch of exclude rules (or none)
3747 * and such a path is used.
3749 return !has_include;
3753 static void prefix_one(char **name)
3755 char *old_name = *name;
3756 if (!old_name)
3757 return;
3758 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3759 free(old_name);
3762 static void prefix_patches(struct patch *p)
3764 if (!prefix || p->is_toplevel_relative)
3765 return;
3766 for ( ; p; p = p->next) {
3767 prefix_one(&p->new_name);
3768 prefix_one(&p->old_name);
3772 #define INACCURATE_EOF (1<<0)
3773 #define RECOUNT (1<<1)
3775 static int apply_patch(int fd, const char *filename, int options)
3777 size_t offset;
3778 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
3779 struct patch *list = NULL, **listp = &list;
3780 int skipped_patch = 0;
3782 patch_input_file = filename;
3783 read_patch_file(&buf, fd);
3784 offset = 0;
3785 while (offset < buf.len) {
3786 struct patch *patch;
3787 int nr;
3789 patch = xcalloc(1, sizeof(*patch));
3790 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3791 patch->recount = !!(options & RECOUNT);
3792 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3793 if (nr < 0)
3794 break;
3795 if (apply_in_reverse)
3796 reverse_patches(patch);
3797 if (prefix)
3798 prefix_patches(patch);
3799 if (use_patch(patch)) {
3800 patch_stats(patch);
3801 *listp = patch;
3802 listp = &patch->next;
3804 else {
3805 free_patch(patch);
3806 skipped_patch++;
3808 offset += nr;
3811 if (!list && !skipped_patch)
3812 die("unrecognized input");
3814 if (whitespace_error && (ws_error_action == die_on_ws_error))
3815 apply = 0;
3817 update_index = check_index && apply;
3818 if (update_index && newfd < 0)
3819 newfd = hold_locked_index(&lock_file, 1);
3821 if (check_index) {
3822 if (read_cache() < 0)
3823 die("unable to read index file");
3826 if ((check || apply) &&
3827 check_patch_list(list) < 0 &&
3828 !apply_with_reject)
3829 exit(1);
3831 if (apply && write_out_results(list))
3832 exit(1);
3834 if (fake_ancestor)
3835 build_fake_ancestor(list, fake_ancestor);
3837 if (diffstat)
3838 stat_patch_list(list);
3840 if (numstat)
3841 numstat_patch_list(list);
3843 if (summary)
3844 summary_patch_list(list);
3846 free_patch_list(list);
3847 strbuf_release(&buf);
3848 string_list_clear(&fn_table, 0);
3849 return 0;
3852 static int git_apply_config(const char *var, const char *value, void *cb)
3854 if (!strcmp(var, "apply.whitespace"))
3855 return git_config_string(&apply_default_whitespace, var, value);
3856 else if (!strcmp(var, "apply.ignorewhitespace"))
3857 return git_config_string(&apply_default_ignorewhitespace, var, value);
3858 return git_default_config(var, value, cb);
3861 static int option_parse_exclude(const struct option *opt,
3862 const char *arg, int unset)
3864 add_name_limit(arg, 1);
3865 return 0;
3868 static int option_parse_include(const struct option *opt,
3869 const char *arg, int unset)
3871 add_name_limit(arg, 0);
3872 has_include = 1;
3873 return 0;
3876 static int option_parse_p(const struct option *opt,
3877 const char *arg, int unset)
3879 p_value = atoi(arg);
3880 p_value_known = 1;
3881 return 0;
3884 static int option_parse_z(const struct option *opt,
3885 const char *arg, int unset)
3887 if (unset)
3888 line_termination = '\n';
3889 else
3890 line_termination = 0;
3891 return 0;
3894 static int option_parse_space_change(const struct option *opt,
3895 const char *arg, int unset)
3897 if (unset)
3898 ws_ignore_action = ignore_ws_none;
3899 else
3900 ws_ignore_action = ignore_ws_change;
3901 return 0;
3904 static int option_parse_whitespace(const struct option *opt,
3905 const char *arg, int unset)
3907 const char **whitespace_option = opt->value;
3909 *whitespace_option = arg;
3910 parse_whitespace_option(arg);
3911 return 0;
3914 static int option_parse_directory(const struct option *opt,
3915 const char *arg, int unset)
3917 root_len = strlen(arg);
3918 if (root_len && arg[root_len - 1] != '/') {
3919 char *new_root;
3920 root = new_root = xmalloc(root_len + 2);
3921 strcpy(new_root, arg);
3922 strcpy(new_root + root_len++, "/");
3923 } else
3924 root = arg;
3925 return 0;
3928 int cmd_apply(int argc, const char **argv, const char *prefix_)
3930 int i;
3931 int errs = 0;
3932 int is_not_gitdir = !startup_info->have_repository;
3933 int force_apply = 0;
3935 const char *whitespace_option = NULL;
3937 struct option builtin_apply_options[] = {
3938 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
3939 "don't apply changes matching the given path",
3940 0, option_parse_exclude },
3941 { OPTION_CALLBACK, 0, "include", NULL, "path",
3942 "apply changes matching the given path",
3943 0, option_parse_include },
3944 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3945 "remove <num> leading slashes from traditional diff paths",
3946 0, option_parse_p },
3947 OPT_BOOLEAN(0, "no-add", &no_add,
3948 "ignore additions made by the patch"),
3949 OPT_BOOLEAN(0, "stat", &diffstat,
3950 "instead of applying the patch, output diffstat for the input"),
3951 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
3952 OPT_NOOP_NOARG(0, "binary"),
3953 OPT_BOOLEAN(0, "numstat", &numstat,
3954 "shows number of added and deleted lines in decimal notation"),
3955 OPT_BOOLEAN(0, "summary", &summary,
3956 "instead of applying the patch, output a summary for the input"),
3957 OPT_BOOLEAN(0, "check", &check,
3958 "instead of applying the patch, see if the patch is applicable"),
3959 OPT_BOOLEAN(0, "index", &check_index,
3960 "make sure the patch is applicable to the current index"),
3961 OPT_BOOLEAN(0, "cached", &cached,
3962 "apply a patch without touching the working tree"),
3963 OPT_BOOLEAN(0, "apply", &force_apply,
3964 "also apply the patch (use with --stat/--summary/--check)"),
3965 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
3966 "build a temporary index based on embedded index information"),
3967 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3968 "paths are separated with NUL character",
3969 PARSE_OPT_NOARG, option_parse_z },
3970 OPT_INTEGER('C', NULL, &p_context,
3971 "ensure at least <n> lines of context match"),
3972 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3973 "detect new or modified lines that have whitespace errors",
3974 0, option_parse_whitespace },
3975 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3976 "ignore changes in whitespace when finding context",
3977 PARSE_OPT_NOARG, option_parse_space_change },
3978 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3979 "ignore changes in whitespace when finding context",
3980 PARSE_OPT_NOARG, option_parse_space_change },
3981 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3982 "apply the patch in reverse"),
3983 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3984 "don't expect at least one line of context"),
3985 OPT_BOOLEAN(0, "reject", &apply_with_reject,
3986 "leave the rejected hunks in corresponding *.rej files"),
3987 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
3988 "allow overlapping hunks"),
3989 OPT__VERBOSE(&apply_verbosely, "be verbose"),
3990 OPT_BIT(0, "inaccurate-eof", &options,
3991 "tolerate incorrectly detected missing new-line at the end of file",
3992 INACCURATE_EOF),
3993 OPT_BIT(0, "recount", &options,
3994 "do not trust the line counts in the hunk headers",
3995 RECOUNT),
3996 { OPTION_CALLBACK, 0, "directory", NULL, "root",
3997 "prepend <root> to all filenames",
3998 0, option_parse_directory },
3999 OPT_END()
4002 prefix = prefix_;
4003 prefix_length = prefix ? strlen(prefix) : 0;
4004 git_config(git_apply_config, NULL);
4005 if (apply_default_whitespace)
4006 parse_whitespace_option(apply_default_whitespace);
4007 if (apply_default_ignorewhitespace)
4008 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4010 argc = parse_options(argc, argv, prefix, builtin_apply_options,
4011 apply_usage, 0);
4013 if (apply_with_reject)
4014 apply = apply_verbosely = 1;
4015 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
4016 apply = 0;
4017 if (check_index && is_not_gitdir)
4018 die("--index outside a repository");
4019 if (cached) {
4020 if (is_not_gitdir)
4021 die("--cached outside a repository");
4022 check_index = 1;
4024 for (i = 0; i < argc; i++) {
4025 const char *arg = argv[i];
4026 int fd;
4028 if (!strcmp(arg, "-")) {
4029 errs |= apply_patch(0, "<stdin>", options);
4030 read_stdin = 0;
4031 continue;
4032 } else if (0 < prefix_length)
4033 arg = prefix_filename(prefix, prefix_length, arg);
4035 fd = open(arg, O_RDONLY);
4036 if (fd < 0)
4037 die_errno("can't open patch '%s'", arg);
4038 read_stdin = 0;
4039 set_default_whitespace_mode(whitespace_option);
4040 errs |= apply_patch(fd, arg, options);
4041 close(fd);
4043 set_default_whitespace_mode(whitespace_option);
4044 if (read_stdin)
4045 errs |= apply_patch(0, "<stdin>", options);
4046 if (whitespace_error) {
4047 if (squelch_whitespace_errors &&
4048 squelch_whitespace_errors < whitespace_error) {
4049 int squelched =
4050 whitespace_error - squelch_whitespace_errors;
4051 warning("squelched %d "
4052 "whitespace error%s",
4053 squelched,
4054 squelched == 1 ? "" : "s");
4056 if (ws_error_action == die_on_ws_error)
4057 die("%d line%s add%s whitespace errors.",
4058 whitespace_error,
4059 whitespace_error == 1 ? "" : "s",
4060 whitespace_error == 1 ? "s" : "");
4061 if (applied_after_fixing_ws && apply)
4062 warning("%d line%s applied after"
4063 " fixing whitespace errors.",
4064 applied_after_fixing_ws,
4065 applied_after_fixing_ws == 1 ? "" : "s");
4066 else if (whitespace_error)
4067 warning("%d line%s add%s whitespace errors.",
4068 whitespace_error,
4069 whitespace_error == 1 ? "" : "s",
4070 whitespace_error == 1 ? "s" : "");
4073 if (update_index) {
4074 if (write_cache(newfd, active_cache, active_nr) ||
4075 commit_locked_index(&lock_file))
4076 die("Unable to write new index file");
4079 return !!errs;