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 */
73 static void grow_hunkmax(void);
74 static int intuit_diff_type(void);
75 static void next_intuit_at(off_t, LINENUM);
76 static void skip_to(off_t, LINENUM);
77 static size_t pgets(bool _do_indent);
78 static char *best_name(const struct file_name *, bool);
79 static char *posix_name(const struct file_name *, bool);
80 static size_t num_components(const char *);
81 static LINENUM strtolinenum(char *, char **);
84 * Prepare to look for the next patch in the patch file.
93 p_end = (LINENUM) - 1;
99 * Open the patch file at the beginning of time.
102 open_patch_file(const char *filename)
104 struct stat filestat;
107 if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
108 pfp = fopen(TMPPATNAME, "w");
110 pfatal("can't create %s", TMPPATNAME);
111 while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
112 nw = fwrite(buf, 1, nr, pfp);
114 pfatal("write error to %s", TMPPATNAME);
116 if (ferror(pfp) || fclose(pfp))
117 pfatal("can't write %s", TMPPATNAME);
118 filename = TMPPATNAME;
120 pfp = fopen(filename, "r");
122 pfatal("patch file %s not found", filename);
123 if (fstat(fileno(pfp), &filestat))
124 pfatal("can't stat %s", filename);
125 p_filesize = filestat.st_size;
126 next_intuit_at(0, 1L); /* start at the beginning */
131 * Make sure our dynamically realloced tables are malloced to begin with.
137 p_line = malloc(hunkmax * sizeof(char *));
139 p_len = malloc(hunkmax * sizeof(unsigned short));
141 p_char = malloc(hunkmax * sizeof(char));
145 * Enlarge the arrays containing the current hunk of patch.
150 int new_hunkmax = hunkmax * 2;
152 if (p_line == NULL || p_len == NULL || p_char == NULL)
153 fatal("Internal memory allocation error\n");
155 p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
156 p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
157 p_char = reallocf(p_char, new_hunkmax * sizeof(char));
159 if (p_line != NULL && p_len != NULL && p_char != NULL) {
160 hunkmax = new_hunkmax;
165 fatal("out of memory\n");
166 out_of_mem = true; /* whatever is null will be allocated again */
167 /* from within plan_a(), of all places */
170 /* True if the remainder of the patch file contains a diff of some sort. */
173 there_is_another_patch(void)
177 if (p_base != 0 && p_base >= p_filesize) {
184 diff_type = intuit_diff_type();
188 say(" Ignoring the trailing garbage.\ndone\n");
190 say(" I can't seem to find a patch in there anywhere.\n");
194 say(" %sooks like %s to me...\n",
195 (p_base == 0 ? "L" : "The next patch l"),
196 diff_type == UNI_DIFF ? "a unified diff" :
197 diff_type == CONTEXT_DIFF ? "a context diff" :
198 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
199 diff_type == NORMAL_DIFF ? "a normal diff" :
201 if (p_indent && verbose)
202 say("(Patch is indented %d space%s.)\n", p_indent,
203 p_indent == 1 ? "" : "s");
204 skip_to(p_start, p_sline);
205 while (filearg[0] == NULL) {
206 if (force || batch) {
207 say("No file to patch. Skipping...\n");
208 filearg[0] = xstrdup(bestguess);
209 skip_rest_of_patch = true;
212 ask("File to patch: ");
215 bestguess = xstrdup(buf);
216 filearg[0] = fetchname(buf, &exists, 0);
219 int def_skip = *bestguess == '\0';
220 ask("No file found--skip this patch? [%c] ",
221 def_skip ? 'y' : 'n');
222 if (*buf == 'n' || (!def_skip && *buf != 'y'))
225 say("Skipping patch...\n");
227 filearg[0] = fetchname(bestguess, &exists, 0);
228 skip_rest_of_patch = true;
236 p4_fetchname(struct file_name *name, char *str)
240 /* Skip leading whitespace. */
241 while (isspace((unsigned char)*str))
244 /* Remove the file revision number. */
245 for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
251 name->path = fetchname(str, &name->exists, strippath);
254 /* Determine what kind of diff is in the remaining part of the patch file. */
257 intuit_diff_type(void)
259 off_t this_line = 0, previous_line;
260 off_t first_command_line = -1;
261 LINENUM fcl_line = -1;
262 bool last_line_was_command = false, this_is_a_command = false;
263 bool stars_last_line = false, stars_this_line = false;
266 struct file_name names[MAX_FILE];
268 memset(names, 0, sizeof(names));
269 ok_to_create_file = false;
270 fseeko(pfp, p_base, SEEK_SET);
271 p_input_line = p_bline - 1;
273 previous_line = this_line;
274 last_line_was_command = this_is_a_command;
275 stars_last_line = stars_this_line;
276 this_line = ftello(pfp);
279 if (pgets(false) == 0) {
280 if (first_command_line >= 0) {
281 /* nothing but deletes!? */
282 p_start = first_command_line;
288 p_sline = p_input_line;
293 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
295 indent += 8 - (indent % 8);
299 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
301 this_is_a_command = (isdigit((unsigned char)*s) &&
302 (*t == 'd' || *t == 'c' || *t == 'a'));
303 if (first_command_line < 0 && this_is_a_command) {
304 first_command_line = this_line;
305 fcl_line = p_input_line;
306 p_indent = indent; /* assume this for now */
308 if (!stars_last_line && strnEQ(s, "*** ", 4))
309 names[OLD_FILE].path = fetchname(s + 4,
310 &names[OLD_FILE].exists, strippath);
311 else if (strnEQ(s, "--- ", 4))
312 names[NEW_FILE].path = fetchname(s + 4,
313 &names[NEW_FILE].exists, strippath);
314 else if (strnEQ(s, "+++ ", 4))
315 /* pretend it is the old name */
316 names[OLD_FILE].path = fetchname(s + 4,
317 &names[OLD_FILE].exists, strippath);
318 else if (strnEQ(s, "Index:", 6))
319 names[INDEX_FILE].path = fetchname(s + 6,
320 &names[INDEX_FILE].exists, strippath);
321 else if (strnEQ(s, "Prereq:", 7)) {
322 for (t = s + 7; isspace((unsigned char)*t); t++)
324 revision = xstrdup(t);
326 *t && !isspace((unsigned char)*t); t++)
329 if (*revision == '\0') {
333 } else if (strnEQ(s, "==== ", 5)) {
334 /* Perforce-style diffs. */
335 if ((t = strstr(s + 5, " - ")) != NULL)
336 p4_fetchname(&names[NEW_FILE], t + 3);
337 p4_fetchname(&names[OLD_FILE], s + 5);
339 if ((!diff_type || diff_type == ED_DIFF) &&
340 first_command_line >= 0 &&
343 p_start = first_command_line;
348 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
349 if (strnEQ(s + 4, "0,0", 3))
350 ok_to_create_file = true;
353 p_sline = p_input_line;
357 stars_this_line = strnEQ(s, "********", 8);
358 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
359 strnEQ(s, "*** ", 4)) {
360 if (strtolinenum(s + 4, &s) == 0)
361 ok_to_create_file = true;
363 * If this is a new context diff the character just
364 * at the end of the line is a '*'.
366 while (*s && *s != '\n')
369 p_start = previous_line;
370 p_sline = p_input_line - 1;
371 retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
374 if ((!diff_type || diff_type == NORMAL_DIFF) &&
375 last_line_was_command &&
376 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
377 p_start = previous_line;
378 p_sline = p_input_line - 1;
380 retval = NORMAL_DIFF;
385 if (retval == UNI_DIFF) {
386 /* unswap old and new */
387 struct file_name tmp = names[OLD_FILE];
388 names[OLD_FILE] = names[NEW_FILE];
389 names[NEW_FILE] = tmp;
391 if (filearg[0] == NULL) {
393 filearg[0] = posix_name(names, ok_to_create_file);
395 /* Ignore the Index: name for context diffs, like GNU */
396 if (names[OLD_FILE].path != NULL ||
397 names[NEW_FILE].path != NULL) {
398 free(names[INDEX_FILE].path);
399 names[INDEX_FILE].path = NULL;
401 filearg[0] = best_name(names, ok_to_create_file);
407 if (filearg[0] != NULL)
408 bestguess = xstrdup(filearg[0]);
409 else if (!ok_to_create_file) {
411 * We don't want to create a new file but we need a
412 * filename to set bestguess. Avoid setting filearg[0]
413 * so the file is not created automatically.
416 bestguess = posix_name(names, true);
418 bestguess = best_name(names, true);
420 free(names[OLD_FILE].path);
421 free(names[NEW_FILE].path);
422 free(names[INDEX_FILE].path);
427 * Remember where this patch ends so we know where to start up again.
430 next_intuit_at(off_t file_pos, LINENUM file_line)
437 * Basically a verbose fseeko() to the actual diff listing.
440 skip_to(off_t file_pos, LINENUM file_line)
444 if (p_base > file_pos)
445 fatal("Internal error: seek %lld>%lld\n",
446 (long long)p_base, (long long)file_pos);
447 if (verbose && p_base < file_pos) {
448 fseeko(pfp, p_base, SEEK_SET);
449 say("The text leading up to this was:\n--------------------------\n");
450 while (ftello(pfp) < file_pos) {
453 fatal("Unexpected end of file\n");
456 say("--------------------------\n");
458 fseeko(pfp, file_pos, SEEK_SET);
459 p_input_line = file_line - 1;
462 /* Make this a function for better debugging. */
466 fatal("malformed patch at line %ld: %s", p_input_line, buf);
467 /* about as informative as "Syntax error" in C */
471 * True if the line has been discarded (i.e. it is a line saying
472 * "\ No newline at end of file".)
475 remove_special_line(void)
483 } while (c != EOF && c != '\n');
488 fseeko(pfp, -1, SEEK_CUR);
494 * True if there is more of the current diff listing to process.
499 off_t line_beginning; /* file pos of the current line */
500 LINENUM repl_beginning; /* index of --- line */
501 LINENUM fillcnt; /* #lines of missing ptrn or repl */
502 LINENUM fillsrc; /* index of first line to copy */
503 LINENUM filldst; /* index of first missing line */
504 bool ptrn_spaces_eaten; /* ptrn was slightly malformed */
505 bool repl_could_be_missing; /* no + or ! lines in this hunk */
506 bool repl_missing; /* we are now backtracking */
507 off_t repl_backtrack_position; /* file pos of first repl line */
508 LINENUM repl_patch_line; /* input line number for same */
509 LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
515 if (p_end == p_efake)
516 p_end = p_bfake; /* don't free twice */
523 p_max = hunkmax; /* gets reduced when --- found */
524 if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
525 line_beginning = ftello(pfp);
530 ptrn_spaces_eaten = false;
531 repl_could_be_missing = true;
532 repl_missing = false;
533 repl_backtrack_position = 0;
539 if (len == 0 || strnNE(buf, "********", 8)) {
540 next_intuit_at(line_beginning, p_input_line);
544 p_hunk_beg = p_input_line + 1;
545 while (p_end < p_max) {
546 line_beginning = ftello(pfp);
550 if (p_max - p_end < 4) {
551 /* assume blank lines got chopped */
552 strlcpy(buf, " \n", buf_size);
554 if (repl_beginning && repl_could_be_missing) {
558 fatal("unexpected end of file in patch\n");
562 if (p_end >= hunkmax)
563 fatal("Internal error: hunk larger than hunk "
565 p_char[p_end] = *buf;
566 p_line[p_end] = NULL;
569 if (strnEQ(buf, "********", 8)) {
570 if (repl_beginning && repl_could_be_missing) {
574 fatal("unexpected end of hunk "
579 if (repl_beginning && repl_could_be_missing) {
583 fatal("unexpected *** at line %ld: %s",
587 p_line[p_end] = savestr(buf);
593 *s && !isdigit((unsigned char)*s); s++)
597 if (strnEQ(s, "0,0", 3))
598 memmove(s, s + 2, strlen(s + 2) + 1);
599 p_first = strtolinenum(s, &s);
602 *s && !isdigit((unsigned char)*s); s++)
606 p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
607 if (p_ptrn_lines < 0)
615 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
616 p_ptrn_lines >= LINENUM_MAX - 6)
619 /* we need this much at least */
620 p_max = p_ptrn_lines + 6;
621 while (p_max >= hunkmax)
627 if (repl_beginning ||
628 (p_end != p_ptrn_lines + 1 +
629 (p_char[p_end - 1] == '\n'))) {
632 * `old' lines were omitted;
633 * set up to fill them in
634 * from 'new' context lines.
636 p_end = p_ptrn_lines + 1;
639 fillcnt = p_ptrn_lines;
641 if (repl_beginning) {
642 if (repl_could_be_missing) {
646 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
647 p_input_line, p_hunk_beg + repl_beginning);
649 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
650 (p_end <= p_ptrn_lines
653 p_input_line, p_hunk_beg);
657 repl_beginning = p_end;
658 repl_backtrack_position = ftello(pfp);
659 repl_patch_line = p_input_line;
660 p_line[p_end] = savestr(buf);
666 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
670 p_newfirst = strtolinenum(s, &s);
672 for (; *s && !isdigit((unsigned char)*s); s++)
676 p_repl_lines = strtolinenum(s, &s) -
678 if (p_repl_lines < 0)
680 } else if (p_newfirst)
686 if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
687 p_repl_lines >= LINENUM_MAX - p_end)
689 p_max = p_repl_lines + p_end;
690 if (p_max > MAXHUNKSIZE)
691 fatal("hunk too large (%ld lines) at line %ld: %s",
692 p_max, p_input_line, buf);
693 while (p_max >= hunkmax)
695 if (p_repl_lines != ptrn_copiable &&
696 (p_context != 0 || p_repl_lines != 1))
697 repl_could_be_missing = false;
703 repl_could_be_missing = false;
705 if (buf[1] == '\n' && canonicalize)
706 strlcpy(buf + 1, " \n", buf_size - 1);
707 if (!isspace((unsigned char)buf[1]) &&
708 buf[1] != '>' && buf[1] != '<' &&
709 repl_beginning && repl_could_be_missing) {
714 if (context < p_context)
718 p_line[p_end] = savestr(buf + 2);
723 if (p_end == p_ptrn_lines) {
724 if (remove_special_line()) {
727 l = strlen(p_line[p_end]) - 1;
728 (p_line[p_end])[l] = 0;
733 case '\n': /* assume the 2 spaces got eaten */
734 if (repl_beginning && repl_could_be_missing &&
735 (!ptrn_spaces_eaten ||
736 diff_type == NEW_CONTEXT_DIFF)) {
740 p_line[p_end] = savestr(buf);
745 if (p_end != p_ptrn_lines + 1) {
746 ptrn_spaces_eaten |= (repl_beginning != 0);
754 if (!isspace((unsigned char)buf[1]) &&
755 repl_beginning && repl_could_be_missing) {
762 p_line[p_end] = savestr(buf + 2);
769 if (repl_beginning && repl_could_be_missing) {
775 /* set up p_len for strncmp() so we don't have to */
776 /* assume null termination */
778 p_len[p_end] = strlen(p_line[p_end]);
784 if (p_end >= 0 && !repl_beginning)
785 fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
789 /* reset state back to just after --- */
790 p_input_line = repl_patch_line;
791 for (p_end--; p_end > repl_beginning; p_end--)
793 fseeko(pfp, repl_backtrack_position, SEEK_SET);
795 /* redundant 'new' context lines were omitted - set */
796 /* up to fill them in from the old file context */
797 if (!p_context && p_repl_lines == 1) {
802 filldst = repl_beginning + 1;
803 fillcnt = p_repl_lines;
805 } else if (!p_context && fillcnt == 1) {
806 /* the first hunk was a null hunk with no context */
807 /* and we were expecting one line -- fix it up. */
808 while (filldst < p_end) {
809 p_line[filldst] = p_line[filldst + 1];
810 p_char[filldst] = p_char[filldst + 1];
811 p_len[filldst] = p_len[filldst + 1];
815 repl_beginning--; /* this doesn't need to be fixed */
818 p_first++; /* do append rather than insert */
822 if (diff_type == CONTEXT_DIFF &&
823 (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
826 "(Fascinating--this is really a new-style context diff but without",
827 "the telltale extra asterisks on the *** line that usually indicate",
828 "the new style...)");
829 diff_type = NEW_CONTEXT_DIFF;
831 /* if there were omitted context lines, fill them in now */
833 p_bfake = filldst; /* remember where not to free() */
834 p_efake = filldst + fillcnt - 1;
835 while (fillcnt-- > 0) {
836 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
839 fatal("replacement text or line numbers mangled in hunk at line %ld\n",
841 p_line[filldst] = p_line[fillsrc];
842 p_char[filldst] = p_char[fillsrc];
843 p_len[filldst] = p_len[fillsrc];
847 while (fillsrc <= p_end && fillsrc != repl_beginning &&
848 p_char[fillsrc] != ' ')
852 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
853 fillsrc, filldst, repl_beginning, p_end + 1);
855 if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
857 if (filldst != p_end + 1 && filldst != repl_beginning)
860 if (p_line[p_end] != NULL) {
861 if (remove_special_line()) {
863 (p_line[p_end])[p_len[p_end]] = 0;
866 } else if (diff_type == UNI_DIFF) {
867 LINENUM fillold; /* index of old lines */
868 LINENUM fillnew; /* index of new lines */
871 line_beginning = ftello(pfp); /* file pos of the current line */
874 if (len == 0 || strnNE(buf, "@@ -", 4)) {
875 next_intuit_at(line_beginning, p_input_line);
881 p_first = strtolinenum(s, &s);
883 p_ptrn_lines = strtolinenum(s + 1, &s);
888 if (*s != '+' || !*++s)
890 p_newfirst = strtolinenum(s, &s);
892 p_repl_lines = strtolinenum(s + 1, &s);
899 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
900 p_newfirst > LINENUM_MAX - p_repl_lines ||
901 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
904 p_first++; /* do append rather than insert */
905 p_max = p_ptrn_lines + p_repl_lines + 1;
906 while (p_max >= hunkmax)
909 fillnew = fillold + p_ptrn_lines;
910 p_end = fillnew + p_repl_lines;
911 snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
912 p_first + p_ptrn_lines - 1);
913 p_line[0] = savestr(buf);
919 snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
920 p_newfirst + p_repl_lines - 1);
921 p_line[fillnew] = savestr(buf);
926 p_char[fillnew++] = '=';
929 p_hunk_beg = p_input_line + 1;
930 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
931 line_beginning = ftello(pfp);
935 if (p_max - fillnew < 3) {
936 /* assume blank lines got chopped */
937 strlcpy(buf, " \n", buf_size);
939 fatal("unexpected end of file in patch\n");
942 if (*buf == '\t' || *buf == '\n') {
943 ch = ' '; /* assume the space got eaten */
947 s = savestr(buf + 1);
950 while (--fillnew > p_ptrn_lines)
951 free(p_line[fillnew]);
957 if (fillold > p_ptrn_lines) {
962 p_char[fillold] = ch;
964 p_len[fillold++] = strlen(s);
965 if (fillold > p_ptrn_lines) {
966 if (remove_special_line()) {
967 p_len[fillold - 1] -= 1;
968 s[p_len[fillold - 1]] = 0;
976 if (fillold > p_ptrn_lines) {
978 while (--fillnew > p_ptrn_lines)
979 free(p_line[fillnew]);
984 p_char[fillold] = ch;
986 p_len[fillold++] = strlen(s);
989 while (--fillnew > p_ptrn_lines)
990 free(p_line[fillnew]);
994 if (fillold > p_ptrn_lines) {
995 if (remove_special_line()) {
996 p_len[fillold - 1] -= 1;
997 s[p_len[fillold - 1]] = 0;
1002 if (fillnew > p_end) {
1004 while (--fillnew > p_ptrn_lines)
1005 free(p_line[fillnew]);
1006 p_end = fillold - 1;
1009 p_char[fillnew] = ch;
1010 p_line[fillnew] = s;
1011 p_len[fillnew++] = strlen(s);
1012 if (fillold > p_ptrn_lines) {
1013 if (remove_special_line()) {
1014 p_len[fillnew - 1] -= 1;
1015 s[p_len[fillnew - 1]] = 0;
1023 if (ch != ' ' && context > 0) {
1024 if (context < p_context)
1025 p_context = context;
1029 } else { /* normal diff--fake it up */
1034 line_beginning = ftello(pfp);
1038 if (len == 0 || !isdigit((unsigned char)*buf)) {
1039 next_intuit_at(line_beginning, p_input_line);
1042 p_first = strtolinenum(buf, &s);
1044 p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1045 if (p_ptrn_lines < 0)
1048 p_ptrn_lines = (*s != 'a');
1050 if (hunk_type == 'a')
1051 p_first++; /* do append rather than insert */
1052 min = strtolinenum(s + 1, &s);
1054 max = strtolinenum(s + 1, &s);
1057 if (min < 0 || min > max || max - min == LINENUM_MAX)
1059 if (hunk_type == 'd')
1062 p_repl_lines = max - min + 1;
1063 if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1064 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1066 p_end = p_ptrn_lines + p_repl_lines + 1;
1067 if (p_end > MAXHUNKSIZE)
1068 fatal("hunk too large (%ld lines) at line %ld: %s",
1069 p_end, p_input_line, buf);
1070 while (p_end >= hunkmax)
1072 snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1073 p_first + p_ptrn_lines - 1);
1074 p_line[0] = savestr(buf);
1080 for (i = 1; i <= p_ptrn_lines; i++) {
1084 fatal("unexpected end of file in patch at line %ld\n",
1087 fatal("< expected at line %ld of patch\n",
1089 p_line[i] = savestr(buf + 2);
1094 p_len[i] = strlen(p_line[i]);
1098 if (remove_special_line()) {
1100 (p_line[i - 1])[p_len[i - 1]] = 0;
1102 if (hunk_type == 'c') {
1106 fatal("unexpected end of file in patch at line %ld\n",
1109 fatal("--- expected at line %ld of patch\n",
1112 snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1113 p_line[i] = savestr(buf);
1119 for (i++; i <= p_end; i++) {
1123 fatal("unexpected end of file in patch at line %ld\n",
1126 fatal("> expected at line %ld of patch\n",
1128 p_line[i] = savestr(buf + 2);
1133 p_len[i] = strlen(p_line[i]);
1137 if (remove_special_line()) {
1139 (p_line[i - 1])[p_len[i - 1]] = 0;
1142 if (reverse) /* backwards patch? */
1144 say("Not enough memory to swap next hunk!\n");
1150 for (i = 0; i <= p_end; i++) {
1151 if (i == p_ptrn_lines)
1155 fprintf(stderr, "%3ld %c %c %s", i, p_char[i],
1156 special, p_line[i]);
1161 if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1162 p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
1167 * Input a line from the patch file.
1168 * Worry about indentation if do_indent is true.
1169 * The line is read directly into the buf global variable which
1170 * is resized if necessary in order to hold the complete line.
1171 * Returns the number of characters read including the terminating
1175 pgets(bool do_indent)
1179 int indent = 0, skipped = 0;
1181 line = fgetln(pfp, &len);
1183 if (len + 1 > buf_size) {
1184 while (len + 1 > buf_size)
1187 buf = malloc(buf_size);
1189 fatal("out of memory\n");
1191 if (do_indent == 1 && p_indent) {
1193 indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1194 line++, skipped++) {
1196 indent += 8 - (indent %7);
1201 memcpy(buf, line, len - skipped);
1202 buf[len - skipped] = '\0';
1209 * Reverse the old and new portions of the current hunk.
1214 char **tp_line; /* the text of the hunk */
1215 unsigned short *tp_len;/* length of each line */
1216 char *tp_char; /* +, -, and ! */
1219 bool blankline = false;
1223 p_first = p_newfirst;
1226 /* make a scratch copy */
1231 p_line = NULL; /* force set_hunkmax to allocate again */
1235 if (p_line == NULL || p_len == NULL || p_char == NULL) {
1243 return false; /* not enough memory to swap hunk! */
1245 /* now turn the new into the old */
1247 i = p_ptrn_lines + 1;
1248 if (tp_char[i] == '\n') { /* account for possible blank line */
1252 if (p_efake >= 0) { /* fix non-freeable ptr range */
1260 for (n = 0; i <= p_end; i++, n++) {
1261 p_line[n] = tp_line[i];
1262 p_char[n] = tp_char[i];
1263 if (p_char[n] == '+')
1265 p_len[n] = tp_len[i];
1268 i = p_ptrn_lines + 1;
1269 p_line[n] = tp_line[i];
1270 p_char[n] = tp_char[i];
1271 p_len[n] = tp_len[i];
1274 if (p_char[0] != '=')
1275 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1276 p_input_line, p_char[0]);
1278 for (s = p_line[0]; *s; s++)
1282 /* now turn the old into the new */
1284 if (p_char[0] != '*')
1285 fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1286 p_input_line, p_char[0]);
1288 for (s = tp_line[0]; *s; s++)
1291 for (i = 0; n <= p_end; i++, n++) {
1292 p_line[n] = tp_line[i];
1293 p_char[n] = tp_char[i];
1294 if (p_char[n] == '-')
1296 p_len[n] = tp_len[i];
1299 if (i != p_ptrn_lines + 1)
1300 fatal("Malformed patch at line %ld: expected %ld lines, "
1302 p_input_line, p_ptrn_lines + 1, i);
1305 p_ptrn_lines = p_repl_lines;
1316 * Return the specified line position in the old file of the old context.
1325 * Return the number of lines of old context.
1328 pch_ptrn_lines(void)
1330 return p_ptrn_lines;
1334 * Return the probable line position in the new file of the first line.
1343 * Return the number of lines in the replacement text including context.
1346 pch_repl_lines(void)
1348 return p_repl_lines;
1352 * Return the number of lines in the whole hunk.
1361 * Return the number of context lines before the first changed line.
1370 * Return the length of a particular patch line.
1373 pch_line_len(LINENUM line)
1379 * Return the control character (+, -, *, !, etc) for a patch line.
1382 pch_char(LINENUM line)
1384 return p_char[line];
1388 * Return a pointer to a particular patch line.
1391 pfetch(LINENUM line)
1393 return p_line[line];
1397 * Return where in the patch file this hunk began, for error messages.
1406 * Apply an ed script by feeding ed itself.
1412 off_t beginning_of_this_line;
1413 FILE *pipefp = NULL;
1416 if (!skip_rest_of_patch) {
1417 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1419 fatal("can't create temp file %s", TMPOUTNAME);
1421 snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1422 verbose ? " " : " -s ", TMPOUTNAME);
1423 pipefp = popen(buf, "w");
1426 beginning_of_this_line = ftello(pfp);
1427 if (pgets(true) == 0) {
1428 next_intuit_at(beginning_of_this_line, p_input_line);
1432 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1434 /* POSIX defines allowed commands as {a,c,d,i,s} */
1435 if (isdigit((unsigned char)*buf) &&
1436 (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1442 t = strchr(buf, '\0') - 1;
1443 while (--t >= buf && *t == '\\')
1444 continuation = !continuation;
1445 if (!continuation ||
1451 } else if (*t != 'd') {
1452 while (pgets(true)) {
1456 if (strEQ(buf, ".\n"))
1461 next_intuit_at(beginning_of_this_line, p_input_line);
1467 fprintf(pipefp, "w\n");
1468 fprintf(pipefp, "q\n");
1473 if (move_file(TMPOUTNAME, outname) < 0) {
1475 chmod(TMPOUTNAME, filemode);
1477 chmod(outname, filemode);
1483 * Choose the name of the file to be patched based on POSIX rules.
1484 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1485 * if the user specified --posix or set POSIXLY_CORRECT.
1488 posix_name(const struct file_name *names, bool assume_exists)
1494 * POSIX states that the filename will be chosen from one
1495 * of the old, new and index names (in that order) if
1496 * the file exists relative to CWD after -p stripping.
1498 for (i = 0; i < MAX_FILE; i++) {
1499 if (names[i].path != NULL && names[i].exists) {
1500 path = names[i].path;
1504 if (path == NULL && !assume_exists) {
1506 * No files found, look for something we can checkout from
1507 * RCS/SCCS dirs. Same order as above.
1509 for (i = 0; i < MAX_FILE; i++) {
1510 if (names[i].path != NULL &&
1511 (path = checked_in(names[i].path)) != NULL)
1515 * Still no match? Check to see if the diff could be creating
1518 if (path == NULL && ok_to_create_file &&
1519 names[NEW_FILE].path != NULL)
1520 path = names[NEW_FILE].path;
1523 return path ? xstrdup(path) : NULL;
1527 compare_names(const struct file_name *names, bool assume_exists, int phase)
1529 size_t min_components, min_baselen, min_len, tmp;
1535 * The "best" name is the one with the fewest number of path
1536 * components, the shortest basename length, and the shortest
1537 * overall length (in that order). We only use the Index: file
1538 * if neither of the old or new files could be intuited from
1541 min_components = min_baselen = min_len = SIZE_MAX;
1542 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1543 path = names[i].path;
1545 (phase == 1 && !names[i].exists && !assume_exists) ||
1546 (phase == 2 && checked_in(path) == NULL))
1548 if ((tmp = num_components(path)) > min_components)
1550 if (tmp < min_components) {
1551 min_components = tmp;
1554 if ((tmp = strlen(basename(path))) > min_baselen)
1556 if (tmp < min_baselen) {
1560 if ((tmp = strlen(path)) > min_len)
1569 * Choose the name of the file to be patched based the "best" one
1573 best_name(const struct file_name *names, bool assume_exists)
1577 best = compare_names(names, assume_exists, 1);
1579 best = compare_names(names, assume_exists, 2);
1581 * Still no match? Check to see if the diff could be creating
1584 if (best == NULL && ok_to_create_file &&
1585 names[NEW_FILE].path != NULL)
1586 best = names[NEW_FILE].path;
1589 return best ? xstrdup(best) : NULL;
1593 num_components(const char *path)
1598 for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1600 cp++; /* skip consecutive slashes */
1606 * Convert number at NPTR into LINENUM and save address of first
1607 * character that is not a digit in ENDPTR. If conversion is not
1608 * possible, call fatal.
1611 strtolinenum(char *nptr, char **endptr)
1618 for (p = nptr; isdigit((unsigned char)*p); p++)
1627 rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1629 fatal("invalid line number at line %ld: `%s' is %s\n",
1630 p_input_line, nptr, errstr);