apply.c:update_pre_post_images(): the preimage can be truncated
[git/raj.git] / builtin / apply.c
blobf8202e3b68c06a4a483cfbe6debd83d23e4777f5
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 "diff.h"
18 #include "parse-options.h"
21 * --check turns on checking that the working tree matches the
22 * files that are being modified, but doesn't apply the patch
23 * --stat does just a diffstat, and doesn't actually apply
24 * --numstat does numeric diffstat, and doesn't actually apply
25 * --index-info shows the old and new index info for paths if available.
26 * --index updates the cache as well.
27 * --cached updates only the cache without ever touching the working tree.
29 static const char *prefix;
30 static int prefix_length = -1;
31 static int newfd = -1;
33 static int unidiff_zero;
34 static int p_value = 1;
35 static int p_value_known;
36 static int check_index;
37 static int update_index;
38 static int cached;
39 static int diffstat;
40 static int numstat;
41 static int summary;
42 static int check;
43 static int apply = 1;
44 static int apply_in_reverse;
45 static int apply_with_reject;
46 static int apply_verbosely;
47 static int allow_overlap;
48 static int no_add;
49 static const char *fake_ancestor;
50 static int line_termination = '\n';
51 static unsigned int p_context = UINT_MAX;
52 static const char * const apply_usage[] = {
53 N_("git apply [options] [<patch>...]"),
54 NULL
57 static enum ws_error_action {
58 nowarn_ws_error,
59 warn_on_ws_error,
60 die_on_ws_error,
61 correct_ws_error
62 } ws_error_action = warn_on_ws_error;
63 static int whitespace_error;
64 static int squelch_whitespace_errors = 5;
65 static int applied_after_fixing_ws;
67 static enum ws_ignore {
68 ignore_ws_none,
69 ignore_ws_change
70 } ws_ignore_action = ignore_ws_none;
73 static const char *patch_input_file;
74 static const char *root;
75 static int root_len;
76 static int read_stdin = 1;
77 static int options;
79 static void parse_whitespace_option(const char *option)
81 if (!option) {
82 ws_error_action = warn_on_ws_error;
83 return;
85 if (!strcmp(option, "warn")) {
86 ws_error_action = warn_on_ws_error;
87 return;
89 if (!strcmp(option, "nowarn")) {
90 ws_error_action = nowarn_ws_error;
91 return;
93 if (!strcmp(option, "error")) {
94 ws_error_action = die_on_ws_error;
95 return;
97 if (!strcmp(option, "error-all")) {
98 ws_error_action = die_on_ws_error;
99 squelch_whitespace_errors = 0;
100 return;
102 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
103 ws_error_action = correct_ws_error;
104 return;
106 die(_("unrecognized whitespace option '%s'"), option);
109 static void parse_ignorewhitespace_option(const char *option)
111 if (!option || !strcmp(option, "no") ||
112 !strcmp(option, "false") || !strcmp(option, "never") ||
113 !strcmp(option, "none")) {
114 ws_ignore_action = ignore_ws_none;
115 return;
117 if (!strcmp(option, "change")) {
118 ws_ignore_action = ignore_ws_change;
119 return;
121 die(_("unrecognized whitespace ignore option '%s'"), option);
124 static void set_default_whitespace_mode(const char *whitespace_option)
126 if (!whitespace_option && !apply_default_whitespace)
127 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
131 * For "diff-stat" like behaviour, we keep track of the biggest change
132 * we've seen, and the longest filename. That allows us to do simple
133 * scaling.
135 static int max_change, max_len;
138 * Various "current state", notably line numbers and what
139 * file (and how) we're patching right now.. The "is_xxxx"
140 * things are flags, where -1 means "don't know yet".
142 static int linenr = 1;
145 * This represents one "hunk" from a patch, starting with
146 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
147 * patch text is pointed at by patch, and its byte length
148 * is stored in size. leading and trailing are the number
149 * of context lines.
151 struct fragment {
152 unsigned long leading, trailing;
153 unsigned long oldpos, oldlines;
154 unsigned long newpos, newlines;
156 * 'patch' is usually borrowed from buf in apply_patch(),
157 * but some codepaths store an allocated buffer.
159 const char *patch;
160 unsigned free_patch:1,
161 rejected:1;
162 int size;
163 int linenr;
164 struct fragment *next;
168 * When dealing with a binary patch, we reuse "leading" field
169 * to store the type of the binary hunk, either deflated "delta"
170 * or deflated "literal".
172 #define binary_patch_method leading
173 #define BINARY_DELTA_DEFLATED 1
174 #define BINARY_LITERAL_DEFLATED 2
177 * This represents a "patch" to a file, both metainfo changes
178 * such as creation/deletion, filemode and content changes represented
179 * as a series of fragments.
181 struct patch {
182 char *new_name, *old_name, *def_name;
183 unsigned int old_mode, new_mode;
184 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
185 int rejected;
186 unsigned ws_rule;
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 /* fmt must contain _one_ %s and no other substitution */
378 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
380 struct strbuf sb = STRBUF_INIT;
382 if (patch->old_name && patch->new_name &&
383 strcmp(patch->old_name, patch->new_name)) {
384 quote_c_style(patch->old_name, &sb, NULL, 0);
385 strbuf_addstr(&sb, " => ");
386 quote_c_style(patch->new_name, &sb, NULL, 0);
387 } else {
388 const char *n = patch->new_name;
389 if (!n)
390 n = patch->old_name;
391 quote_c_style(n, &sb, NULL, 0);
393 fprintf(output, fmt, sb.buf);
394 fputc('\n', output);
395 strbuf_release(&sb);
398 #define SLOP (16)
400 static void read_patch_file(struct strbuf *sb, int fd)
402 if (strbuf_read(sb, fd, 0) < 0)
403 die_errno("git apply: failed to read");
406 * Make sure that we have some slop in the buffer
407 * so that we can do speculative "memcmp" etc, and
408 * see to it that it is NUL-filled.
410 strbuf_grow(sb, SLOP);
411 memset(sb->buf + sb->len, 0, SLOP);
414 static unsigned long linelen(const char *buffer, unsigned long size)
416 unsigned long len = 0;
417 while (size--) {
418 len++;
419 if (*buffer++ == '\n')
420 break;
422 return len;
425 static int is_dev_null(const char *str)
427 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
430 #define TERM_SPACE 1
431 #define TERM_TAB 2
433 static int name_terminate(const char *name, int namelen, int c, int terminate)
435 if (c == ' ' && !(terminate & TERM_SPACE))
436 return 0;
437 if (c == '\t' && !(terminate & TERM_TAB))
438 return 0;
440 return 1;
443 /* remove double slashes to make --index work with such filenames */
444 static char *squash_slash(char *name)
446 int i = 0, j = 0;
448 if (!name)
449 return NULL;
451 while (name[i]) {
452 if ((name[j++] = name[i++]) == '/')
453 while (name[i] == '/')
454 i++;
456 name[j] = '\0';
457 return name;
460 static char *find_name_gnu(const char *line, const char *def, int p_value)
462 struct strbuf name = STRBUF_INIT;
463 char *cp;
466 * Proposed "new-style" GNU patch/diff format; see
467 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
469 if (unquote_c_style(&name, line, NULL)) {
470 strbuf_release(&name);
471 return NULL;
474 for (cp = name.buf; p_value; p_value--) {
475 cp = strchr(cp, '/');
476 if (!cp) {
477 strbuf_release(&name);
478 return NULL;
480 cp++;
483 strbuf_remove(&name, 0, cp - name.buf);
484 if (root)
485 strbuf_insert(&name, 0, root, root_len);
486 return squash_slash(strbuf_detach(&name, NULL));
489 static size_t sane_tz_len(const char *line, size_t len)
491 const char *tz, *p;
493 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
494 return 0;
495 tz = line + len - strlen(" +0500");
497 if (tz[1] != '+' && tz[1] != '-')
498 return 0;
500 for (p = tz + 2; p != line + len; p++)
501 if (!isdigit(*p))
502 return 0;
504 return line + len - tz;
507 static size_t tz_with_colon_len(const char *line, size_t len)
509 const char *tz, *p;
511 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
512 return 0;
513 tz = line + len - strlen(" +08:00");
515 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
516 return 0;
517 p = tz + 2;
518 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
519 !isdigit(*p++) || !isdigit(*p++))
520 return 0;
522 return line + len - tz;
525 static size_t date_len(const char *line, size_t len)
527 const char *date, *p;
529 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
530 return 0;
531 p = date = line + len - strlen("72-02-05");
533 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
534 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
535 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
536 return 0;
538 if (date - line >= strlen("19") &&
539 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
540 date -= strlen("19");
542 return line + len - date;
545 static size_t short_time_len(const char *line, size_t len)
547 const char *time, *p;
549 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
550 return 0;
551 p = time = line + len - strlen(" 07:01:32");
553 /* Permit 1-digit hours? */
554 if (*p++ != ' ' ||
555 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
556 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
557 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
558 return 0;
560 return line + len - time;
563 static size_t fractional_time_len(const char *line, size_t len)
565 const char *p;
566 size_t n;
568 /* Expected format: 19:41:17.620000023 */
569 if (!len || !isdigit(line[len - 1]))
570 return 0;
571 p = line + len - 1;
573 /* Fractional seconds. */
574 while (p > line && isdigit(*p))
575 p--;
576 if (*p != '.')
577 return 0;
579 /* Hours, minutes, and whole seconds. */
580 n = short_time_len(line, p - line);
581 if (!n)
582 return 0;
584 return line + len - p + n;
587 static size_t trailing_spaces_len(const char *line, size_t len)
589 const char *p;
591 /* Expected format: ' ' x (1 or more) */
592 if (!len || line[len - 1] != ' ')
593 return 0;
595 p = line + len;
596 while (p != line) {
597 p--;
598 if (*p != ' ')
599 return line + len - (p + 1);
602 /* All spaces! */
603 return len;
606 static size_t diff_timestamp_len(const char *line, size_t len)
608 const char *end = line + len;
609 size_t n;
612 * Posix: 2010-07-05 19:41:17
613 * GNU: 2010-07-05 19:41:17.620000023 -0500
616 if (!isdigit(end[-1]))
617 return 0;
619 n = sane_tz_len(line, end - line);
620 if (!n)
621 n = tz_with_colon_len(line, end - line);
622 end -= n;
624 n = short_time_len(line, end - line);
625 if (!n)
626 n = fractional_time_len(line, end - line);
627 end -= n;
629 n = date_len(line, end - line);
630 if (!n) /* No date. Too bad. */
631 return 0;
632 end -= n;
634 if (end == line) /* No space before date. */
635 return 0;
636 if (end[-1] == '\t') { /* Success! */
637 end--;
638 return line + len - end;
640 if (end[-1] != ' ') /* No space before date. */
641 return 0;
643 /* Whitespace damage. */
644 end -= trailing_spaces_len(line, end - line);
645 return line + len - end;
648 static char *null_strdup(const char *s)
650 return s ? xstrdup(s) : NULL;
653 static char *find_name_common(const char *line, const char *def,
654 int p_value, const char *end, int terminate)
656 int len;
657 const char *start = NULL;
659 if (p_value == 0)
660 start = line;
661 while (line != end) {
662 char c = *line;
664 if (!end && isspace(c)) {
665 if (c == '\n')
666 break;
667 if (name_terminate(start, line-start, c, terminate))
668 break;
670 line++;
671 if (c == '/' && !--p_value)
672 start = line;
674 if (!start)
675 return squash_slash(null_strdup(def));
676 len = line - start;
677 if (!len)
678 return squash_slash(null_strdup(def));
681 * Generally we prefer the shorter name, especially
682 * if the other one is just a variation of that with
683 * something else tacked on to the end (ie "file.orig"
684 * or "file~").
686 if (def) {
687 int deflen = strlen(def);
688 if (deflen < len && !strncmp(start, def, deflen))
689 return squash_slash(xstrdup(def));
692 if (root) {
693 char *ret = xmalloc(root_len + len + 1);
694 strcpy(ret, root);
695 memcpy(ret + root_len, start, len);
696 ret[root_len + len] = '\0';
697 return squash_slash(ret);
700 return squash_slash(xmemdupz(start, len));
703 static char *find_name(const char *line, char *def, int p_value, int terminate)
705 if (*line == '"') {
706 char *name = find_name_gnu(line, def, p_value);
707 if (name)
708 return name;
711 return find_name_common(line, def, p_value, NULL, terminate);
714 static char *find_name_traditional(const char *line, char *def, int p_value)
716 size_t len = strlen(line);
717 size_t date_len;
719 if (*line == '"') {
720 char *name = find_name_gnu(line, def, p_value);
721 if (name)
722 return name;
725 len = strchrnul(line, '\n') - line;
726 date_len = diff_timestamp_len(line, len);
727 if (!date_len)
728 return find_name_common(line, def, p_value, NULL, TERM_TAB);
729 len -= date_len;
731 return find_name_common(line, def, p_value, line + len, 0);
734 static int count_slashes(const char *cp)
736 int cnt = 0;
737 char ch;
739 while ((ch = *cp++))
740 if (ch == '/')
741 cnt++;
742 return cnt;
746 * Given the string after "--- " or "+++ ", guess the appropriate
747 * p_value for the given patch.
749 static int guess_p_value(const char *nameline)
751 char *name, *cp;
752 int val = -1;
754 if (is_dev_null(nameline))
755 return -1;
756 name = find_name_traditional(nameline, NULL, 0);
757 if (!name)
758 return -1;
759 cp = strchr(name, '/');
760 if (!cp)
761 val = 0;
762 else if (prefix) {
764 * Does it begin with "a/$our-prefix" and such? Then this is
765 * very likely to apply to our directory.
767 if (!strncmp(name, prefix, prefix_length))
768 val = count_slashes(prefix);
769 else {
770 cp++;
771 if (!strncmp(cp, prefix, prefix_length))
772 val = count_slashes(prefix) + 1;
775 free(name);
776 return val;
780 * Does the ---/+++ line has the POSIX timestamp after the last HT?
781 * GNU diff puts epoch there to signal a creation/deletion event. Is
782 * this such a timestamp?
784 static int has_epoch_timestamp(const char *nameline)
787 * We are only interested in epoch timestamp; any non-zero
788 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
789 * For the same reason, the date must be either 1969-12-31 or
790 * 1970-01-01, and the seconds part must be "00".
792 const char stamp_regexp[] =
793 "^(1969-12-31|1970-01-01)"
795 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
797 "([-+][0-2][0-9]:?[0-5][0-9])\n";
798 const char *timestamp = NULL, *cp, *colon;
799 static regex_t *stamp;
800 regmatch_t m[10];
801 int zoneoffset;
802 int hourminute;
803 int status;
805 for (cp = nameline; *cp != '\n'; cp++) {
806 if (*cp == '\t')
807 timestamp = cp + 1;
809 if (!timestamp)
810 return 0;
811 if (!stamp) {
812 stamp = xmalloc(sizeof(*stamp));
813 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
814 warning(_("Cannot prepare timestamp regexp %s"),
815 stamp_regexp);
816 return 0;
820 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
821 if (status) {
822 if (status != REG_NOMATCH)
823 warning(_("regexec returned %d for input: %s"),
824 status, timestamp);
825 return 0;
828 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
829 if (*colon == ':')
830 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
831 else
832 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
833 if (timestamp[m[3].rm_so] == '-')
834 zoneoffset = -zoneoffset;
837 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
838 * (west of GMT) or 1970-01-01 (east of GMT)
840 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
841 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
842 return 0;
844 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
845 strtol(timestamp + 14, NULL, 10) -
846 zoneoffset);
848 return ((zoneoffset < 0 && hourminute == 1440) ||
849 (0 <= zoneoffset && !hourminute));
853 * Get the name etc info from the ---/+++ lines of a traditional patch header
855 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
856 * files, we can happily check the index for a match, but for creating a
857 * new file we should try to match whatever "patch" does. I have no idea.
859 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
861 char *name;
863 first += 4; /* skip "--- " */
864 second += 4; /* skip "+++ " */
865 if (!p_value_known) {
866 int p, q;
867 p = guess_p_value(first);
868 q = guess_p_value(second);
869 if (p < 0) p = q;
870 if (0 <= p && p == q) {
871 p_value = p;
872 p_value_known = 1;
875 if (is_dev_null(first)) {
876 patch->is_new = 1;
877 patch->is_delete = 0;
878 name = find_name_traditional(second, NULL, p_value);
879 patch->new_name = name;
880 } else if (is_dev_null(second)) {
881 patch->is_new = 0;
882 patch->is_delete = 1;
883 name = find_name_traditional(first, NULL, p_value);
884 patch->old_name = name;
885 } else {
886 char *first_name;
887 first_name = find_name_traditional(first, NULL, p_value);
888 name = find_name_traditional(second, first_name, p_value);
889 free(first_name);
890 if (has_epoch_timestamp(first)) {
891 patch->is_new = 1;
892 patch->is_delete = 0;
893 patch->new_name = name;
894 } else if (has_epoch_timestamp(second)) {
895 patch->is_new = 0;
896 patch->is_delete = 1;
897 patch->old_name = name;
898 } else {
899 patch->old_name = name;
900 patch->new_name = xstrdup(name);
903 if (!name)
904 die(_("unable to find filename in patch at line %d"), linenr);
907 static int gitdiff_hdrend(const char *line, struct patch *patch)
909 return -1;
913 * We're anal about diff header consistency, to make
914 * sure that we don't end up having strange ambiguous
915 * patches floating around.
917 * As a result, gitdiff_{old|new}name() will check
918 * their names against any previous information, just
919 * to make sure..
921 #define DIFF_OLD_NAME 0
922 #define DIFF_NEW_NAME 1
924 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, int side)
926 if (!orig_name && !isnull)
927 return find_name(line, NULL, p_value, TERM_TAB);
929 if (orig_name) {
930 int len;
931 const char *name;
932 char *another;
933 name = orig_name;
934 len = strlen(name);
935 if (isnull)
936 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name, linenr);
937 another = find_name(line, NULL, p_value, TERM_TAB);
938 if (!another || memcmp(another, name, len + 1))
939 die((side == DIFF_NEW_NAME) ?
940 _("git apply: bad git-diff - inconsistent new filename on line %d") :
941 _("git apply: bad git-diff - inconsistent old filename on line %d"), linenr);
942 free(another);
943 return orig_name;
945 else {
946 /* expect "/dev/null" */
947 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
948 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr);
949 return NULL;
953 static int gitdiff_oldname(const char *line, struct patch *patch)
955 char *orig = patch->old_name;
956 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name,
957 DIFF_OLD_NAME);
958 if (orig != patch->old_name)
959 free(orig);
960 return 0;
963 static int gitdiff_newname(const char *line, struct patch *patch)
965 char *orig = patch->new_name;
966 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name,
967 DIFF_NEW_NAME);
968 if (orig != patch->new_name)
969 free(orig);
970 return 0;
973 static int gitdiff_oldmode(const char *line, struct patch *patch)
975 patch->old_mode = strtoul(line, NULL, 8);
976 return 0;
979 static int gitdiff_newmode(const char *line, struct patch *patch)
981 patch->new_mode = strtoul(line, NULL, 8);
982 return 0;
985 static int gitdiff_delete(const char *line, struct patch *patch)
987 patch->is_delete = 1;
988 free(patch->old_name);
989 patch->old_name = null_strdup(patch->def_name);
990 return gitdiff_oldmode(line, patch);
993 static int gitdiff_newfile(const char *line, struct patch *patch)
995 patch->is_new = 1;
996 free(patch->new_name);
997 patch->new_name = null_strdup(patch->def_name);
998 return gitdiff_newmode(line, patch);
1001 static int gitdiff_copysrc(const char *line, struct patch *patch)
1003 patch->is_copy = 1;
1004 free(patch->old_name);
1005 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1006 return 0;
1009 static int gitdiff_copydst(const char *line, struct patch *patch)
1011 patch->is_copy = 1;
1012 free(patch->new_name);
1013 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1014 return 0;
1017 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1019 patch->is_rename = 1;
1020 free(patch->old_name);
1021 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1022 return 0;
1025 static int gitdiff_renamedst(const char *line, struct patch *patch)
1027 patch->is_rename = 1;
1028 free(patch->new_name);
1029 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1030 return 0;
1033 static int gitdiff_similarity(const char *line, struct patch *patch)
1035 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1036 patch->score = 0;
1037 return 0;
1040 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1042 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1043 patch->score = 0;
1044 return 0;
1047 static int gitdiff_index(const char *line, struct patch *patch)
1050 * index line is N hexadecimal, "..", N hexadecimal,
1051 * and optional space with octal mode.
1053 const char *ptr, *eol;
1054 int len;
1056 ptr = strchr(line, '.');
1057 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1058 return 0;
1059 len = ptr - line;
1060 memcpy(patch->old_sha1_prefix, line, len);
1061 patch->old_sha1_prefix[len] = 0;
1063 line = ptr + 2;
1064 ptr = strchr(line, ' ');
1065 eol = strchr(line, '\n');
1067 if (!ptr || eol < ptr)
1068 ptr = eol;
1069 len = ptr - line;
1071 if (40 < len)
1072 return 0;
1073 memcpy(patch->new_sha1_prefix, line, len);
1074 patch->new_sha1_prefix[len] = 0;
1075 if (*ptr == ' ')
1076 patch->old_mode = strtoul(ptr+1, NULL, 8);
1077 return 0;
1081 * This is normal for a diff that doesn't change anything: we'll fall through
1082 * into the next diff. Tell the parser to break out.
1084 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1086 return -1;
1090 * Skip p_value leading components from "line"; as we do not accept
1091 * absolute paths, return NULL in that case.
1093 static const char *skip_tree_prefix(const char *line, int llen)
1095 int nslash;
1096 int i;
1098 if (!p_value)
1099 return (llen && line[0] == '/') ? NULL : line;
1101 nslash = p_value;
1102 for (i = 0; i < llen; i++) {
1103 int ch = line[i];
1104 if (ch == '/' && --nslash <= 0)
1105 return (i == 0) ? NULL : &line[i + 1];
1107 return NULL;
1111 * This is to extract the same name that appears on "diff --git"
1112 * line. We do not find and return anything if it is a rename
1113 * patch, and it is OK because we will find the name elsewhere.
1114 * We need to reliably find name only when it is mode-change only,
1115 * creation or deletion of an empty file. In any of these cases,
1116 * both sides are the same name under a/ and b/ respectively.
1118 static char *git_header_name(const char *line, int llen)
1120 const char *name;
1121 const char *second = NULL;
1122 size_t len, line_len;
1124 line += strlen("diff --git ");
1125 llen -= strlen("diff --git ");
1127 if (*line == '"') {
1128 const char *cp;
1129 struct strbuf first = STRBUF_INIT;
1130 struct strbuf sp = STRBUF_INIT;
1132 if (unquote_c_style(&first, line, &second))
1133 goto free_and_fail1;
1135 /* strip the a/b prefix including trailing slash */
1136 cp = skip_tree_prefix(first.buf, first.len);
1137 if (!cp)
1138 goto free_and_fail1;
1139 strbuf_remove(&first, 0, cp - first.buf);
1142 * second points at one past closing dq of name.
1143 * find the second name.
1145 while ((second < line + llen) && isspace(*second))
1146 second++;
1148 if (line + llen <= second)
1149 goto free_and_fail1;
1150 if (*second == '"') {
1151 if (unquote_c_style(&sp, second, NULL))
1152 goto free_and_fail1;
1153 cp = skip_tree_prefix(sp.buf, sp.len);
1154 if (!cp)
1155 goto free_and_fail1;
1156 /* They must match, otherwise ignore */
1157 if (strcmp(cp, first.buf))
1158 goto free_and_fail1;
1159 strbuf_release(&sp);
1160 return strbuf_detach(&first, NULL);
1163 /* unquoted second */
1164 cp = skip_tree_prefix(second, line + llen - second);
1165 if (!cp)
1166 goto free_and_fail1;
1167 if (line + llen - cp != first.len ||
1168 memcmp(first.buf, cp, first.len))
1169 goto free_and_fail1;
1170 return strbuf_detach(&first, NULL);
1172 free_and_fail1:
1173 strbuf_release(&first);
1174 strbuf_release(&sp);
1175 return NULL;
1178 /* unquoted first name */
1179 name = skip_tree_prefix(line, llen);
1180 if (!name)
1181 return NULL;
1184 * since the first name is unquoted, a dq if exists must be
1185 * the beginning of the second name.
1187 for (second = name; second < line + llen; second++) {
1188 if (*second == '"') {
1189 struct strbuf sp = STRBUF_INIT;
1190 const char *np;
1192 if (unquote_c_style(&sp, second, NULL))
1193 goto free_and_fail2;
1195 np = skip_tree_prefix(sp.buf, sp.len);
1196 if (!np)
1197 goto free_and_fail2;
1199 len = sp.buf + sp.len - np;
1200 if (len < second - name &&
1201 !strncmp(np, name, len) &&
1202 isspace(name[len])) {
1203 /* Good */
1204 strbuf_remove(&sp, 0, np - sp.buf);
1205 return strbuf_detach(&sp, NULL);
1208 free_and_fail2:
1209 strbuf_release(&sp);
1210 return NULL;
1215 * Accept a name only if it shows up twice, exactly the same
1216 * form.
1218 second = strchr(name, '\n');
1219 if (!second)
1220 return NULL;
1221 line_len = second - name;
1222 for (len = 0 ; ; len++) {
1223 switch (name[len]) {
1224 default:
1225 continue;
1226 case '\n':
1227 return NULL;
1228 case '\t': case ' ':
1230 * Is this the separator between the preimage
1231 * and the postimage pathname? Again, we are
1232 * only interested in the case where there is
1233 * no rename, as this is only to set def_name
1234 * and a rename patch has the names elsewhere
1235 * in an unambiguous form.
1237 if (!name[len + 1])
1238 return NULL; /* no postimage name */
1239 second = skip_tree_prefix(name + len + 1,
1240 line_len - (len + 1));
1241 if (!second)
1242 return NULL;
1244 * Does len bytes starting at "name" and "second"
1245 * (that are separated by one HT or SP we just
1246 * found) exactly match?
1248 if (second[len] == '\n' && !strncmp(name, second, len))
1249 return xmemdupz(name, len);
1254 /* Verify that we recognize the lines following a git header */
1255 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1257 unsigned long offset;
1259 /* A git diff has explicit new/delete information, so we don't guess */
1260 patch->is_new = 0;
1261 patch->is_delete = 0;
1264 * Some things may not have the old name in the
1265 * rest of the headers anywhere (pure mode changes,
1266 * or removing or adding empty files), so we get
1267 * the default name from the header.
1269 patch->def_name = git_header_name(line, len);
1270 if (patch->def_name && root) {
1271 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1272 strcpy(s, root);
1273 strcpy(s + root_len, patch->def_name);
1274 free(patch->def_name);
1275 patch->def_name = s;
1278 line += len;
1279 size -= len;
1280 linenr++;
1281 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1282 static const struct opentry {
1283 const char *str;
1284 int (*fn)(const char *, struct patch *);
1285 } optable[] = {
1286 { "@@ -", gitdiff_hdrend },
1287 { "--- ", gitdiff_oldname },
1288 { "+++ ", gitdiff_newname },
1289 { "old mode ", gitdiff_oldmode },
1290 { "new mode ", gitdiff_newmode },
1291 { "deleted file mode ", gitdiff_delete },
1292 { "new file mode ", gitdiff_newfile },
1293 { "copy from ", gitdiff_copysrc },
1294 { "copy to ", gitdiff_copydst },
1295 { "rename old ", gitdiff_renamesrc },
1296 { "rename new ", gitdiff_renamedst },
1297 { "rename from ", gitdiff_renamesrc },
1298 { "rename to ", gitdiff_renamedst },
1299 { "similarity index ", gitdiff_similarity },
1300 { "dissimilarity index ", gitdiff_dissimilarity },
1301 { "index ", gitdiff_index },
1302 { "", gitdiff_unrecognized },
1304 int i;
1306 len = linelen(line, size);
1307 if (!len || line[len-1] != '\n')
1308 break;
1309 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1310 const struct opentry *p = optable + i;
1311 int oplen = strlen(p->str);
1312 if (len < oplen || memcmp(p->str, line, oplen))
1313 continue;
1314 if (p->fn(line + oplen, patch) < 0)
1315 return offset;
1316 break;
1320 return offset;
1323 static int parse_num(const char *line, unsigned long *p)
1325 char *ptr;
1327 if (!isdigit(*line))
1328 return 0;
1329 *p = strtoul(line, &ptr, 10);
1330 return ptr - line;
1333 static int parse_range(const char *line, int len, int offset, const char *expect,
1334 unsigned long *p1, unsigned long *p2)
1336 int digits, ex;
1338 if (offset < 0 || offset >= len)
1339 return -1;
1340 line += offset;
1341 len -= offset;
1343 digits = parse_num(line, p1);
1344 if (!digits)
1345 return -1;
1347 offset += digits;
1348 line += digits;
1349 len -= digits;
1351 *p2 = 1;
1352 if (*line == ',') {
1353 digits = parse_num(line+1, p2);
1354 if (!digits)
1355 return -1;
1357 offset += digits+1;
1358 line += digits+1;
1359 len -= digits+1;
1362 ex = strlen(expect);
1363 if (ex > len)
1364 return -1;
1365 if (memcmp(line, expect, ex))
1366 return -1;
1368 return offset + ex;
1371 static void recount_diff(const char *line, int size, struct fragment *fragment)
1373 int oldlines = 0, newlines = 0, ret = 0;
1375 if (size < 1) {
1376 warning("recount: ignore empty hunk");
1377 return;
1380 for (;;) {
1381 int len = linelen(line, size);
1382 size -= len;
1383 line += len;
1385 if (size < 1)
1386 break;
1388 switch (*line) {
1389 case ' ': case '\n':
1390 newlines++;
1391 /* fall through */
1392 case '-':
1393 oldlines++;
1394 continue;
1395 case '+':
1396 newlines++;
1397 continue;
1398 case '\\':
1399 continue;
1400 case '@':
1401 ret = size < 3 || prefixcmp(line, "@@ ");
1402 break;
1403 case 'd':
1404 ret = size < 5 || prefixcmp(line, "diff ");
1405 break;
1406 default:
1407 ret = -1;
1408 break;
1410 if (ret) {
1411 warning(_("recount: unexpected line: %.*s"),
1412 (int)linelen(line, size), line);
1413 return;
1415 break;
1417 fragment->oldlines = oldlines;
1418 fragment->newlines = newlines;
1422 * Parse a unified diff fragment header of the
1423 * form "@@ -a,b +c,d @@"
1425 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1427 int offset;
1429 if (!len || line[len-1] != '\n')
1430 return -1;
1432 /* Figure out the number of lines in a fragment */
1433 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1434 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1436 return offset;
1439 static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)
1441 unsigned long offset, len;
1443 patch->is_toplevel_relative = 0;
1444 patch->is_rename = patch->is_copy = 0;
1445 patch->is_new = patch->is_delete = -1;
1446 patch->old_mode = patch->new_mode = 0;
1447 patch->old_name = patch->new_name = NULL;
1448 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1449 unsigned long nextlen;
1451 len = linelen(line, size);
1452 if (!len)
1453 break;
1455 /* Testing this early allows us to take a few shortcuts.. */
1456 if (len < 6)
1457 continue;
1460 * Make sure we don't find any unconnected patch fragments.
1461 * That's a sign that we didn't find a header, and that a
1462 * patch has become corrupted/broken up.
1464 if (!memcmp("@@ -", line, 4)) {
1465 struct fragment dummy;
1466 if (parse_fragment_header(line, len, &dummy) < 0)
1467 continue;
1468 die(_("patch fragment without header at line %d: %.*s"),
1469 linenr, (int)len-1, line);
1472 if (size < len + 6)
1473 break;
1476 * Git patch? It might not have a real patch, just a rename
1477 * or mode change, so we handle that specially
1479 if (!memcmp("diff --git ", line, 11)) {
1480 int git_hdr_len = parse_git_header(line, len, size, patch);
1481 if (git_hdr_len <= len)
1482 continue;
1483 if (!patch->old_name && !patch->new_name) {
1484 if (!patch->def_name)
1485 die(Q_("git diff header lacks filename information when removing "
1486 "%d leading pathname component (line %d)",
1487 "git diff header lacks filename information when removing "
1488 "%d leading pathname components (line %d)",
1489 p_value),
1490 p_value, linenr);
1491 patch->old_name = xstrdup(patch->def_name);
1492 patch->new_name = xstrdup(patch->def_name);
1494 if (!patch->is_delete && !patch->new_name)
1495 die("git diff header lacks filename information "
1496 "(line %d)", linenr);
1497 patch->is_toplevel_relative = 1;
1498 *hdrsize = git_hdr_len;
1499 return offset;
1502 /* --- followed by +++ ? */
1503 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1504 continue;
1507 * We only accept unified patches, so we want it to
1508 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1509 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1511 nextlen = linelen(line + len, size - len);
1512 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1513 continue;
1515 /* Ok, we'll consider it a patch */
1516 parse_traditional_patch(line, line+len, patch);
1517 *hdrsize = len + nextlen;
1518 linenr += 2;
1519 return offset;
1521 return -1;
1524 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1526 char *err;
1528 if (!result)
1529 return;
1531 whitespace_error++;
1532 if (squelch_whitespace_errors &&
1533 squelch_whitespace_errors < whitespace_error)
1534 return;
1536 err = whitespace_error_string(result);
1537 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1538 patch_input_file, linenr, err, len, line);
1539 free(err);
1542 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1544 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1546 record_ws_error(result, line + 1, len - 2, linenr);
1550 * Parse a unified diff. Note that this really needs to parse each
1551 * fragment separately, since the only way to know the difference
1552 * between a "---" that is part of a patch, and a "---" that starts
1553 * the next patch is to look at the line counts..
1555 static int parse_fragment(const char *line, unsigned long size,
1556 struct patch *patch, struct fragment *fragment)
1558 int added, deleted;
1559 int len = linelen(line, size), offset;
1560 unsigned long oldlines, newlines;
1561 unsigned long leading, trailing;
1563 offset = parse_fragment_header(line, len, fragment);
1564 if (offset < 0)
1565 return -1;
1566 if (offset > 0 && patch->recount)
1567 recount_diff(line + offset, size - offset, fragment);
1568 oldlines = fragment->oldlines;
1569 newlines = fragment->newlines;
1570 leading = 0;
1571 trailing = 0;
1573 /* Parse the thing.. */
1574 line += len;
1575 size -= len;
1576 linenr++;
1577 added = deleted = 0;
1578 for (offset = len;
1579 0 < size;
1580 offset += len, size -= len, line += len, linenr++) {
1581 if (!oldlines && !newlines)
1582 break;
1583 len = linelen(line, size);
1584 if (!len || line[len-1] != '\n')
1585 return -1;
1586 switch (*line) {
1587 default:
1588 return -1;
1589 case '\n': /* newer GNU diff, an empty context line */
1590 case ' ':
1591 oldlines--;
1592 newlines--;
1593 if (!deleted && !added)
1594 leading++;
1595 trailing++;
1596 break;
1597 case '-':
1598 if (apply_in_reverse &&
1599 ws_error_action != nowarn_ws_error)
1600 check_whitespace(line, len, patch->ws_rule);
1601 deleted++;
1602 oldlines--;
1603 trailing = 0;
1604 break;
1605 case '+':
1606 if (!apply_in_reverse &&
1607 ws_error_action != nowarn_ws_error)
1608 check_whitespace(line, len, patch->ws_rule);
1609 added++;
1610 newlines--;
1611 trailing = 0;
1612 break;
1615 * We allow "\ No newline at end of file". Depending
1616 * on locale settings when the patch was produced we
1617 * don't know what this line looks like. The only
1618 * thing we do know is that it begins with "\ ".
1619 * Checking for 12 is just for sanity check -- any
1620 * l10n of "\ No newline..." is at least that long.
1622 case '\\':
1623 if (len < 12 || memcmp(line, "\\ ", 2))
1624 return -1;
1625 break;
1628 if (oldlines || newlines)
1629 return -1;
1630 fragment->leading = leading;
1631 fragment->trailing = trailing;
1634 * If a fragment ends with an incomplete line, we failed to include
1635 * it in the above loop because we hit oldlines == newlines == 0
1636 * before seeing it.
1638 if (12 < size && !memcmp(line, "\\ ", 2))
1639 offset += linelen(line, size);
1641 patch->lines_added += added;
1642 patch->lines_deleted += deleted;
1644 if (0 < patch->is_new && oldlines)
1645 return error(_("new file depends on old contents"));
1646 if (0 < patch->is_delete && newlines)
1647 return error(_("deleted file still has contents"));
1648 return offset;
1652 * We have seen "diff --git a/... b/..." header (or a traditional patch
1653 * header). Read hunks that belong to this patch into fragments and hang
1654 * them to the given patch structure.
1656 * The (fragment->patch, fragment->size) pair points into the memory given
1657 * by the caller, not a copy, when we return.
1659 static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)
1661 unsigned long offset = 0;
1662 unsigned long oldlines = 0, newlines = 0, context = 0;
1663 struct fragment **fragp = &patch->fragments;
1665 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1666 struct fragment *fragment;
1667 int len;
1669 fragment = xcalloc(1, sizeof(*fragment));
1670 fragment->linenr = linenr;
1671 len = parse_fragment(line, size, patch, fragment);
1672 if (len <= 0)
1673 die(_("corrupt patch at line %d"), linenr);
1674 fragment->patch = line;
1675 fragment->size = len;
1676 oldlines += fragment->oldlines;
1677 newlines += fragment->newlines;
1678 context += fragment->leading + fragment->trailing;
1680 *fragp = fragment;
1681 fragp = &fragment->next;
1683 offset += len;
1684 line += len;
1685 size -= len;
1689 * If something was removed (i.e. we have old-lines) it cannot
1690 * be creation, and if something was added it cannot be
1691 * deletion. However, the reverse is not true; --unified=0
1692 * patches that only add are not necessarily creation even
1693 * though they do not have any old lines, and ones that only
1694 * delete are not necessarily deletion.
1696 * Unfortunately, a real creation/deletion patch do _not_ have
1697 * any context line by definition, so we cannot safely tell it
1698 * apart with --unified=0 insanity. At least if the patch has
1699 * more than one hunk it is not creation or deletion.
1701 if (patch->is_new < 0 &&
1702 (oldlines || (patch->fragments && patch->fragments->next)))
1703 patch->is_new = 0;
1704 if (patch->is_delete < 0 &&
1705 (newlines || (patch->fragments && patch->fragments->next)))
1706 patch->is_delete = 0;
1708 if (0 < patch->is_new && oldlines)
1709 die(_("new file %s depends on old contents"), patch->new_name);
1710 if (0 < patch->is_delete && newlines)
1711 die(_("deleted file %s still has contents"), patch->old_name);
1712 if (!patch->is_delete && !newlines && context)
1713 fprintf_ln(stderr,
1714 _("** warning: "
1715 "file %s becomes empty but is not deleted"),
1716 patch->new_name);
1718 return offset;
1721 static inline int metadata_changes(struct patch *patch)
1723 return patch->is_rename > 0 ||
1724 patch->is_copy > 0 ||
1725 patch->is_new > 0 ||
1726 patch->is_delete ||
1727 (patch->old_mode && patch->new_mode &&
1728 patch->old_mode != patch->new_mode);
1731 static char *inflate_it(const void *data, unsigned long size,
1732 unsigned long inflated_size)
1734 git_zstream stream;
1735 void *out;
1736 int st;
1738 memset(&stream, 0, sizeof(stream));
1740 stream.next_in = (unsigned char *)data;
1741 stream.avail_in = size;
1742 stream.next_out = out = xmalloc(inflated_size);
1743 stream.avail_out = inflated_size;
1744 git_inflate_init(&stream);
1745 st = git_inflate(&stream, Z_FINISH);
1746 git_inflate_end(&stream);
1747 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1748 free(out);
1749 return NULL;
1751 return out;
1755 * Read a binary hunk and return a new fragment; fragment->patch
1756 * points at an allocated memory that the caller must free, so
1757 * it is marked as "->free_patch = 1".
1759 static struct fragment *parse_binary_hunk(char **buf_p,
1760 unsigned long *sz_p,
1761 int *status_p,
1762 int *used_p)
1765 * Expect a line that begins with binary patch method ("literal"
1766 * or "delta"), followed by the length of data before deflating.
1767 * a sequence of 'length-byte' followed by base-85 encoded data
1768 * should follow, terminated by a newline.
1770 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1771 * and we would limit the patch line to 66 characters,
1772 * so one line can fit up to 13 groups that would decode
1773 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1774 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1776 int llen, used;
1777 unsigned long size = *sz_p;
1778 char *buffer = *buf_p;
1779 int patch_method;
1780 unsigned long origlen;
1781 char *data = NULL;
1782 int hunk_size = 0;
1783 struct fragment *frag;
1785 llen = linelen(buffer, size);
1786 used = llen;
1788 *status_p = 0;
1790 if (!prefixcmp(buffer, "delta ")) {
1791 patch_method = BINARY_DELTA_DEFLATED;
1792 origlen = strtoul(buffer + 6, NULL, 10);
1794 else if (!prefixcmp(buffer, "literal ")) {
1795 patch_method = BINARY_LITERAL_DEFLATED;
1796 origlen = strtoul(buffer + 8, NULL, 10);
1798 else
1799 return NULL;
1801 linenr++;
1802 buffer += llen;
1803 while (1) {
1804 int byte_length, max_byte_length, newsize;
1805 llen = linelen(buffer, size);
1806 used += llen;
1807 linenr++;
1808 if (llen == 1) {
1809 /* consume the blank line */
1810 buffer++;
1811 size--;
1812 break;
1815 * Minimum line is "A00000\n" which is 7-byte long,
1816 * and the line length must be multiple of 5 plus 2.
1818 if ((llen < 7) || (llen-2) % 5)
1819 goto corrupt;
1820 max_byte_length = (llen - 2) / 5 * 4;
1821 byte_length = *buffer;
1822 if ('A' <= byte_length && byte_length <= 'Z')
1823 byte_length = byte_length - 'A' + 1;
1824 else if ('a' <= byte_length && byte_length <= 'z')
1825 byte_length = byte_length - 'a' + 27;
1826 else
1827 goto corrupt;
1828 /* if the input length was not multiple of 4, we would
1829 * have filler at the end but the filler should never
1830 * exceed 3 bytes
1832 if (max_byte_length < byte_length ||
1833 byte_length <= max_byte_length - 4)
1834 goto corrupt;
1835 newsize = hunk_size + byte_length;
1836 data = xrealloc(data, newsize);
1837 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1838 goto corrupt;
1839 hunk_size = newsize;
1840 buffer += llen;
1841 size -= llen;
1844 frag = xcalloc(1, sizeof(*frag));
1845 frag->patch = inflate_it(data, hunk_size, origlen);
1846 frag->free_patch = 1;
1847 if (!frag->patch)
1848 goto corrupt;
1849 free(data);
1850 frag->size = origlen;
1851 *buf_p = buffer;
1852 *sz_p = size;
1853 *used_p = used;
1854 frag->binary_patch_method = patch_method;
1855 return frag;
1857 corrupt:
1858 free(data);
1859 *status_p = -1;
1860 error(_("corrupt binary patch at line %d: %.*s"),
1861 linenr-1, llen-1, buffer);
1862 return NULL;
1865 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1868 * We have read "GIT binary patch\n"; what follows is a line
1869 * that says the patch method (currently, either "literal" or
1870 * "delta") and the length of data before deflating; a
1871 * sequence of 'length-byte' followed by base-85 encoded data
1872 * follows.
1874 * When a binary patch is reversible, there is another binary
1875 * hunk in the same format, starting with patch method (either
1876 * "literal" or "delta") with the length of data, and a sequence
1877 * of length-byte + base-85 encoded data, terminated with another
1878 * empty line. This data, when applied to the postimage, produces
1879 * the preimage.
1881 struct fragment *forward;
1882 struct fragment *reverse;
1883 int status;
1884 int used, used_1;
1886 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1887 if (!forward && !status)
1888 /* there has to be one hunk (forward hunk) */
1889 return error(_("unrecognized binary patch at line %d"), linenr-1);
1890 if (status)
1891 /* otherwise we already gave an error message */
1892 return status;
1894 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1895 if (reverse)
1896 used += used_1;
1897 else if (status) {
1899 * Not having reverse hunk is not an error, but having
1900 * a corrupt reverse hunk is.
1902 free((void*) forward->patch);
1903 free(forward);
1904 return status;
1906 forward->next = reverse;
1907 patch->fragments = forward;
1908 patch->is_binary = 1;
1909 return used;
1913 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1914 * reading after seeing a single patch (i.e. changes to a single file).
1915 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1916 * Return the number of bytes consumed, so that the caller can call us
1917 * again for the next patch.
1919 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1921 int hdrsize, patchsize;
1922 int offset = find_header(buffer, size, &hdrsize, patch);
1924 if (offset < 0)
1925 return offset;
1927 patch->ws_rule = whitespace_rule(patch->new_name
1928 ? patch->new_name
1929 : patch->old_name);
1931 patchsize = parse_single_patch(buffer + offset + hdrsize,
1932 size - offset - hdrsize, patch);
1934 if (!patchsize) {
1935 static const char *binhdr[] = {
1936 "Binary files ",
1937 "Files ",
1938 NULL,
1940 static const char git_binary[] = "GIT binary patch\n";
1941 int i;
1942 int hd = hdrsize + offset;
1943 unsigned long llen = linelen(buffer + hd, size - hd);
1945 if (llen == sizeof(git_binary) - 1 &&
1946 !memcmp(git_binary, buffer + hd, llen)) {
1947 int used;
1948 linenr++;
1949 used = parse_binary(buffer + hd + llen,
1950 size - hd - llen, patch);
1951 if (used)
1952 patchsize = used + llen;
1953 else
1954 patchsize = 0;
1956 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1957 for (i = 0; binhdr[i]; i++) {
1958 int len = strlen(binhdr[i]);
1959 if (len < size - hd &&
1960 !memcmp(binhdr[i], buffer + hd, len)) {
1961 linenr++;
1962 patch->is_binary = 1;
1963 patchsize = llen;
1964 break;
1969 /* Empty patch cannot be applied if it is a text patch
1970 * without metadata change. A binary patch appears
1971 * empty to us here.
1973 if ((apply || check) &&
1974 (!patch->is_binary && !metadata_changes(patch)))
1975 die(_("patch with only garbage at line %d"), linenr);
1978 return offset + hdrsize + patchsize;
1981 #define swap(a,b) myswap((a),(b),sizeof(a))
1983 #define myswap(a, b, size) do { \
1984 unsigned char mytmp[size]; \
1985 memcpy(mytmp, &a, size); \
1986 memcpy(&a, &b, size); \
1987 memcpy(&b, mytmp, size); \
1988 } while (0)
1990 static void reverse_patches(struct patch *p)
1992 for (; p; p = p->next) {
1993 struct fragment *frag = p->fragments;
1995 swap(p->new_name, p->old_name);
1996 swap(p->new_mode, p->old_mode);
1997 swap(p->is_new, p->is_delete);
1998 swap(p->lines_added, p->lines_deleted);
1999 swap(p->old_sha1_prefix, p->new_sha1_prefix);
2001 for (; frag; frag = frag->next) {
2002 swap(frag->newpos, frag->oldpos);
2003 swap(frag->newlines, frag->oldlines);
2008 static const char pluses[] =
2009 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2010 static const char minuses[]=
2011 "----------------------------------------------------------------------";
2013 static void show_stats(struct patch *patch)
2015 struct strbuf qname = STRBUF_INIT;
2016 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2017 int max, add, del;
2019 quote_c_style(cp, &qname, NULL, 0);
2022 * "scale" the filename
2024 max = max_len;
2025 if (max > 50)
2026 max = 50;
2028 if (qname.len > max) {
2029 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2030 if (!cp)
2031 cp = qname.buf + qname.len + 3 - max;
2032 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2035 if (patch->is_binary) {
2036 printf(" %-*s | Bin\n", max, qname.buf);
2037 strbuf_release(&qname);
2038 return;
2041 printf(" %-*s |", max, qname.buf);
2042 strbuf_release(&qname);
2045 * scale the add/delete
2047 max = max + max_change > 70 ? 70 - max : max_change;
2048 add = patch->lines_added;
2049 del = patch->lines_deleted;
2051 if (max_change > 0) {
2052 int total = ((add + del) * max + max_change / 2) / max_change;
2053 add = (add * max + max_change / 2) / max_change;
2054 del = total - add;
2056 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2057 add, pluses, del, minuses);
2060 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2062 switch (st->st_mode & S_IFMT) {
2063 case S_IFLNK:
2064 if (strbuf_readlink(buf, path, st->st_size) < 0)
2065 return error(_("unable to read symlink %s"), path);
2066 return 0;
2067 case S_IFREG:
2068 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2069 return error(_("unable to open or read %s"), path);
2070 convert_to_git(path, buf->buf, buf->len, buf, 0);
2071 return 0;
2072 default:
2073 return -1;
2078 * Update the preimage, and the common lines in postimage,
2079 * from buffer buf of length len. If postlen is 0 the postimage
2080 * is updated in place, otherwise it's updated on a new buffer
2081 * of length postlen
2084 static void update_pre_post_images(struct image *preimage,
2085 struct image *postimage,
2086 char *buf,
2087 size_t len, size_t postlen)
2089 int i, ctx, reduced;
2090 char *new, *old, *fixed;
2091 struct image fixed_preimage;
2094 * Update the preimage with whitespace fixes. Note that we
2095 * are not losing preimage->buf -- apply_one_fragment() will
2096 * free "oldlines".
2098 prepare_image(&fixed_preimage, buf, len, 1);
2099 assert(postlen
2100 ? fixed_preimage.nr == preimage->nr
2101 : fixed_preimage.nr <= preimage->nr);
2102 for (i = 0; i < fixed_preimage.nr; i++)
2103 fixed_preimage.line[i].flag = preimage->line[i].flag;
2104 free(preimage->line_allocated);
2105 *preimage = fixed_preimage;
2108 * Adjust the common context lines in postimage. This can be
2109 * done in-place when we are just doing whitespace fixing,
2110 * which does not make the string grow, but needs a new buffer
2111 * when ignoring whitespace causes the update, since in this case
2112 * we could have e.g. tabs converted to multiple spaces.
2113 * We trust the caller to tell us if the update can be done
2114 * in place (postlen==0) or not.
2116 old = postimage->buf;
2117 if (postlen)
2118 new = postimage->buf = xmalloc(postlen);
2119 else
2120 new = old;
2121 fixed = preimage->buf;
2123 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2124 size_t len = postimage->line[i].len;
2125 if (!(postimage->line[i].flag & LINE_COMMON)) {
2126 /* an added line -- no counterparts in preimage */
2127 memmove(new, old, len);
2128 old += len;
2129 new += len;
2130 continue;
2133 /* a common context -- skip it in the original postimage */
2134 old += len;
2136 /* and find the corresponding one in the fixed preimage */
2137 while (ctx < preimage->nr &&
2138 !(preimage->line[ctx].flag & LINE_COMMON)) {
2139 fixed += preimage->line[ctx].len;
2140 ctx++;
2144 * preimage is expected to run out, if the caller
2145 * fixed addition of trailing blank lines.
2147 if (preimage->nr <= ctx) {
2148 reduced++;
2149 continue;
2152 /* and copy it in, while fixing the line length */
2153 len = preimage->line[ctx].len;
2154 memcpy(new, fixed, len);
2155 new += len;
2156 fixed += len;
2157 postimage->line[i].len = len;
2158 ctx++;
2161 /* Fix the length of the whole thing */
2162 postimage->len = new - postimage->buf;
2163 postimage->nr -= reduced;
2166 static int match_fragment(struct image *img,
2167 struct image *preimage,
2168 struct image *postimage,
2169 unsigned long try,
2170 int try_lno,
2171 unsigned ws_rule,
2172 int match_beginning, int match_end)
2174 int i;
2175 char *fixed_buf, *buf, *orig, *target;
2176 struct strbuf fixed;
2177 size_t fixed_len;
2178 int preimage_limit;
2180 if (preimage->nr + try_lno <= img->nr) {
2182 * The hunk falls within the boundaries of img.
2184 preimage_limit = preimage->nr;
2185 if (match_end && (preimage->nr + try_lno != img->nr))
2186 return 0;
2187 } else if (ws_error_action == correct_ws_error &&
2188 (ws_rule & WS_BLANK_AT_EOF)) {
2190 * This hunk extends beyond the end of img, and we are
2191 * removing blank lines at the end of the file. This
2192 * many lines from the beginning of the preimage must
2193 * match with img, and the remainder of the preimage
2194 * must be blank.
2196 preimage_limit = img->nr - try_lno;
2197 } else {
2199 * The hunk extends beyond the end of the img and
2200 * we are not removing blanks at the end, so we
2201 * should reject the hunk at this position.
2203 return 0;
2206 if (match_beginning && try_lno)
2207 return 0;
2209 /* Quick hash check */
2210 for (i = 0; i < preimage_limit; i++)
2211 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2212 (preimage->line[i].hash != img->line[try_lno + i].hash))
2213 return 0;
2215 if (preimage_limit == preimage->nr) {
2217 * Do we have an exact match? If we were told to match
2218 * at the end, size must be exactly at try+fragsize,
2219 * otherwise try+fragsize must be still within the preimage,
2220 * and either case, the old piece should match the preimage
2221 * exactly.
2223 if ((match_end
2224 ? (try + preimage->len == img->len)
2225 : (try + preimage->len <= img->len)) &&
2226 !memcmp(img->buf + try, preimage->buf, preimage->len))
2227 return 1;
2228 } else {
2230 * The preimage extends beyond the end of img, so
2231 * there cannot be an exact match.
2233 * There must be one non-blank context line that match
2234 * a line before the end of img.
2236 char *buf_end;
2238 buf = preimage->buf;
2239 buf_end = buf;
2240 for (i = 0; i < preimage_limit; i++)
2241 buf_end += preimage->line[i].len;
2243 for ( ; buf < buf_end; buf++)
2244 if (!isspace(*buf))
2245 break;
2246 if (buf == buf_end)
2247 return 0;
2251 * No exact match. If we are ignoring whitespace, run a line-by-line
2252 * fuzzy matching. We collect all the line length information because
2253 * we need it to adjust whitespace if we match.
2255 if (ws_ignore_action == ignore_ws_change) {
2256 size_t imgoff = 0;
2257 size_t preoff = 0;
2258 size_t postlen = postimage->len;
2259 size_t extra_chars;
2260 char *preimage_eof;
2261 char *preimage_end;
2262 for (i = 0; i < preimage_limit; i++) {
2263 size_t prelen = preimage->line[i].len;
2264 size_t imglen = img->line[try_lno+i].len;
2266 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2267 preimage->buf + preoff, prelen))
2268 return 0;
2269 if (preimage->line[i].flag & LINE_COMMON)
2270 postlen += imglen - prelen;
2271 imgoff += imglen;
2272 preoff += prelen;
2276 * Ok, the preimage matches with whitespace fuzz.
2278 * imgoff now holds the true length of the target that
2279 * matches the preimage before the end of the file.
2281 * Count the number of characters in the preimage that fall
2282 * beyond the end of the file and make sure that all of them
2283 * are whitespace characters. (This can only happen if
2284 * we are removing blank lines at the end of the file.)
2286 buf = preimage_eof = preimage->buf + preoff;
2287 for ( ; i < preimage->nr; i++)
2288 preoff += preimage->line[i].len;
2289 preimage_end = preimage->buf + preoff;
2290 for ( ; buf < preimage_end; buf++)
2291 if (!isspace(*buf))
2292 return 0;
2295 * Update the preimage and the common postimage context
2296 * lines to use the same whitespace as the target.
2297 * If whitespace is missing in the target (i.e.
2298 * if the preimage extends beyond the end of the file),
2299 * use the whitespace from the preimage.
2301 extra_chars = preimage_end - preimage_eof;
2302 strbuf_init(&fixed, imgoff + extra_chars);
2303 strbuf_add(&fixed, img->buf + try, imgoff);
2304 strbuf_add(&fixed, preimage_eof, extra_chars);
2305 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2306 update_pre_post_images(preimage, postimage,
2307 fixed_buf, fixed_len, postlen);
2308 return 1;
2311 if (ws_error_action != correct_ws_error)
2312 return 0;
2315 * The hunk does not apply byte-by-byte, but the hash says
2316 * it might with whitespace fuzz. We haven't been asked to
2317 * ignore whitespace, we were asked to correct whitespace
2318 * errors, so let's try matching after whitespace correction.
2320 * The preimage may extend beyond the end of the file,
2321 * but in this loop we will only handle the part of the
2322 * preimage that falls within the file.
2324 strbuf_init(&fixed, preimage->len + 1);
2325 orig = preimage->buf;
2326 target = img->buf + try;
2327 for (i = 0; i < preimage_limit; i++) {
2328 size_t oldlen = preimage->line[i].len;
2329 size_t tgtlen = img->line[try_lno + i].len;
2330 size_t fixstart = fixed.len;
2331 struct strbuf tgtfix;
2332 int match;
2334 /* Try fixing the line in the preimage */
2335 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2337 /* Try fixing the line in the target */
2338 strbuf_init(&tgtfix, tgtlen);
2339 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2342 * If they match, either the preimage was based on
2343 * a version before our tree fixed whitespace breakage,
2344 * or we are lacking a whitespace-fix patch the tree
2345 * the preimage was based on already had (i.e. target
2346 * has whitespace breakage, the preimage doesn't).
2347 * In either case, we are fixing the whitespace breakages
2348 * so we might as well take the fix together with their
2349 * real change.
2351 match = (tgtfix.len == fixed.len - fixstart &&
2352 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2353 fixed.len - fixstart));
2355 strbuf_release(&tgtfix);
2356 if (!match)
2357 goto unmatch_exit;
2359 orig += oldlen;
2360 target += tgtlen;
2365 * Now handle the lines in the preimage that falls beyond the
2366 * end of the file (if any). They will only match if they are
2367 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2368 * false).
2370 for ( ; i < preimage->nr; i++) {
2371 size_t fixstart = fixed.len; /* start of the fixed preimage */
2372 size_t oldlen = preimage->line[i].len;
2373 int j;
2375 /* Try fixing the line in the preimage */
2376 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2378 for (j = fixstart; j < fixed.len; j++)
2379 if (!isspace(fixed.buf[j]))
2380 goto unmatch_exit;
2382 orig += oldlen;
2386 * Yes, the preimage is based on an older version that still
2387 * has whitespace breakages unfixed, and fixing them makes the
2388 * hunk match. Update the context lines in the postimage.
2390 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2391 update_pre_post_images(preimage, postimage,
2392 fixed_buf, fixed_len, 0);
2393 return 1;
2395 unmatch_exit:
2396 strbuf_release(&fixed);
2397 return 0;
2400 static int find_pos(struct image *img,
2401 struct image *preimage,
2402 struct image *postimage,
2403 int line,
2404 unsigned ws_rule,
2405 int match_beginning, int match_end)
2407 int i;
2408 unsigned long backwards, forwards, try;
2409 int backwards_lno, forwards_lno, try_lno;
2412 * If match_beginning or match_end is specified, there is no
2413 * point starting from a wrong line that will never match and
2414 * wander around and wait for a match at the specified end.
2416 if (match_beginning)
2417 line = 0;
2418 else if (match_end)
2419 line = img->nr - preimage->nr;
2422 * Because the comparison is unsigned, the following test
2423 * will also take care of a negative line number that can
2424 * result when match_end and preimage is larger than the target.
2426 if ((size_t) line > img->nr)
2427 line = img->nr;
2429 try = 0;
2430 for (i = 0; i < line; i++)
2431 try += img->line[i].len;
2434 * There's probably some smart way to do this, but I'll leave
2435 * that to the smart and beautiful people. I'm simple and stupid.
2437 backwards = try;
2438 backwards_lno = line;
2439 forwards = try;
2440 forwards_lno = line;
2441 try_lno = line;
2443 for (i = 0; ; i++) {
2444 if (match_fragment(img, preimage, postimage,
2445 try, try_lno, ws_rule,
2446 match_beginning, match_end))
2447 return try_lno;
2449 again:
2450 if (backwards_lno == 0 && forwards_lno == img->nr)
2451 break;
2453 if (i & 1) {
2454 if (backwards_lno == 0) {
2455 i++;
2456 goto again;
2458 backwards_lno--;
2459 backwards -= img->line[backwards_lno].len;
2460 try = backwards;
2461 try_lno = backwards_lno;
2462 } else {
2463 if (forwards_lno == img->nr) {
2464 i++;
2465 goto again;
2467 forwards += img->line[forwards_lno].len;
2468 forwards_lno++;
2469 try = forwards;
2470 try_lno = forwards_lno;
2474 return -1;
2477 static void remove_first_line(struct image *img)
2479 img->buf += img->line[0].len;
2480 img->len -= img->line[0].len;
2481 img->line++;
2482 img->nr--;
2485 static void remove_last_line(struct image *img)
2487 img->len -= img->line[--img->nr].len;
2491 * The change from "preimage" and "postimage" has been found to
2492 * apply at applied_pos (counts in line numbers) in "img".
2493 * Update "img" to remove "preimage" and replace it with "postimage".
2495 static void update_image(struct image *img,
2496 int applied_pos,
2497 struct image *preimage,
2498 struct image *postimage)
2501 * remove the copy of preimage at offset in img
2502 * and replace it with postimage
2504 int i, nr;
2505 size_t remove_count, insert_count, applied_at = 0;
2506 char *result;
2507 int preimage_limit;
2510 * If we are removing blank lines at the end of img,
2511 * the preimage may extend beyond the end.
2512 * If that is the case, we must be careful only to
2513 * remove the part of the preimage that falls within
2514 * the boundaries of img. Initialize preimage_limit
2515 * to the number of lines in the preimage that falls
2516 * within the boundaries.
2518 preimage_limit = preimage->nr;
2519 if (preimage_limit > img->nr - applied_pos)
2520 preimage_limit = img->nr - applied_pos;
2522 for (i = 0; i < applied_pos; i++)
2523 applied_at += img->line[i].len;
2525 remove_count = 0;
2526 for (i = 0; i < preimage_limit; i++)
2527 remove_count += img->line[applied_pos + i].len;
2528 insert_count = postimage->len;
2530 /* Adjust the contents */
2531 result = xmalloc(img->len + insert_count - remove_count + 1);
2532 memcpy(result, img->buf, applied_at);
2533 memcpy(result + applied_at, postimage->buf, postimage->len);
2534 memcpy(result + applied_at + postimage->len,
2535 img->buf + (applied_at + remove_count),
2536 img->len - (applied_at + remove_count));
2537 free(img->buf);
2538 img->buf = result;
2539 img->len += insert_count - remove_count;
2540 result[img->len] = '\0';
2542 /* Adjust the line table */
2543 nr = img->nr + postimage->nr - preimage_limit;
2544 if (preimage_limit < postimage->nr) {
2546 * NOTE: this knows that we never call remove_first_line()
2547 * on anything other than pre/post image.
2549 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2550 img->line_allocated = img->line;
2552 if (preimage_limit != postimage->nr)
2553 memmove(img->line + applied_pos + postimage->nr,
2554 img->line + applied_pos + preimage_limit,
2555 (img->nr - (applied_pos + preimage_limit)) *
2556 sizeof(*img->line));
2557 memcpy(img->line + applied_pos,
2558 postimage->line,
2559 postimage->nr * sizeof(*img->line));
2560 if (!allow_overlap)
2561 for (i = 0; i < postimage->nr; i++)
2562 img->line[applied_pos + i].flag |= LINE_PATCHED;
2563 img->nr = nr;
2567 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2568 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2569 * replace the part of "img" with "postimage" text.
2571 static int apply_one_fragment(struct image *img, struct fragment *frag,
2572 int inaccurate_eof, unsigned ws_rule,
2573 int nth_fragment)
2575 int match_beginning, match_end;
2576 const char *patch = frag->patch;
2577 int size = frag->size;
2578 char *old, *oldlines;
2579 struct strbuf newlines;
2580 int new_blank_lines_at_end = 0;
2581 int found_new_blank_lines_at_end = 0;
2582 int hunk_linenr = frag->linenr;
2583 unsigned long leading, trailing;
2584 int pos, applied_pos;
2585 struct image preimage;
2586 struct image postimage;
2588 memset(&preimage, 0, sizeof(preimage));
2589 memset(&postimage, 0, sizeof(postimage));
2590 oldlines = xmalloc(size);
2591 strbuf_init(&newlines, size);
2593 old = oldlines;
2594 while (size > 0) {
2595 char first;
2596 int len = linelen(patch, size);
2597 int plen;
2598 int added_blank_line = 0;
2599 int is_blank_context = 0;
2600 size_t start;
2602 if (!len)
2603 break;
2606 * "plen" is how much of the line we should use for
2607 * the actual patch data. Normally we just remove the
2608 * first character on the line, but if the line is
2609 * followed by "\ No newline", then we also remove the
2610 * last one (which is the newline, of course).
2612 plen = len - 1;
2613 if (len < size && patch[len] == '\\')
2614 plen--;
2615 first = *patch;
2616 if (apply_in_reverse) {
2617 if (first == '-')
2618 first = '+';
2619 else if (first == '+')
2620 first = '-';
2623 switch (first) {
2624 case '\n':
2625 /* Newer GNU diff, empty context line */
2626 if (plen < 0)
2627 /* ... followed by '\No newline'; nothing */
2628 break;
2629 *old++ = '\n';
2630 strbuf_addch(&newlines, '\n');
2631 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2632 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2633 is_blank_context = 1;
2634 break;
2635 case ' ':
2636 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2637 ws_blank_line(patch + 1, plen, ws_rule))
2638 is_blank_context = 1;
2639 case '-':
2640 memcpy(old, patch + 1, plen);
2641 add_line_info(&preimage, old, plen,
2642 (first == ' ' ? LINE_COMMON : 0));
2643 old += plen;
2644 if (first == '-')
2645 break;
2646 /* Fall-through for ' ' */
2647 case '+':
2648 /* --no-add does not add new lines */
2649 if (first == '+' && no_add)
2650 break;
2652 start = newlines.len;
2653 if (first != '+' ||
2654 !whitespace_error ||
2655 ws_error_action != correct_ws_error) {
2656 strbuf_add(&newlines, patch + 1, plen);
2658 else {
2659 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2661 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2662 (first == '+' ? 0 : LINE_COMMON));
2663 if (first == '+' &&
2664 (ws_rule & WS_BLANK_AT_EOF) &&
2665 ws_blank_line(patch + 1, plen, ws_rule))
2666 added_blank_line = 1;
2667 break;
2668 case '@': case '\\':
2669 /* Ignore it, we already handled it */
2670 break;
2671 default:
2672 if (apply_verbosely)
2673 error(_("invalid start of line: '%c'"), first);
2674 return -1;
2676 if (added_blank_line) {
2677 if (!new_blank_lines_at_end)
2678 found_new_blank_lines_at_end = hunk_linenr;
2679 new_blank_lines_at_end++;
2681 else if (is_blank_context)
2683 else
2684 new_blank_lines_at_end = 0;
2685 patch += len;
2686 size -= len;
2687 hunk_linenr++;
2689 if (inaccurate_eof &&
2690 old > oldlines && old[-1] == '\n' &&
2691 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2692 old--;
2693 strbuf_setlen(&newlines, newlines.len - 1);
2696 leading = frag->leading;
2697 trailing = frag->trailing;
2700 * A hunk to change lines at the beginning would begin with
2701 * @@ -1,L +N,M @@
2702 * but we need to be careful. -U0 that inserts before the second
2703 * line also has this pattern.
2705 * And a hunk to add to an empty file would begin with
2706 * @@ -0,0 +N,M @@
2708 * In other words, a hunk that is (frag->oldpos <= 1) with or
2709 * without leading context must match at the beginning.
2711 match_beginning = (!frag->oldpos ||
2712 (frag->oldpos == 1 && !unidiff_zero));
2715 * A hunk without trailing lines must match at the end.
2716 * However, we simply cannot tell if a hunk must match end
2717 * from the lack of trailing lines if the patch was generated
2718 * with unidiff without any context.
2720 match_end = !unidiff_zero && !trailing;
2722 pos = frag->newpos ? (frag->newpos - 1) : 0;
2723 preimage.buf = oldlines;
2724 preimage.len = old - oldlines;
2725 postimage.buf = newlines.buf;
2726 postimage.len = newlines.len;
2727 preimage.line = preimage.line_allocated;
2728 postimage.line = postimage.line_allocated;
2730 for (;;) {
2732 applied_pos = find_pos(img, &preimage, &postimage, pos,
2733 ws_rule, match_beginning, match_end);
2735 if (applied_pos >= 0)
2736 break;
2738 /* Am I at my context limits? */
2739 if ((leading <= p_context) && (trailing <= p_context))
2740 break;
2741 if (match_beginning || match_end) {
2742 match_beginning = match_end = 0;
2743 continue;
2747 * Reduce the number of context lines; reduce both
2748 * leading and trailing if they are equal otherwise
2749 * just reduce the larger context.
2751 if (leading >= trailing) {
2752 remove_first_line(&preimage);
2753 remove_first_line(&postimage);
2754 pos--;
2755 leading--;
2757 if (trailing > leading) {
2758 remove_last_line(&preimage);
2759 remove_last_line(&postimage);
2760 trailing--;
2764 if (applied_pos >= 0) {
2765 if (new_blank_lines_at_end &&
2766 preimage.nr + applied_pos >= img->nr &&
2767 (ws_rule & WS_BLANK_AT_EOF) &&
2768 ws_error_action != nowarn_ws_error) {
2769 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2770 found_new_blank_lines_at_end);
2771 if (ws_error_action == correct_ws_error) {
2772 while (new_blank_lines_at_end--)
2773 remove_last_line(&postimage);
2776 * We would want to prevent write_out_results()
2777 * from taking place in apply_patch() that follows
2778 * the callchain led us here, which is:
2779 * apply_patch->check_patch_list->check_patch->
2780 * apply_data->apply_fragments->apply_one_fragment
2782 if (ws_error_action == die_on_ws_error)
2783 apply = 0;
2786 if (apply_verbosely && applied_pos != pos) {
2787 int offset = applied_pos - pos;
2788 if (apply_in_reverse)
2789 offset = 0 - offset;
2790 fprintf_ln(stderr,
2791 Q_("Hunk #%d succeeded at %d (offset %d line).",
2792 "Hunk #%d succeeded at %d (offset %d lines).",
2793 offset),
2794 nth_fragment, applied_pos + 1, offset);
2798 * Warn if it was necessary to reduce the number
2799 * of context lines.
2801 if ((leading != frag->leading) ||
2802 (trailing != frag->trailing))
2803 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2804 " to apply fragment at %d"),
2805 leading, trailing, applied_pos+1);
2806 update_image(img, applied_pos, &preimage, &postimage);
2807 } else {
2808 if (apply_verbosely)
2809 error(_("while searching for:\n%.*s"),
2810 (int)(old - oldlines), oldlines);
2813 free(oldlines);
2814 strbuf_release(&newlines);
2815 free(preimage.line_allocated);
2816 free(postimage.line_allocated);
2818 return (applied_pos < 0);
2821 static int apply_binary_fragment(struct image *img, struct patch *patch)
2823 struct fragment *fragment = patch->fragments;
2824 unsigned long len;
2825 void *dst;
2827 if (!fragment)
2828 return error(_("missing binary patch data for '%s'"),
2829 patch->new_name ?
2830 patch->new_name :
2831 patch->old_name);
2833 /* Binary patch is irreversible without the optional second hunk */
2834 if (apply_in_reverse) {
2835 if (!fragment->next)
2836 return error("cannot reverse-apply a binary patch "
2837 "without the reverse hunk to '%s'",
2838 patch->new_name
2839 ? patch->new_name : patch->old_name);
2840 fragment = fragment->next;
2842 switch (fragment->binary_patch_method) {
2843 case BINARY_DELTA_DEFLATED:
2844 dst = patch_delta(img->buf, img->len, fragment->patch,
2845 fragment->size, &len);
2846 if (!dst)
2847 return -1;
2848 clear_image(img);
2849 img->buf = dst;
2850 img->len = len;
2851 return 0;
2852 case BINARY_LITERAL_DEFLATED:
2853 clear_image(img);
2854 img->len = fragment->size;
2855 img->buf = xmalloc(img->len+1);
2856 memcpy(img->buf, fragment->patch, img->len);
2857 img->buf[img->len] = '\0';
2858 return 0;
2860 return -1;
2864 * Replace "img" with the result of applying the binary patch.
2865 * The binary patch data itself in patch->fragment is still kept
2866 * but the preimage prepared by the caller in "img" is freed here
2867 * or in the helper function apply_binary_fragment() this calls.
2869 static int apply_binary(struct image *img, struct patch *patch)
2871 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2872 unsigned char sha1[20];
2875 * For safety, we require patch index line to contain
2876 * full 40-byte textual SHA1 for old and new, at least for now.
2878 if (strlen(patch->old_sha1_prefix) != 40 ||
2879 strlen(patch->new_sha1_prefix) != 40 ||
2880 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2881 get_sha1_hex(patch->new_sha1_prefix, sha1))
2882 return error("cannot apply binary patch to '%s' "
2883 "without full index line", name);
2885 if (patch->old_name) {
2887 * See if the old one matches what the patch
2888 * applies to.
2890 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2891 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2892 return error("the patch applies to '%s' (%s), "
2893 "which does not match the "
2894 "current contents.",
2895 name, sha1_to_hex(sha1));
2897 else {
2898 /* Otherwise, the old one must be empty. */
2899 if (img->len)
2900 return error("the patch applies to an empty "
2901 "'%s' but it is not empty", name);
2904 get_sha1_hex(patch->new_sha1_prefix, sha1);
2905 if (is_null_sha1(sha1)) {
2906 clear_image(img);
2907 return 0; /* deletion patch */
2910 if (has_sha1_file(sha1)) {
2911 /* We already have the postimage */
2912 enum object_type type;
2913 unsigned long size;
2914 char *result;
2916 result = read_sha1_file(sha1, &type, &size);
2917 if (!result)
2918 return error("the necessary postimage %s for "
2919 "'%s' cannot be read",
2920 patch->new_sha1_prefix, name);
2921 clear_image(img);
2922 img->buf = result;
2923 img->len = size;
2924 } else {
2926 * We have verified buf matches the preimage;
2927 * apply the patch data to it, which is stored
2928 * in the patch->fragments->{patch,size}.
2930 if (apply_binary_fragment(img, patch))
2931 return error(_("binary patch does not apply to '%s'"),
2932 name);
2934 /* verify that the result matches */
2935 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2936 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2937 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
2938 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2941 return 0;
2944 static int apply_fragments(struct image *img, struct patch *patch)
2946 struct fragment *frag = patch->fragments;
2947 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2948 unsigned ws_rule = patch->ws_rule;
2949 unsigned inaccurate_eof = patch->inaccurate_eof;
2950 int nth = 0;
2952 if (patch->is_binary)
2953 return apply_binary(img, patch);
2955 while (frag) {
2956 nth++;
2957 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
2958 error(_("patch failed: %s:%ld"), name, frag->oldpos);
2959 if (!apply_with_reject)
2960 return -1;
2961 frag->rejected = 1;
2963 frag = frag->next;
2965 return 0;
2968 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2970 if (!ce)
2971 return 0;
2973 if (S_ISGITLINK(ce->ce_mode)) {
2974 strbuf_grow(buf, 100);
2975 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2976 } else {
2977 enum object_type type;
2978 unsigned long sz;
2979 char *result;
2981 result = read_sha1_file(ce->sha1, &type, &sz);
2982 if (!result)
2983 return -1;
2984 /* XXX read_sha1_file NUL-terminates */
2985 strbuf_attach(buf, result, sz, sz + 1);
2987 return 0;
2990 static struct patch *in_fn_table(const char *name)
2992 struct string_list_item *item;
2994 if (name == NULL)
2995 return NULL;
2997 item = string_list_lookup(&fn_table, name);
2998 if (item != NULL)
2999 return (struct patch *)item->util;
3001 return NULL;
3005 * item->util in the filename table records the status of the path.
3006 * Usually it points at a patch (whose result records the contents
3007 * of it after applying it), but it could be PATH_WAS_DELETED for a
3008 * path that a previously applied patch has already removed.
3010 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3011 #define PATH_WAS_DELETED ((struct patch *) -1)
3013 static int to_be_deleted(struct patch *patch)
3015 return patch == PATH_TO_BE_DELETED;
3018 static int was_deleted(struct patch *patch)
3020 return patch == PATH_WAS_DELETED;
3023 static void add_to_fn_table(struct patch *patch)
3025 struct string_list_item *item;
3028 * Always add new_name unless patch is a deletion
3029 * This should cover the cases for normal diffs,
3030 * file creations and copies
3032 if (patch->new_name != NULL) {
3033 item = string_list_insert(&fn_table, patch->new_name);
3034 item->util = patch;
3038 * store a failure on rename/deletion cases because
3039 * later chunks shouldn't patch old names
3041 if ((patch->new_name == NULL) || (patch->is_rename)) {
3042 item = string_list_insert(&fn_table, patch->old_name);
3043 item->util = PATH_WAS_DELETED;
3047 static void prepare_fn_table(struct patch *patch)
3050 * store information about incoming file deletion
3052 while (patch) {
3053 if ((patch->new_name == NULL) || (patch->is_rename)) {
3054 struct string_list_item *item;
3055 item = string_list_insert(&fn_table, patch->old_name);
3056 item->util = PATH_TO_BE_DELETED;
3058 patch = patch->next;
3062 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
3064 struct strbuf buf = STRBUF_INIT;
3065 struct image image;
3066 size_t len;
3067 char *img;
3068 struct patch *tpatch;
3070 if (!(patch->is_copy || patch->is_rename) &&
3071 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
3072 if (was_deleted(tpatch)) {
3073 return error(_("patch %s has been renamed/deleted"),
3074 patch->old_name);
3076 /* We have a patched copy in memory; use that. */
3077 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
3078 } else if (cached) {
3079 if (read_file_or_gitlink(ce, &buf))
3080 return error(_("read of %s failed"), patch->old_name);
3081 } else if (patch->old_name) {
3082 if (S_ISGITLINK(patch->old_mode)) {
3083 if (ce) {
3084 read_file_or_gitlink(ce, &buf);
3085 } else {
3087 * There is no way to apply subproject
3088 * patch without looking at the index.
3089 * NEEDSWORK: shouldn't this be flagged
3090 * as an error???
3092 free_fragment_list(patch->fragments);
3093 patch->fragments = NULL;
3095 } else {
3096 if (read_old_data(st, patch->old_name, &buf))
3097 return error(_("read of %s failed"), patch->old_name);
3101 img = strbuf_detach(&buf, &len);
3102 prepare_image(&image, img, len, !patch->is_binary);
3104 if (apply_fragments(&image, patch) < 0)
3105 return -1; /* note with --reject this succeeds. */
3106 patch->result = image.buf;
3107 patch->resultsize = image.len;
3108 add_to_fn_table(patch);
3109 free(image.line_allocated);
3111 if (0 < patch->is_delete && patch->resultsize)
3112 return error(_("removal patch leaves file contents"));
3114 return 0;
3117 static int check_to_create_blob(const char *new_name, int ok_if_exists)
3119 struct stat nst;
3120 if (!lstat(new_name, &nst)) {
3121 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3122 return 0;
3124 * A leading component of new_name might be a symlink
3125 * that is going to be removed with this patch, but
3126 * still pointing at somewhere that has the path.
3127 * In such a case, path "new_name" does not exist as
3128 * far as git is concerned.
3130 if (has_symlink_leading_path(new_name, strlen(new_name)))
3131 return 0;
3133 return error(_("%s: already exists in working directory"), new_name);
3135 else if ((errno != ENOENT) && (errno != ENOTDIR))
3136 return error("%s: %s", new_name, strerror(errno));
3137 return 0;
3140 static int verify_index_match(struct cache_entry *ce, struct stat *st)
3142 if (S_ISGITLINK(ce->ce_mode)) {
3143 if (!S_ISDIR(st->st_mode))
3144 return -1;
3145 return 0;
3147 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3150 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3152 const char *old_name = patch->old_name;
3153 struct patch *tpatch = NULL;
3154 int stat_ret = 0;
3155 unsigned st_mode = 0;
3158 * Make sure that we do not have local modifications from the
3159 * index when we are looking at the index. Also make sure
3160 * we have the preimage file to be patched in the work tree,
3161 * unless --cached, which tells git to apply only in the index.
3163 if (!old_name)
3164 return 0;
3166 assert(patch->is_new <= 0);
3168 if (!(patch->is_copy || patch->is_rename) &&
3169 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3170 if (was_deleted(tpatch))
3171 return error(_("%s: has been deleted/renamed"), old_name);
3172 st_mode = tpatch->new_mode;
3173 } else if (!cached) {
3174 stat_ret = lstat(old_name, st);
3175 if (stat_ret && errno != ENOENT)
3176 return error(_("%s: %s"), old_name, strerror(errno));
3179 if (to_be_deleted(tpatch))
3180 tpatch = NULL;
3182 if (check_index && !tpatch) {
3183 int pos = cache_name_pos(old_name, strlen(old_name));
3184 if (pos < 0) {
3185 if (patch->is_new < 0)
3186 goto is_new;
3187 return error(_("%s: does not exist in index"), old_name);
3189 *ce = active_cache[pos];
3190 if (stat_ret < 0) {
3191 struct checkout costate;
3192 /* checkout */
3193 memset(&costate, 0, sizeof(costate));
3194 costate.base_dir = "";
3195 costate.refresh_cache = 1;
3196 if (checkout_entry(*ce, &costate, NULL) ||
3197 lstat(old_name, st))
3198 return -1;
3200 if (!cached && verify_index_match(*ce, st))
3201 return error(_("%s: does not match index"), old_name);
3202 if (cached)
3203 st_mode = (*ce)->ce_mode;
3204 } else if (stat_ret < 0) {
3205 if (patch->is_new < 0)
3206 goto is_new;
3207 return error(_("%s: %s"), old_name, strerror(errno));
3210 if (!cached && !tpatch)
3211 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3213 if (patch->is_new < 0)
3214 patch->is_new = 0;
3215 if (!patch->old_mode)
3216 patch->old_mode = st_mode;
3217 if ((st_mode ^ patch->old_mode) & S_IFMT)
3218 return error(_("%s: wrong type"), old_name);
3219 if (st_mode != patch->old_mode)
3220 warning(_("%s has type %o, expected %o"),
3221 old_name, st_mode, patch->old_mode);
3222 if (!patch->new_mode && !patch->is_delete)
3223 patch->new_mode = st_mode;
3224 return 0;
3226 is_new:
3227 patch->is_new = 1;
3228 patch->is_delete = 0;
3229 free(patch->old_name);
3230 patch->old_name = NULL;
3231 return 0;
3235 * Check and apply the patch in-core; leave the result in patch->result
3236 * for the caller to write it out to the final destination.
3238 static int check_patch(struct patch *patch)
3240 struct stat st;
3241 const char *old_name = patch->old_name;
3242 const char *new_name = patch->new_name;
3243 const char *name = old_name ? old_name : new_name;
3244 struct cache_entry *ce = NULL;
3245 struct patch *tpatch;
3246 int ok_if_exists;
3247 int status;
3249 patch->rejected = 1; /* we will drop this after we succeed */
3251 status = check_preimage(patch, &ce, &st);
3252 if (status)
3253 return status;
3254 old_name = patch->old_name;
3256 if ((tpatch = in_fn_table(new_name)) &&
3257 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3259 * A type-change diff is always split into a patch to
3260 * delete old, immediately followed by a patch to
3261 * create new (see diff.c::run_diff()); in such a case
3262 * it is Ok that the entry to be deleted by the
3263 * previous patch is still in the working tree and in
3264 * the index.
3266 ok_if_exists = 1;
3267 else
3268 ok_if_exists = 0;
3270 if (new_name &&
3271 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3272 if (check_index &&
3273 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3274 !ok_if_exists)
3275 return error(_("%s: already exists in index"), new_name);
3276 if (!cached) {
3277 int err = check_to_create_blob(new_name, ok_if_exists);
3278 if (err)
3279 return err;
3281 if (!patch->new_mode) {
3282 if (0 < patch->is_new)
3283 patch->new_mode = S_IFREG | 0644;
3284 else
3285 patch->new_mode = patch->old_mode;
3289 if (new_name && old_name) {
3290 int same = !strcmp(old_name, new_name);
3291 if (!patch->new_mode)
3292 patch->new_mode = patch->old_mode;
3293 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3294 if (same)
3295 return error(_("new mode (%o) of %s does not "
3296 "match old mode (%o)"),
3297 patch->new_mode, new_name,
3298 patch->old_mode);
3299 else
3300 return error(_("new mode (%o) of %s does not "
3301 "match old mode (%o) of %s"),
3302 patch->new_mode, new_name,
3303 patch->old_mode, old_name);
3307 if (apply_data(patch, &st, ce) < 0)
3308 return error(_("%s: patch does not apply"), name);
3309 patch->rejected = 0;
3310 return 0;
3313 static int check_patch_list(struct patch *patch)
3315 int err = 0;
3317 prepare_fn_table(patch);
3318 while (patch) {
3319 if (apply_verbosely)
3320 say_patch_name(stderr,
3321 _("Checking patch %s..."), patch);
3322 err |= check_patch(patch);
3323 patch = patch->next;
3325 return err;
3328 /* This function tries to read the sha1 from the current index */
3329 static int get_current_sha1(const char *path, unsigned char *sha1)
3331 int pos;
3333 if (read_cache() < 0)
3334 return -1;
3335 pos = cache_name_pos(path, strlen(path));
3336 if (pos < 0)
3337 return -1;
3338 hashcpy(sha1, active_cache[pos]->sha1);
3339 return 0;
3342 /* Build an index that contains the just the files needed for a 3way merge */
3343 static void build_fake_ancestor(struct patch *list, const char *filename)
3345 struct patch *patch;
3346 struct index_state result = { NULL };
3347 int fd;
3349 /* Once we start supporting the reverse patch, it may be
3350 * worth showing the new sha1 prefix, but until then...
3352 for (patch = list; patch; patch = patch->next) {
3353 const unsigned char *sha1_ptr;
3354 unsigned char sha1[20];
3355 struct cache_entry *ce;
3356 const char *name;
3358 name = patch->old_name ? patch->old_name : patch->new_name;
3359 if (0 < patch->is_new)
3360 continue;
3361 else if (get_sha1(patch->old_sha1_prefix, sha1))
3362 /* git diff has no index line for mode/type changes */
3363 if (!patch->lines_added && !patch->lines_deleted) {
3364 if (get_current_sha1(patch->old_name, sha1))
3365 die("mode change for %s, which is not "
3366 "in current HEAD", name);
3367 sha1_ptr = sha1;
3368 } else
3369 die("sha1 information is lacking or useless "
3370 "(%s).", name);
3371 else
3372 sha1_ptr = sha1;
3374 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3375 if (!ce)
3376 die(_("make_cache_entry failed for path '%s'"), name);
3377 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3378 die ("Could not add %s to temporary index", name);
3381 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3382 if (fd < 0 || write_index(&result, fd) || close(fd))
3383 die ("Could not write temporary index to %s", filename);
3385 discard_index(&result);
3388 static void stat_patch_list(struct patch *patch)
3390 int files, adds, dels;
3392 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3393 files++;
3394 adds += patch->lines_added;
3395 dels += patch->lines_deleted;
3396 show_stats(patch);
3399 print_stat_summary(stdout, files, adds, dels);
3402 static void numstat_patch_list(struct patch *patch)
3404 for ( ; patch; patch = patch->next) {
3405 const char *name;
3406 name = patch->new_name ? patch->new_name : patch->old_name;
3407 if (patch->is_binary)
3408 printf("-\t-\t");
3409 else
3410 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3411 write_name_quoted(name, stdout, line_termination);
3415 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3417 if (mode)
3418 printf(" %s mode %06o %s\n", newdelete, mode, name);
3419 else
3420 printf(" %s %s\n", newdelete, name);
3423 static void show_mode_change(struct patch *p, int show_name)
3425 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3426 if (show_name)
3427 printf(" mode change %06o => %06o %s\n",
3428 p->old_mode, p->new_mode, p->new_name);
3429 else
3430 printf(" mode change %06o => %06o\n",
3431 p->old_mode, p->new_mode);
3435 static void show_rename_copy(struct patch *p)
3437 const char *renamecopy = p->is_rename ? "rename" : "copy";
3438 const char *old, *new;
3440 /* Find common prefix */
3441 old = p->old_name;
3442 new = p->new_name;
3443 while (1) {
3444 const char *slash_old, *slash_new;
3445 slash_old = strchr(old, '/');
3446 slash_new = strchr(new, '/');
3447 if (!slash_old ||
3448 !slash_new ||
3449 slash_old - old != slash_new - new ||
3450 memcmp(old, new, slash_new - new))
3451 break;
3452 old = slash_old + 1;
3453 new = slash_new + 1;
3455 /* p->old_name thru old is the common prefix, and old and new
3456 * through the end of names are renames
3458 if (old != p->old_name)
3459 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3460 (int)(old - p->old_name), p->old_name,
3461 old, new, p->score);
3462 else
3463 printf(" %s %s => %s (%d%%)\n", renamecopy,
3464 p->old_name, p->new_name, p->score);
3465 show_mode_change(p, 0);
3468 static void summary_patch_list(struct patch *patch)
3470 struct patch *p;
3472 for (p = patch; p; p = p->next) {
3473 if (p->is_new)
3474 show_file_mode_name("create", p->new_mode, p->new_name);
3475 else if (p->is_delete)
3476 show_file_mode_name("delete", p->old_mode, p->old_name);
3477 else {
3478 if (p->is_rename || p->is_copy)
3479 show_rename_copy(p);
3480 else {
3481 if (p->score) {
3482 printf(" rewrite %s (%d%%)\n",
3483 p->new_name, p->score);
3484 show_mode_change(p, 0);
3486 else
3487 show_mode_change(p, 1);
3493 static void patch_stats(struct patch *patch)
3495 int lines = patch->lines_added + patch->lines_deleted;
3497 if (lines > max_change)
3498 max_change = lines;
3499 if (patch->old_name) {
3500 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3501 if (!len)
3502 len = strlen(patch->old_name);
3503 if (len > max_len)
3504 max_len = len;
3506 if (patch->new_name) {
3507 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3508 if (!len)
3509 len = strlen(patch->new_name);
3510 if (len > max_len)
3511 max_len = len;
3515 static void remove_file(struct patch *patch, int rmdir_empty)
3517 if (update_index) {
3518 if (remove_file_from_cache(patch->old_name) < 0)
3519 die(_("unable to remove %s from index"), patch->old_name);
3521 if (!cached) {
3522 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3523 remove_path(patch->old_name);
3528 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3530 struct stat st;
3531 struct cache_entry *ce;
3532 int namelen = strlen(path);
3533 unsigned ce_size = cache_entry_size(namelen);
3535 if (!update_index)
3536 return;
3538 ce = xcalloc(1, ce_size);
3539 memcpy(ce->name, path, namelen);
3540 ce->ce_mode = create_ce_mode(mode);
3541 ce->ce_flags = namelen;
3542 if (S_ISGITLINK(mode)) {
3543 const char *s = buf;
3545 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3546 die(_("corrupt patch for subproject %s"), path);
3547 } else {
3548 if (!cached) {
3549 if (lstat(path, &st) < 0)
3550 die_errno(_("unable to stat newly created file '%s'"),
3551 path);
3552 fill_stat_cache_info(ce, &st);
3554 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3555 die(_("unable to create backing store for newly created file %s"), path);
3557 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3558 die(_("unable to add cache entry for %s"), path);
3561 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3563 int fd;
3564 struct strbuf nbuf = STRBUF_INIT;
3566 if (S_ISGITLINK(mode)) {
3567 struct stat st;
3568 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3569 return 0;
3570 return mkdir(path, 0777);
3573 if (has_symlinks && S_ISLNK(mode))
3574 /* Although buf:size is counted string, it also is NUL
3575 * terminated.
3577 return symlink(buf, path);
3579 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3580 if (fd < 0)
3581 return -1;
3583 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3584 size = nbuf.len;
3585 buf = nbuf.buf;
3587 write_or_die(fd, buf, size);
3588 strbuf_release(&nbuf);
3590 if (close(fd) < 0)
3591 die_errno(_("closing file '%s'"), path);
3592 return 0;
3596 * We optimistically assume that the directories exist,
3597 * which is true 99% of the time anyway. If they don't,
3598 * we create them and try again.
3600 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3602 if (cached)
3603 return;
3604 if (!try_create_file(path, mode, buf, size))
3605 return;
3607 if (errno == ENOENT) {
3608 if (safe_create_leading_directories(path))
3609 return;
3610 if (!try_create_file(path, mode, buf, size))
3611 return;
3614 if (errno == EEXIST || errno == EACCES) {
3615 /* We may be trying to create a file where a directory
3616 * used to be.
3618 struct stat st;
3619 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3620 errno = EEXIST;
3623 if (errno == EEXIST) {
3624 unsigned int nr = getpid();
3626 for (;;) {
3627 char newpath[PATH_MAX];
3628 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3629 if (!try_create_file(newpath, mode, buf, size)) {
3630 if (!rename(newpath, path))
3631 return;
3632 unlink_or_warn(newpath);
3633 break;
3635 if (errno != EEXIST)
3636 break;
3637 ++nr;
3640 die_errno(_("unable to write file '%s' mode %o"), path, mode);
3643 static void create_file(struct patch *patch)
3645 char *path = patch->new_name;
3646 unsigned mode = patch->new_mode;
3647 unsigned long size = patch->resultsize;
3648 char *buf = patch->result;
3650 if (!mode)
3651 mode = S_IFREG | 0644;
3652 create_one_file(path, mode, buf, size);
3653 add_index_file(path, mode, buf, size);
3656 /* phase zero is to remove, phase one is to create */
3657 static void write_out_one_result(struct patch *patch, int phase)
3659 if (patch->is_delete > 0) {
3660 if (phase == 0)
3661 remove_file(patch, 1);
3662 return;
3664 if (patch->is_new > 0 || patch->is_copy) {
3665 if (phase == 1)
3666 create_file(patch);
3667 return;
3670 * Rename or modification boils down to the same
3671 * thing: remove the old, write the new
3673 if (phase == 0)
3674 remove_file(patch, patch->is_rename);
3675 if (phase == 1)
3676 create_file(patch);
3679 static int write_out_one_reject(struct patch *patch)
3681 FILE *rej;
3682 char namebuf[PATH_MAX];
3683 struct fragment *frag;
3684 int cnt = 0;
3685 struct strbuf sb = STRBUF_INIT;
3687 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3688 if (!frag->rejected)
3689 continue;
3690 cnt++;
3693 if (!cnt) {
3694 if (apply_verbosely)
3695 say_patch_name(stderr,
3696 _("Applied patch %s cleanly."), patch);
3697 return 0;
3700 /* This should not happen, because a removal patch that leaves
3701 * contents are marked "rejected" at the patch level.
3703 if (!patch->new_name)
3704 die(_("internal error"));
3706 /* Say this even without --verbose */
3707 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
3708 "Applying patch %%s with %d rejects...",
3709 cnt),
3710 cnt);
3711 say_patch_name(stderr, sb.buf, patch);
3712 strbuf_release(&sb);
3714 cnt = strlen(patch->new_name);
3715 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3716 cnt = ARRAY_SIZE(namebuf) - 5;
3717 warning(_("truncating .rej filename to %.*s.rej"),
3718 cnt - 1, patch->new_name);
3720 memcpy(namebuf, patch->new_name, cnt);
3721 memcpy(namebuf + cnt, ".rej", 5);
3723 rej = fopen(namebuf, "w");
3724 if (!rej)
3725 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
3727 /* Normal git tools never deal with .rej, so do not pretend
3728 * this is a git patch by saying --git nor give extended
3729 * headers. While at it, maybe please "kompare" that wants
3730 * the trailing TAB and some garbage at the end of line ;-).
3732 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3733 patch->new_name, patch->new_name);
3734 for (cnt = 1, frag = patch->fragments;
3735 frag;
3736 cnt++, frag = frag->next) {
3737 if (!frag->rejected) {
3738 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
3739 continue;
3741 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
3742 fprintf(rej, "%.*s", frag->size, frag->patch);
3743 if (frag->patch[frag->size-1] != '\n')
3744 fputc('\n', rej);
3746 fclose(rej);
3747 return -1;
3750 static int write_out_results(struct patch *list)
3752 int phase;
3753 int errs = 0;
3754 struct patch *l;
3756 for (phase = 0; phase < 2; phase++) {
3757 l = list;
3758 while (l) {
3759 if (l->rejected)
3760 errs = 1;
3761 else {
3762 write_out_one_result(l, phase);
3763 if (phase == 1 && write_out_one_reject(l))
3764 errs = 1;
3766 l = l->next;
3769 return errs;
3772 static struct lock_file lock_file;
3774 static struct string_list limit_by_name;
3775 static int has_include;
3776 static void add_name_limit(const char *name, int exclude)
3778 struct string_list_item *it;
3780 it = string_list_append(&limit_by_name, name);
3781 it->util = exclude ? NULL : (void *) 1;
3784 static int use_patch(struct patch *p)
3786 const char *pathname = p->new_name ? p->new_name : p->old_name;
3787 int i;
3789 /* Paths outside are not touched regardless of "--include" */
3790 if (0 < prefix_length) {
3791 int pathlen = strlen(pathname);
3792 if (pathlen <= prefix_length ||
3793 memcmp(prefix, pathname, prefix_length))
3794 return 0;
3797 /* See if it matches any of exclude/include rule */
3798 for (i = 0; i < limit_by_name.nr; i++) {
3799 struct string_list_item *it = &limit_by_name.items[i];
3800 if (!fnmatch(it->string, pathname, 0))
3801 return (it->util != NULL);
3805 * If we had any include, a path that does not match any rule is
3806 * not used. Otherwise, we saw bunch of exclude rules (or none)
3807 * and such a path is used.
3809 return !has_include;
3813 static void prefix_one(char **name)
3815 char *old_name = *name;
3816 if (!old_name)
3817 return;
3818 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3819 free(old_name);
3822 static void prefix_patches(struct patch *p)
3824 if (!prefix || p->is_toplevel_relative)
3825 return;
3826 for ( ; p; p = p->next) {
3827 prefix_one(&p->new_name);
3828 prefix_one(&p->old_name);
3832 #define INACCURATE_EOF (1<<0)
3833 #define RECOUNT (1<<1)
3835 static int apply_patch(int fd, const char *filename, int options)
3837 size_t offset;
3838 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
3839 struct patch *list = NULL, **listp = &list;
3840 int skipped_patch = 0;
3842 patch_input_file = filename;
3843 read_patch_file(&buf, fd);
3844 offset = 0;
3845 while (offset < buf.len) {
3846 struct patch *patch;
3847 int nr;
3849 patch = xcalloc(1, sizeof(*patch));
3850 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3851 patch->recount = !!(options & RECOUNT);
3852 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3853 if (nr < 0)
3854 break;
3855 if (apply_in_reverse)
3856 reverse_patches(patch);
3857 if (prefix)
3858 prefix_patches(patch);
3859 if (use_patch(patch)) {
3860 patch_stats(patch);
3861 *listp = patch;
3862 listp = &patch->next;
3864 else {
3865 free_patch(patch);
3866 skipped_patch++;
3868 offset += nr;
3871 if (!list && !skipped_patch)
3872 die(_("unrecognized input"));
3874 if (whitespace_error && (ws_error_action == die_on_ws_error))
3875 apply = 0;
3877 update_index = check_index && apply;
3878 if (update_index && newfd < 0)
3879 newfd = hold_locked_index(&lock_file, 1);
3881 if (check_index) {
3882 if (read_cache() < 0)
3883 die(_("unable to read index file"));
3886 if ((check || apply) &&
3887 check_patch_list(list) < 0 &&
3888 !apply_with_reject)
3889 exit(1);
3891 if (apply && write_out_results(list))
3892 exit(1);
3894 if (fake_ancestor)
3895 build_fake_ancestor(list, fake_ancestor);
3897 if (diffstat)
3898 stat_patch_list(list);
3900 if (numstat)
3901 numstat_patch_list(list);
3903 if (summary)
3904 summary_patch_list(list);
3906 free_patch_list(list);
3907 strbuf_release(&buf);
3908 string_list_clear(&fn_table, 0);
3909 return 0;
3912 static int git_apply_config(const char *var, const char *value, void *cb)
3914 if (!strcmp(var, "apply.whitespace"))
3915 return git_config_string(&apply_default_whitespace, var, value);
3916 else if (!strcmp(var, "apply.ignorewhitespace"))
3917 return git_config_string(&apply_default_ignorewhitespace, var, value);
3918 return git_default_config(var, value, cb);
3921 static int option_parse_exclude(const struct option *opt,
3922 const char *arg, int unset)
3924 add_name_limit(arg, 1);
3925 return 0;
3928 static int option_parse_include(const struct option *opt,
3929 const char *arg, int unset)
3931 add_name_limit(arg, 0);
3932 has_include = 1;
3933 return 0;
3936 static int option_parse_p(const struct option *opt,
3937 const char *arg, int unset)
3939 p_value = atoi(arg);
3940 p_value_known = 1;
3941 return 0;
3944 static int option_parse_z(const struct option *opt,
3945 const char *arg, int unset)
3947 if (unset)
3948 line_termination = '\n';
3949 else
3950 line_termination = 0;
3951 return 0;
3954 static int option_parse_space_change(const struct option *opt,
3955 const char *arg, int unset)
3957 if (unset)
3958 ws_ignore_action = ignore_ws_none;
3959 else
3960 ws_ignore_action = ignore_ws_change;
3961 return 0;
3964 static int option_parse_whitespace(const struct option *opt,
3965 const char *arg, int unset)
3967 const char **whitespace_option = opt->value;
3969 *whitespace_option = arg;
3970 parse_whitespace_option(arg);
3971 return 0;
3974 static int option_parse_directory(const struct option *opt,
3975 const char *arg, int unset)
3977 root_len = strlen(arg);
3978 if (root_len && arg[root_len - 1] != '/') {
3979 char *new_root;
3980 root = new_root = xmalloc(root_len + 2);
3981 strcpy(new_root, arg);
3982 strcpy(new_root + root_len++, "/");
3983 } else
3984 root = arg;
3985 return 0;
3988 int cmd_apply(int argc, const char **argv, const char *prefix_)
3990 int i;
3991 int errs = 0;
3992 int is_not_gitdir = !startup_info->have_repository;
3993 int force_apply = 0;
3995 const char *whitespace_option = NULL;
3997 struct option builtin_apply_options[] = {
3998 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),
3999 N_("don't apply changes matching the given path"),
4000 0, option_parse_exclude },
4001 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),
4002 N_("apply changes matching the given path"),
4003 0, option_parse_include },
4004 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),
4005 N_("remove <num> leading slashes from traditional diff paths"),
4006 0, option_parse_p },
4007 OPT_BOOLEAN(0, "no-add", &no_add,
4008 N_("ignore additions made by the patch")),
4009 OPT_BOOLEAN(0, "stat", &diffstat,
4010 N_("instead of applying the patch, output diffstat for the input")),
4011 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4012 OPT_NOOP_NOARG(0, "binary"),
4013 OPT_BOOLEAN(0, "numstat", &numstat,
4014 N_("shows number of added and deleted lines in decimal notation")),
4015 OPT_BOOLEAN(0, "summary", &summary,
4016 N_("instead of applying the patch, output a summary for the input")),
4017 OPT_BOOLEAN(0, "check", &check,
4018 N_("instead of applying the patch, see if the patch is applicable")),
4019 OPT_BOOLEAN(0, "index", &check_index,
4020 N_("make sure the patch is applicable to the current index")),
4021 OPT_BOOLEAN(0, "cached", &cached,
4022 N_("apply a patch without touching the working tree")),
4023 OPT_BOOLEAN(0, "apply", &force_apply,
4024 N_("also apply the patch (use with --stat/--summary/--check)")),
4025 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
4026 N_("build a temporary index based on embedded index information")),
4027 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
4028 N_("paths are separated with NUL character"),
4029 PARSE_OPT_NOARG, option_parse_z },
4030 OPT_INTEGER('C', NULL, &p_context,
4031 N_("ensure at least <n> lines of context match")),
4032 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),
4033 N_("detect new or modified lines that have whitespace errors"),
4034 0, option_parse_whitespace },
4035 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4036 N_("ignore changes in whitespace when finding context"),
4037 PARSE_OPT_NOARG, option_parse_space_change },
4038 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4039 N_("ignore changes in whitespace when finding context"),
4040 PARSE_OPT_NOARG, option_parse_space_change },
4041 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
4042 N_("apply the patch in reverse")),
4043 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
4044 N_("don't expect at least one line of context")),
4045 OPT_BOOLEAN(0, "reject", &apply_with_reject,
4046 N_("leave the rejected hunks in corresponding *.rej files")),
4047 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
4048 N_("allow overlapping hunks")),
4049 OPT__VERBOSE(&apply_verbosely, N_("be verbose")),
4050 OPT_BIT(0, "inaccurate-eof", &options,
4051 N_("tolerate incorrectly detected missing new-line at the end of file"),
4052 INACCURATE_EOF),
4053 OPT_BIT(0, "recount", &options,
4054 N_("do not trust the line counts in the hunk headers"),
4055 RECOUNT),
4056 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),
4057 N_("prepend <root> to all filenames"),
4058 0, option_parse_directory },
4059 OPT_END()
4062 prefix = prefix_;
4063 prefix_length = prefix ? strlen(prefix) : 0;
4064 git_config(git_apply_config, NULL);
4065 if (apply_default_whitespace)
4066 parse_whitespace_option(apply_default_whitespace);
4067 if (apply_default_ignorewhitespace)
4068 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4070 argc = parse_options(argc, argv, prefix, builtin_apply_options,
4071 apply_usage, 0);
4073 if (apply_with_reject)
4074 apply = apply_verbosely = 1;
4075 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
4076 apply = 0;
4077 if (check_index && is_not_gitdir)
4078 die(_("--index outside a repository"));
4079 if (cached) {
4080 if (is_not_gitdir)
4081 die(_("--cached outside a repository"));
4082 check_index = 1;
4084 for (i = 0; i < argc; i++) {
4085 const char *arg = argv[i];
4086 int fd;
4088 if (!strcmp(arg, "-")) {
4089 errs |= apply_patch(0, "<stdin>", options);
4090 read_stdin = 0;
4091 continue;
4092 } else if (0 < prefix_length)
4093 arg = prefix_filename(prefix, prefix_length, arg);
4095 fd = open(arg, O_RDONLY);
4096 if (fd < 0)
4097 die_errno(_("can't open patch '%s'"), arg);
4098 read_stdin = 0;
4099 set_default_whitespace_mode(whitespace_option);
4100 errs |= apply_patch(fd, arg, options);
4101 close(fd);
4103 set_default_whitespace_mode(whitespace_option);
4104 if (read_stdin)
4105 errs |= apply_patch(0, "<stdin>", options);
4106 if (whitespace_error) {
4107 if (squelch_whitespace_errors &&
4108 squelch_whitespace_errors < whitespace_error) {
4109 int squelched =
4110 whitespace_error - squelch_whitespace_errors;
4111 warning(Q_("squelched %d whitespace error",
4112 "squelched %d whitespace errors",
4113 squelched),
4114 squelched);
4116 if (ws_error_action == die_on_ws_error)
4117 die(Q_("%d line adds whitespace errors.",
4118 "%d lines add whitespace errors.",
4119 whitespace_error),
4120 whitespace_error);
4121 if (applied_after_fixing_ws && apply)
4122 warning("%d line%s applied after"
4123 " fixing whitespace errors.",
4124 applied_after_fixing_ws,
4125 applied_after_fixing_ws == 1 ? "" : "s");
4126 else if (whitespace_error)
4127 warning(Q_("%d line adds whitespace errors.",
4128 "%d lines add whitespace errors.",
4129 whitespace_error),
4130 whitespace_error);
4133 if (update_index) {
4134 if (write_cache(newfd, active_cache, active_nr) ||
4135 commit_locked_index(&lock_file))
4136 die(_("Unable to write new index file"));
4139 return !!errs;