2 * Copyright 1986, Larry Wall
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following condition is met:
6 * 1. Redistributions of source code must retain the above copyright notice,
7 * this condition and the following disclaimer.
9 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
10 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
11 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
13 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
15 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
16 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
17 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
21 * patch - a program to apply diffs to original files
23 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
26 * $OpenBSD: pch.c,v 1.43 2014/11/18 17:03:35 tobias Exp $
30 #include <sys/types.h>
45 #include "pathnames.h"
47 /* Patch (diff listing) abstract type. */
49 static off_t p_filesize; /* size of the patch file */
50 static LINENUM p_first; /* 1st line number */
51 static LINENUM p_newfirst; /* 1st line number of replacement */
52 static LINENUM p_ptrn_lines; /* # lines in pattern */
53 static LINENUM p_repl_lines; /* # lines in replacement text */
54 static LINENUM p_end = -1; /* last line in hunk */
55 static LINENUM p_max; /* max allowed value of p_end */
56 static LINENUM p_context = 3; /* # of context lines */
57 static LINENUM p_input_line = 0; /* current line # from patch file */
58 static char **p_line = NULL;/* the text of the hunk */
59 static unsigned short *p_len = NULL; /* length of each line */
60 static char *p_char = NULL; /* +, -, and ! */
61 static int hunkmax = INITHUNKMAX; /* size of above arrays to begin with */
62 static int p_indent; /* indent to patch */
63 static off_t p_base; /* where to intuit this time */
64 static LINENUM p_bline; /* line # of p_base */
65 static off_t p_start; /* where intuit found a patch */
66 static LINENUM p_sline; /* and the line number for it */
67 static LINENUM p_hunk_beg; /* line number of current hunk */
68 static LINENUM p_efake = -1; /* end of faked up lines--don't free */
69 static LINENUM p_bfake = -1; /* beg of faked up lines */
70 static FILE *pfp = NULL; /* patch file pointer */
71 static char *bestguess = NULL; /* guess at correct filename */
75 static void grow_hunkmax(void);
76 static int intuit_diff_type(void);
77 static void next_intuit_at(off_t, LINENUM);
78 static void skip_to(off_t, LINENUM);
79 static size_t pgets(bool _do_indent);
80 static char *best_name(const struct file_name *, bool);
81 static char *posix_name(const struct file_name *, bool);
82 static size_t num_components(const char *);
83 static LINENUM strtolinenum(char *, char **);
86 * Prepare to look for the next patch in the patch file.
95 p_end = (LINENUM) - 1;
101 * Open the patch file at the beginning of time.
104 open_patch_file(const char *filename)
106 struct stat filestat;
109 if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
110 pfp = fopen(TMPPATNAME, "w");
112 pfatal("can't create %s", TMPPATNAME);
113 while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
114 nw = fwrite(buf, 1, nr, pfp);
116 pfatal("write error to %s", TMPPATNAME);
118 if (ferror(pfp) || fclose(pfp))
119 pfatal("can't write %s", TMPPATNAME);
120 filename = TMPPATNAME;
122 pfp = fopen(filename, "r");
124 pfatal("patch file %s not found", filename);
125 if (fstat(fileno(pfp), &filestat))
126 pfatal("can't stat %s", filename);
127 p_filesize = filestat.st_size;
128 next_intuit_at(0, 1L); /* start at the beginning */
133 * Make sure our dynamically realloced tables are malloced to begin with.
139 p_line = malloc(hunkmax * sizeof(char *));
141 p_len = malloc(hunkmax * sizeof(unsigned short));
143 p_char = malloc(hunkmax * sizeof(char));
147 * Enlarge the arrays containing the current hunk of patch.
152 int new_hunkmax = hunkmax * 2;
154 if (p_line == NULL || p_len == NULL || p_char == NULL)
155 fatal("Internal memory allocation error\n");
157 p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
158 p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
159 p_char = reallocf(p_char, new_hunkmax * sizeof(char));
161 if (p_line != NULL && p_len != NULL && p_char != NULL) {
162 hunkmax = new_hunkmax;
167 fatal("out of memory\n");
168 out_of_mem = true; /* whatever is null will be allocated again */
169 /* from within plan_a(), of all places */
172 /* True if the remainder of the patch file contains a diff of some sort. */
175 there_is_another_patch(void)
179 if (p_base != 0 && p_base >= p_filesize) {
186 nonempty_patchf_seen = true;
189 diff_type = intuit_diff_type();
193 say(" Ignoring the trailing garbage.\ndone\n");
195 say(" I can't seem to find a patch in there anywhere.\n");
199 say(" %sooks like %s to me...\n",
200 (p_base == 0 ? "L" : "The next patch l"),
201 diff_type == UNI_DIFF ? "a unified diff" :
202 diff_type == CONTEXT_DIFF ? "a context diff" :
203 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
204 diff_type == NORMAL_DIFF ? "a normal diff" :
206 if (p_indent && verbose)
207 say("(Patch is indented %d space%s.)\n", p_indent,
208 p_indent == 1 ? "" : "s");
209 skip_to(p_start, p_sline);
210 while (filearg[0] == NULL) {
211 if (force || batch) {
212 say("No file to patch. Skipping...\n");
213 filearg[0] = xstrdup(bestguess);
214 skip_rest_of_patch = true;
217 ask("File to patch: ");
220 bestguess = xstrdup(buf);
221 filearg[0] = fetchname(buf, &exists, 0);
224 * fetchname can now return buf = NULL, exists = true, to
225 * indicate to the caller that /dev/null was specified. Retain
226 * previous behavior for now until this can be better evaluted.
228 if (filearg[0] == NULL || !exists) {
229 int def_skip = *bestguess == '\0';
230 ask("No file found--skip this patch? [%c] ",
231 def_skip ? 'y' : 'n');
232 if (*buf == 'n' || (!def_skip && *buf != 'y'))
235 say("Skipping patch...\n");
237 filearg[0] = fetchname(bestguess, &exists, 0);
238 skip_rest_of_patch = true;
246 p4_fetchname(struct file_name *name, char *str)
250 /* Skip leading whitespace. */
251 while (isspace((unsigned char)*str))
254 /* Remove the file revision number. */
255 for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
261 name->path = fetchname(str, &name->exists, strippath);
264 /* Determine what kind of diff is in the remaining part of the patch file. */
267 intuit_diff_type(void)
269 off_t this_line = 0, previous_line;
270 off_t first_command_line = -1;
271 LINENUM fcl_line = -1;
272 bool last_line_was_command = false, this_is_a_command = false;
273 bool stars_last_line = false, stars_this_line = false;
276 struct file_name names[MAX_FILE];
277 int piece_of_git = 0;
279 memset(names, 0, sizeof(names));
280 ok_to_create_file = false;
281 fseeko(pfp, p_base, SEEK_SET);
282 p_input_line = p_bline - 1;
284 previous_line = this_line;
285 last_line_was_command = this_is_a_command;
286 stars_last_line = stars_this_line;
287 this_line = ftello(pfp);
290 if (pgets(false) == 0) {
291 if (first_command_line >= 0) {
292 /* nothing but deletes!? */
293 p_start = first_command_line;
299 p_sline = p_input_line;
304 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
306 indent += 8 - (indent % 8);
310 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
312 this_is_a_command = (isdigit((unsigned char)*s) &&
313 (*t == 'd' || *t == 'c' || *t == 'a'));
314 if (first_command_line < 0 && this_is_a_command) {
315 first_command_line = this_line;
316 fcl_line = p_input_line;
317 p_indent = indent; /* assume this for now */
319 if (!stars_last_line && strnEQ(s, "*** ", 4))
320 names[OLD_FILE].path = fetchname(s + 4,
321 &names[OLD_FILE].exists, strippath);
322 else if (strnEQ(s, "--- ", 4)) {
324 if (piece_of_git && strippath == 957 &&
325 strnEQ(s, "--- a/", 6))
327 names[NEW_FILE].path = fetchname(s + off,
328 &names[NEW_FILE].exists, strippath);
329 } else if (strnEQ(s, "+++ ", 4)) {
330 /* pretend it is the old name */
332 if (piece_of_git && strippath == 957 &&
333 strnEQ(s, "+++ b/", 6))
335 names[OLD_FILE].path = fetchname(s + off,
336 &names[OLD_FILE].exists, strippath);
337 } else if (strnEQ(s, "Index:", 6))
338 names[INDEX_FILE].path = fetchname(s + 6,
339 &names[INDEX_FILE].exists, strippath);
340 else if (strnEQ(s, "Prereq:", 7)) {
341 for (t = s + 7; isspace((unsigned char)*t); t++)
343 revision = xstrdup(t);
345 *t && !isspace((unsigned char)*t); t++)
348 if (*revision == '\0') {
352 } else if (strnEQ(s, "diff --git a/", 13)) {
353 /* Git-style diffs. */
355 } else if (strnEQ(s, "==== ", 5)) {
356 /* Perforce-style diffs. */
357 if ((t = strstr(s + 5, " - ")) != NULL)
358 p4_fetchname(&names[NEW_FILE], t + 3);
359 p4_fetchname(&names[OLD_FILE], s + 5);
361 if ((!diff_type || diff_type == ED_DIFF) &&
362 first_command_line >= 0 &&
365 p_start = first_command_line;
370 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
371 if (strnEQ(s + 4, "0,0", 3))
372 ok_to_create_file = true;
375 p_sline = p_input_line;
379 stars_this_line = strnEQ(s, "********", 8);
380 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
381 strnEQ(s, "*** ", 4)) {
382 if (strtolinenum(s + 4, &s) == 0)
383 ok_to_create_file = true;
385 * If this is a new context diff the character just
386 * at the end of the line is a '*'.
388 while (*s && *s != '\n')
391 p_start = previous_line;
392 p_sline = p_input_line - 1;
393 retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
396 if ((!diff_type || diff_type == NORMAL_DIFF) &&
397 last_line_was_command &&
398 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
399 p_start = previous_line;
400 p_sline = p_input_line - 1;
402 retval = NORMAL_DIFF;
407 if (retval == UNI_DIFF) {
408 /* unswap old and new */
409 struct file_name tmp = names[OLD_FILE];
410 names[OLD_FILE] = names[NEW_FILE];
411 names[NEW_FILE] = tmp;
420 * If we've successfully determined a diff type, stored in
421 * retval, path == NULL means _PATH_DEVNULL if exists is set.
422 * Explicitly specify it here to make it easier to detect later
423 * on that we're actually creating a file and not that we've
424 * just goofed something up.
426 if (names[OLD_FILE].path != NULL)
427 source_file = xstrdup(names[OLD_FILE].path);
428 else if (names[OLD_FILE].exists)
429 source_file = xstrdup(_PATH_DEVNULL);
431 if (filearg[0] == NULL) {
433 filearg[0] = posix_name(names, ok_to_create_file);
435 /* Ignore the Index: name for context diffs, like GNU */
436 if (names[OLD_FILE].path != NULL ||
437 names[NEW_FILE].path != NULL) {
438 free(names[INDEX_FILE].path);
439 names[INDEX_FILE].path = NULL;
441 filearg[0] = best_name(names, ok_to_create_file);
447 if (filearg[0] != NULL)
448 bestguess = xstrdup(filearg[0]);
449 else if (!ok_to_create_file) {
451 * We don't want to create a new file but we need a
452 * filename to set bestguess. Avoid setting filearg[0]
453 * so the file is not created automatically.
456 bestguess = posix_name(names, true);
458 bestguess = best_name(names, true);
460 free(names[OLD_FILE].path);
461 free(names[NEW_FILE].path);
462 free(names[INDEX_FILE].path);
467 * Remember where this patch ends so we know where to start up again.
470 next_intuit_at(off_t file_pos, LINENUM file_line)
477 * Basically a verbose fseeko() to the actual diff listing.
480 skip_to(off_t file_pos, LINENUM file_line)
484 if (p_base > file_pos)
485 fatal("Internal error: seek %lld>%lld\n",
486 (long long)p_base, (long long)file_pos);
487 if (verbose && p_base < file_pos) {
488 fseeko(pfp, p_base, SEEK_SET);
489 say("The text leading up to this was:\n--------------------------\n");
490 while (ftello(pfp) < file_pos) {
493 fatal("Unexpected end of file\n");
496 say("--------------------------\n");
498 fseeko(pfp, file_pos, SEEK_SET);
499 p_input_line = file_line - 1;
502 /* Make this a function for better debugging. */
506 fatal("malformed patch at line %ld: %s", p_input_line, buf);
507 /* about as informative as "Syntax error" in C */
511 * True if the line has been discarded (i.e. it is a line saying
512 * "\ No newline at end of file".)
515 remove_special_line(void)
523 } while (c != EOF && c != '\n');
528 fseeko(pfp, -1, SEEK_CUR);
534 * True if there is more of the current diff listing to process.
539 off_t line_beginning; /* file pos of the current line */
540 LINENUM repl_beginning; /* index of --- line */
541 LINENUM fillcnt; /* #lines of missing ptrn or repl */
542 LINENUM fillsrc; /* index of first line to copy */
543 LINENUM filldst; /* index of first missing line */
544 bool ptrn_spaces_eaten; /* ptrn was slightly malformed */
545 bool repl_could_be_missing; /* no + or ! lines in this hunk */
546 bool repl_missing; /* we are now backtracking */
547 off_t repl_backtrack_position; /* file pos of first repl line */
548 LINENUM repl_patch_line; /* input line number for same */
549 LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
555 if (p_end == p_efake)
556 p_end = p_bfake; /* don't free twice */
563 p_max = hunkmax; /* gets reduced when --- found */
564 if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
565 line_beginning = ftello(pfp);
570 ptrn_spaces_eaten = false;
571 repl_could_be_missing = true;
572 repl_missing = false;
573 repl_backtrack_position = 0;
579 if (len == 0 || strnNE(buf, "********", 8)) {
580 next_intuit_at(line_beginning, p_input_line);
584 p_hunk_beg = p_input_line + 1;
585 while (p_end < p_max) {
586 line_beginning = ftello(pfp);
590 if (repl_beginning && repl_could_be_missing) {
594 fatal("unexpected end of file in patch\n");
597 if (p_end >= hunkmax)
598 fatal("Internal error: hunk larger than hunk "
600 p_char[p_end] = *buf;
601 p_line[p_end] = NULL;
604 if (strnEQ(buf, "********", 8)) {
605 if (repl_beginning && repl_could_be_missing) {
609 fatal("unexpected end of hunk "
614 if (repl_beginning && repl_could_be_missing) {
618 fatal("unexpected *** at line %ld: %s",
622 p_line[p_end] = savestr(buf);
628 *s && !isdigit((unsigned char)*s); s++)
632 if (strnEQ(s, "0,0", 3))
633 memmove(s, s + 2, strlen(s + 2) + 1);
634 p_first = strtolinenum(s, &s);
637 *s && !isdigit((unsigned char)*s); s++)
641 p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
642 if (p_ptrn_lines < 0)
650 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
651 p_ptrn_lines >= LINENUM_MAX - 6)
654 /* we need this much at least */
655 p_max = p_ptrn_lines + 6;
656 while (p_max >= hunkmax)
662 if (repl_beginning ||
663 (p_end != p_ptrn_lines + 1 +
664 (p_char[p_end - 1] == '\n'))) {
667 * `old' lines were omitted;
668 * set up to fill them in
669 * from 'new' context lines.
671 p_end = p_ptrn_lines + 1;
674 fillcnt = p_ptrn_lines;
676 if (repl_beginning) {
677 if (repl_could_be_missing) {
681 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
682 p_input_line, p_hunk_beg + repl_beginning);
684 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
685 (p_end <= p_ptrn_lines
688 p_input_line, p_hunk_beg);
692 repl_beginning = p_end;
693 repl_backtrack_position = ftello(pfp);
694 repl_patch_line = p_input_line;
695 p_line[p_end] = savestr(buf);
701 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
705 p_newfirst = strtolinenum(s, &s);
707 for (; *s && !isdigit((unsigned char)*s); s++)
711 p_repl_lines = strtolinenum(s, &s) -
713 if (p_repl_lines < 0)
715 } else if (p_newfirst)
721 if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
722 p_repl_lines >= LINENUM_MAX - p_end)
724 p_max = p_repl_lines + p_end;
725 if (p_max > MAXHUNKSIZE)
726 fatal("hunk too large (%ld lines) at line %ld: %s",
727 p_max, p_input_line, buf);
728 while (p_max >= hunkmax)
730 if (p_repl_lines != ptrn_copiable &&
731 (p_context != 0 || p_repl_lines != 1))
732 repl_could_be_missing = false;
738 repl_could_be_missing = false;
740 if (buf[1] == '\n' && canonicalize)
741 strlcpy(buf + 1, " \n", buf_size - 1);
742 if (!isspace((unsigned char)buf[1]) &&
743 buf[1] != '>' && buf[1] != '<' &&
744 repl_beginning && repl_could_be_missing) {
749 if (context < p_context)
753 p_line[p_end] = savestr(buf + 2);
758 if (p_end == p_ptrn_lines) {
759 if (remove_special_line()) {
762 l = strlen(p_line[p_end]) - 1;
763 (p_line[p_end])[l] = 0;
768 case '\n': /* assume the 2 spaces got eaten */
769 if (repl_beginning && repl_could_be_missing &&
770 (!ptrn_spaces_eaten ||
771 diff_type == NEW_CONTEXT_DIFF)) {
775 p_line[p_end] = savestr(buf);
780 if (p_end != p_ptrn_lines + 1) {
781 ptrn_spaces_eaten |= (repl_beginning != 0);
789 if (!isspace((unsigned char)buf[1]) &&
790 repl_beginning && repl_could_be_missing) {
797 p_line[p_end] = savestr(buf + 2);
804 if (repl_beginning && repl_could_be_missing) {
810 /* set up p_len for strncmp() so we don't have to */
811 /* assume null termination */
813 p_len[p_end] = strlen(p_line[p_end]);
819 if (p_end >= 0 && !repl_beginning)
820 fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
824 /* reset state back to just after --- */
825 p_input_line = repl_patch_line;
826 for (p_end--; p_end > repl_beginning; p_end--)
828 fseeko(pfp, repl_backtrack_position, SEEK_SET);
830 /* redundant 'new' context lines were omitted - set */
831 /* up to fill them in from the old file context */
832 if (!p_context && p_repl_lines == 1) {
837 filldst = repl_beginning + 1;
838 fillcnt = p_repl_lines;
840 } else if (!p_context && fillcnt == 1) {
841 /* the first hunk was a null hunk with no context */
842 /* and we were expecting one line -- fix it up. */
843 while (filldst < p_end) {
844 p_line[filldst] = p_line[filldst + 1];
845 p_char[filldst] = p_char[filldst + 1];
846 p_len[filldst] = p_len[filldst + 1];
850 repl_beginning--; /* this doesn't need to be fixed */
853 p_first++; /* do append rather than insert */
857 if (diff_type == CONTEXT_DIFF &&
858 (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
861 "(Fascinating--this is really a new-style context diff but without",
862 "the telltale extra asterisks on the *** line that usually indicate",
863 "the new style...)");
864 diff_type = NEW_CONTEXT_DIFF;
866 /* if there were omitted context lines, fill them in now */
868 p_bfake = filldst; /* remember where not to free() */
869 p_efake = filldst + fillcnt - 1;
870 while (fillcnt-- > 0) {
871 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
874 fatal("replacement text or line numbers mangled in hunk at line %ld\n",
876 p_line[filldst] = p_line[fillsrc];
877 p_char[filldst] = p_char[fillsrc];
878 p_len[filldst] = p_len[fillsrc];
882 while (fillsrc <= p_end && fillsrc != repl_beginning &&
883 p_char[fillsrc] != ' ')
887 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
888 fillsrc, filldst, repl_beginning, p_end + 1);
890 if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
892 if (filldst != p_end + 1 && filldst != repl_beginning)
895 if (p_line[p_end] != NULL) {
896 if (remove_special_line()) {
898 (p_line[p_end])[p_len[p_end]] = 0;
901 } else if (diff_type == UNI_DIFF) {
902 LINENUM fillold; /* index of old lines */
903 LINENUM fillnew; /* index of new lines */
906 line_beginning = ftello(pfp); /* file pos of the current line */
909 if (len == 0 || strnNE(buf, "@@ -", 4)) {
910 next_intuit_at(line_beginning, p_input_line);
916 p_first = strtolinenum(s, &s);
918 p_ptrn_lines = strtolinenum(s + 1, &s);
923 if (*s != '+' || !*++s)
925 p_newfirst = strtolinenum(s, &s);
927 p_repl_lines = strtolinenum(s + 1, &s);
934 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
935 p_newfirst > LINENUM_MAX - p_repl_lines ||
936 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
939 p_first++; /* do append rather than insert */
940 p_max = p_ptrn_lines + p_repl_lines + 1;
941 while (p_max >= hunkmax)
944 fillnew = fillold + p_ptrn_lines;
945 p_end = fillnew + p_repl_lines;
946 snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
947 p_first + p_ptrn_lines - 1);
948 p_line[0] = savestr(buf);
954 snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
955 p_newfirst + p_repl_lines - 1);
956 p_line[fillnew] = savestr(buf);
961 p_char[fillnew++] = '=';
964 p_hunk_beg = p_input_line + 1;
965 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
966 line_beginning = ftello(pfp);
970 if (p_max - fillnew < 3) {
971 /* assume blank lines got chopped */
972 strlcpy(buf, " \n", buf_size);
974 fatal("unexpected end of file in patch\n");
977 if (*buf == '\t' || *buf == '\n') {
978 ch = ' '; /* assume the space got eaten */
982 s = savestr(buf + 1);
985 while (--fillnew > p_ptrn_lines)
986 free(p_line[fillnew]);
992 if (fillold > p_ptrn_lines) {
997 p_char[fillold] = ch;
999 p_len[fillold++] = strlen(s);
1000 if (fillold > p_ptrn_lines) {
1001 if (remove_special_line()) {
1002 p_len[fillold - 1] -= 1;
1003 s[p_len[fillold - 1]] = 0;
1011 if (fillold > p_ptrn_lines) {
1013 while (--fillnew > p_ptrn_lines)
1014 free(p_line[fillnew]);
1015 p_end = fillold - 1;
1019 p_char[fillold] = ch;
1020 p_line[fillold] = s;
1021 p_len[fillold++] = strlen(s);
1024 while (--fillnew > p_ptrn_lines)
1025 free(p_line[fillnew]);
1026 p_end = fillold - 1;
1029 if (fillold > p_ptrn_lines) {
1030 if (remove_special_line()) {
1031 p_len[fillold - 1] -= 1;
1032 s[p_len[fillold - 1]] = 0;
1037 if (fillnew > p_end) {
1039 while (--fillnew > p_ptrn_lines)
1040 free(p_line[fillnew]);
1041 p_end = fillold - 1;
1044 p_char[fillnew] = ch;
1045 p_line[fillnew] = s;
1046 p_len[fillnew++] = strlen(s);
1047 if (fillold > p_ptrn_lines) {
1048 if (remove_special_line()) {
1049 p_len[fillnew - 1] -= 1;
1050 s[p_len[fillnew - 1]] = 0;
1058 if (ch != ' ' && context > 0) {
1059 if (context < p_context)
1060 p_context = context;
1064 } else { /* normal diff--fake it up */
1069 line_beginning = ftello(pfp);
1073 if (len == 0 || !isdigit((unsigned char)*buf)) {
1074 next_intuit_at(line_beginning, p_input_line);
1077 p_first = strtolinenum(buf, &s);
1079 p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1080 if (p_ptrn_lines < 0)
1083 p_ptrn_lines = (*s != 'a');
1085 if (hunk_type == 'a')
1086 p_first++; /* do append rather than insert */
1087 min = strtolinenum(s + 1, &s);
1089 max = strtolinenum(s + 1, &s);
1092 if (min < 0 || min > max || max - min == LINENUM_MAX)
1094 if (hunk_type == 'd')
1097 p_repl_lines = max - min + 1;
1098 if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1099 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1101 p_end = p_ptrn_lines + p_repl_lines + 1;
1102 if (p_end > MAXHUNKSIZE)
1103 fatal("hunk too large (%ld lines) at line %ld: %s",
1104 p_end, p_input_line, buf);
1105 while (p_end >= hunkmax)
1107 snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1108 p_first + p_ptrn_lines - 1);
1109 p_line[0] = savestr(buf);
1115 for (i = 1; i <= p_ptrn_lines; i++) {
1119 fatal("unexpected end of file in patch at line %ld\n",
1122 fatal("< expected at line %ld of patch\n",
1124 p_line[i] = savestr(buf + 2);
1129 p_len[i] = strlen(p_line[i]);
1133 if (remove_special_line()) {
1135 (p_line[i - 1])[p_len[i - 1]] = 0;
1137 if (hunk_type == 'c') {
1141 fatal("unexpected end of file in patch at line %ld\n",
1144 fatal("--- expected at line %ld of patch\n",
1147 snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1148 p_line[i] = savestr(buf);
1154 for (i++; i <= p_end; i++) {
1158 fatal("unexpected end of file in patch at line %ld\n",
1161 fatal("> expected at line %ld of patch\n",
1163 /* Don't overrun if we don't have enough line */
1165 p_line[i] = savestr(buf + 2);
1167 p_line[i] = savestr("");
1173 p_len[i] = strlen(p_line[i]);
1177 if (remove_special_line()) {
1179 (p_line[i - 1])[p_len[i - 1]] = 0;
1182 if (reverse) /* backwards patch? */
1184 say("Not enough memory to swap next hunk!\n");
1190 for (i = 0; i <= p_end; i++) {
1191 if (i == p_ptrn_lines)
1195 fprintf(stderr, "%3ld %c %c %s", i, p_char[i],
1196 special, p_line[i]);
1201 if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1202 p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
1207 * Input a line from the patch file.
1208 * Worry about indentation if do_indent is true.
1209 * The line is read directly into the buf global variable which
1210 * is resized if necessary in order to hold the complete line.
1211 * Returns the number of characters read including the terminating
1215 pgets(bool do_indent)
1219 int indent = 0, skipped = 0;
1221 line = fgetln(pfp, &len);
1223 if (len + 1 > buf_size) {
1224 while (len + 1 > buf_size)
1227 buf = malloc(buf_size);
1229 fatal("out of memory\n");
1231 if (do_indent == 1 && p_indent) {
1233 indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1234 line++, skipped++) {
1236 indent += 8 - (indent %7);
1241 memcpy(buf, line, len - skipped);
1242 buf[len - skipped] = '\0';
1249 * Reverse the old and new portions of the current hunk.
1254 char **tp_line; /* the text of the hunk */
1255 unsigned short *tp_len;/* length of each line */
1256 char *tp_char; /* +, -, and ! */
1259 bool blankline = false;
1263 p_first = p_newfirst;
1266 /* make a scratch copy */
1271 p_line = NULL; /* force set_hunkmax to allocate again */
1275 if (p_line == NULL || p_len == NULL || p_char == NULL) {
1283 return false; /* not enough memory to swap hunk! */
1285 /* now turn the new into the old */
1287 i = p_ptrn_lines + 1;
1288 if (tp_char[i] == '\n') { /* account for possible blank line */
1292 if (p_efake >= 0) { /* fix non-freeable ptr range */
1300 for (n = 0; i <= p_end; i++, n++) {
1301 p_line[n] = tp_line[i];
1302 p_char[n] = tp_char[i];
1303 if (p_char[n] == '+')
1305 p_len[n] = tp_len[i];
1308 i = p_ptrn_lines + 1;
1309 p_line[n] = tp_line[i];
1310 p_char[n] = tp_char[i];
1311 p_len[n] = tp_len[i];
1314 if (p_char[0] != '=')
1315 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1316 p_input_line, p_char[0]);
1318 for (s = p_line[0]; *s; s++)
1322 /* now turn the old into the new */
1324 if (p_char[0] != '*')
1325 fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1326 p_input_line, p_char[0]);
1328 for (s = tp_line[0]; *s; s++)
1331 for (i = 0; n <= p_end; i++, n++) {
1332 p_line[n] = tp_line[i];
1333 p_char[n] = tp_char[i];
1334 if (p_char[n] == '-')
1336 p_len[n] = tp_len[i];
1339 if (i != p_ptrn_lines + 1)
1340 fatal("Malformed patch at line %ld: expected %ld lines, "
1342 p_input_line, p_ptrn_lines + 1, i);
1345 p_ptrn_lines = p_repl_lines;
1356 * Return the specified line position in the old file of the old context.
1365 * Return the number of lines of old context.
1368 pch_ptrn_lines(void)
1370 return p_ptrn_lines;
1374 * Return the probable line position in the new file of the first line.
1383 * Return the number of lines in the replacement text including context.
1386 pch_repl_lines(void)
1388 return p_repl_lines;
1392 * Return the number of lines in the whole hunk.
1401 * Return the number of context lines before the first changed line.
1410 * Return the length of a particular patch line.
1413 pch_line_len(LINENUM line)
1419 * Return the control character (+, -, *, !, etc) for a patch line.
1422 pch_char(LINENUM line)
1424 return p_char[line];
1428 * Return a pointer to a particular patch line.
1431 pfetch(LINENUM line)
1433 return p_line[line];
1437 * Return where in the patch file this hunk began, for error messages.
1446 * Apply an ed script by feeding ed itself.
1452 off_t beginning_of_this_line;
1453 FILE *pipefp = NULL;
1456 if (!skip_rest_of_patch) {
1457 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1459 fatal("can't create temp file %s", TMPOUTNAME);
1461 snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1462 verbose ? " " : " -s ", TMPOUTNAME);
1463 pipefp = popen(buf, "w");
1466 beginning_of_this_line = ftello(pfp);
1467 if (pgets(true) == 0) {
1468 next_intuit_at(beginning_of_this_line, p_input_line);
1472 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1474 /* POSIX defines allowed commands as {a,c,d,i,s} */
1475 if (isdigit((unsigned char)*buf) &&
1476 (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1482 t = strchr(buf, '\0') - 1;
1483 while (--t >= buf && *t == '\\')
1484 continuation = !continuation;
1485 if (!continuation ||
1491 } else if (*t != 'd') {
1492 while (pgets(true)) {
1496 if (strEQ(buf, ".\n"))
1501 next_intuit_at(beginning_of_this_line, p_input_line);
1507 fprintf(pipefp, "w\n");
1508 fprintf(pipefp, "q\n");
1513 if (move_file(TMPOUTNAME, outname) < 0) {
1515 chmod(TMPOUTNAME, filemode);
1517 chmod(outname, filemode);
1523 * Choose the name of the file to be patched based on POSIX rules.
1524 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1525 * if the user specified --posix or set POSIXLY_CORRECT.
1528 posix_name(const struct file_name *names, bool assume_exists)
1534 * POSIX states that the filename will be chosen from one
1535 * of the old, new and index names (in that order) if
1536 * the file exists relative to CWD after -p stripping.
1538 for (i = 0; i < MAX_FILE; i++) {
1539 if (names[i].path != NULL && names[i].exists) {
1540 path = names[i].path;
1544 if (path == NULL && !assume_exists) {
1546 * No files found, check to see if the diff could be
1547 * creating a new file.
1549 if (path == NULL && ok_to_create_file &&
1550 names[NEW_FILE].path != NULL)
1551 path = names[NEW_FILE].path;
1554 return path ? xstrdup(path) : NULL;
1558 compare_names(const struct file_name *names, bool assume_exists)
1560 size_t min_components, min_baselen, min_len, tmp;
1566 * The "best" name is the one with the fewest number of path
1567 * components, the shortest basename length, and the shortest
1568 * overall length (in that order). We only use the Index: file
1569 * if neither of the old or new files could be intuited from
1572 min_components = min_baselen = min_len = SIZE_MAX;
1573 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1574 path = names[i].path;
1575 if (path == NULL || (!names[i].exists && !assume_exists))
1577 if ((tmp = num_components(path)) > min_components)
1579 if (tmp < min_components) {
1580 min_components = tmp;
1583 if ((tmp = strlen(basename(path))) > min_baselen)
1585 if (tmp < min_baselen) {
1589 if ((tmp = strlen(path)) > min_len)
1598 * Choose the name of the file to be patched based the "best" one
1602 best_name(const struct file_name *names, bool assume_exists)
1606 best = compare_names(names, assume_exists);
1608 /* No match? Check to see if the diff could be creating a new file. */
1609 if (best == NULL && ok_to_create_file)
1610 best = names[NEW_FILE].path;
1612 return best ? xstrdup(best) : NULL;
1616 num_components(const char *path)
1621 for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1623 cp++; /* skip consecutive slashes */
1629 * Convert number at NPTR into LINENUM and save address of first
1630 * character that is not a digit in ENDPTR. If conversion is not
1631 * possible, call fatal.
1634 strtolinenum(char *nptr, char **endptr)
1641 for (p = nptr; isdigit((unsigned char)*p); p++)
1650 rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1652 fatal("invalid line number at line %ld: `%s' is %s\n",
1653 p_input_line, nptr, errstr);