git
/
apply.c
5194 строки · 134.8 Кб
1/*
2* apply.c
3*
4* Copyright (C) Linus Torvalds, 2005
5*
6* This applies patches on top of some (arbitrary) version of the SCM.
7*
8*/
9
10#define USE_THE_REPOSITORY_VARIABLE
11
12#include "git-compat-util.h"
13#include "abspath.h"
14#include "base85.h"
15#include "config.h"
16#include "object-store-ll.h"
17#include "delta.h"
18#include "diff.h"
19#include "dir.h"
20#include "environment.h"
21#include "gettext.h"
22#include "hex.h"
23#include "xdiff-interface.h"
24#include "merge-ll.h"
25#include "lockfile.h"
26#include "name-hash.h"
27#include "object-name.h"
28#include "object-file.h"
29#include "parse-options.h"
30#include "path.h"
31#include "quote.h"
32#include "read-cache.h"
33#include "rerere.h"
34#include "apply.h"
35#include "entry.h"
36#include "setup.h"
37#include "symlinks.h"
38#include "wildmatch.h"
39#include "ws.h"
40
41struct gitdiff_data {
42struct strbuf *root;
43int linenr;
44int p_value;
45};
46
47static void git_apply_config(void)
48{
49git_config_get_string("apply.whitespace", &apply_default_whitespace);
50git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace);
51git_config(git_xmerge_config, NULL);
52}
53
54static int parse_whitespace_option(struct apply_state *state, const char *option)
55{
56if (!option) {
57state->ws_error_action = warn_on_ws_error;
58return 0;
59}
60if (!strcmp(option, "warn")) {
61state->ws_error_action = warn_on_ws_error;
62return 0;
63}
64if (!strcmp(option, "nowarn")) {
65state->ws_error_action = nowarn_ws_error;
66return 0;
67}
68if (!strcmp(option, "error")) {
69state->ws_error_action = die_on_ws_error;
70return 0;
71}
72if (!strcmp(option, "error-all")) {
73state->ws_error_action = die_on_ws_error;
74state->squelch_whitespace_errors = 0;
75return 0;
76}
77if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
78state->ws_error_action = correct_ws_error;
79return 0;
80}
81/*
82* Please update $__git_whitespacelist in git-completion.bash,
83* Documentation/git-apply.txt, and Documentation/git-am.txt
84* when you add new options.
85*/
86return error(_("unrecognized whitespace option '%s'"), option);
87}
88
89static int parse_ignorewhitespace_option(struct apply_state *state,
90const char *option)
91{
92if (!option || !strcmp(option, "no") ||
93!strcmp(option, "false") || !strcmp(option, "never") ||
94!strcmp(option, "none")) {
95state->ws_ignore_action = ignore_ws_none;
96return 0;
97}
98if (!strcmp(option, "change")) {
99state->ws_ignore_action = ignore_ws_change;
100return 0;
101}
102return error(_("unrecognized whitespace ignore option '%s'"), option);
103}
104
105int init_apply_state(struct apply_state *state,
106struct repository *repo,
107const char *prefix)
108{
109memset(state, 0, sizeof(*state));
110state->prefix = prefix;
111state->repo = repo;
112state->apply = 1;
113state->line_termination = '\n';
114state->p_value = 1;
115state->p_context = UINT_MAX;
116state->squelch_whitespace_errors = 5;
117state->ws_error_action = warn_on_ws_error;
118state->ws_ignore_action = ignore_ws_none;
119state->linenr = 1;
120string_list_init_nodup(&state->fn_table);
121string_list_init_nodup(&state->limit_by_name);
122strset_init(&state->removed_symlinks);
123strset_init(&state->kept_symlinks);
124strbuf_init(&state->root, 0);
125
126git_apply_config();
127if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
128return -1;
129if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
130return -1;
131return 0;
132}
133
134void clear_apply_state(struct apply_state *state)
135{
136string_list_clear(&state->limit_by_name, 0);
137strset_clear(&state->removed_symlinks);
138strset_clear(&state->kept_symlinks);
139strbuf_release(&state->root);
140FREE_AND_NULL(state->fake_ancestor);
141
142/* &state->fn_table is cleared at the end of apply_patch() */
143}
144
145static void mute_routine(const char *msg UNUSED, va_list params UNUSED)
146{
147/* do nothing */
148}
149
150int check_apply_state(struct apply_state *state, int force_apply)
151{
152int is_not_gitdir = !startup_info->have_repository;
153
154if (state->apply_with_reject && state->threeway)
155return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
156if (state->threeway) {
157if (is_not_gitdir)
158return error(_("'%s' outside a repository"), "--3way");
159state->check_index = 1;
160}
161if (state->apply_with_reject) {
162state->apply = 1;
163if (state->apply_verbosity == verbosity_normal)
164state->apply_verbosity = verbosity_verbose;
165}
166if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
167state->apply = 0;
168if (state->check_index && is_not_gitdir)
169return error(_("'%s' outside a repository"), "--index");
170if (state->cached) {
171if (is_not_gitdir)
172return error(_("'%s' outside a repository"), "--cached");
173state->check_index = 1;
174}
175if (state->ita_only && (state->check_index || is_not_gitdir))
176state->ita_only = 0;
177if (state->check_index)
178state->unsafe_paths = 0;
179
180if (state->apply_verbosity <= verbosity_silent) {
181state->saved_error_routine = get_error_routine();
182state->saved_warn_routine = get_warn_routine();
183set_error_routine(mute_routine);
184set_warn_routine(mute_routine);
185}
186
187return 0;
188}
189
190static void set_default_whitespace_mode(struct apply_state *state)
191{
192if (!state->whitespace_option && !apply_default_whitespace)
193state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
194}
195
196/*
197* This represents one "hunk" from a patch, starting with
198* "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
199* patch text is pointed at by patch, and its byte length
200* is stored in size. leading and trailing are the number
201* of context lines.
202*/
203struct fragment {
204unsigned long leading, trailing;
205unsigned long oldpos, oldlines;
206unsigned long newpos, newlines;
207/*
208* 'patch' is usually borrowed from buf in apply_patch(),
209* but some codepaths store an allocated buffer.
210*/
211const char *patch;
212unsigned free_patch:1,
213rejected:1;
214int size;
215int linenr;
216struct fragment *next;
217};
218
219/*
220* When dealing with a binary patch, we reuse "leading" field
221* to store the type of the binary hunk, either deflated "delta"
222* or deflated "literal".
223*/
224#define binary_patch_method leading
225#define BINARY_DELTA_DEFLATED 1
226#define BINARY_LITERAL_DEFLATED 2
227
228static void free_fragment_list(struct fragment *list)
229{
230while (list) {
231struct fragment *next = list->next;
232if (list->free_patch)
233free((char *)list->patch);
234free(list);
235list = next;
236}
237}
238
239void release_patch(struct patch *patch)
240{
241free_fragment_list(patch->fragments);
242free(patch->def_name);
243free(patch->old_name);
244free(patch->new_name);
245free(patch->result);
246}
247
248static void free_patch(struct patch *patch)
249{
250release_patch(patch);
251free(patch);
252}
253
254static void free_patch_list(struct patch *list)
255{
256while (list) {
257struct patch *next = list->next;
258free_patch(list);
259list = next;
260}
261}
262
263/*
264* A line in a file, len-bytes long (includes the terminating LF,
265* except for an incomplete line at the end if the file ends with
266* one), and its contents hashes to 'hash'.
267*/
268struct line {
269size_t len;
270unsigned hash : 24;
271unsigned flag : 8;
272#define LINE_COMMON 1
273#define LINE_PATCHED 2
274};
275
276/*
277* This represents a "file", which is an array of "lines".
278*/
279struct image {
280char *buf;
281size_t len;
282size_t nr;
283size_t alloc;
284struct line *line_allocated;
285struct line *line;
286};
287
288static uint32_t hash_line(const char *cp, size_t len)
289{
290size_t i;
291uint32_t h;
292for (i = 0, h = 0; i < len; i++) {
293if (!isspace(cp[i])) {
294h = h * 3 + (cp[i] & 0xff);
295}
296}
297return h;
298}
299
300/*
301* Compare lines s1 of length n1 and s2 of length n2, ignoring
302* whitespace difference. Returns 1 if they match, 0 otherwise
303*/
304static int fuzzy_matchlines(const char *s1, size_t n1,
305const char *s2, size_t n2)
306{
307const char *end1 = s1 + n1;
308const char *end2 = s2 + n2;
309
310/* ignore line endings */
311while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
312end1--;
313while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
314end2--;
315
316while (s1 < end1 && s2 < end2) {
317if (isspace(*s1)) {
318/*
319* Skip whitespace. We check on both buffers
320* because we don't want "a b" to match "ab".
321*/
322if (!isspace(*s2))
323return 0;
324while (s1 < end1 && isspace(*s1))
325s1++;
326while (s2 < end2 && isspace(*s2))
327s2++;
328} else if (*s1++ != *s2++)
329return 0;
330}
331
332/* If we reached the end on one side only, lines don't match. */
333return s1 == end1 && s2 == end2;
334}
335
336static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
337{
338ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
339img->line_allocated[img->nr].len = len;
340img->line_allocated[img->nr].hash = hash_line(bol, len);
341img->line_allocated[img->nr].flag = flag;
342img->nr++;
343}
344
345/*
346* "buf" has the file contents to be patched (read from various sources).
347* attach it to "image" and add line-based index to it.
348* "image" now owns the "buf".
349*/
350static void prepare_image(struct image *image, char *buf, size_t len,
351int prepare_linetable)
352{
353const char *cp, *ep;
354
355memset(image, 0, sizeof(*image));
356image->buf = buf;
357image->len = len;
358
359if (!prepare_linetable)
360return;
361
362ep = image->buf + image->len;
363cp = image->buf;
364while (cp < ep) {
365const char *next;
366for (next = cp; next < ep && *next != '\n'; next++)
367;
368if (next < ep)
369next++;
370add_line_info(image, cp, next - cp, 0);
371cp = next;
372}
373image->line = image->line_allocated;
374}
375
376static void clear_image(struct image *image)
377{
378free(image->buf);
379free(image->line_allocated);
380memset(image, 0, sizeof(*image));
381}
382
383/* fmt must contain _one_ %s and no other substitution */
384static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
385{
386struct strbuf sb = STRBUF_INIT;
387
388if (patch->old_name && patch->new_name &&
389strcmp(patch->old_name, patch->new_name)) {
390quote_c_style(patch->old_name, &sb, NULL, 0);
391strbuf_addstr(&sb, " => ");
392quote_c_style(patch->new_name, &sb, NULL, 0);
393} else {
394const char *n = patch->new_name;
395if (!n)
396n = patch->old_name;
397quote_c_style(n, &sb, NULL, 0);
398}
399fprintf(output, fmt, sb.buf);
400fputc('\n', output);
401strbuf_release(&sb);
402}
403
404#define SLOP (16)
405
406/*
407* apply.c isn't equipped to handle arbitrarily large patches, because
408* it intermingles `unsigned long` with `int` for the type used to store
409* buffer lengths.
410*
411* Only process patches that are just shy of 1 GiB large in order to
412* avoid any truncation or overflow issues.
413*/
414#define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
415
416static int read_patch_file(struct strbuf *sb, int fd)
417{
418if (strbuf_read(sb, fd, 0) < 0)
419return error_errno(_("failed to read patch"));
420else if (sb->len >= MAX_APPLY_SIZE)
421return error(_("patch too large"));
422/*
423* Make sure that we have some slop in the buffer
424* so that we can do speculative "memcmp" etc, and
425* see to it that it is NUL-filled.
426*/
427strbuf_grow(sb, SLOP);
428memset(sb->buf + sb->len, 0, SLOP);
429return 0;
430}
431
432static unsigned long linelen(const char *buffer, unsigned long size)
433{
434unsigned long len = 0;
435while (size--) {
436len++;
437if (*buffer++ == '\n')
438break;
439}
440return len;
441}
442
443static int is_dev_null(const char *str)
444{
445return skip_prefix(str, "/dev/null", &str) && isspace(*str);
446}
447
448#define TERM_SPACE 1
449#define TERM_TAB 2
450
451static int name_terminate(int c, int terminate)
452{
453if (c == ' ' && !(terminate & TERM_SPACE))
454return 0;
455if (c == '\t' && !(terminate & TERM_TAB))
456return 0;
457
458return 1;
459}
460
461/* remove double slashes to make --index work with such filenames */
462static char *squash_slash(char *name)
463{
464int i = 0, j = 0;
465
466if (!name)
467return NULL;
468
469while (name[i]) {
470if ((name[j++] = name[i++]) == '/')
471while (name[i] == '/')
472i++;
473}
474name[j] = '\0';
475return name;
476}
477
478static char *find_name_gnu(struct strbuf *root,
479const char *line,
480int p_value)
481{
482struct strbuf name = STRBUF_INIT;
483char *cp;
484
485/*
486* Proposed "new-style" GNU patch/diff format; see
487* https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
488*/
489if (unquote_c_style(&name, line, NULL)) {
490strbuf_release(&name);
491return NULL;
492}
493
494for (cp = name.buf; p_value; p_value--) {
495cp = strchr(cp, '/');
496if (!cp) {
497strbuf_release(&name);
498return NULL;
499}
500cp++;
501}
502
503strbuf_remove(&name, 0, cp - name.buf);
504if (root->len)
505strbuf_insert(&name, 0, root->buf, root->len);
506return squash_slash(strbuf_detach(&name, NULL));
507}
508
509static size_t sane_tz_len(const char *line, size_t len)
510{
511const char *tz, *p;
512
513if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
514return 0;
515tz = line + len - strlen(" +0500");
516
517if (tz[1] != '+' && tz[1] != '-')
518return 0;
519
520for (p = tz + 2; p != line + len; p++)
521if (!isdigit(*p))
522return 0;
523
524return line + len - tz;
525}
526
527static size_t tz_with_colon_len(const char *line, size_t len)
528{
529const char *tz, *p;
530
531if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
532return 0;
533tz = line + len - strlen(" +08:00");
534
535if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
536return 0;
537p = tz + 2;
538if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
539!isdigit(*p++) || !isdigit(*p++))
540return 0;
541
542return line + len - tz;
543}
544
545static size_t date_len(const char *line, size_t len)
546{
547const char *date, *p;
548
549if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
550return 0;
551p = date = line + len - strlen("72-02-05");
552
553if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
554!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
555!isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
556return 0;
557
558if (date - line >= strlen("19") &&
559isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
560date -= strlen("19");
561
562return line + len - date;
563}
564
565static size_t short_time_len(const char *line, size_t len)
566{
567const char *time, *p;
568
569if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
570return 0;
571p = time = line + len - strlen(" 07:01:32");
572
573/* Permit 1-digit hours? */
574if (*p++ != ' ' ||
575!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
576!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
577!isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
578return 0;
579
580return line + len - time;
581}
582
583static size_t fractional_time_len(const char *line, size_t len)
584{
585const char *p;
586size_t n;
587
588/* Expected format: 19:41:17.620000023 */
589if (!len || !isdigit(line[len - 1]))
590return 0;
591p = line + len - 1;
592
593/* Fractional seconds. */
594while (p > line && isdigit(*p))
595p--;
596if (*p != '.')
597return 0;
598
599/* Hours, minutes, and whole seconds. */
600n = short_time_len(line, p - line);
601if (!n)
602return 0;
603
604return line + len - p + n;
605}
606
607static size_t trailing_spaces_len(const char *line, size_t len)
608{
609const char *p;
610
611/* Expected format: ' ' x (1 or more) */
612if (!len || line[len - 1] != ' ')
613return 0;
614
615p = line + len;
616while (p != line) {
617p--;
618if (*p != ' ')
619return line + len - (p + 1);
620}
621
622/* All spaces! */
623return len;
624}
625
626static size_t diff_timestamp_len(const char *line, size_t len)
627{
628const char *end = line + len;
629size_t n;
630
631/*
632* Posix: 2010-07-05 19:41:17
633* GNU: 2010-07-05 19:41:17.620000023 -0500
634*/
635
636if (!isdigit(end[-1]))
637return 0;
638
639n = sane_tz_len(line, end - line);
640if (!n)
641n = tz_with_colon_len(line, end - line);
642end -= n;
643
644n = short_time_len(line, end - line);
645if (!n)
646n = fractional_time_len(line, end - line);
647end -= n;
648
649n = date_len(line, end - line);
650if (!n) /* No date. Too bad. */
651return 0;
652end -= n;
653
654if (end == line) /* No space before date. */
655return 0;
656if (end[-1] == '\t') { /* Success! */
657end--;
658return line + len - end;
659}
660if (end[-1] != ' ') /* No space before date. */
661return 0;
662
663/* Whitespace damage. */
664end -= trailing_spaces_len(line, end - line);
665return line + len - end;
666}
667
668static char *find_name_common(struct strbuf *root,
669const char *line,
670const char *def,
671int p_value,
672const char *end,
673int terminate)
674{
675int len;
676const char *start = NULL;
677
678if (p_value == 0)
679start = line;
680while (line != end) {
681char c = *line;
682
683if (!end && isspace(c)) {
684if (c == '\n')
685break;
686if (name_terminate(c, terminate))
687break;
688}
689line++;
690if (c == '/' && !--p_value)
691start = line;
692}
693if (!start)
694return squash_slash(xstrdup_or_null(def));
695len = line - start;
696if (!len)
697return squash_slash(xstrdup_or_null(def));
698
699/*
700* Generally we prefer the shorter name, especially
701* if the other one is just a variation of that with
702* something else tacked on to the end (ie "file.orig"
703* or "file~").
704*/
705if (def) {
706int deflen = strlen(def);
707if (deflen < len && !strncmp(start, def, deflen))
708return squash_slash(xstrdup(def));
709}
710
711if (root->len) {
712char *ret = xstrfmt("%s%.*s", root->buf, len, start);
713return squash_slash(ret);
714}
715
716return squash_slash(xmemdupz(start, len));
717}
718
719static char *find_name(struct strbuf *root,
720const char *line,
721char *def,
722int p_value,
723int terminate)
724{
725if (*line == '"') {
726char *name = find_name_gnu(root, line, p_value);
727if (name)
728return name;
729}
730
731return find_name_common(root, line, def, p_value, NULL, terminate);
732}
733
734static char *find_name_traditional(struct strbuf *root,
735const char *line,
736char *def,
737int p_value)
738{
739size_t len;
740size_t date_len;
741
742if (*line == '"') {
743char *name = find_name_gnu(root, line, p_value);
744if (name)
745return name;
746}
747
748len = strchrnul(line, '\n') - line;
749date_len = diff_timestamp_len(line, len);
750if (!date_len)
751return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
752len -= date_len;
753
754return find_name_common(root, line, def, p_value, line + len, 0);
755}
756
757/*
758* Given the string after "--- " or "+++ ", guess the appropriate
759* p_value for the given patch.
760*/
761static int guess_p_value(struct apply_state *state, const char *nameline)
762{
763char *name, *cp;
764int val = -1;
765
766if (is_dev_null(nameline))
767return -1;
768name = find_name_traditional(&state->root, nameline, NULL, 0);
769if (!name)
770return -1;
771cp = strchr(name, '/');
772if (!cp)
773val = 0;
774else if (state->prefix) {
775/*
776* Does it begin with "a/$our-prefix" and such? Then this is
777* very likely to apply to our directory.
778*/
779if (starts_with(name, state->prefix))
780val = count_slashes(state->prefix);
781else {
782cp++;
783if (starts_with(cp, state->prefix))
784val = count_slashes(state->prefix) + 1;
785}
786}
787free(name);
788return val;
789}
790
791/*
792* Does the ---/+++ line have the POSIX timestamp after the last HT?
793* GNU diff puts epoch there to signal a creation/deletion event. Is
794* this such a timestamp?
795*/
796static int has_epoch_timestamp(const char *nameline)
797{
798/*
799* We are only interested in epoch timestamp; any non-zero
800* fraction cannot be one, hence "(\.0+)?" in the regexp below.
801* For the same reason, the date must be either 1969-12-31 or
802* 1970-01-01, and the seconds part must be "00".
803*/
804const char stamp_regexp[] =
805"^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
806" "
807"([-+][0-2][0-9]:?[0-5][0-9])\n";
808const char *timestamp = NULL, *cp, *colon;
809static regex_t *stamp;
810regmatch_t m[10];
811int zoneoffset, epoch_hour, hour, minute;
812int status;
813
814for (cp = nameline; *cp != '\n'; cp++) {
815if (*cp == '\t')
816timestamp = cp + 1;
817}
818if (!timestamp)
819return 0;
820
821/*
822* YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
823* (west of GMT) or 1970-01-01 (east of GMT)
824*/
825if (skip_prefix(timestamp, "1969-12-31 ", ×tamp))
826epoch_hour = 24;
827else if (skip_prefix(timestamp, "1970-01-01 ", ×tamp))
828epoch_hour = 0;
829else
830return 0;
831
832if (!stamp) {
833stamp = xmalloc(sizeof(*stamp));
834if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
835warning(_("Cannot prepare timestamp regexp %s"),
836stamp_regexp);
837return 0;
838}
839}
840
841status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
842if (status) {
843if (status != REG_NOMATCH)
844warning(_("regexec returned %d for input: %s"),
845status, timestamp);
846return 0;
847}
848
849hour = strtol(timestamp, NULL, 10);
850minute = strtol(timestamp + m[1].rm_so, NULL, 10);
851
852zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
853if (*colon == ':')
854zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
855else
856zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
857if (timestamp[m[3].rm_so] == '-')
858zoneoffset = -zoneoffset;
859
860return hour * 60 + minute - zoneoffset == epoch_hour * 60;
861}
862
863/*
864* Get the name etc info from the ---/+++ lines of a traditional patch header
865*
866* FIXME! The end-of-filename heuristics are kind of screwy. For existing
867* files, we can happily check the index for a match, but for creating a
868* new file we should try to match whatever "patch" does. I have no idea.
869*/
870static int parse_traditional_patch(struct apply_state *state,
871const char *first,
872const char *second,
873struct patch *patch)
874{
875char *name;
876
877first += 4; /* skip "--- " */
878second += 4; /* skip "+++ " */
879if (!state->p_value_known) {
880int p, q;
881p = guess_p_value(state, first);
882q = guess_p_value(state, second);
883if (p < 0) p = q;
884if (0 <= p && p == q) {
885state->p_value = p;
886state->p_value_known = 1;
887}
888}
889if (is_dev_null(first)) {
890patch->is_new = 1;
891patch->is_delete = 0;
892name = find_name_traditional(&state->root, second, NULL, state->p_value);
893patch->new_name = name;
894} else if (is_dev_null(second)) {
895patch->is_new = 0;
896patch->is_delete = 1;
897name = find_name_traditional(&state->root, first, NULL, state->p_value);
898patch->old_name = name;
899} else {
900char *first_name;
901first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
902name = find_name_traditional(&state->root, second, first_name, state->p_value);
903free(first_name);
904if (has_epoch_timestamp(first)) {
905patch->is_new = 1;
906patch->is_delete = 0;
907patch->new_name = name;
908} else if (has_epoch_timestamp(second)) {
909patch->is_new = 0;
910patch->is_delete = 1;
911patch->old_name = name;
912} else {
913patch->old_name = name;
914patch->new_name = xstrdup_or_null(name);
915}
916}
917if (!name)
918return error(_("unable to find filename in patch at line %d"), state->linenr);
919
920return 0;
921}
922
923static int gitdiff_hdrend(struct gitdiff_data *state UNUSED,
924const char *line UNUSED,
925struct patch *patch UNUSED)
926{
927return 1;
928}
929
930/*
931* We're anal about diff header consistency, to make
932* sure that we don't end up having strange ambiguous
933* patches floating around.
934*
935* As a result, gitdiff_{old|new}name() will check
936* their names against any previous information, just
937* to make sure..
938*/
939#define DIFF_OLD_NAME 0
940#define DIFF_NEW_NAME 1
941
942static int gitdiff_verify_name(struct gitdiff_data *state,
943const char *line,
944int isnull,
945char **name,
946int side)
947{
948if (!*name && !isnull) {
949*name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
950return 0;
951}
952
953if (*name) {
954char *another;
955if (isnull)
956return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
957*name, state->linenr);
958another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
959if (!another || strcmp(another, *name)) {
960free(another);
961return error((side == DIFF_NEW_NAME) ?
962_("git apply: bad git-diff - inconsistent new filename on line %d") :
963_("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
964}
965free(another);
966} else {
967if (!is_dev_null(line))
968return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
969}
970
971return 0;
972}
973
974static int gitdiff_oldname(struct gitdiff_data *state,
975const char *line,
976struct patch *patch)
977{
978return gitdiff_verify_name(state, line,
979patch->is_new, &patch->old_name,
980DIFF_OLD_NAME);
981}
982
983static int gitdiff_newname(struct gitdiff_data *state,
984const char *line,
985struct patch *patch)
986{
987return gitdiff_verify_name(state, line,
988patch->is_delete, &patch->new_name,
989DIFF_NEW_NAME);
990}
991
992static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
993{
994char *end;
995*mode = strtoul(line, &end, 8);
996if (end == line || !isspace(*end))
997return error(_("invalid mode on line %d: %s"), linenr, line);
998*mode = canon_mode(*mode);
999return 0;
1000}
1001
1002static int gitdiff_oldmode(struct gitdiff_data *state,
1003const char *line,
1004struct patch *patch)
1005{
1006return parse_mode_line(line, state->linenr, &patch->old_mode);
1007}
1008
1009static int gitdiff_newmode(struct gitdiff_data *state,
1010const char *line,
1011struct patch *patch)
1012{
1013return parse_mode_line(line, state->linenr, &patch->new_mode);
1014}
1015
1016static int gitdiff_delete(struct gitdiff_data *state,
1017const char *line,
1018struct patch *patch)
1019{
1020patch->is_delete = 1;
1021free(patch->old_name);
1022patch->old_name = xstrdup_or_null(patch->def_name);
1023return gitdiff_oldmode(state, line, patch);
1024}
1025
1026static int gitdiff_newfile(struct gitdiff_data *state,
1027const char *line,
1028struct patch *patch)
1029{
1030patch->is_new = 1;
1031free(patch->new_name);
1032patch->new_name = xstrdup_or_null(patch->def_name);
1033return gitdiff_newmode(state, line, patch);
1034}
1035
1036static int gitdiff_copysrc(struct gitdiff_data *state,
1037const char *line,
1038struct patch *patch)
1039{
1040patch->is_copy = 1;
1041free(patch->old_name);
1042patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1043return 0;
1044}
1045
1046static int gitdiff_copydst(struct gitdiff_data *state,
1047const char *line,
1048struct patch *patch)
1049{
1050patch->is_copy = 1;
1051free(patch->new_name);
1052patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1053return 0;
1054}
1055
1056static int gitdiff_renamesrc(struct gitdiff_data *state,
1057const char *line,
1058struct patch *patch)
1059{
1060patch->is_rename = 1;
1061free(patch->old_name);
1062patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1063return 0;
1064}
1065
1066static int gitdiff_renamedst(struct gitdiff_data *state,
1067const char *line,
1068struct patch *patch)
1069{
1070patch->is_rename = 1;
1071free(patch->new_name);
1072patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1073return 0;
1074}
1075
1076static int gitdiff_similarity(struct gitdiff_data *state UNUSED,
1077const char *line,
1078struct patch *patch)
1079{
1080unsigned long val = strtoul(line, NULL, 10);
1081if (val <= 100)
1082patch->score = val;
1083return 0;
1084}
1085
1086static int gitdiff_dissimilarity(struct gitdiff_data *state UNUSED,
1087const char *line,
1088struct patch *patch)
1089{
1090unsigned long val = strtoul(line, NULL, 10);
1091if (val <= 100)
1092patch->score = val;
1093return 0;
1094}
1095
1096static int gitdiff_index(struct gitdiff_data *state,
1097const char *line,
1098struct patch *patch)
1099{
1100/*
1101* index line is N hexadecimal, "..", N hexadecimal,
1102* and optional space with octal mode.
1103*/
1104const char *ptr, *eol;
1105int len;
1106const unsigned hexsz = the_hash_algo->hexsz;
1107
1108ptr = strchr(line, '.');
1109if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
1110return 0;
1111len = ptr - line;
1112memcpy(patch->old_oid_prefix, line, len);
1113patch->old_oid_prefix[len] = 0;
1114
1115line = ptr + 2;
1116ptr = strchr(line, ' ');
1117eol = strchrnul(line, '\n');
1118
1119if (!ptr || eol < ptr)
1120ptr = eol;
1121len = ptr - line;
1122
1123if (hexsz < len)
1124return 0;
1125memcpy(patch->new_oid_prefix, line, len);
1126patch->new_oid_prefix[len] = 0;
1127if (*ptr == ' ')
1128return gitdiff_oldmode(state, ptr + 1, patch);
1129return 0;
1130}
1131
1132/*
1133* This is normal for a diff that doesn't change anything: we'll fall through
1134* into the next diff. Tell the parser to break out.
1135*/
1136static int gitdiff_unrecognized(struct gitdiff_data *state UNUSED,
1137const char *line UNUSED,
1138struct patch *patch UNUSED)
1139{
1140return 1;
1141}
1142
1143/*
1144* Skip p_value leading components from "line"; as we do not accept
1145* absolute paths, return NULL in that case.
1146*/
1147static const char *skip_tree_prefix(int p_value,
1148const char *line,
1149int llen)
1150{
1151int nslash;
1152int i;
1153
1154if (!p_value)
1155return (llen && line[0] == '/') ? NULL : line;
1156
1157nslash = p_value;
1158for (i = 0; i < llen; i++) {
1159int ch = line[i];
1160if (ch == '/' && --nslash <= 0)
1161return (i == 0) ? NULL : &line[i + 1];
1162}
1163return NULL;
1164}
1165
1166/*
1167* This is to extract the same name that appears on "diff --git"
1168* line. We do not find and return anything if it is a rename
1169* patch, and it is OK because we will find the name elsewhere.
1170* We need to reliably find name only when it is mode-change only,
1171* creation or deletion of an empty file. In any of these cases,
1172* both sides are the same name under a/ and b/ respectively.
1173*/
1174static char *git_header_name(int p_value,
1175const char *line,
1176int llen)
1177{
1178const char *name;
1179const char *second = NULL;
1180size_t len, line_len;
1181
1182line += strlen("diff --git ");
1183llen -= strlen("diff --git ");
1184
1185if (*line == '"') {
1186const char *cp;
1187struct strbuf first = STRBUF_INIT;
1188struct strbuf sp = STRBUF_INIT;
1189
1190if (unquote_c_style(&first, line, &second))
1191goto free_and_fail1;
1192
1193/* strip the a/b prefix including trailing slash */
1194cp = skip_tree_prefix(p_value, first.buf, first.len);
1195if (!cp)
1196goto free_and_fail1;
1197strbuf_remove(&first, 0, cp - first.buf);
1198
1199/*
1200* second points at one past closing dq of name.
1201* find the second name.
1202*/
1203while ((second < line + llen) && isspace(*second))
1204second++;
1205
1206if (line + llen <= second)
1207goto free_and_fail1;
1208if (*second == '"') {
1209if (unquote_c_style(&sp, second, NULL))
1210goto free_and_fail1;
1211cp = skip_tree_prefix(p_value, sp.buf, sp.len);
1212if (!cp)
1213goto free_and_fail1;
1214/* They must match, otherwise ignore */
1215if (strcmp(cp, first.buf))
1216goto free_and_fail1;
1217strbuf_release(&sp);
1218return strbuf_detach(&first, NULL);
1219}
1220
1221/* unquoted second */
1222cp = skip_tree_prefix(p_value, second, line + llen - second);
1223if (!cp)
1224goto free_and_fail1;
1225if (line + llen - cp != first.len ||
1226memcmp(first.buf, cp, first.len))
1227goto free_and_fail1;
1228return strbuf_detach(&first, NULL);
1229
1230free_and_fail1:
1231strbuf_release(&first);
1232strbuf_release(&sp);
1233return NULL;
1234}
1235
1236/* unquoted first name */
1237name = skip_tree_prefix(p_value, line, llen);
1238if (!name)
1239return NULL;
1240
1241/*
1242* since the first name is unquoted, a dq if exists must be
1243* the beginning of the second name.
1244*/
1245for (second = name; second < line + llen; second++) {
1246if (*second == '"') {
1247struct strbuf sp = STRBUF_INIT;
1248const char *np;
1249
1250if (unquote_c_style(&sp, second, NULL))
1251goto free_and_fail2;
1252
1253np = skip_tree_prefix(p_value, sp.buf, sp.len);
1254if (!np)
1255goto free_and_fail2;
1256
1257len = sp.buf + sp.len - np;
1258if (len < second - name &&
1259!strncmp(np, name, len) &&
1260isspace(name[len])) {
1261/* Good */
1262strbuf_remove(&sp, 0, np - sp.buf);
1263return strbuf_detach(&sp, NULL);
1264}
1265
1266free_and_fail2:
1267strbuf_release(&sp);
1268return NULL;
1269}
1270}
1271
1272/*
1273* Accept a name only if it shows up twice, exactly the same
1274* form.
1275*/
1276second = strchr(name, '\n');
1277if (!second)
1278return NULL;
1279line_len = second - name;
1280for (len = 0 ; ; len++) {
1281switch (name[len]) {
1282default:
1283continue;
1284case '\n':
1285return NULL;
1286case '\t': case ' ':
1287/*
1288* Is this the separator between the preimage
1289* and the postimage pathname? Again, we are
1290* only interested in the case where there is
1291* no rename, as this is only to set def_name
1292* and a rename patch has the names elsewhere
1293* in an unambiguous form.
1294*/
1295if (!name[len + 1])
1296return NULL; /* no postimage name */
1297second = skip_tree_prefix(p_value, name + len + 1,
1298line_len - (len + 1));
1299/*
1300* If we are at the SP at the end of a directory,
1301* skip_tree_prefix() may return NULL as that makes
1302* it appears as if we have an absolute path.
1303* Keep going to find another SP.
1304*/
1305if (!second)
1306continue;
1307
1308/*
1309* Does len bytes starting at "name" and "second"
1310* (that are separated by one HT or SP we just
1311* found) exactly match?
1312*/
1313if (second[len] == '\n' && !strncmp(name, second, len))
1314return xmemdupz(name, len);
1315}
1316}
1317}
1318
1319static int check_header_line(int linenr, struct patch *patch)
1320{
1321int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1322(patch->is_rename == 1) + (patch->is_copy == 1);
1323if (extensions > 1)
1324return error(_("inconsistent header lines %d and %d"),
1325patch->extension_linenr, linenr);
1326if (extensions && !patch->extension_linenr)
1327patch->extension_linenr = linenr;
1328return 0;
1329}
1330
1331int parse_git_diff_header(struct strbuf *root,
1332int *linenr,
1333int p_value,
1334const char *line,
1335int len,
1336unsigned int size,
1337struct patch *patch)
1338{
1339unsigned long offset;
1340struct gitdiff_data parse_hdr_state;
1341
1342/* A git diff has explicit new/delete information, so we don't guess */
1343patch->is_new = 0;
1344patch->is_delete = 0;
1345
1346/*
1347* Some things may not have the old name in the
1348* rest of the headers anywhere (pure mode changes,
1349* or removing or adding empty files), so we get
1350* the default name from the header.
1351*/
1352patch->def_name = git_header_name(p_value, line, len);
1353if (patch->def_name && root->len) {
1354char *s = xstrfmt("%s%s", root->buf, patch->def_name);
1355free(patch->def_name);
1356patch->def_name = s;
1357}
1358
1359line += len;
1360size -= len;
1361(*linenr)++;
1362parse_hdr_state.root = root;
1363parse_hdr_state.linenr = *linenr;
1364parse_hdr_state.p_value = p_value;
1365
1366for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
1367static const struct opentry {
1368const char *str;
1369int (*fn)(struct gitdiff_data *, const char *, struct patch *);
1370} optable[] = {
1371{ "@@ -", gitdiff_hdrend },
1372{ "--- ", gitdiff_oldname },
1373{ "+++ ", gitdiff_newname },
1374{ "old mode ", gitdiff_oldmode },
1375{ "new mode ", gitdiff_newmode },
1376{ "deleted file mode ", gitdiff_delete },
1377{ "new file mode ", gitdiff_newfile },
1378{ "copy from ", gitdiff_copysrc },
1379{ "copy to ", gitdiff_copydst },
1380{ "rename old ", gitdiff_renamesrc },
1381{ "rename new ", gitdiff_renamedst },
1382{ "rename from ", gitdiff_renamesrc },
1383{ "rename to ", gitdiff_renamedst },
1384{ "similarity index ", gitdiff_similarity },
1385{ "dissimilarity index ", gitdiff_dissimilarity },
1386{ "index ", gitdiff_index },
1387{ "", gitdiff_unrecognized },
1388};
1389int i;
1390
1391len = linelen(line, size);
1392if (!len || line[len-1] != '\n')
1393break;
1394for (i = 0; i < ARRAY_SIZE(optable); i++) {
1395const struct opentry *p = optable + i;
1396int oplen = strlen(p->str);
1397int res;
1398if (len < oplen || memcmp(p->str, line, oplen))
1399continue;
1400res = p->fn(&parse_hdr_state, line + oplen, patch);
1401if (res < 0)
1402return -1;
1403if (check_header_line(*linenr, patch))
1404return -1;
1405if (res > 0)
1406goto done;
1407break;
1408}
1409}
1410
1411done:
1412if (!patch->old_name && !patch->new_name) {
1413if (!patch->def_name) {
1414error(Q_("git diff header lacks filename information when removing "
1415"%d leading pathname component (line %d)",
1416"git diff header lacks filename information when removing "
1417"%d leading pathname components (line %d)",
1418parse_hdr_state.p_value),
1419parse_hdr_state.p_value, *linenr);
1420return -128;
1421}
1422patch->old_name = xstrdup(patch->def_name);
1423patch->new_name = xstrdup(patch->def_name);
1424}
1425if ((!patch->new_name && !patch->is_delete) ||
1426(!patch->old_name && !patch->is_new)) {
1427error(_("git diff header lacks filename information "
1428"(line %d)"), *linenr);
1429return -128;
1430}
1431patch->is_toplevel_relative = 1;
1432return offset;
1433}
1434
1435static int parse_num(const char *line, unsigned long *p)
1436{
1437char *ptr;
1438
1439if (!isdigit(*line))
1440return 0;
1441*p = strtoul(line, &ptr, 10);
1442return ptr - line;
1443}
1444
1445static int parse_range(const char *line, int len, int offset, const char *expect,
1446unsigned long *p1, unsigned long *p2)
1447{
1448int digits, ex;
1449
1450if (offset < 0 || offset >= len)
1451return -1;
1452line += offset;
1453len -= offset;
1454
1455digits = parse_num(line, p1);
1456if (!digits)
1457return -1;
1458
1459offset += digits;
1460line += digits;
1461len -= digits;
1462
1463*p2 = 1;
1464if (*line == ',') {
1465digits = parse_num(line+1, p2);
1466if (!digits)
1467return -1;
1468
1469offset += digits+1;
1470line += digits+1;
1471len -= digits+1;
1472}
1473
1474ex = strlen(expect);
1475if (ex > len)
1476return -1;
1477if (memcmp(line, expect, ex))
1478return -1;
1479
1480return offset + ex;
1481}
1482
1483static void recount_diff(const char *line, int size, struct fragment *fragment)
1484{
1485int oldlines = 0, newlines = 0, ret = 0;
1486
1487if (size < 1) {
1488warning("recount: ignore empty hunk");
1489return;
1490}
1491
1492for (;;) {
1493int len = linelen(line, size);
1494size -= len;
1495line += len;
1496
1497if (size < 1)
1498break;
1499
1500switch (*line) {
1501case ' ': case '\n':
1502newlines++;
1503/* fall through */
1504case '-':
1505oldlines++;
1506continue;
1507case '+':
1508newlines++;
1509continue;
1510case '\\':
1511continue;
1512case '@':
1513ret = size < 3 || !starts_with(line, "@@ ");
1514break;
1515case 'd':
1516ret = size < 5 || !starts_with(line, "diff ");
1517break;
1518default:
1519ret = -1;
1520break;
1521}
1522if (ret) {
1523warning(_("recount: unexpected line: %.*s"),
1524(int)linelen(line, size), line);
1525return;
1526}
1527break;
1528}
1529fragment->oldlines = oldlines;
1530fragment->newlines = newlines;
1531}
1532
1533/*
1534* Parse a unified diff fragment header of the
1535* form "@@ -a,b +c,d @@"
1536*/
1537static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1538{
1539int offset;
1540
1541if (!len || line[len-1] != '\n')
1542return -1;
1543
1544/* Figure out the number of lines in a fragment */
1545offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1546offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1547
1548return offset;
1549}
1550
1551/*
1552* Find file diff header
1553*
1554* Returns:
1555* -1 if no header was found
1556* -128 in case of error
1557* the size of the header in bytes (called "offset") otherwise
1558*/
1559static int find_header(struct apply_state *state,
1560const char *line,
1561unsigned long size,
1562int *hdrsize,
1563struct patch *patch)
1564{
1565unsigned long offset, len;
1566
1567patch->is_toplevel_relative = 0;
1568patch->is_rename = patch->is_copy = 0;
1569patch->is_new = patch->is_delete = -1;
1570patch->old_mode = patch->new_mode = 0;
1571patch->old_name = patch->new_name = NULL;
1572for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1573unsigned long nextlen;
1574
1575len = linelen(line, size);
1576if (!len)
1577break;
1578
1579/* Testing this early allows us to take a few shortcuts.. */
1580if (len < 6)
1581continue;
1582
1583/*
1584* Make sure we don't find any unconnected patch fragments.
1585* That's a sign that we didn't find a header, and that a
1586* patch has become corrupted/broken up.
1587*/
1588if (!memcmp("@@ -", line, 4)) {
1589struct fragment dummy;
1590if (parse_fragment_header(line, len, &dummy) < 0)
1591continue;
1592error(_("patch fragment without header at line %d: %.*s"),
1593state->linenr, (int)len-1, line);
1594return -128;
1595}
1596
1597if (size < len + 6)
1598break;
1599
1600/*
1601* Git patch? It might not have a real patch, just a rename
1602* or mode change, so we handle that specially
1603*/
1604if (!memcmp("diff --git ", line, 11)) {
1605int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
1606state->p_value, line, len,
1607size, patch);
1608if (git_hdr_len < 0)
1609return -128;
1610if (git_hdr_len <= len)
1611continue;
1612*hdrsize = git_hdr_len;
1613return offset;
1614}
1615
1616/* --- followed by +++ ? */
1617if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1618continue;
1619
1620/*
1621* We only accept unified patches, so we want it to
1622* at least have "@@ -a,b +c,d @@\n", which is 14 chars
1623* minimum ("@@ -0,0 +1 @@\n" is the shortest).
1624*/
1625nextlen = linelen(line + len, size - len);
1626if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1627continue;
1628
1629/* Ok, we'll consider it a patch */
1630if (parse_traditional_patch(state, line, line+len, patch))
1631return -128;
1632*hdrsize = len + nextlen;
1633state->linenr += 2;
1634return offset;
1635}
1636return -1;
1637}
1638
1639static void record_ws_error(struct apply_state *state,
1640unsigned result,
1641const char *line,
1642int len,
1643int linenr)
1644{
1645char *err;
1646
1647if (!result)
1648return;
1649
1650state->whitespace_error++;
1651if (state->squelch_whitespace_errors &&
1652state->squelch_whitespace_errors < state->whitespace_error)
1653return;
1654
1655err = whitespace_error_string(result);
1656if (state->apply_verbosity > verbosity_silent)
1657fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1658state->patch_input_file, linenr, err, len, line);
1659free(err);
1660}
1661
1662static void check_whitespace(struct apply_state *state,
1663const char *line,
1664int len,
1665unsigned ws_rule)
1666{
1667unsigned result = ws_check(line + 1, len - 1, ws_rule);
1668
1669record_ws_error(state, result, line + 1, len - 2, state->linenr);
1670}
1671
1672/*
1673* Check if the patch has context lines with CRLF or
1674* the patch wants to remove lines with CRLF.
1675*/
1676static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1677{
1678if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1679patch->ws_rule |= WS_CR_AT_EOL;
1680patch->crlf_in_old = 1;
1681}
1682}
1683
1684
1685/*
1686* Parse a unified diff. Note that this really needs to parse each
1687* fragment separately, since the only way to know the difference
1688* between a "---" that is part of a patch, and a "---" that starts
1689* the next patch is to look at the line counts..
1690*/
1691static int parse_fragment(struct apply_state *state,
1692const char *line,
1693unsigned long size,
1694struct patch *patch,
1695struct fragment *fragment)
1696{
1697int added, deleted;
1698int len = linelen(line, size), offset;
1699unsigned long oldlines, newlines;
1700unsigned long leading, trailing;
1701
1702offset = parse_fragment_header(line, len, fragment);
1703if (offset < 0)
1704return -1;
1705if (offset > 0 && patch->recount)
1706recount_diff(line + offset, size - offset, fragment);
1707oldlines = fragment->oldlines;
1708newlines = fragment->newlines;
1709leading = 0;
1710trailing = 0;
1711
1712/* Parse the thing.. */
1713line += len;
1714size -= len;
1715state->linenr++;
1716added = deleted = 0;
1717for (offset = len;
17180 < size;
1719offset += len, size -= len, line += len, state->linenr++) {
1720if (!oldlines && !newlines)
1721break;
1722len = linelen(line, size);
1723if (!len || line[len-1] != '\n')
1724return -1;
1725switch (*line) {
1726default:
1727return -1;
1728case '\n': /* newer GNU diff, an empty context line */
1729case ' ':
1730oldlines--;
1731newlines--;
1732if (!deleted && !added)
1733leading++;
1734trailing++;
1735check_old_for_crlf(patch, line, len);
1736if (!state->apply_in_reverse &&
1737state->ws_error_action == correct_ws_error)
1738check_whitespace(state, line, len, patch->ws_rule);
1739break;
1740case '-':
1741if (!state->apply_in_reverse)
1742check_old_for_crlf(patch, line, len);
1743if (state->apply_in_reverse &&
1744state->ws_error_action != nowarn_ws_error)
1745check_whitespace(state, line, len, patch->ws_rule);
1746deleted++;
1747oldlines--;
1748trailing = 0;
1749break;
1750case '+':
1751if (state->apply_in_reverse)
1752check_old_for_crlf(patch, line, len);
1753if (!state->apply_in_reverse &&
1754state->ws_error_action != nowarn_ws_error)
1755check_whitespace(state, line, len, patch->ws_rule);
1756added++;
1757newlines--;
1758trailing = 0;
1759break;
1760
1761/*
1762* We allow "\ No newline at end of file". Depending
1763* on locale settings when the patch was produced we
1764* don't know what this line looks like. The only
1765* thing we do know is that it begins with "\ ".
1766* Checking for 12 is just for sanity check -- any
1767* l10n of "\ No newline..." is at least that long.
1768*/
1769case '\\':
1770if (len < 12 || memcmp(line, "\\ ", 2))
1771return -1;
1772break;
1773}
1774}
1775if (oldlines || newlines)
1776return -1;
1777if (!patch->recount && !deleted && !added)
1778return -1;
1779
1780fragment->leading = leading;
1781fragment->trailing = trailing;
1782
1783/*
1784* If a fragment ends with an incomplete line, we failed to include
1785* it in the above loop because we hit oldlines == newlines == 0
1786* before seeing it.
1787*/
1788if (12 < size && !memcmp(line, "\\ ", 2))
1789offset += linelen(line, size);
1790
1791patch->lines_added += added;
1792patch->lines_deleted += deleted;
1793
1794if (0 < patch->is_new && oldlines)
1795return error(_("new file depends on old contents"));
1796if (0 < patch->is_delete && newlines)
1797return error(_("deleted file still has contents"));
1798return offset;
1799}
1800
1801/*
1802* We have seen "diff --git a/... b/..." header (or a traditional patch
1803* header). Read hunks that belong to this patch into fragments and hang
1804* them to the given patch structure.
1805*
1806* The (fragment->patch, fragment->size) pair points into the memory given
1807* by the caller, not a copy, when we return.
1808*
1809* Returns:
1810* -1 in case of error,
1811* the number of bytes in the patch otherwise.
1812*/
1813static int parse_single_patch(struct apply_state *state,
1814const char *line,
1815unsigned long size,
1816struct patch *patch)
1817{
1818unsigned long offset = 0;
1819unsigned long oldlines = 0, newlines = 0, context = 0;
1820struct fragment **fragp = &patch->fragments;
1821
1822while (size > 4 && !memcmp(line, "@@ -", 4)) {
1823struct fragment *fragment;
1824int len;
1825
1826CALLOC_ARRAY(fragment, 1);
1827fragment->linenr = state->linenr;
1828len = parse_fragment(state, line, size, patch, fragment);
1829if (len <= 0) {
1830free(fragment);
1831return error(_("corrupt patch at line %d"), state->linenr);
1832}
1833fragment->patch = line;
1834fragment->size = len;
1835oldlines += fragment->oldlines;
1836newlines += fragment->newlines;
1837context += fragment->leading + fragment->trailing;
1838
1839*fragp = fragment;
1840fragp = &fragment->next;
1841
1842offset += len;
1843line += len;
1844size -= len;
1845}
1846
1847/*
1848* If something was removed (i.e. we have old-lines) it cannot
1849* be creation, and if something was added it cannot be
1850* deletion. However, the reverse is not true; --unified=0
1851* patches that only add are not necessarily creation even
1852* though they do not have any old lines, and ones that only
1853* delete are not necessarily deletion.
1854*
1855* Unfortunately, a real creation/deletion patch do _not_ have
1856* any context line by definition, so we cannot safely tell it
1857* apart with --unified=0 insanity. At least if the patch has
1858* more than one hunk it is not creation or deletion.
1859*/
1860if (patch->is_new < 0 &&
1861(oldlines || (patch->fragments && patch->fragments->next)))
1862patch->is_new = 0;
1863if (patch->is_delete < 0 &&
1864(newlines || (patch->fragments && patch->fragments->next)))
1865patch->is_delete = 0;
1866
1867if (0 < patch->is_new && oldlines)
1868return error(_("new file %s depends on old contents"), patch->new_name);
1869if (0 < patch->is_delete && newlines)
1870return error(_("deleted file %s still has contents"), patch->old_name);
1871if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1872fprintf_ln(stderr,
1873_("** warning: "
1874"file %s becomes empty but is not deleted"),
1875patch->new_name);
1876
1877return offset;
1878}
1879
1880static inline int metadata_changes(struct patch *patch)
1881{
1882return patch->is_rename > 0 ||
1883patch->is_copy > 0 ||
1884patch->is_new > 0 ||
1885patch->is_delete ||
1886(patch->old_mode && patch->new_mode &&
1887patch->old_mode != patch->new_mode);
1888}
1889
1890static char *inflate_it(const void *data, unsigned long size,
1891unsigned long inflated_size)
1892{
1893git_zstream stream;
1894void *out;
1895int st;
1896
1897memset(&stream, 0, sizeof(stream));
1898
1899stream.next_in = (unsigned char *)data;
1900stream.avail_in = size;
1901stream.next_out = out = xmalloc(inflated_size);
1902stream.avail_out = inflated_size;
1903git_inflate_init(&stream);
1904st = git_inflate(&stream, Z_FINISH);
1905git_inflate_end(&stream);
1906if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1907free(out);
1908return NULL;
1909}
1910return out;
1911}
1912
1913/*
1914* Read a binary hunk and return a new fragment; fragment->patch
1915* points at an allocated memory that the caller must free, so
1916* it is marked as "->free_patch = 1".
1917*/
1918static struct fragment *parse_binary_hunk(struct apply_state *state,
1919char **buf_p,
1920unsigned long *sz_p,
1921int *status_p,
1922int *used_p)
1923{
1924/*
1925* Expect a line that begins with binary patch method ("literal"
1926* or "delta"), followed by the length of data before deflating.
1927* a sequence of 'length-byte' followed by base-85 encoded data
1928* should follow, terminated by a newline.
1929*
1930* Each 5-byte sequence of base-85 encodes up to 4 bytes,
1931* and we would limit the patch line to 66 characters,
1932* so one line can fit up to 13 groups that would decode
1933* to 52 bytes max. The length byte 'A'-'Z' corresponds
1934* to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1935*/
1936int llen, used;
1937unsigned long size = *sz_p;
1938char *buffer = *buf_p;
1939int patch_method;
1940unsigned long origlen;
1941char *data = NULL;
1942int hunk_size = 0;
1943struct fragment *frag;
1944
1945llen = linelen(buffer, size);
1946used = llen;
1947
1948*status_p = 0;
1949
1950if (starts_with(buffer, "delta ")) {
1951patch_method = BINARY_DELTA_DEFLATED;
1952origlen = strtoul(buffer + 6, NULL, 10);
1953}
1954else if (starts_with(buffer, "literal ")) {
1955patch_method = BINARY_LITERAL_DEFLATED;
1956origlen = strtoul(buffer + 8, NULL, 10);
1957}
1958else
1959return NULL;
1960
1961state->linenr++;
1962buffer += llen;
1963size -= llen;
1964while (1) {
1965int byte_length, max_byte_length, newsize;
1966llen = linelen(buffer, size);
1967used += llen;
1968state->linenr++;
1969if (llen == 1) {
1970/* consume the blank line */
1971buffer++;
1972size--;
1973break;
1974}
1975/*
1976* Minimum line is "A00000\n" which is 7-byte long,
1977* and the line length must be multiple of 5 plus 2.
1978*/
1979if ((llen < 7) || (llen-2) % 5)
1980goto corrupt;
1981max_byte_length = (llen - 2) / 5 * 4;
1982byte_length = *buffer;
1983if ('A' <= byte_length && byte_length <= 'Z')
1984byte_length = byte_length - 'A' + 1;
1985else if ('a' <= byte_length && byte_length <= 'z')
1986byte_length = byte_length - 'a' + 27;
1987else
1988goto corrupt;
1989/* if the input length was not multiple of 4, we would
1990* have filler at the end but the filler should never
1991* exceed 3 bytes
1992*/
1993if (max_byte_length < byte_length ||
1994byte_length <= max_byte_length - 4)
1995goto corrupt;
1996newsize = hunk_size + byte_length;
1997data = xrealloc(data, newsize);
1998if (decode_85(data + hunk_size, buffer + 1, byte_length))
1999goto corrupt;
2000hunk_size = newsize;
2001buffer += llen;
2002size -= llen;
2003}
2004
2005CALLOC_ARRAY(frag, 1);
2006frag->patch = inflate_it(data, hunk_size, origlen);
2007frag->free_patch = 1;
2008if (!frag->patch)
2009goto corrupt;
2010free(data);
2011frag->size = origlen;
2012*buf_p = buffer;
2013*sz_p = size;
2014*used_p = used;
2015frag->binary_patch_method = patch_method;
2016return frag;
2017
2018corrupt:
2019free(data);
2020*status_p = -1;
2021error(_("corrupt binary patch at line %d: %.*s"),
2022state->linenr-1, llen-1, buffer);
2023return NULL;
2024}
2025
2026/*
2027* Returns:
2028* -1 in case of error,
2029* the length of the parsed binary patch otherwise
2030*/
2031static int parse_binary(struct apply_state *state,
2032char *buffer,
2033unsigned long size,
2034struct patch *patch)
2035{
2036/*
2037* We have read "GIT binary patch\n"; what follows is a line
2038* that says the patch method (currently, either "literal" or
2039* "delta") and the length of data before deflating; a
2040* sequence of 'length-byte' followed by base-85 encoded data
2041* follows.
2042*
2043* When a binary patch is reversible, there is another binary
2044* hunk in the same format, starting with patch method (either
2045* "literal" or "delta") with the length of data, and a sequence
2046* of length-byte + base-85 encoded data, terminated with another
2047* empty line. This data, when applied to the postimage, produces
2048* the preimage.
2049*/
2050struct fragment *forward;
2051struct fragment *reverse;
2052int status;
2053int used, used_1;
2054
2055forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2056if (!forward && !status)
2057/* there has to be one hunk (forward hunk) */
2058return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2059if (status)
2060/* otherwise we already gave an error message */
2061return status;
2062
2063reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2064if (reverse)
2065used += used_1;
2066else if (status) {
2067/*
2068* Not having reverse hunk is not an error, but having
2069* a corrupt reverse hunk is.
2070*/
2071free((void*) forward->patch);
2072free(forward);
2073return status;
2074}
2075forward->next = reverse;
2076patch->fragments = forward;
2077patch->is_binary = 1;
2078return used;
2079}
2080
2081static void prefix_one(struct apply_state *state, char **name)
2082{
2083char *old_name = *name;
2084if (!old_name)
2085return;
2086*name = prefix_filename(state->prefix, *name);
2087free(old_name);
2088}
2089
2090static void prefix_patch(struct apply_state *state, struct patch *p)
2091{
2092if (!state->prefix || p->is_toplevel_relative)
2093return;
2094prefix_one(state, &p->new_name);
2095prefix_one(state, &p->old_name);
2096}
2097
2098/*
2099* include/exclude
2100*/
2101
2102static void add_name_limit(struct apply_state *state,
2103const char *name,
2104int exclude)
2105{
2106struct string_list_item *it;
2107
2108it = string_list_append(&state->limit_by_name, name);
2109it->util = exclude ? NULL : (void *) 1;
2110}
2111
2112static int use_patch(struct apply_state *state, struct patch *p)
2113{
2114const char *pathname = p->new_name ? p->new_name : p->old_name;
2115int i;
2116
2117/* Paths outside are not touched regardless of "--include" */
2118if (state->prefix && *state->prefix) {
2119const char *rest;
2120if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
2121return 0;
2122}
2123
2124/* See if it matches any of exclude/include rule */
2125for (i = 0; i < state->limit_by_name.nr; i++) {
2126struct string_list_item *it = &state->limit_by_name.items[i];
2127if (!wildmatch(it->string, pathname, 0))
2128return (it->util != NULL);
2129}
2130
2131/*
2132* If we had any include, a path that does not match any rule is
2133* not used. Otherwise, we saw bunch of exclude rules (or none)
2134* and such a path is used.
2135*/
2136return !state->has_include;
2137}
2138
2139/*
2140* Read the patch text in "buffer" that extends for "size" bytes; stop
2141* reading after seeing a single patch (i.e. changes to a single file).
2142* Create fragments (i.e. patch hunks) and hang them to the given patch.
2143*
2144* Returns:
2145* -1 if no header was found or parse_binary() failed,
2146* -128 on another error,
2147* the number of bytes consumed otherwise,
2148* so that the caller can call us again for the next patch.
2149*/
2150static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2151{
2152int hdrsize, patchsize;
2153int offset = find_header(state, buffer, size, &hdrsize, patch);
2154
2155if (offset < 0)
2156return offset;
2157
2158prefix_patch(state, patch);
2159
2160if (!use_patch(state, patch))
2161patch->ws_rule = 0;
2162else if (patch->new_name)
2163patch->ws_rule = whitespace_rule(state->repo->index,
2164patch->new_name);
2165else
2166patch->ws_rule = whitespace_rule(state->repo->index,
2167patch->old_name);
2168
2169patchsize = parse_single_patch(state,
2170buffer + offset + hdrsize,
2171size - offset - hdrsize,
2172patch);
2173
2174if (patchsize < 0)
2175return -128;
2176
2177if (!patchsize) {
2178static const char git_binary[] = "GIT binary patch\n";
2179int hd = hdrsize + offset;
2180unsigned long llen = linelen(buffer + hd, size - hd);
2181
2182if (llen == sizeof(git_binary) - 1 &&
2183!memcmp(git_binary, buffer + hd, llen)) {
2184int used;
2185state->linenr++;
2186used = parse_binary(state, buffer + hd + llen,
2187size - hd - llen, patch);
2188if (used < 0)
2189return -1;
2190if (used)
2191patchsize = used + llen;
2192else
2193patchsize = 0;
2194}
2195else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2196static const char *binhdr[] = {
2197"Binary files ",
2198"Files ",
2199NULL,
2200};
2201int i;
2202for (i = 0; binhdr[i]; i++) {
2203int len = strlen(binhdr[i]);
2204if (len < size - hd &&
2205!memcmp(binhdr[i], buffer + hd, len)) {
2206state->linenr++;
2207patch->is_binary = 1;
2208patchsize = llen;
2209break;
2210}
2211}
2212}
2213
2214/* Empty patch cannot be applied if it is a text patch
2215* without metadata change. A binary patch appears
2216* empty to us here.
2217*/
2218if ((state->apply || state->check) &&
2219(!patch->is_binary && !metadata_changes(patch))) {
2220error(_("patch with only garbage at line %d"), state->linenr);
2221return -128;
2222}
2223}
2224
2225return offset + hdrsize + patchsize;
2226}
2227
2228static void reverse_patches(struct patch *p)
2229{
2230for (; p; p = p->next) {
2231struct fragment *frag = p->fragments;
2232
2233SWAP(p->new_name, p->old_name);
2234if (p->new_mode)
2235SWAP(p->new_mode, p->old_mode);
2236SWAP(p->is_new, p->is_delete);
2237SWAP(p->lines_added, p->lines_deleted);
2238SWAP(p->old_oid_prefix, p->new_oid_prefix);
2239
2240for (; frag; frag = frag->next) {
2241SWAP(frag->newpos, frag->oldpos);
2242SWAP(frag->newlines, frag->oldlines);
2243}
2244}
2245}
2246
2247static const char pluses[] =
2248"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2249static const char minuses[]=
2250"----------------------------------------------------------------------";
2251
2252static void show_stats(struct apply_state *state, struct patch *patch)
2253{
2254struct strbuf qname = STRBUF_INIT;
2255char *cp = patch->new_name ? patch->new_name : patch->old_name;
2256int max, add, del;
2257
2258quote_c_style(cp, &qname, NULL, 0);
2259
2260/*
2261* "scale" the filename
2262*/
2263max = state->max_len;
2264if (max > 50)
2265max = 50;
2266
2267if (qname.len > max) {
2268cp = strchr(qname.buf + qname.len + 3 - max, '/');
2269if (!cp)
2270cp = qname.buf + qname.len + 3 - max;
2271strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2272}
2273
2274if (patch->is_binary) {
2275printf(" %-*s | Bin\n", max, qname.buf);
2276strbuf_release(&qname);
2277return;
2278}
2279
2280printf(" %-*s |", max, qname.buf);
2281strbuf_release(&qname);
2282
2283/*
2284* scale the add/delete
2285*/
2286max = max + state->max_change > 70 ? 70 - max : state->max_change;
2287add = patch->lines_added;
2288del = patch->lines_deleted;
2289
2290if (state->max_change > 0) {
2291int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2292add = (add * max + state->max_change / 2) / state->max_change;
2293del = total - add;
2294}
2295printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2296add, pluses, del, minuses);
2297}
2298
2299static int read_old_data(struct stat *st, struct patch *patch,
2300const char *path, struct strbuf *buf)
2301{
2302int conv_flags = patch->crlf_in_old ?
2303CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
2304switch (st->st_mode & S_IFMT) {
2305case S_IFLNK:
2306if (strbuf_readlink(buf, path, st->st_size) < 0)
2307return error(_("unable to read symlink %s"), path);
2308return 0;
2309case S_IFREG:
2310if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2311return error(_("unable to open or read %s"), path);
2312/*
2313* "git apply" without "--index/--cached" should never look
2314* at the index; the target file may not have been added to
2315* the index yet, and we may not even be in any Git repository.
2316* Pass NULL to convert_to_git() to stress this; the function
2317* should never look at the index when explicit crlf option
2318* is given.
2319*/
2320convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
2321return 0;
2322default:
2323return -1;
2324}
2325}
2326
2327/*
2328* Update the preimage, and the common lines in postimage,
2329* from buffer buf of length len. If postlen is 0 the postimage
2330* is updated in place, otherwise it's updated on a new buffer
2331* of length postlen
2332*/
2333
2334static void update_pre_post_images(struct image *preimage,
2335struct image *postimage,
2336char *buf,
2337size_t len, size_t postlen)
2338{
2339int i, ctx, reduced;
2340char *new_buf, *old_buf, *fixed;
2341struct image fixed_preimage;
2342
2343/*
2344* Update the preimage with whitespace fixes. Note that we
2345* are not losing preimage->buf -- apply_one_fragment() will
2346* free "oldlines".
2347*/
2348prepare_image(&fixed_preimage, buf, len, 1);
2349assert(postlen
2350? fixed_preimage.nr == preimage->nr
2351: fixed_preimage.nr <= preimage->nr);
2352for (i = 0; i < fixed_preimage.nr; i++)
2353fixed_preimage.line[i].flag = preimage->line[i].flag;
2354free(preimage->line_allocated);
2355*preimage = fixed_preimage;
2356
2357/*
2358* Adjust the common context lines in postimage. This can be
2359* done in-place when we are shrinking it with whitespace
2360* fixing, but needs a new buffer when ignoring whitespace or
2361* expanding leading tabs to spaces.
2362*
2363* We trust the caller to tell us if the update can be done
2364* in place (postlen==0) or not.
2365*/
2366old_buf = postimage->buf;
2367if (postlen)
2368new_buf = postimage->buf = xmalloc(postlen);
2369else
2370new_buf = old_buf;
2371fixed = preimage->buf;
2372
2373for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2374size_t l_len = postimage->line[i].len;
2375if (!(postimage->line[i].flag & LINE_COMMON)) {
2376/* an added line -- no counterparts in preimage */
2377memmove(new_buf, old_buf, l_len);
2378old_buf += l_len;
2379new_buf += l_len;
2380continue;
2381}
2382
2383/* a common context -- skip it in the original postimage */
2384old_buf += l_len;
2385
2386/* and find the corresponding one in the fixed preimage */
2387while (ctx < preimage->nr &&
2388!(preimage->line[ctx].flag & LINE_COMMON)) {
2389fixed += preimage->line[ctx].len;
2390ctx++;
2391}
2392
2393/*
2394* preimage is expected to run out, if the caller
2395* fixed addition of trailing blank lines.
2396*/
2397if (preimage->nr <= ctx) {
2398reduced++;
2399continue;
2400}
2401
2402/* and copy it in, while fixing the line length */
2403l_len = preimage->line[ctx].len;
2404memcpy(new_buf, fixed, l_len);
2405new_buf += l_len;
2406fixed += l_len;
2407postimage->line[i].len = l_len;
2408ctx++;
2409}
2410
2411if (postlen
2412? postlen < new_buf - postimage->buf
2413: postimage->len < new_buf - postimage->buf)
2414BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2415(int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));
2416
2417/* Fix the length of the whole thing */
2418postimage->len = new_buf - postimage->buf;
2419postimage->nr -= reduced;
2420}
2421
2422static int line_by_line_fuzzy_match(struct image *img,
2423struct image *preimage,
2424struct image *postimage,
2425unsigned long current,
2426int current_lno,
2427int preimage_limit)
2428{
2429int i;
2430size_t imgoff = 0;
2431size_t preoff = 0;
2432size_t postlen = postimage->len;
2433size_t extra_chars;
2434char *buf;
2435char *preimage_eof;
2436char *preimage_end;
2437struct strbuf fixed;
2438char *fixed_buf;
2439size_t fixed_len;
2440
2441for (i = 0; i < preimage_limit; i++) {
2442size_t prelen = preimage->line[i].len;
2443size_t imglen = img->line[current_lno+i].len;
2444
2445if (!fuzzy_matchlines(img->buf + current + imgoff, imglen,
2446preimage->buf + preoff, prelen))
2447return 0;
2448if (preimage->line[i].flag & LINE_COMMON)
2449postlen += imglen - prelen;
2450imgoff += imglen;
2451preoff += prelen;
2452}
2453
2454/*
2455* Ok, the preimage matches with whitespace fuzz.
2456*
2457* imgoff now holds the true length of the target that
2458* matches the preimage before the end of the file.
2459*
2460* Count the number of characters in the preimage that fall
2461* beyond the end of the file and make sure that all of them
2462* are whitespace characters. (This can only happen if
2463* we are removing blank lines at the end of the file.)
2464*/
2465buf = preimage_eof = preimage->buf + preoff;
2466for ( ; i < preimage->nr; i++)
2467preoff += preimage->line[i].len;
2468preimage_end = preimage->buf + preoff;
2469for ( ; buf < preimage_end; buf++)
2470if (!isspace(*buf))
2471return 0;
2472
2473/*
2474* Update the preimage and the common postimage context
2475* lines to use the same whitespace as the target.
2476* If whitespace is missing in the target (i.e.
2477* if the preimage extends beyond the end of the file),
2478* use the whitespace from the preimage.
2479*/
2480extra_chars = preimage_end - preimage_eof;
2481strbuf_init(&fixed, imgoff + extra_chars);
2482strbuf_add(&fixed, img->buf + current, imgoff);
2483strbuf_add(&fixed, preimage_eof, extra_chars);
2484fixed_buf = strbuf_detach(&fixed, &fixed_len);
2485update_pre_post_images(preimage, postimage,
2486fixed_buf, fixed_len, postlen);
2487return 1;
2488}
2489
2490static int match_fragment(struct apply_state *state,
2491struct image *img,
2492struct image *preimage,
2493struct image *postimage,
2494unsigned long current,
2495int current_lno,
2496unsigned ws_rule,
2497int match_beginning, int match_end)
2498{
2499int i;
2500const char *orig, *target;
2501struct strbuf fixed = STRBUF_INIT;
2502size_t postlen;
2503int preimage_limit;
2504int ret;
2505
2506if (preimage->nr + current_lno <= img->nr) {
2507/*
2508* The hunk falls within the boundaries of img.
2509*/
2510preimage_limit = preimage->nr;
2511if (match_end && (preimage->nr + current_lno != img->nr)) {
2512ret = 0;
2513goto out;
2514}
2515} else if (state->ws_error_action == correct_ws_error &&
2516(ws_rule & WS_BLANK_AT_EOF)) {
2517/*
2518* This hunk extends beyond the end of img, and we are
2519* removing blank lines at the end of the file. This
2520* many lines from the beginning of the preimage must
2521* match with img, and the remainder of the preimage
2522* must be blank.
2523*/
2524preimage_limit = img->nr - current_lno;
2525} else {
2526/*
2527* The hunk extends beyond the end of the img and
2528* we are not removing blanks at the end, so we
2529* should reject the hunk at this position.
2530*/
2531ret = 0;
2532goto out;
2533}
2534
2535if (match_beginning && current_lno) {
2536ret = 0;
2537goto out;
2538}
2539
2540/* Quick hash check */
2541for (i = 0; i < preimage_limit; i++) {
2542if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2543(preimage->line[i].hash != img->line[current_lno + i].hash)) {
2544ret = 0;
2545goto out;
2546}
2547}
2548
2549if (preimage_limit == preimage->nr) {
2550/*
2551* Do we have an exact match? If we were told to match
2552* at the end, size must be exactly at current+fragsize,
2553* otherwise current+fragsize must be still within the preimage,
2554* and either case, the old piece should match the preimage
2555* exactly.
2556*/
2557if ((match_end
2558? (current + preimage->len == img->len)
2559: (current + preimage->len <= img->len)) &&
2560!memcmp(img->buf + current, preimage->buf, preimage->len)) {
2561ret = 1;
2562goto out;
2563}
2564} else {
2565/*
2566* The preimage extends beyond the end of img, so
2567* there cannot be an exact match.
2568*
2569* There must be one non-blank context line that match
2570* a line before the end of img.
2571*/
2572const char *buf, *buf_end;
2573
2574buf = preimage->buf;
2575buf_end = buf;
2576for (i = 0; i < preimage_limit; i++)
2577buf_end += preimage->line[i].len;
2578
2579for ( ; buf < buf_end; buf++)
2580if (!isspace(*buf))
2581break;
2582if (buf == buf_end) {
2583ret = 0;
2584goto out;
2585}
2586}
2587
2588/*
2589* No exact match. If we are ignoring whitespace, run a line-by-line
2590* fuzzy matching. We collect all the line length information because
2591* we need it to adjust whitespace if we match.
2592*/
2593if (state->ws_ignore_action == ignore_ws_change) {
2594ret = line_by_line_fuzzy_match(img, preimage, postimage,
2595current, current_lno, preimage_limit);
2596goto out;
2597}
2598
2599if (state->ws_error_action != correct_ws_error) {
2600ret = 0;
2601goto out;
2602}
2603
2604/*
2605* The hunk does not apply byte-by-byte, but the hash says
2606* it might with whitespace fuzz. We weren't asked to
2607* ignore whitespace, we were asked to correct whitespace
2608* errors, so let's try matching after whitespace correction.
2609*
2610* While checking the preimage against the target, whitespace
2611* errors in both fixed, we count how large the corresponding
2612* postimage needs to be. The postimage prepared by
2613* apply_one_fragment() has whitespace errors fixed on added
2614* lines already, but the common lines were propagated as-is,
2615* which may become longer when their whitespace errors are
2616* fixed.
2617*/
2618
2619/* First count added lines in postimage */
2620postlen = 0;
2621for (i = 0; i < postimage->nr; i++) {
2622if (!(postimage->line[i].flag & LINE_COMMON))
2623postlen += postimage->line[i].len;
2624}
2625
2626/*
2627* The preimage may extend beyond the end of the file,
2628* but in this loop we will only handle the part of the
2629* preimage that falls within the file.
2630*/
2631strbuf_grow(&fixed, preimage->len + 1);
2632orig = preimage->buf;
2633target = img->buf + current;
2634for (i = 0; i < preimage_limit; i++) {
2635size_t oldlen = preimage->line[i].len;
2636size_t tgtlen = img->line[current_lno + i].len;
2637size_t fixstart = fixed.len;
2638struct strbuf tgtfix;
2639int match;
2640
2641/* Try fixing the line in the preimage */
2642ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2643
2644/* Try fixing the line in the target */
2645strbuf_init(&tgtfix, tgtlen);
2646ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2647
2648/*
2649* If they match, either the preimage was based on
2650* a version before our tree fixed whitespace breakage,
2651* or we are lacking a whitespace-fix patch the tree
2652* the preimage was based on already had (i.e. target
2653* has whitespace breakage, the preimage doesn't).
2654* In either case, we are fixing the whitespace breakages
2655* so we might as well take the fix together with their
2656* real change.
2657*/
2658match = (tgtfix.len == fixed.len - fixstart &&
2659!memcmp(tgtfix.buf, fixed.buf + fixstart,
2660fixed.len - fixstart));
2661
2662/* Add the length if this is common with the postimage */
2663if (preimage->line[i].flag & LINE_COMMON)
2664postlen += tgtfix.len;
2665
2666strbuf_release(&tgtfix);
2667if (!match) {
2668ret = 0;
2669goto out;
2670}
2671
2672orig += oldlen;
2673target += tgtlen;
2674}
2675
2676
2677/*
2678* Now handle the lines in the preimage that falls beyond the
2679* end of the file (if any). They will only match if they are
2680* empty or only contain whitespace (if WS_BLANK_AT_EOL is
2681* false).
2682*/
2683for ( ; i < preimage->nr; i++) {
2684size_t fixstart = fixed.len; /* start of the fixed preimage */
2685size_t oldlen = preimage->line[i].len;
2686int j;
2687
2688/* Try fixing the line in the preimage */
2689ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2690
2691for (j = fixstart; j < fixed.len; j++) {
2692if (!isspace(fixed.buf[j])) {
2693ret = 0;
2694goto out;
2695}
2696}
2697
2698
2699orig += oldlen;
2700}
2701
2702/*
2703* Yes, the preimage is based on an older version that still
2704* has whitespace breakages unfixed, and fixing them makes the
2705* hunk match. Update the context lines in the postimage.
2706*/
2707if (postlen < postimage->len)
2708postlen = 0;
2709update_pre_post_images(preimage, postimage,
2710fixed.buf, fixed.len, postlen);
2711
2712ret = 1;
2713
2714out:
2715strbuf_release(&fixed);
2716return ret;
2717}
2718
2719static int find_pos(struct apply_state *state,
2720struct image *img,
2721struct image *preimage,
2722struct image *postimage,
2723int line,
2724unsigned ws_rule,
2725int match_beginning, int match_end)
2726{
2727int i;
2728unsigned long backwards, forwards, current;
2729int backwards_lno, forwards_lno, current_lno;
2730
2731/*
2732* When running with --allow-overlap, it is possible that a hunk is
2733* seen that pretends to start at the beginning (but no longer does),
2734* and that *still* needs to match the end. So trust `match_end` more
2735* than `match_beginning`.
2736*/
2737if (state->allow_overlap && match_beginning && match_end &&
2738img->nr - preimage->nr != 0)
2739match_beginning = 0;
2740
2741/*
2742* If match_beginning or match_end is specified, there is no
2743* point starting from a wrong line that will never match and
2744* wander around and wait for a match at the specified end.
2745*/
2746if (match_beginning)
2747line = 0;
2748else if (match_end)
2749line = img->nr - preimage->nr;
2750
2751/*
2752* Because the comparison is unsigned, the following test
2753* will also take care of a negative line number that can
2754* result when match_end and preimage is larger than the target.
2755*/
2756if ((size_t) line > img->nr)
2757line = img->nr;
2758
2759current = 0;
2760for (i = 0; i < line; i++)
2761current += img->line[i].len;
2762
2763/*
2764* There's probably some smart way to do this, but I'll leave
2765* that to the smart and beautiful people. I'm simple and stupid.
2766*/
2767backwards = current;
2768backwards_lno = line;
2769forwards = current;
2770forwards_lno = line;
2771current_lno = line;
2772
2773for (i = 0; ; i++) {
2774if (match_fragment(state, img, preimage, postimage,
2775current, current_lno, ws_rule,
2776match_beginning, match_end))
2777return current_lno;
2778
2779again:
2780if (backwards_lno == 0 && forwards_lno == img->nr)
2781break;
2782
2783if (i & 1) {
2784if (backwards_lno == 0) {
2785i++;
2786goto again;
2787}
2788backwards_lno--;
2789backwards -= img->line[backwards_lno].len;
2790current = backwards;
2791current_lno = backwards_lno;
2792} else {
2793if (forwards_lno == img->nr) {
2794i++;
2795goto again;
2796}
2797forwards += img->line[forwards_lno].len;
2798forwards_lno++;
2799current = forwards;
2800current_lno = forwards_lno;
2801}
2802
2803}
2804return -1;
2805}
2806
2807static void remove_first_line(struct image *img)
2808{
2809img->buf += img->line[0].len;
2810img->len -= img->line[0].len;
2811img->line++;
2812img->nr--;
2813}
2814
2815static void remove_last_line(struct image *img)
2816{
2817img->len -= img->line[--img->nr].len;
2818}
2819
2820/*
2821* The change from "preimage" and "postimage" has been found to
2822* apply at applied_pos (counts in line numbers) in "img".
2823* Update "img" to remove "preimage" and replace it with "postimage".
2824*/
2825static void update_image(struct apply_state *state,
2826struct image *img,
2827int applied_pos,
2828struct image *preimage,
2829struct image *postimage)
2830{
2831/*
2832* remove the copy of preimage at offset in img
2833* and replace it with postimage
2834*/
2835int i, nr;
2836size_t remove_count, insert_count, applied_at = 0;
2837char *result;
2838int preimage_limit;
2839
2840/*
2841* If we are removing blank lines at the end of img,
2842* the preimage may extend beyond the end.
2843* If that is the case, we must be careful only to
2844* remove the part of the preimage that falls within
2845* the boundaries of img. Initialize preimage_limit
2846* to the number of lines in the preimage that falls
2847* within the boundaries.
2848*/
2849preimage_limit = preimage->nr;
2850if (preimage_limit > img->nr - applied_pos)
2851preimage_limit = img->nr - applied_pos;
2852
2853for (i = 0; i < applied_pos; i++)
2854applied_at += img->line[i].len;
2855
2856remove_count = 0;
2857for (i = 0; i < preimage_limit; i++)
2858remove_count += img->line[applied_pos + i].len;
2859insert_count = postimage->len;
2860
2861/* Adjust the contents */
2862result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2863memcpy(result, img->buf, applied_at);
2864memcpy(result + applied_at, postimage->buf, postimage->len);
2865memcpy(result + applied_at + postimage->len,
2866img->buf + (applied_at + remove_count),
2867img->len - (applied_at + remove_count));
2868free(img->buf);
2869img->buf = result;
2870img->len += insert_count - remove_count;
2871result[img->len] = '\0';
2872
2873/* Adjust the line table */
2874nr = img->nr + postimage->nr - preimage_limit;
2875if (preimage_limit < postimage->nr) {
2876/*
2877* NOTE: this knows that we never call remove_first_line()
2878* on anything other than pre/post image.
2879*/
2880REALLOC_ARRAY(img->line, nr);
2881img->line_allocated = img->line;
2882}
2883if (preimage_limit != postimage->nr)
2884MOVE_ARRAY(img->line + applied_pos + postimage->nr,
2885img->line + applied_pos + preimage_limit,
2886img->nr - (applied_pos + preimage_limit));
2887COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);
2888if (!state->allow_overlap)
2889for (i = 0; i < postimage->nr; i++)
2890img->line[applied_pos + i].flag |= LINE_PATCHED;
2891img->nr = nr;
2892}
2893
2894/*
2895* Use the patch-hunk text in "frag" to prepare two images (preimage and
2896* postimage) for the hunk. Find lines that match "preimage" in "img" and
2897* replace the part of "img" with "postimage" text.
2898*/
2899static int apply_one_fragment(struct apply_state *state,
2900struct image *img, struct fragment *frag,
2901int inaccurate_eof, unsigned ws_rule,
2902int nth_fragment)
2903{
2904int match_beginning, match_end;
2905const char *patch = frag->patch;
2906int size = frag->size;
2907char *old, *oldlines;
2908struct strbuf newlines;
2909int new_blank_lines_at_end = 0;
2910int found_new_blank_lines_at_end = 0;
2911int hunk_linenr = frag->linenr;
2912unsigned long leading, trailing;
2913int pos, applied_pos;
2914struct image preimage;
2915struct image postimage;
2916
2917memset(&preimage, 0, sizeof(preimage));
2918memset(&postimage, 0, sizeof(postimage));
2919oldlines = xmalloc(size);
2920strbuf_init(&newlines, size);
2921
2922old = oldlines;
2923while (size > 0) {
2924char first;
2925int len = linelen(patch, size);
2926int plen;
2927int added_blank_line = 0;
2928int is_blank_context = 0;
2929size_t start;
2930
2931if (!len)
2932break;
2933
2934/*
2935* "plen" is how much of the line we should use for
2936* the actual patch data. Normally we just remove the
2937* first character on the line, but if the line is
2938* followed by "\ No newline", then we also remove the
2939* last one (which is the newline, of course).
2940*/
2941plen = len - 1;
2942if (len < size && patch[len] == '\\')
2943plen--;
2944first = *patch;
2945if (state->apply_in_reverse) {
2946if (first == '-')
2947first = '+';
2948else if (first == '+')
2949first = '-';
2950}
2951
2952switch (first) {
2953case '\n':
2954/* Newer GNU diff, empty context line */
2955if (plen < 0)
2956/* ... followed by '\No newline'; nothing */
2957break;
2958*old++ = '\n';
2959strbuf_addch(&newlines, '\n');
2960add_line_info(&preimage, "\n", 1, LINE_COMMON);
2961add_line_info(&postimage, "\n", 1, LINE_COMMON);
2962is_blank_context = 1;
2963break;
2964case ' ':
2965if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2966ws_blank_line(patch + 1, plen))
2967is_blank_context = 1;
2968/* fallthrough */
2969case '-':
2970memcpy(old, patch + 1, plen);
2971add_line_info(&preimage, old, plen,
2972(first == ' ' ? LINE_COMMON : 0));
2973old += plen;
2974if (first == '-')
2975break;
2976/* fallthrough */
2977case '+':
2978/* --no-add does not add new lines */
2979if (first == '+' && state->no_add)
2980break;
2981
2982start = newlines.len;
2983if (first != '+' ||
2984!state->whitespace_error ||
2985state->ws_error_action != correct_ws_error) {
2986strbuf_add(&newlines, patch + 1, plen);
2987}
2988else {
2989ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2990}
2991add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2992(first == '+' ? 0 : LINE_COMMON));
2993if (first == '+' &&
2994(ws_rule & WS_BLANK_AT_EOF) &&
2995ws_blank_line(patch + 1, plen))
2996added_blank_line = 1;
2997break;
2998case '@': case '\\':
2999/* Ignore it, we already handled it */
3000break;
3001default:
3002if (state->apply_verbosity > verbosity_normal)
3003error(_("invalid start of line: '%c'"), first);
3004applied_pos = -1;
3005goto out;
3006}
3007if (added_blank_line) {
3008if (!new_blank_lines_at_end)
3009found_new_blank_lines_at_end = hunk_linenr;
3010new_blank_lines_at_end++;
3011}
3012else if (is_blank_context)
3013;
3014else
3015new_blank_lines_at_end = 0;
3016patch += len;
3017size -= len;
3018hunk_linenr++;
3019}
3020if (inaccurate_eof &&
3021old > oldlines && old[-1] == '\n' &&
3022newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
3023old--;
3024strbuf_setlen(&newlines, newlines.len - 1);
3025preimage.line_allocated[preimage.nr - 1].len--;
3026postimage.line_allocated[postimage.nr - 1].len--;
3027}
3028
3029leading = frag->leading;
3030trailing = frag->trailing;
3031
3032/*
3033* A hunk to change lines at the beginning would begin with
3034* @@ -1,L +N,M @@
3035* but we need to be careful. -U0 that inserts before the second
3036* line also has this pattern.
3037*
3038* And a hunk to add to an empty file would begin with
3039* @@ -0,0 +N,M @@
3040*
3041* In other words, a hunk that is (frag->oldpos <= 1) with or
3042* without leading context must match at the beginning.
3043*/
3044match_beginning = (!frag->oldpos ||
3045(frag->oldpos == 1 && !state->unidiff_zero));
3046
3047/*
3048* A hunk without trailing lines must match at the end.
3049* However, we simply cannot tell if a hunk must match end
3050* from the lack of trailing lines if the patch was generated
3051* with unidiff without any context.
3052*/
3053match_end = !state->unidiff_zero && !trailing;
3054
3055pos = frag->newpos ? (frag->newpos - 1) : 0;
3056preimage.buf = oldlines;
3057preimage.len = old - oldlines;
3058postimage.buf = newlines.buf;
3059postimage.len = newlines.len;
3060preimage.line = preimage.line_allocated;
3061postimage.line = postimage.line_allocated;
3062
3063for (;;) {
3064
3065applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3066ws_rule, match_beginning, match_end);
3067
3068if (applied_pos >= 0)
3069break;
3070
3071/* Am I at my context limits? */
3072if ((leading <= state->p_context) && (trailing <= state->p_context))
3073break;
3074if (match_beginning || match_end) {
3075match_beginning = match_end = 0;
3076continue;
3077}
3078
3079/*
3080* Reduce the number of context lines; reduce both
3081* leading and trailing if they are equal otherwise
3082* just reduce the larger context.
3083*/
3084if (leading >= trailing) {
3085remove_first_line(&preimage);
3086remove_first_line(&postimage);
3087pos--;
3088leading--;
3089}
3090if (trailing > leading) {
3091remove_last_line(&preimage);
3092remove_last_line(&postimage);
3093trailing--;
3094}
3095}
3096
3097if (applied_pos >= 0) {
3098if (new_blank_lines_at_end &&
3099preimage.nr + applied_pos >= img->nr &&
3100(ws_rule & WS_BLANK_AT_EOF) &&
3101state->ws_error_action != nowarn_ws_error) {
3102record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3103found_new_blank_lines_at_end);
3104if (state->ws_error_action == correct_ws_error) {
3105while (new_blank_lines_at_end--)
3106remove_last_line(&postimage);
3107}
3108/*
3109* We would want to prevent write_out_results()
3110* from taking place in apply_patch() that follows
3111* the callchain led us here, which is:
3112* apply_patch->check_patch_list->check_patch->
3113* apply_data->apply_fragments->apply_one_fragment
3114*/
3115if (state->ws_error_action == die_on_ws_error)
3116state->apply = 0;
3117}
3118
3119if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3120int offset = applied_pos - pos;
3121if (state->apply_in_reverse)
3122offset = 0 - offset;
3123fprintf_ln(stderr,
3124Q_("Hunk #%d succeeded at %d (offset %d line).",
3125"Hunk #%d succeeded at %d (offset %d lines).",
3126offset),
3127nth_fragment, applied_pos + 1, offset);
3128}
3129
3130/*
3131* Warn if it was necessary to reduce the number
3132* of context lines.
3133*/
3134if ((leading != frag->leading ||
3135trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3136fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3137" to apply fragment at %d"),
3138leading, trailing, applied_pos+1);
3139update_image(state, img, applied_pos, &preimage, &postimage);
3140} else {
3141if (state->apply_verbosity > verbosity_normal)
3142error(_("while searching for:\n%.*s"),
3143(int)(old - oldlines), oldlines);
3144}
3145
3146out:
3147free(oldlines);
3148strbuf_release(&newlines);
3149free(preimage.line_allocated);
3150free(postimage.line_allocated);
3151
3152return (applied_pos < 0);
3153}
3154
3155static int apply_binary_fragment(struct apply_state *state,
3156struct image *img,
3157struct patch *patch)
3158{
3159struct fragment *fragment = patch->fragments;
3160unsigned long len;
3161void *dst;
3162
3163if (!fragment)
3164return error(_("missing binary patch data for '%s'"),
3165patch->new_name ?
3166patch->new_name :
3167patch->old_name);
3168
3169/* Binary patch is irreversible without the optional second hunk */
3170if (state->apply_in_reverse) {
3171if (!fragment->next)
3172return error(_("cannot reverse-apply a binary patch "
3173"without the reverse hunk to '%s'"),
3174patch->new_name
3175? patch->new_name : patch->old_name);
3176fragment = fragment->next;
3177}
3178switch (fragment->binary_patch_method) {
3179case BINARY_DELTA_DEFLATED:
3180dst = patch_delta(img->buf, img->len, fragment->patch,
3181fragment->size, &len);
3182if (!dst)
3183return -1;
3184clear_image(img);
3185img->buf = dst;
3186img->len = len;
3187return 0;
3188case BINARY_LITERAL_DEFLATED:
3189clear_image(img);
3190img->len = fragment->size;
3191img->buf = xmemdupz(fragment->patch, img->len);
3192return 0;
3193}
3194return -1;
3195}
3196
3197/*
3198* Replace "img" with the result of applying the binary patch.
3199* The binary patch data itself in patch->fragment is still kept
3200* but the preimage prepared by the caller in "img" is freed here
3201* or in the helper function apply_binary_fragment() this calls.
3202*/
3203static int apply_binary(struct apply_state *state,
3204struct image *img,
3205struct patch *patch)
3206{
3207const char *name = patch->old_name ? patch->old_name : patch->new_name;
3208struct object_id oid;
3209const unsigned hexsz = the_hash_algo->hexsz;
3210
3211/*
3212* For safety, we require patch index line to contain
3213* full hex textual object ID for old and new, at least for now.
3214*/
3215if (strlen(patch->old_oid_prefix) != hexsz ||
3216strlen(patch->new_oid_prefix) != hexsz ||
3217get_oid_hex(patch->old_oid_prefix, &oid) ||
3218get_oid_hex(patch->new_oid_prefix, &oid))
3219return error(_("cannot apply binary patch to '%s' "
3220"without full index line"), name);
3221
3222if (patch->old_name) {
3223/*
3224* See if the old one matches what the patch
3225* applies to.
3226*/
3227hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3228&oid);
3229if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
3230return error(_("the patch applies to '%s' (%s), "
3231"which does not match the "
3232"current contents."),
3233name, oid_to_hex(&oid));
3234}
3235else {
3236/* Otherwise, the old one must be empty. */
3237if (img->len)
3238return error(_("the patch applies to an empty "
3239"'%s' but it is not empty"), name);
3240}
3241
3242get_oid_hex(patch->new_oid_prefix, &oid);
3243if (is_null_oid(&oid)) {
3244clear_image(img);
3245return 0; /* deletion patch */
3246}
3247
3248if (has_object(the_repository, &oid, 0)) {
3249/* We already have the postimage */
3250enum object_type type;
3251unsigned long size;
3252char *result;
3253
3254result = repo_read_object_file(the_repository, &oid, &type,
3255&size);
3256if (!result)
3257return error(_("the necessary postimage %s for "
3258"'%s' cannot be read"),
3259patch->new_oid_prefix, name);
3260clear_image(img);
3261img->buf = result;
3262img->len = size;
3263} else {
3264/*
3265* We have verified buf matches the preimage;
3266* apply the patch data to it, which is stored
3267* in the patch->fragments->{patch,size}.
3268*/
3269if (apply_binary_fragment(state, img, patch))
3270return error(_("binary patch does not apply to '%s'"),
3271name);
3272
3273/* verify that the result matches */
3274hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3275&oid);
3276if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
3277return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3278name, patch->new_oid_prefix, oid_to_hex(&oid));
3279}
3280
3281return 0;
3282}
3283
3284static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3285{
3286struct fragment *frag = patch->fragments;
3287const char *name = patch->old_name ? patch->old_name : patch->new_name;
3288unsigned ws_rule = patch->ws_rule;
3289unsigned inaccurate_eof = patch->inaccurate_eof;
3290int nth = 0;
3291
3292if (patch->is_binary)
3293return apply_binary(state, img, patch);
3294
3295while (frag) {
3296nth++;
3297if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3298error(_("patch failed: %s:%ld"), name, frag->oldpos);
3299if (!state->apply_with_reject)
3300return -1;
3301frag->rejected = 1;
3302}
3303frag = frag->next;
3304}
3305return 0;
3306}
3307
3308static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3309{
3310if (S_ISGITLINK(mode)) {
3311strbuf_grow(buf, 100);
3312strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3313} else {
3314enum object_type type;
3315unsigned long sz;
3316char *result;
3317
3318result = repo_read_object_file(the_repository, oid, &type,
3319&sz);
3320if (!result)
3321return -1;
3322/* XXX read_sha1_file NUL-terminates */
3323strbuf_attach(buf, result, sz, sz + 1);
3324}
3325return 0;
3326}
3327
3328static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3329{
3330if (!ce)
3331return 0;
3332return read_blob_object(buf, &ce->oid, ce->ce_mode);
3333}
3334
3335static struct patch *in_fn_table(struct apply_state *state, const char *name)
3336{
3337struct string_list_item *item;
3338
3339if (!name)
3340return NULL;
3341
3342item = string_list_lookup(&state->fn_table, name);
3343if (item)
3344return (struct patch *)item->util;
3345
3346return NULL;
3347}
3348
3349/*
3350* item->util in the filename table records the status of the path.
3351* Usually it points at a patch (whose result records the contents
3352* of it after applying it), but it could be PATH_WAS_DELETED for a
3353* path that a previously applied patch has already removed, or
3354* PATH_TO_BE_DELETED for a path that a later patch would remove.
3355*
3356* The latter is needed to deal with a case where two paths A and B
3357* are swapped by first renaming A to B and then renaming B to A;
3358* moving A to B should not be prevented due to presence of B as we
3359* will remove it in a later patch.
3360*/
3361#define PATH_TO_BE_DELETED ((struct patch *) -2)
3362#define PATH_WAS_DELETED ((struct patch *) -1)
3363
3364static int to_be_deleted(struct patch *patch)
3365{
3366return patch == PATH_TO_BE_DELETED;
3367}
3368
3369static int was_deleted(struct patch *patch)
3370{
3371return patch == PATH_WAS_DELETED;
3372}
3373
3374static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3375{
3376struct string_list_item *item;
3377
3378/*
3379* Always add new_name unless patch is a deletion
3380* This should cover the cases for normal diffs,
3381* file creations and copies
3382*/
3383if (patch->new_name) {
3384item = string_list_insert(&state->fn_table, patch->new_name);
3385item->util = patch;
3386}
3387
3388/*
3389* store a failure on rename/deletion cases because
3390* later chunks shouldn't patch old names
3391*/
3392if ((patch->new_name == NULL) || (patch->is_rename)) {
3393item = string_list_insert(&state->fn_table, patch->old_name);
3394item->util = PATH_WAS_DELETED;
3395}
3396}
3397
3398static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3399{
3400/*
3401* store information about incoming file deletion
3402*/
3403while (patch) {
3404if ((patch->new_name == NULL) || (patch->is_rename)) {
3405struct string_list_item *item;
3406item = string_list_insert(&state->fn_table, patch->old_name);
3407item->util = PATH_TO_BE_DELETED;
3408}
3409patch = patch->next;
3410}
3411}
3412
3413static int checkout_target(struct index_state *istate,
3414struct cache_entry *ce, struct stat *st)
3415{
3416struct checkout costate = CHECKOUT_INIT;
3417
3418costate.refresh_cache = 1;
3419costate.istate = istate;
3420if (checkout_entry(ce, &costate, NULL, NULL) ||
3421lstat(ce->name, st))
3422return error(_("cannot checkout %s"), ce->name);
3423return 0;
3424}
3425
3426static struct patch *previous_patch(struct apply_state *state,
3427struct patch *patch,
3428int *gone)
3429{
3430struct patch *previous;
3431
3432*gone = 0;
3433if (patch->is_copy || patch->is_rename)
3434return NULL; /* "git" patches do not depend on the order */
3435
3436previous = in_fn_table(state, patch->old_name);
3437if (!previous)
3438return NULL;
3439
3440if (to_be_deleted(previous))
3441return NULL; /* the deletion hasn't happened yet */
3442
3443if (was_deleted(previous))
3444*gone = 1;
3445
3446return previous;
3447}
3448
3449static int verify_index_match(struct apply_state *state,
3450const struct cache_entry *ce,
3451struct stat *st)
3452{
3453if (S_ISGITLINK(ce->ce_mode)) {
3454if (!S_ISDIR(st->st_mode))
3455return -1;
3456return 0;
3457}
3458return ie_match_stat(state->repo->index, ce, st,
3459CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
3460}
3461
3462#define SUBMODULE_PATCH_WITHOUT_INDEX 1
3463
3464static int load_patch_target(struct apply_state *state,
3465struct strbuf *buf,
3466const struct cache_entry *ce,
3467struct stat *st,
3468struct patch *patch,
3469const char *name,
3470unsigned expected_mode)
3471{
3472if (state->cached || state->check_index) {
3473if (read_file_or_gitlink(ce, buf))
3474return error(_("failed to read %s"), name);
3475} else if (name) {
3476if (S_ISGITLINK(expected_mode)) {
3477if (ce)
3478return read_file_or_gitlink(ce, buf);
3479else
3480return SUBMODULE_PATCH_WITHOUT_INDEX;
3481} else if (has_symlink_leading_path(name, strlen(name))) {
3482return error(_("reading from '%s' beyond a symbolic link"), name);
3483} else {
3484if (read_old_data(st, patch, name, buf))
3485return error(_("failed to read %s"), name);
3486}
3487}
3488return 0;
3489}
3490
3491/*
3492* We are about to apply "patch"; populate the "image" with the
3493* current version we have, from the working tree or from the index,
3494* depending on the situation e.g. --cached/--index. If we are
3495* applying a non-git patch that incrementally updates the tree,
3496* we read from the result of a previous diff.
3497*/
3498static int load_preimage(struct apply_state *state,
3499struct image *image,
3500struct patch *patch, struct stat *st,
3501const struct cache_entry *ce)
3502{
3503struct strbuf buf = STRBUF_INIT;
3504size_t len;
3505char *img;
3506struct patch *previous;
3507int status;
3508
3509previous = previous_patch(state, patch, &status);
3510if (status)
3511return error(_("path %s has been renamed/deleted"),
3512patch->old_name);
3513if (previous) {
3514/* We have a patched copy in memory; use that. */
3515strbuf_add(&buf, previous->result, previous->resultsize);
3516} else {
3517status = load_patch_target(state, &buf, ce, st, patch,
3518patch->old_name, patch->old_mode);
3519if (status < 0)
3520return status;
3521else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3522/*
3523* There is no way to apply subproject
3524* patch without looking at the index.
3525* NEEDSWORK: shouldn't this be flagged
3526* as an error???
3527*/
3528free_fragment_list(patch->fragments);
3529patch->fragments = NULL;
3530} else if (status) {
3531return error(_("failed to read %s"), patch->old_name);
3532}
3533}
3534
3535img = strbuf_detach(&buf, &len);
3536prepare_image(image, img, len, !patch->is_binary);
3537return 0;
3538}
3539
3540static int resolve_to(struct image *image, const struct object_id *result_id)
3541{
3542unsigned long size;
3543enum object_type type;
3544
3545clear_image(image);
3546
3547image->buf = repo_read_object_file(the_repository, result_id, &type,
3548&size);
3549if (!image->buf || type != OBJ_BLOB)
3550die("unable to read blob object %s", oid_to_hex(result_id));
3551image->len = size;
3552
3553return 0;
3554}
3555
3556static int three_way_merge(struct apply_state *state,
3557struct image *image,
3558char *path,
3559const struct object_id *base,
3560const struct object_id *ours,
3561const struct object_id *theirs)
3562{
3563mmfile_t base_file, our_file, their_file;
3564mmbuffer_t result = { NULL };
3565enum ll_merge_result status;
3566
3567/* resolve trivial cases first */
3568if (oideq(base, ours))
3569return resolve_to(image, theirs);
3570else if (oideq(base, theirs) || oideq(ours, theirs))
3571return resolve_to(image, ours);
3572
3573read_mmblob(&base_file, base);
3574read_mmblob(&our_file, ours);
3575read_mmblob(&their_file, theirs);
3576status = ll_merge(&result, path,
3577&base_file, "base",
3578&our_file, "ours",
3579&their_file, "theirs",
3580state->repo->index,
3581NULL);
3582if (status == LL_MERGE_BINARY_CONFLICT)
3583warning("Cannot merge binary files: %s (%s vs. %s)",
3584path, "ours", "theirs");
3585free(base_file.ptr);
3586free(our_file.ptr);
3587free(their_file.ptr);
3588if (status < 0 || !result.ptr) {
3589free(result.ptr);
3590return -1;
3591}
3592clear_image(image);
3593image->buf = result.ptr;
3594image->len = result.size;
3595
3596return status;
3597}
3598
3599/*
3600* When directly falling back to add/add three-way merge, we read from
3601* the current contents of the new_name. In no cases other than that
3602* this function will be called.
3603*/
3604static int load_current(struct apply_state *state,
3605struct image *image,
3606struct patch *patch)
3607{
3608struct strbuf buf = STRBUF_INIT;
3609int status, pos;
3610size_t len;
3611char *img;
3612struct stat st;
3613struct cache_entry *ce;
3614char *name = patch->new_name;
3615unsigned mode = patch->new_mode;
3616
3617if (!patch->is_new)
3618BUG("patch to %s is not a creation", patch->old_name);
3619
3620pos = index_name_pos(state->repo->index, name, strlen(name));
3621if (pos < 0)
3622return error(_("%s: does not exist in index"), name);
3623ce = state->repo->index->cache[pos];
3624if (lstat(name, &st)) {
3625if (errno != ENOENT)
3626return error_errno("%s", name);
3627if (checkout_target(state->repo->index, ce, &st))
3628return -1;
3629}
3630if (verify_index_match(state, ce, &st))
3631return error(_("%s: does not match index"), name);
3632
3633status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
3634if (status < 0)
3635return status;
3636else if (status)
3637return -1;
3638img = strbuf_detach(&buf, &len);
3639prepare_image(image, img, len, !patch->is_binary);
3640return 0;
3641}
3642
3643static int try_threeway(struct apply_state *state,
3644struct image *image,
3645struct patch *patch,
3646struct stat *st,
3647const struct cache_entry *ce)
3648{
3649struct object_id pre_oid, post_oid, our_oid;
3650struct strbuf buf = STRBUF_INIT;
3651size_t len;
3652int status;
3653char *img;
3654struct image tmp_image;
3655
3656/* No point falling back to 3-way merge in these cases */
3657if (patch->is_delete ||
3658S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3659(patch->is_new && !patch->direct_to_threeway) ||
3660(patch->is_rename && !patch->lines_added && !patch->lines_deleted))
3661return -1;
3662
3663/* Preimage the patch was prepared for */
3664if (patch->is_new)
3665write_object_file("", 0, OBJ_BLOB, &pre_oid);
3666else if (repo_get_oid(the_repository, patch->old_oid_prefix, &pre_oid) ||
3667read_blob_object(&buf, &pre_oid, patch->old_mode))
3668return error(_("repository lacks the necessary blob to perform 3-way merge."));
3669
3670if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
3671fprintf(stderr, _("Performing three-way merge...\n"));
3672
3673img = strbuf_detach(&buf, &len);
3674prepare_image(&tmp_image, img, len, 1);
3675/* Apply the patch to get the post image */
3676if (apply_fragments(state, &tmp_image, patch) < 0) {
3677clear_image(&tmp_image);
3678return -1;
3679}
3680/* post_oid is theirs */
3681write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &post_oid);
3682clear_image(&tmp_image);
3683
3684/* our_oid is ours */
3685if (patch->is_new) {
3686if (load_current(state, &tmp_image, patch))
3687return error(_("cannot read the current contents of '%s'"),
3688patch->new_name);
3689} else {
3690if (load_preimage(state, &tmp_image, patch, st, ce))
3691return error(_("cannot read the current contents of '%s'"),
3692patch->old_name);
3693}
3694write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &our_oid);
3695clear_image(&tmp_image);
3696
3697/* in-core three-way merge between post and our using pre as base */
3698status = three_way_merge(state, image, patch->new_name,
3699&pre_oid, &our_oid, &post_oid);
3700if (status < 0) {
3701if (state->apply_verbosity > verbosity_silent)
3702fprintf(stderr,
3703_("Failed to perform three-way merge...\n"));
3704return status;
3705}
3706
3707if (status) {
3708patch->conflicted_threeway = 1;
3709if (patch->is_new)
3710oidclr(&patch->threeway_stage[0], the_repository->hash_algo);
3711else
3712oidcpy(&patch->threeway_stage[0], &pre_oid);
3713oidcpy(&patch->threeway_stage[1], &our_oid);
3714oidcpy(&patch->threeway_stage[2], &post_oid);
3715if (state->apply_verbosity > verbosity_silent)
3716fprintf(stderr,
3717_("Applied patch to '%s' with conflicts.\n"),
3718patch->new_name);
3719} else {
3720if (state->apply_verbosity > verbosity_silent)
3721fprintf(stderr,
3722_("Applied patch to '%s' cleanly.\n"),
3723patch->new_name);
3724}
3725return 0;
3726}
3727
3728static int apply_data(struct apply_state *state, struct patch *patch,
3729struct stat *st, const struct cache_entry *ce)
3730{
3731struct image image;
3732
3733if (load_preimage(state, &image, patch, st, ce) < 0)
3734return -1;
3735
3736if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
3737if (state->apply_verbosity > verbosity_silent &&
3738state->threeway && !patch->direct_to_threeway)
3739fprintf(stderr, _("Falling back to direct application...\n"));
3740
3741/* Note: with --reject, apply_fragments() returns 0 */
3742if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0) {
3743clear_image(&image);
3744return -1;
3745}
3746}
3747patch->result = image.buf;
3748patch->resultsize = image.len;
3749add_to_fn_table(state, patch);
3750free(image.line_allocated);
3751
3752if (0 < patch->is_delete && patch->resultsize)
3753return error(_("removal patch leaves file contents"));
3754
3755return 0;
3756}
3757
3758/*
3759* If "patch" that we are looking at modifies or deletes what we have,
3760* we would want it not to lose any local modification we have, either
3761* in the working tree or in the index.
3762*
3763* This also decides if a non-git patch is a creation patch or a
3764* modification to an existing empty file. We do not check the state
3765* of the current tree for a creation patch in this function; the caller
3766* check_patch() separately makes sure (and errors out otherwise) that
3767* the path the patch creates does not exist in the current tree.
3768*/
3769static int check_preimage(struct apply_state *state,
3770struct patch *patch,
3771struct cache_entry **ce,
3772struct stat *st)
3773{
3774const char *old_name = patch->old_name;
3775struct patch *previous = NULL;
3776int stat_ret = 0, status;
3777unsigned st_mode = 0;
3778
3779if (!old_name)
3780return 0;
3781
3782assert(patch->is_new <= 0);
3783previous = previous_patch(state, patch, &status);
3784
3785if (status)
3786return error(_("path %s has been renamed/deleted"), old_name);
3787if (previous) {
3788st_mode = previous->new_mode;
3789} else if (!state->cached) {
3790stat_ret = lstat(old_name, st);
3791if (stat_ret && errno != ENOENT)
3792return error_errno("%s", old_name);
3793}
3794
3795if (state->check_index && !previous) {
3796int pos = index_name_pos(state->repo->index, old_name,
3797strlen(old_name));
3798if (pos < 0) {
3799if (patch->is_new < 0)
3800goto is_new;
3801return error(_("%s: does not exist in index"), old_name);
3802}
3803*ce = state->repo->index->cache[pos];
3804if (stat_ret < 0) {
3805if (checkout_target(state->repo->index, *ce, st))
3806return -1;
3807}
3808if (!state->cached && verify_index_match(state, *ce, st))
3809return error(_("%s: does not match index"), old_name);
3810if (state->cached)
3811st_mode = (*ce)->ce_mode;
3812} else if (stat_ret < 0) {
3813if (patch->is_new < 0)
3814goto is_new;
3815return error_errno("%s", old_name);
3816}
3817
3818if (!state->cached && !previous) {
3819if (*ce && !(*ce)->ce_mode)
3820BUG("ce_mode == 0 for path '%s'", old_name);
3821
3822if (trust_executable_bit)
3823st_mode = ce_mode_from_stat(*ce, st->st_mode);
3824else if (*ce)
3825st_mode = (*ce)->ce_mode;
3826else
3827st_mode = patch->old_mode;
3828}
3829
3830if (patch->is_new < 0)
3831patch->is_new = 0;
3832if (!patch->old_mode)
3833patch->old_mode = st_mode;
3834if ((st_mode ^ patch->old_mode) & S_IFMT)
3835return error(_("%s: wrong type"), old_name);
3836if (st_mode != patch->old_mode)
3837warning(_("%s has type %o, expected %o"),
3838old_name, st_mode, patch->old_mode);
3839if (!patch->new_mode && !patch->is_delete)
3840patch->new_mode = st_mode;
3841return 0;
3842
3843is_new:
3844patch->is_new = 1;
3845patch->is_delete = 0;
3846FREE_AND_NULL(patch->old_name);
3847return 0;
3848}
3849
3850
3851#define EXISTS_IN_INDEX 1
3852#define EXISTS_IN_WORKTREE 2
3853#define EXISTS_IN_INDEX_AS_ITA 3
3854
3855static int check_to_create(struct apply_state *state,
3856const char *new_name,
3857int ok_if_exists)
3858{
3859struct stat nst;
3860
3861if (state->check_index && (!ok_if_exists || !state->cached)) {
3862int pos;
3863
3864pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3865if (pos >= 0) {
3866struct cache_entry *ce = state->repo->index->cache[pos];
3867
3868/* allow ITA, as they do not yet exist in the index */
3869if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3870return EXISTS_IN_INDEX;
3871
3872/* ITA entries can never match working tree files */
3873if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3874return EXISTS_IN_INDEX_AS_ITA;
3875}
3876}
3877
3878if (state->cached)
3879return 0;
3880
3881if (!lstat(new_name, &nst)) {
3882if (S_ISDIR(nst.st_mode) || ok_if_exists)
3883return 0;
3884/*
3885* A leading component of new_name might be a symlink
3886* that is going to be removed with this patch, but
3887* still pointing at somewhere that has the path.
3888* In such a case, path "new_name" does not exist as
3889* far as git is concerned.
3890*/
3891if (has_symlink_leading_path(new_name, strlen(new_name)))
3892return 0;
3893
3894return EXISTS_IN_WORKTREE;
3895} else if (!is_missing_file_error(errno)) {
3896return error_errno("%s", new_name);
3897}
3898return 0;
3899}
3900
3901static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3902{
3903for ( ; patch; patch = patch->next) {
3904if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3905(patch->is_rename || patch->is_delete))
3906/* the symlink at patch->old_name is removed */
3907strset_add(&state->removed_symlinks, patch->old_name);
3908
3909if (patch->new_name && S_ISLNK(patch->new_mode))
3910/* the symlink at patch->new_name is created or remains */
3911strset_add(&state->kept_symlinks, patch->new_name);
3912}
3913}
3914
3915static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3916{
3917do {
3918while (--name->len && name->buf[name->len] != '/')
3919; /* scan backwards */
3920if (!name->len)
3921break;
3922name->buf[name->len] = '\0';
3923if (strset_contains(&state->kept_symlinks, name->buf))
3924return 1;
3925if (strset_contains(&state->removed_symlinks, name->buf))
3926/*
3927* This cannot be "return 0", because we may
3928* see a new one created at a higher level.
3929*/
3930continue;
3931
3932/* otherwise, check the preimage */
3933if (state->check_index) {
3934struct cache_entry *ce;
3935
3936ce = index_file_exists(state->repo->index, name->buf,
3937name->len, ignore_case);
3938if (ce && S_ISLNK(ce->ce_mode))
3939return 1;
3940} else {
3941struct stat st;
3942if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3943return 1;
3944}
3945} while (1);
3946return 0;
3947}
3948
3949static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3950{
3951int ret;
3952struct strbuf name = STRBUF_INIT;
3953
3954assert(*name_ != '\0');
3955strbuf_addstr(&name, name_);
3956ret = path_is_beyond_symlink_1(state, &name);
3957strbuf_release(&name);
3958
3959return ret;
3960}
3961
3962static int check_unsafe_path(struct patch *patch)
3963{
3964const char *old_name = NULL;
3965const char *new_name = NULL;
3966if (patch->is_delete)
3967old_name = patch->old_name;
3968else if (!patch->is_new && !patch->is_copy)
3969old_name = patch->old_name;
3970if (!patch->is_delete)
3971new_name = patch->new_name;
3972
3973if (old_name && !verify_path(old_name, patch->old_mode))
3974return error(_("invalid path '%s'"), old_name);
3975if (new_name && !verify_path(new_name, patch->new_mode))
3976return error(_("invalid path '%s'"), new_name);
3977return 0;
3978}
3979
3980/*
3981* Check and apply the patch in-core; leave the result in patch->result
3982* for the caller to write it out to the final destination.
3983*/
3984static int check_patch(struct apply_state *state, struct patch *patch)
3985{
3986struct stat st;
3987const char *old_name = patch->old_name;
3988const char *new_name = patch->new_name;
3989const char *name = old_name ? old_name : new_name;
3990struct cache_entry *ce = NULL;
3991struct patch *tpatch;
3992int ok_if_exists;
3993int status;
3994
3995patch->rejected = 1; /* we will drop this after we succeed */
3996
3997status = check_preimage(state, patch, &ce, &st);
3998if (status)
3999return status;
4000old_name = patch->old_name;
4001
4002/*
4003* A type-change diff is always split into a patch to delete
4004* old, immediately followed by a patch to create new (see
4005* diff.c::run_diff()); in such a case it is Ok that the entry
4006* to be deleted by the previous patch is still in the working
4007* tree and in the index.
4008*
4009* A patch to swap-rename between A and B would first rename A
4010* to B and then rename B to A. While applying the first one,
4011* the presence of B should not stop A from getting renamed to
4012* B; ask to_be_deleted() about the later rename. Removal of
4013* B and rename from A to B is handled the same way by asking
4014* was_deleted().
4015*/
4016if ((tpatch = in_fn_table(state, new_name)) &&
4017(was_deleted(tpatch) || to_be_deleted(tpatch)))
4018ok_if_exists = 1;
4019else
4020ok_if_exists = 0;
4021
4022if (new_name &&
4023((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
4024int err = check_to_create(state, new_name, ok_if_exists);
4025
4026if (err && state->threeway) {
4027patch->direct_to_threeway = 1;
4028} else switch (err) {
4029case 0:
4030break; /* happy */
4031case EXISTS_IN_INDEX:
4032return error(_("%s: already exists in index"), new_name);
4033case EXISTS_IN_INDEX_AS_ITA:
4034return error(_("%s: does not match index"), new_name);
4035case EXISTS_IN_WORKTREE:
4036return error(_("%s: already exists in working directory"),
4037new_name);
4038default:
4039return err;
4040}
4041
4042if (!patch->new_mode) {
4043if (0 < patch->is_new)
4044patch->new_mode = S_IFREG | 0644;
4045else
4046patch->new_mode = patch->old_mode;
4047}
4048}
4049
4050if (new_name && old_name) {
4051int same = !strcmp(old_name, new_name);
4052if (!patch->new_mode)
4053patch->new_mode = patch->old_mode;
4054if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
4055if (same)
4056return error(_("new mode (%o) of %s does not "
4057"match old mode (%o)"),
4058patch->new_mode, new_name,
4059patch->old_mode);
4060else
4061return error(_("new mode (%o) of %s does not "
4062"match old mode (%o) of %s"),
4063patch->new_mode, new_name,
4064patch->old_mode, old_name);
4065}
4066}
4067
4068if (!state->unsafe_paths && check_unsafe_path(patch))
4069return -128;
4070
4071/*
4072* An attempt to read from or delete a path that is beyond a
4073* symbolic link will be prevented by load_patch_target() that
4074* is called at the beginning of apply_data() so we do not
4075* have to worry about a patch marked with "is_delete" bit
4076* here. We however need to make sure that the patch result
4077* is not deposited to a path that is beyond a symbolic link
4078* here.
4079*/
4080if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4081return error(_("affected file '%s' is beyond a symbolic link"),
4082patch->new_name);
4083
4084if (apply_data(state, patch, &st, ce) < 0)
4085return error(_("%s: patch does not apply"), name);
4086patch->rejected = 0;
4087return 0;
4088}
4089
4090static int check_patch_list(struct apply_state *state, struct patch *patch)
4091{
4092int err = 0;
4093
4094prepare_symlink_changes(state, patch);
4095prepare_fn_table(state, patch);
4096while (patch) {
4097int res;
4098if (state->apply_verbosity > verbosity_normal)
4099say_patch_name(stderr,
4100_("Checking patch %s..."), patch);
4101res = check_patch(state, patch);
4102if (res == -128)
4103return -128;
4104err |= res;
4105patch = patch->next;
4106}
4107return err;
4108}
4109
4110static int read_apply_cache(struct apply_state *state)
4111{
4112if (state->index_file)
4113return read_index_from(state->repo->index, state->index_file,
4114get_git_dir());
4115else
4116return repo_read_index(state->repo);
4117}
4118
4119/* This function tries to read the object name from the current index */
4120static int get_current_oid(struct apply_state *state, const char *path,
4121struct object_id *oid)
4122{
4123int pos;
4124
4125if (read_apply_cache(state) < 0)
4126return -1;
4127pos = index_name_pos(state->repo->index, path, strlen(path));
4128if (pos < 0)
4129return -1;
4130oidcpy(oid, &state->repo->index->cache[pos]->oid);
4131return 0;
4132}
4133
4134static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4135{
4136/*
4137* A usable gitlink patch has only one fragment (hunk) that looks like:
4138* @@ -1 +1 @@
4139* -Subproject commit <old sha1>
4140* +Subproject commit <new sha1>
4141* or
4142* @@ -1 +0,0 @@
4143* -Subproject commit <old sha1>
4144* for a removal patch.
4145*/
4146struct fragment *hunk = p->fragments;
4147static const char heading[] = "-Subproject commit ";
4148char *preimage;
4149
4150if (/* does the patch have only one hunk? */
4151hunk && !hunk->next &&
4152/* is its preimage one line? */
4153hunk->oldpos == 1 && hunk->oldlines == 1 &&
4154/* does preimage begin with the heading? */
4155(preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4156starts_with(++preimage, heading) &&
4157/* does it record full SHA-1? */
4158!get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4159preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
4160/* does the abbreviated name on the index line agree with it? */
4161starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
4162return 0; /* it all looks fine */
4163
4164/* we may have full object name on the index line */
4165return get_oid_hex(p->old_oid_prefix, oid);
4166}
4167
4168/* Build an index that contains just the files needed for a 3way merge */
4169static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4170{
4171struct patch *patch;
4172struct index_state result = INDEX_STATE_INIT(state->repo);
4173struct lock_file lock = LOCK_INIT;
4174int res;
4175
4176/* Once we start supporting the reverse patch, it may be
4177* worth showing the new sha1 prefix, but until then...
4178*/
4179for (patch = list; patch; patch = patch->next) {
4180struct object_id oid;
4181struct cache_entry *ce;
4182const char *name;
4183
4184name = patch->old_name ? patch->old_name : patch->new_name;
4185if (0 < patch->is_new)
4186continue;
4187
4188if (S_ISGITLINK(patch->old_mode)) {
4189if (!preimage_oid_in_gitlink_patch(patch, &oid))
4190; /* ok, the textual part looks sane */
4191else
4192return error(_("sha1 information is lacking or "
4193"useless for submodule %s"), name);
4194} else if (!repo_get_oid_blob(the_repository, patch->old_oid_prefix, &oid)) {
4195; /* ok */
4196} else if (!patch->lines_added && !patch->lines_deleted) {
4197/* mode-only change: update the current */
4198if (get_current_oid(state, patch->old_name, &oid))
4199return error(_("mode change for %s, which is not "
4200"in current HEAD"), name);
4201} else
4202return error(_("sha1 information is lacking or useless "
4203"(%s)."), name);
4204
4205ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
4206if (!ce)
4207return error(_("make_cache_entry failed for path '%s'"),
4208name);
4209if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4210discard_cache_entry(ce);
4211return error(_("could not add %s to temporary index"),
4212name);
4213}
4214}
4215
4216hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
4217res = write_locked_index(&result, &lock, COMMIT_LOCK);
4218discard_index(&result);
4219
4220if (res)
4221return error(_("could not write temporary index to %s"),
4222state->fake_ancestor);
4223
4224return 0;
4225}
4226
4227static void stat_patch_list(struct apply_state *state, struct patch *patch)
4228{
4229int files, adds, dels;
4230
4231for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4232files++;
4233adds += patch->lines_added;
4234dels += patch->lines_deleted;
4235show_stats(state, patch);
4236}
4237
4238print_stat_summary(stdout, files, adds, dels);
4239}
4240
4241static void numstat_patch_list(struct apply_state *state,
4242struct patch *patch)
4243{
4244for ( ; patch; patch = patch->next) {
4245const char *name;
4246name = patch->new_name ? patch->new_name : patch->old_name;
4247if (patch->is_binary)
4248printf("-\t-\t");
4249else
4250printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4251write_name_quoted(name, stdout, state->line_termination);
4252}
4253}
4254
4255static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4256{
4257if (mode)
4258printf(" %s mode %06o %s\n", newdelete, mode, name);
4259else
4260printf(" %s %s\n", newdelete, name);
4261}
4262
4263static void show_mode_change(struct patch *p, int show_name)
4264{
4265if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4266if (show_name)
4267printf(" mode change %06o => %06o %s\n",
4268p->old_mode, p->new_mode, p->new_name);
4269else
4270printf(" mode change %06o => %06o\n",
4271p->old_mode, p->new_mode);
4272}
4273}
4274
4275static void show_rename_copy(struct patch *p)
4276{
4277const char *renamecopy = p->is_rename ? "rename" : "copy";
4278const char *old_name, *new_name;
4279
4280/* Find common prefix */
4281old_name = p->old_name;
4282new_name = p->new_name;
4283while (1) {
4284const char *slash_old, *slash_new;
4285slash_old = strchr(old_name, '/');
4286slash_new = strchr(new_name, '/');
4287if (!slash_old ||
4288!slash_new ||
4289slash_old - old_name != slash_new - new_name ||
4290memcmp(old_name, new_name, slash_new - new_name))
4291break;
4292old_name = slash_old + 1;
4293new_name = slash_new + 1;
4294}
4295/* p->old_name through old_name is the common prefix, and old_name and
4296* new_name through the end of names are renames
4297*/
4298if (old_name != p->old_name)
4299printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4300(int)(old_name - p->old_name), p->old_name,
4301old_name, new_name, p->score);
4302else
4303printf(" %s %s => %s (%d%%)\n", renamecopy,
4304p->old_name, p->new_name, p->score);
4305show_mode_change(p, 0);
4306}
4307
4308static void summary_patch_list(struct patch *patch)
4309{
4310struct patch *p;
4311
4312for (p = patch; p; p = p->next) {
4313if (p->is_new)
4314show_file_mode_name("create", p->new_mode, p->new_name);
4315else if (p->is_delete)
4316show_file_mode_name("delete", p->old_mode, p->old_name);
4317else {
4318if (p->is_rename || p->is_copy)
4319show_rename_copy(p);
4320else {
4321if (p->score) {
4322printf(" rewrite %s (%d%%)\n",
4323p->new_name, p->score);
4324show_mode_change(p, 0);
4325}
4326else
4327show_mode_change(p, 1);
4328}
4329}
4330}
4331}
4332
4333static void patch_stats(struct apply_state *state, struct patch *patch)
4334{
4335int lines = patch->lines_added + patch->lines_deleted;
4336
4337if (lines > state->max_change)
4338state->max_change = lines;
4339if (patch->old_name) {
4340int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4341if (!len)
4342len = strlen(patch->old_name);
4343if (len > state->max_len)
4344state->max_len = len;
4345}
4346if (patch->new_name) {
4347int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4348if (!len)
4349len = strlen(patch->new_name);
4350if (len > state->max_len)
4351state->max_len = len;
4352}
4353}
4354
4355static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4356{
4357if (state->update_index && !state->ita_only) {
4358if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
4359return error(_("unable to remove %s from index"), patch->old_name);
4360}
4361if (!state->cached) {
4362if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4363remove_path(patch->old_name);
4364}
4365}
4366return 0;
4367}
4368
4369static int add_index_file(struct apply_state *state,
4370const char *path,
4371unsigned mode,
4372void *buf,
4373unsigned long size)
4374{
4375struct stat st;
4376struct cache_entry *ce;
4377int namelen = strlen(path);
4378
4379ce = make_empty_cache_entry(state->repo->index, namelen);
4380memcpy(ce->name, path, namelen);
4381ce->ce_mode = create_ce_mode(mode);
4382ce->ce_flags = create_ce_flags(0);
4383ce->ce_namelen = namelen;
4384if (state->ita_only) {
4385ce->ce_flags |= CE_INTENT_TO_ADD;
4386set_object_name_for_intent_to_add_entry(ce);
4387} else if (S_ISGITLINK(mode)) {
4388const char *s;
4389
4390if (!skip_prefix(buf, "Subproject commit ", &s) ||
4391get_oid_hex(s, &ce->oid)) {
4392discard_cache_entry(ce);
4393return error(_("corrupt patch for submodule %s"), path);
4394}
4395} else {
4396if (!state->cached) {
4397if (lstat(path, &st) < 0) {
4398discard_cache_entry(ce);
4399return error_errno(_("unable to stat newly "
4400"created file '%s'"),
4401path);
4402}
4403fill_stat_cache_info(state->repo->index, ce, &st);
4404}
4405if (write_object_file(buf, size, OBJ_BLOB, &ce->oid) < 0) {
4406discard_cache_entry(ce);
4407return error(_("unable to create backing store "
4408"for newly created file %s"), path);
4409}
4410}
4411if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4412discard_cache_entry(ce);
4413return error(_("unable to add cache entry for %s"), path);
4414}
4415
4416return 0;
4417}
4418
4419/*
4420* Returns:
4421* -1 if an unrecoverable error happened
4422* 0 if everything went well
4423* 1 if a recoverable error happened
4424*/
4425static int try_create_file(struct apply_state *state, const char *path,
4426unsigned int mode, const char *buf,
4427unsigned long size)
4428{
4429int fd, res;
4430struct strbuf nbuf = STRBUF_INIT;
4431
4432if (S_ISGITLINK(mode)) {
4433struct stat st;
4434if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4435return 0;
4436return !!mkdir(path, 0777);
4437}
4438
4439if (has_symlinks && S_ISLNK(mode))
4440/* Although buf:size is counted string, it also is NUL
4441* terminated.
4442*/
4443return !!symlink(buf, path);
4444
4445fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4446if (fd < 0)
4447return 1;
4448
4449if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
4450size = nbuf.len;
4451buf = nbuf.buf;
4452}
4453
4454res = write_in_full(fd, buf, size) < 0;
4455if (res)
4456error_errno(_("failed to write to '%s'"), path);
4457strbuf_release(&nbuf);
4458
4459if (close(fd) < 0 && !res)
4460return error_errno(_("closing file '%s'"), path);
4461
4462return res ? -1 : 0;
4463}
4464
4465/*
4466* We optimistically assume that the directories exist,
4467* which is true 99% of the time anyway. If they don't,
4468* we create them and try again.
4469*
4470* Returns:
4471* -1 on error
4472* 0 otherwise
4473*/
4474static int create_one_file(struct apply_state *state,
4475char *path,
4476unsigned mode,
4477const char *buf,
4478unsigned long size)
4479{
4480char *newpath = NULL;
4481int res;
4482
4483if (state->cached)
4484return 0;
4485
4486/*
4487* We already try to detect whether files are beyond a symlink in our
4488* up-front checks. But in the case where symlinks are created by any
4489* of the intermediate hunks it can happen that our up-front checks
4490* didn't yet see the symlink, but at the point of arriving here there
4491* in fact is one. We thus repeat the check for symlinks here.
4492*
4493* Note that this does not make the up-front check obsolete as the
4494* failure mode is different:
4495*
4496* - The up-front checks cause us to abort before we have written
4497* anything into the working directory. So when we exit this way the
4498* working directory remains clean.
4499*
4500* - The checks here happen in the middle of the action where we have
4501* already started to apply the patch. The end result will be a dirty
4502* working directory.
4503*
4504* Ideally, we should update the up-front checks to catch what would
4505* happen when we apply the patch before we damage the working tree.
4506* We have all the information necessary to do so. But for now, as a
4507* part of embargoed security work, having this check would serve as a
4508* reasonable first step.
4509*/
4510if (path_is_beyond_symlink(state, path))
4511return error(_("affected file '%s' is beyond a symbolic link"), path);
4512
4513res = try_create_file(state, path, mode, buf, size);
4514if (res < 0)
4515return -1;
4516if (!res)
4517return 0;
4518
4519if (errno == ENOENT) {
4520if (safe_create_leading_directories_no_share(path))
4521return 0;
4522res = try_create_file(state, path, mode, buf, size);
4523if (res < 0)
4524return -1;
4525if (!res)
4526return 0;
4527}
4528
4529if (errno == EEXIST || errno == EACCES) {
4530/* We may be trying to create a file where a directory
4531* used to be.
4532*/
4533struct stat st;
4534if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4535errno = EEXIST;
4536}
4537
4538if (errno == EEXIST) {
4539unsigned int nr = getpid();
4540
4541for (;;) {
4542newpath = mkpathdup("%s~%u", path, nr);
4543res = try_create_file(state, newpath, mode, buf, size);
4544if (res < 0)
4545goto out;
4546if (!res) {
4547if (!rename(newpath, path))
4548goto out;
4549unlink_or_warn(newpath);
4550break;
4551}
4552if (errno != EEXIST)
4553break;
4554++nr;
4555FREE_AND_NULL(newpath);
4556}
4557}
4558res = error_errno(_("unable to write file '%s' mode %o"), path, mode);
4559out:
4560free(newpath);
4561return res;
4562}
4563
4564static int add_conflicted_stages_file(struct apply_state *state,
4565struct patch *patch)
4566{
4567int stage, namelen;
4568unsigned mode;
4569struct cache_entry *ce;
4570
4571if (!state->update_index)
4572return 0;
4573namelen = strlen(patch->new_name);
4574mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4575
4576remove_file_from_index(state->repo->index, patch->new_name);
4577for (stage = 1; stage < 4; stage++) {
4578if (is_null_oid(&patch->threeway_stage[stage - 1]))
4579continue;
4580ce = make_empty_cache_entry(state->repo->index, namelen);
4581memcpy(ce->name, patch->new_name, namelen);
4582ce->ce_mode = create_ce_mode(mode);
4583ce->ce_flags = create_ce_flags(stage);
4584ce->ce_namelen = namelen;
4585oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4586if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4587discard_cache_entry(ce);
4588return error(_("unable to add cache entry for %s"),
4589patch->new_name);
4590}
4591}
4592
4593return 0;
4594}
4595
4596static int create_file(struct apply_state *state, struct patch *patch)
4597{
4598char *path = patch->new_name;
4599unsigned mode = patch->new_mode;
4600unsigned long size = patch->resultsize;
4601char *buf = patch->result;
4602
4603if (!mode)
4604mode = S_IFREG | 0644;
4605if (create_one_file(state, path, mode, buf, size))
4606return -1;
4607
4608if (patch->conflicted_threeway)
4609return add_conflicted_stages_file(state, patch);
4610else if (state->update_index)
4611return add_index_file(state, path, mode, buf, size);
4612return 0;
4613}
4614
4615/* phase zero is to remove, phase one is to create */
4616static int write_out_one_result(struct apply_state *state,
4617struct patch *patch,
4618int phase)
4619{
4620if (patch->is_delete > 0) {
4621if (phase == 0)
4622return remove_file(state, patch, 1);
4623return 0;
4624}
4625if (patch->is_new > 0 || patch->is_copy) {
4626if (phase == 1)
4627return create_file(state, patch);
4628return 0;
4629}
4630/*
4631* Rename or modification boils down to the same
4632* thing: remove the old, write the new
4633*/
4634if (phase == 0)
4635return remove_file(state, patch, patch->is_rename);
4636if (phase == 1)
4637return create_file(state, patch);
4638return 0;
4639}
4640
4641static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4642{
4643FILE *rej;
4644char *namebuf;
4645struct fragment *frag;
4646int fd, cnt = 0;
4647struct strbuf sb = STRBUF_INIT;
4648
4649for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4650if (!frag->rejected)
4651continue;
4652cnt++;
4653}
4654
4655if (!cnt) {
4656if (state->apply_verbosity > verbosity_normal)
4657say_patch_name(stderr,
4658_("Applied patch %s cleanly."), patch);
4659return 0;
4660}
4661
4662/* This should not happen, because a removal patch that leaves
4663* contents are marked "rejected" at the patch level.
4664*/
4665if (!patch->new_name)
4666die(_("internal error"));
4667
4668/* Say this even without --verbose */
4669strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4670"Applying patch %%s with %d rejects...",
4671cnt),
4672cnt);
4673if (state->apply_verbosity > verbosity_silent)
4674say_patch_name(stderr, sb.buf, patch);
4675strbuf_release(&sb);
4676
4677namebuf = xstrfmt("%s.rej", patch->new_name);
4678
4679fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4680if (fd < 0) {
4681if (errno != EEXIST) {
4682error_errno(_("cannot open %s"), namebuf);
4683goto error;
4684}
4685if (unlink(namebuf)) {
4686error_errno(_("cannot unlink '%s'"), namebuf);
4687goto error;
4688}
4689fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4690if (fd < 0) {
4691error_errno(_("cannot open %s"), namebuf);
4692goto error;
4693}
4694}
4695rej = fdopen(fd, "w");
4696if (!rej) {
4697error_errno(_("cannot open %s"), namebuf);
4698close(fd);
4699goto error;
4700}
4701
4702/* Normal git tools never deal with .rej, so do not pretend
4703* this is a git patch by saying --git or giving extended
4704* headers. While at it, maybe please "kompare" that wants
4705* the trailing TAB and some garbage at the end of line ;-).
4706*/
4707fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4708patch->new_name, patch->new_name);
4709for (cnt = 1, frag = patch->fragments;
4710frag;
4711cnt++, frag = frag->next) {
4712if (!frag->rejected) {
4713if (state->apply_verbosity > verbosity_silent)
4714fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4715continue;
4716}
4717if (state->apply_verbosity > verbosity_silent)
4718fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4719fprintf(rej, "%.*s", frag->size, frag->patch);
4720if (frag->patch[frag->size-1] != '\n')
4721fputc('\n', rej);
4722}
4723fclose(rej);
4724error:
4725free(namebuf);
4726return -1;
4727}
4728
4729/*
4730* Returns:
4731* -1 if an error happened
4732* 0 if the patch applied cleanly
4733* 1 if the patch did not apply cleanly
4734*/
4735static int write_out_results(struct apply_state *state, struct patch *list)
4736{
4737int phase;
4738int errs = 0;
4739struct patch *l;
4740struct string_list cpath = STRING_LIST_INIT_DUP;
4741
4742for (phase = 0; phase < 2; phase++) {
4743l = list;
4744while (l) {
4745if (l->rejected)
4746errs = 1;
4747else {
4748if (write_out_one_result(state, l, phase)) {
4749string_list_clear(&cpath, 0);
4750return -1;
4751}
4752if (phase == 1) {
4753if (write_out_one_reject(state, l))
4754errs = 1;
4755if (l->conflicted_threeway) {
4756string_list_append(&cpath, l->new_name);
4757errs = 1;
4758}
4759}
4760}
4761l = l->next;
4762}
4763}
4764
4765if (cpath.nr) {
4766struct string_list_item *item;
4767
4768string_list_sort(&cpath);
4769if (state->apply_verbosity > verbosity_silent) {
4770for_each_string_list_item(item, &cpath)
4771fprintf(stderr, "U %s\n", item->string);
4772}
4773string_list_clear(&cpath, 0);
4774
4775/*
4776* rerere relies on the partially merged result being in the working
4777* tree with conflict markers, but that isn't written with --cached.
4778*/
4779if (!state->cached)
4780repo_rerere(state->repo, 0);
4781}
4782
4783return errs;
4784}
4785
4786/*
4787* Try to apply a patch.
4788*
4789* Returns:
4790* -128 if a bad error happened (like patch unreadable)
4791* -1 if patch did not apply and user cannot deal with it
4792* 0 if the patch applied
4793* 1 if the patch did not apply but user might fix it
4794*/
4795static int apply_patch(struct apply_state *state,
4796int fd,
4797const char *filename,
4798int options)
4799{
4800size_t offset;
4801struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4802struct patch *list = NULL, **listp = &list;
4803int skipped_patch = 0;
4804int res = 0;
4805int flush_attributes = 0;
4806
4807state->patch_input_file = filename;
4808if (read_patch_file(&buf, fd) < 0)
4809return -128;
4810offset = 0;
4811while (offset < buf.len) {
4812struct patch *patch;
4813int nr;
4814
4815CALLOC_ARRAY(patch, 1);
4816patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4817patch->recount = !!(options & APPLY_OPT_RECOUNT);
4818nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4819if (nr < 0) {
4820free_patch(patch);
4821if (nr == -128) {
4822res = -128;
4823goto end;
4824}
4825break;
4826}
4827if (state->apply_in_reverse)
4828reverse_patches(patch);
4829if (use_patch(state, patch)) {
4830patch_stats(state, patch);
4831if (!list || !state->apply_in_reverse) {
4832*listp = patch;
4833listp = &patch->next;
4834} else {
4835patch->next = list;
4836list = patch;
4837}
4838
4839if ((patch->new_name &&
4840ends_with_path_components(patch->new_name,
4841GITATTRIBUTES_FILE)) ||
4842(patch->old_name &&
4843ends_with_path_components(patch->old_name,
4844GITATTRIBUTES_FILE)))
4845flush_attributes = 1;
4846}
4847else {
4848if (state->apply_verbosity > verbosity_normal)
4849say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4850free_patch(patch);
4851skipped_patch++;
4852}
4853offset += nr;
4854}
4855
4856if (!list && !skipped_patch) {
4857if (!state->allow_empty) {
4858error(_("No valid patches in input (allow with \"--allow-empty\")"));
4859res = -128;
4860}
4861goto end;
4862}
4863
4864if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4865state->apply = 0;
4866
4867state->update_index = (state->check_index || state->ita_only) && state->apply;
4868if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
4869if (state->index_file)
4870hold_lock_file_for_update(&state->lock_file,
4871state->index_file,
4872LOCK_DIE_ON_ERROR);
4873else
4874repo_hold_locked_index(state->repo, &state->lock_file,
4875LOCK_DIE_ON_ERROR);
4876}
4877
4878if (state->check_index && read_apply_cache(state) < 0) {
4879error(_("unable to read index file"));
4880res = -128;
4881goto end;
4882}
4883
4884if (state->check || state->apply) {
4885int r = check_patch_list(state, list);
4886if (r == -128) {
4887res = -128;
4888goto end;
4889}
4890if (r < 0 && !state->apply_with_reject) {
4891res = -1;
4892goto end;
4893}
4894}
4895
4896if (state->apply) {
4897int write_res = write_out_results(state, list);
4898if (write_res < 0) {
4899res = -128;
4900goto end;
4901}
4902if (write_res > 0) {
4903/* with --3way, we still need to write the index out */
4904res = state->apply_with_reject ? -1 : 1;
4905goto end;
4906}
4907}
4908
4909if (state->fake_ancestor &&
4910build_fake_ancestor(state, list)) {
4911res = -128;
4912goto end;
4913}
4914
4915if (state->diffstat && state->apply_verbosity > verbosity_silent)
4916stat_patch_list(state, list);
4917
4918if (state->numstat && state->apply_verbosity > verbosity_silent)
4919numstat_patch_list(state, list);
4920
4921if (state->summary && state->apply_verbosity > verbosity_silent)
4922summary_patch_list(list);
4923
4924if (flush_attributes)
4925reset_parsed_attributes();
4926end:
4927free_patch_list(list);
4928strbuf_release(&buf);
4929string_list_clear(&state->fn_table, 0);
4930return res;
4931}
4932
4933static int apply_option_parse_exclude(const struct option *opt,
4934const char *arg, int unset)
4935{
4936struct apply_state *state = opt->value;
4937
4938BUG_ON_OPT_NEG(unset);
4939
4940add_name_limit(state, arg, 1);
4941return 0;
4942}
4943
4944static int apply_option_parse_include(const struct option *opt,
4945const char *arg, int unset)
4946{
4947struct apply_state *state = opt->value;
4948
4949BUG_ON_OPT_NEG(unset);
4950
4951add_name_limit(state, arg, 0);
4952state->has_include = 1;
4953return 0;
4954}
4955
4956static int apply_option_parse_p(const struct option *opt,
4957const char *arg,
4958int unset)
4959{
4960struct apply_state *state = opt->value;
4961
4962BUG_ON_OPT_NEG(unset);
4963
4964state->p_value = atoi(arg);
4965state->p_value_known = 1;
4966return 0;
4967}
4968
4969static int apply_option_parse_space_change(const struct option *opt,
4970const char *arg, int unset)
4971{
4972struct apply_state *state = opt->value;
4973
4974BUG_ON_OPT_ARG(arg);
4975
4976if (unset)
4977state->ws_ignore_action = ignore_ws_none;
4978else
4979state->ws_ignore_action = ignore_ws_change;
4980return 0;
4981}
4982
4983static int apply_option_parse_whitespace(const struct option *opt,
4984const char *arg, int unset)
4985{
4986struct apply_state *state = opt->value;
4987
4988BUG_ON_OPT_NEG(unset);
4989
4990state->whitespace_option = arg;
4991if (parse_whitespace_option(state, arg))
4992return -1;
4993return 0;
4994}
4995
4996static int apply_option_parse_directory(const struct option *opt,
4997const char *arg, int unset)
4998{
4999struct apply_state *state = opt->value;
5000
5001BUG_ON_OPT_NEG(unset);
5002
5003strbuf_reset(&state->root);
5004strbuf_addstr(&state->root, arg);
5005strbuf_complete(&state->root, '/');
5006return 0;
5007}
5008
5009int apply_all_patches(struct apply_state *state,
5010int argc,
5011const char **argv,
5012int options)
5013{
5014int i;
5015int res;
5016int errs = 0;
5017int read_stdin = 1;
5018
5019for (i = 0; i < argc; i++) {
5020const char *arg = argv[i];
5021char *to_free = NULL;
5022int fd;
5023
5024if (!strcmp(arg, "-")) {
5025res = apply_patch(state, 0, "<stdin>", options);
5026if (res < 0)
5027goto end;
5028errs |= res;
5029read_stdin = 0;
5030continue;
5031} else
5032arg = to_free = prefix_filename(state->prefix, arg);
5033
5034fd = open(arg, O_RDONLY);
5035if (fd < 0) {
5036error(_("can't open patch '%s': %s"), arg, strerror(errno));
5037res = -128;
5038free(to_free);
5039goto end;
5040}
5041read_stdin = 0;
5042set_default_whitespace_mode(state);
5043res = apply_patch(state, fd, arg, options);
5044close(fd);
5045free(to_free);
5046if (res < 0)
5047goto end;
5048errs |= res;
5049}
5050set_default_whitespace_mode(state);
5051if (read_stdin) {
5052res = apply_patch(state, 0, "<stdin>", options);
5053if (res < 0)
5054goto end;
5055errs |= res;
5056}
5057
5058if (state->whitespace_error) {
5059if (state->squelch_whitespace_errors &&
5060state->squelch_whitespace_errors < state->whitespace_error) {
5061int squelched =
5062state->whitespace_error - state->squelch_whitespace_errors;
5063warning(Q_("squelched %d whitespace error",
5064"squelched %d whitespace errors",
5065squelched),
5066squelched);
5067}
5068if (state->ws_error_action == die_on_ws_error) {
5069error(Q_("%d line adds whitespace errors.",
5070"%d lines add whitespace errors.",
5071state->whitespace_error),
5072state->whitespace_error);
5073res = -128;
5074goto end;
5075}
5076if (state->applied_after_fixing_ws && state->apply)
5077warning(Q_("%d line applied after"
5078" fixing whitespace errors.",
5079"%d lines applied after"
5080" fixing whitespace errors.",
5081state->applied_after_fixing_ws),
5082state->applied_after_fixing_ws);
5083else if (state->whitespace_error)
5084warning(Q_("%d line adds whitespace errors.",
5085"%d lines add whitespace errors.",
5086state->whitespace_error),
5087state->whitespace_error);
5088}
5089
5090if (state->update_index) {
5091res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
5092if (res) {
5093error(_("Unable to write new index file"));
5094res = -128;
5095goto end;
5096}
5097}
5098
5099res = !!errs;
5100
5101end:
5102rollback_lock_file(&state->lock_file);
5103
5104if (state->apply_verbosity <= verbosity_silent) {
5105set_error_routine(state->saved_error_routine);
5106set_warn_routine(state->saved_warn_routine);
5107}
5108
5109if (res > -1)
5110return res;
5111return (res == -1 ? 1 : 128);
5112}
5113
5114int apply_parse_options(int argc, const char **argv,
5115struct apply_state *state,
5116int *force_apply, int *options,
5117const char * const *apply_usage)
5118{
5119struct option builtin_apply_options[] = {
5120OPT_CALLBACK_F(0, "exclude", state, N_("path"),
5121N_("don't apply changes matching the given path"),
5122PARSE_OPT_NONEG, apply_option_parse_exclude),
5123OPT_CALLBACK_F(0, "include", state, N_("path"),
5124N_("apply changes matching the given path"),
5125PARSE_OPT_NONEG, apply_option_parse_include),
5126OPT_CALLBACK('p', NULL, state, N_("num"),
5127N_("remove <num> leading slashes from traditional diff paths"),
5128apply_option_parse_p),
5129OPT_BOOL(0, "no-add", &state->no_add,
5130N_("ignore additions made by the patch")),
5131OPT_BOOL(0, "stat", &state->diffstat,
5132N_("instead of applying the patch, output diffstat for the input")),
5133OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5134OPT_NOOP_NOARG(0, "binary"),
5135OPT_BOOL(0, "numstat", &state->numstat,
5136N_("show number of added and deleted lines in decimal notation")),
5137OPT_BOOL(0, "summary", &state->summary,
5138N_("instead of applying the patch, output a summary for the input")),
5139OPT_BOOL(0, "check", &state->check,
5140N_("instead of applying the patch, see if the patch is applicable")),
5141OPT_BOOL(0, "index", &state->check_index,
5142N_("make sure the patch is applicable to the current index")),
5143OPT_BOOL('N', "intent-to-add", &state->ita_only,
5144N_("mark new files with `git add --intent-to-add`")),
5145OPT_BOOL(0, "cached", &state->cached,
5146N_("apply a patch without touching the working tree")),
5147OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
5148N_("accept a patch that touches outside the working area"),
5149PARSE_OPT_NOCOMPLETE),
5150OPT_BOOL(0, "apply", force_apply,
5151N_("also apply the patch (use with --stat/--summary/--check)")),
5152OPT_BOOL('3', "3way", &state->threeway,
5153N_( "attempt three-way merge, fall back on normal patch if that fails")),
5154OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
5155N_("build a temporary index based on embedded index information")),
5156/* Think twice before adding "--nul" synonym to this */
5157OPT_SET_INT('z', NULL, &state->line_termination,
5158N_("paths are separated with NUL character"), '\0'),
5159OPT_INTEGER('C', NULL, &state->p_context,
5160N_("ensure at least <n> lines of context match")),
5161OPT_CALLBACK(0, "whitespace", state, N_("action"),
5162N_("detect new or modified lines that have whitespace errors"),
5163apply_option_parse_whitespace),
5164OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
5165N_("ignore changes in whitespace when finding context"),
5166PARSE_OPT_NOARG, apply_option_parse_space_change),
5167OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
5168N_("ignore changes in whitespace when finding context"),
5169PARSE_OPT_NOARG, apply_option_parse_space_change),
5170OPT_BOOL('R', "reverse", &state->apply_in_reverse,
5171N_("apply the patch in reverse")),
5172OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
5173N_("don't expect at least one line of context")),
5174OPT_BOOL(0, "reject", &state->apply_with_reject,
5175N_("leave the rejected hunks in corresponding *.rej files")),
5176OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
5177N_("allow overlapping hunks")),
5178OPT__VERBOSITY(&state->apply_verbosity),
5179OPT_BIT(0, "inaccurate-eof", options,
5180N_("tolerate incorrectly detected missing new-line at the end of file"),
5181APPLY_OPT_INACCURATE_EOF),
5182OPT_BIT(0, "recount", options,
5183N_("do not trust the line counts in the hunk headers"),
5184APPLY_OPT_RECOUNT),
5185OPT_CALLBACK(0, "directory", state, N_("root"),
5186N_("prepend <root> to all filenames"),
5187apply_option_parse_directory),
5188OPT_BOOL(0, "allow-empty", &state->allow_empty,
5189N_("don't return error for empty patches")),
5190OPT_END()
5191};
5192
5193return parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);
5194}
5195