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 ask("No file found--skip this patch? [n] ");
223 say("Skipping patch...\n");
225 filearg[0] = fetchname(bestguess, &exists, 0);
226 skip_rest_of_patch = true;
234 p4_fetchname(struct file_name *name, char *str)
238 /* Skip leading whitespace. */
239 while (isspace((unsigned char)*str))
242 /* Remove the file revision number. */
243 for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
249 name->path = fetchname(str, &name->exists, strippath);
252 /* Determine what kind of diff is in the remaining part of the patch file. */
255 intuit_diff_type(void)
257 off_t this_line = 0, previous_line;
258 off_t first_command_line = -1;
259 LINENUM fcl_line = -1;
260 bool last_line_was_command = false, this_is_a_command = false;
261 bool stars_last_line = false, stars_this_line = false;
264 struct file_name names[MAX_FILE];
266 memset(names, 0, sizeof(names));
267 ok_to_create_file = false;
268 fseeko(pfp, p_base, SEEK_SET);
269 p_input_line = p_bline - 1;
271 previous_line = this_line;
272 last_line_was_command = this_is_a_command;
273 stars_last_line = stars_this_line;
274 this_line = ftello(pfp);
277 if (pgets(false) == 0) {
278 if (first_command_line >= 0) {
279 /* nothing but deletes!? */
280 p_start = first_command_line;
286 p_sline = p_input_line;
291 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
293 indent += 8 - (indent % 8);
297 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
299 this_is_a_command = (isdigit((unsigned char)*s) &&
300 (*t == 'd' || *t == 'c' || *t == 'a'));
301 if (first_command_line < 0 && this_is_a_command) {
302 first_command_line = this_line;
303 fcl_line = p_input_line;
304 p_indent = indent; /* assume this for now */
306 if (!stars_last_line && strnEQ(s, "*** ", 4))
307 names[OLD_FILE].path = fetchname(s + 4,
308 &names[OLD_FILE].exists, strippath);
309 else if (strnEQ(s, "--- ", 4))
310 names[NEW_FILE].path = fetchname(s + 4,
311 &names[NEW_FILE].exists, strippath);
312 else if (strnEQ(s, "+++ ", 4))
313 /* pretend it is the old name */
314 names[OLD_FILE].path = fetchname(s + 4,
315 &names[OLD_FILE].exists, strippath);
316 else if (strnEQ(s, "Index:", 6))
317 names[INDEX_FILE].path = fetchname(s + 6,
318 &names[INDEX_FILE].exists, strippath);
319 else if (strnEQ(s, "Prereq:", 7)) {
320 for (t = s + 7; isspace((unsigned char)*t); t++)
322 revision = xstrdup(t);
324 *t && !isspace((unsigned char)*t); t++)
327 if (*revision == '\0') {
331 } else if (strnEQ(s, "==== ", 5)) {
332 /* Perforce-style diffs. */
333 if ((t = strstr(s + 5, " - ")) != NULL)
334 p4_fetchname(&names[NEW_FILE], t + 3);
335 p4_fetchname(&names[OLD_FILE], s + 5);
337 if ((!diff_type || diff_type == ED_DIFF) &&
338 first_command_line >= 0 &&
341 p_start = first_command_line;
346 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
347 if (strnEQ(s + 4, "0,0", 3))
348 ok_to_create_file = true;
351 p_sline = p_input_line;
355 stars_this_line = strnEQ(s, "********", 8);
356 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
357 strnEQ(s, "*** ", 4)) {
358 if (strtolinenum(s + 4, &s) == 0)
359 ok_to_create_file = true;
361 * If this is a new context diff the character just
362 * at the end of the line is a '*'.
364 while (*s && *s != '\n')
367 p_start = previous_line;
368 p_sline = p_input_line - 1;
369 retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
372 if ((!diff_type || diff_type == NORMAL_DIFF) &&
373 last_line_was_command &&
374 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
375 p_start = previous_line;
376 p_sline = p_input_line - 1;
378 retval = NORMAL_DIFF;
383 if (retval == UNI_DIFF) {
384 /* unswap old and new */
385 struct file_name tmp = names[OLD_FILE];
386 names[OLD_FILE] = names[NEW_FILE];
387 names[NEW_FILE] = tmp;
389 if (filearg[0] == NULL) {
391 filearg[0] = posix_name(names, ok_to_create_file);
393 /* Ignore the Index: name for context diffs, like GNU */
394 if (names[OLD_FILE].path != NULL ||
395 names[NEW_FILE].path != NULL) {
396 free(names[INDEX_FILE].path);
397 names[INDEX_FILE].path = NULL;
399 filearg[0] = best_name(names, ok_to_create_file);
405 if (filearg[0] != NULL)
406 bestguess = xstrdup(filearg[0]);
407 else if (!ok_to_create_file) {
409 * We don't want to create a new file but we need a
410 * filename to set bestguess. Avoid setting filearg[0]
411 * so the file is not created automatically.
414 bestguess = posix_name(names, true);
416 bestguess = best_name(names, true);
418 free(names[OLD_FILE].path);
419 free(names[NEW_FILE].path);
420 free(names[INDEX_FILE].path);
425 * Remember where this patch ends so we know where to start up again.
428 next_intuit_at(off_t file_pos, LINENUM file_line)
435 * Basically a verbose fseeko() to the actual diff listing.
438 skip_to(off_t file_pos, LINENUM file_line)
442 if (p_base > file_pos)
443 fatal("Internal error: seek %lld>%lld\n",
444 (long long)p_base, (long long)file_pos);
445 if (verbose && p_base < file_pos) {
446 fseeko(pfp, p_base, SEEK_SET);
447 say("The text leading up to this was:\n--------------------------\n");
448 while (ftello(pfp) < file_pos) {
451 fatal("Unexpected end of file\n");
454 say("--------------------------\n");
456 fseeko(pfp, file_pos, SEEK_SET);
457 p_input_line = file_line - 1;
460 /* Make this a function for better debugging. */
464 fatal("malformed patch at line %ld: %s", p_input_line, buf);
465 /* about as informative as "Syntax error" in C */
469 * True if the line has been discarded (i.e. it is a line saying
470 * "\ No newline at end of file".)
473 remove_special_line(void)
481 } while (c != EOF && c != '\n');
486 fseeko(pfp, -1, SEEK_CUR);
492 * True if there is more of the current diff listing to process.
497 off_t line_beginning; /* file pos of the current line */
498 LINENUM repl_beginning; /* index of --- line */
499 LINENUM fillcnt; /* #lines of missing ptrn or repl */
500 LINENUM fillsrc; /* index of first line to copy */
501 LINENUM filldst; /* index of first missing line */
502 bool ptrn_spaces_eaten; /* ptrn was slightly malformed */
503 bool repl_could_be_missing; /* no + or ! lines in this hunk */
504 bool repl_missing; /* we are now backtracking */
505 off_t repl_backtrack_position; /* file pos of first repl line */
506 LINENUM repl_patch_line; /* input line number for same */
507 LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
513 if (p_end == p_efake)
514 p_end = p_bfake; /* don't free twice */
521 p_max = hunkmax; /* gets reduced when --- found */
522 if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
523 line_beginning = ftello(pfp);
528 ptrn_spaces_eaten = false;
529 repl_could_be_missing = true;
530 repl_missing = false;
531 repl_backtrack_position = 0;
537 if (len == 0 || strnNE(buf, "********", 8)) {
538 next_intuit_at(line_beginning, p_input_line);
542 p_hunk_beg = p_input_line + 1;
543 while (p_end < p_max) {
544 line_beginning = ftello(pfp);
548 if (p_max - p_end < 4) {
549 /* assume blank lines got chopped */
550 strlcpy(buf, " \n", buf_size);
552 if (repl_beginning && repl_could_be_missing) {
556 fatal("unexpected end of file in patch\n");
560 if (p_end >= hunkmax)
561 fatal("Internal error: hunk larger than hunk "
563 p_char[p_end] = *buf;
564 p_line[p_end] = NULL;
567 if (strnEQ(buf, "********", 8)) {
568 if (repl_beginning && repl_could_be_missing) {
572 fatal("unexpected end of hunk "
577 if (repl_beginning && repl_could_be_missing) {
581 fatal("unexpected *** at line %ld: %s",
585 p_line[p_end] = savestr(buf);
591 *s && !isdigit((unsigned char)*s); s++)
595 if (strnEQ(s, "0,0", 3))
596 memmove(s, s + 2, strlen(s + 2) + 1);
597 p_first = strtolinenum(s, &s);
600 *s && !isdigit((unsigned char)*s); s++)
604 p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
605 if (p_ptrn_lines < 0)
613 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
614 p_ptrn_lines >= LINENUM_MAX - 6)
617 /* we need this much at least */
618 p_max = p_ptrn_lines + 6;
619 while (p_max >= hunkmax)
625 if (repl_beginning ||
626 (p_end != p_ptrn_lines + 1 +
627 (p_char[p_end - 1] == '\n'))) {
630 * `old' lines were omitted;
631 * set up to fill them in
632 * from 'new' context lines.
634 p_end = p_ptrn_lines + 1;
637 fillcnt = p_ptrn_lines;
639 if (repl_beginning) {
640 if (repl_could_be_missing) {
644 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
645 p_input_line, p_hunk_beg + repl_beginning);
647 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
648 (p_end <= p_ptrn_lines
651 p_input_line, p_hunk_beg);
655 repl_beginning = p_end;
656 repl_backtrack_position = ftello(pfp);
657 repl_patch_line = p_input_line;
658 p_line[p_end] = savestr(buf);
664 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
668 p_newfirst = strtolinenum(s, &s);
670 for (; *s && !isdigit((unsigned char)*s); s++)
674 p_repl_lines = strtolinenum(s, &s) -
676 if (p_repl_lines < 0)
678 } else if (p_newfirst)
684 if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
685 p_repl_lines >= LINENUM_MAX - p_end)
687 p_max = p_repl_lines + p_end;
688 if (p_max > MAXHUNKSIZE)
689 fatal("hunk too large (%ld lines) at line %ld: %s",
690 p_max, p_input_line, buf);
691 while (p_max >= hunkmax)
693 if (p_repl_lines != ptrn_copiable &&
694 (p_context != 0 || p_repl_lines != 1))
695 repl_could_be_missing = false;
701 repl_could_be_missing = false;
703 if (buf[1] == '\n' && canonicalize)
704 strlcpy(buf + 1, " \n", buf_size - 1);
705 if (!isspace((unsigned char)buf[1]) &&
706 buf[1] != '>' && buf[1] != '<' &&
707 repl_beginning && repl_could_be_missing) {
712 if (context < p_context)
716 p_line[p_end] = savestr(buf + 2);
721 if (p_end == p_ptrn_lines) {
722 if (remove_special_line()) {
725 l = strlen(p_line[p_end]) - 1;
726 (p_line[p_end])[l] = 0;
731 case '\n': /* assume the 2 spaces got eaten */
732 if (repl_beginning && repl_could_be_missing &&
733 (!ptrn_spaces_eaten ||
734 diff_type == NEW_CONTEXT_DIFF)) {
738 p_line[p_end] = savestr(buf);
743 if (p_end != p_ptrn_lines + 1) {
744 ptrn_spaces_eaten |= (repl_beginning != 0);
752 if (!isspace((unsigned char)buf[1]) &&
753 repl_beginning && repl_could_be_missing) {
760 p_line[p_end] = savestr(buf + 2);
767 if (repl_beginning && repl_could_be_missing) {
773 /* set up p_len for strncmp() so we don't have to */
774 /* assume null termination */
776 p_len[p_end] = strlen(p_line[p_end]);
782 if (p_end >= 0 && !repl_beginning)
783 fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
787 /* reset state back to just after --- */
788 p_input_line = repl_patch_line;
789 for (p_end--; p_end > repl_beginning; p_end--)
791 fseeko(pfp, repl_backtrack_position, SEEK_SET);
793 /* redundant 'new' context lines were omitted - set */
794 /* up to fill them in from the old file context */
795 if (!p_context && p_repl_lines == 1) {
800 filldst = repl_beginning + 1;
801 fillcnt = p_repl_lines;
803 } else if (!p_context && fillcnt == 1) {
804 /* the first hunk was a null hunk with no context */
805 /* and we were expecting one line -- fix it up. */
806 while (filldst < p_end) {
807 p_line[filldst] = p_line[filldst + 1];
808 p_char[filldst] = p_char[filldst + 1];
809 p_len[filldst] = p_len[filldst + 1];
813 repl_beginning--; /* this doesn't need to be fixed */
816 p_first++; /* do append rather than insert */
820 if (diff_type == CONTEXT_DIFF &&
821 (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
824 "(Fascinating--this is really a new-style context diff but without",
825 "the telltale extra asterisks on the *** line that usually indicate",
826 "the new style...)");
827 diff_type = NEW_CONTEXT_DIFF;
829 /* if there were omitted context lines, fill them in now */
831 p_bfake = filldst; /* remember where not to free() */
832 p_efake = filldst + fillcnt - 1;
833 while (fillcnt-- > 0) {
834 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
837 fatal("replacement text or line numbers mangled in hunk at line %ld\n",
839 p_line[filldst] = p_line[fillsrc];
840 p_char[filldst] = p_char[fillsrc];
841 p_len[filldst] = p_len[fillsrc];
845 while (fillsrc <= p_end && fillsrc != repl_beginning &&
846 p_char[fillsrc] != ' ')
850 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
851 fillsrc, filldst, repl_beginning, p_end + 1);
853 if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
855 if (filldst != p_end + 1 && filldst != repl_beginning)
858 if (p_line[p_end] != NULL) {
859 if (remove_special_line()) {
861 (p_line[p_end])[p_len[p_end]] = 0;
864 } else if (diff_type == UNI_DIFF) {
865 LINENUM fillold; /* index of old lines */
866 LINENUM fillnew; /* index of new lines */
869 line_beginning = ftello(pfp); /* file pos of the current line */
872 if (len == 0 || strnNE(buf, "@@ -", 4)) {
873 next_intuit_at(line_beginning, p_input_line);
879 p_first = strtolinenum(s, &s);
881 p_ptrn_lines = strtolinenum(s + 1, &s);
886 if (*s != '+' || !*++s)
888 p_newfirst = strtolinenum(s, &s);
890 p_repl_lines = strtolinenum(s + 1, &s);
897 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
898 p_newfirst > LINENUM_MAX - p_repl_lines ||
899 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
902 p_first++; /* do append rather than insert */
903 p_max = p_ptrn_lines + p_repl_lines + 1;
904 while (p_max >= hunkmax)
907 fillnew = fillold + p_ptrn_lines;
908 p_end = fillnew + p_repl_lines;
909 snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
910 p_first + p_ptrn_lines - 1);
911 p_line[0] = savestr(buf);
917 snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
918 p_newfirst + p_repl_lines - 1);
919 p_line[fillnew] = savestr(buf);
924 p_char[fillnew++] = '=';
927 p_hunk_beg = p_input_line + 1;
928 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
929 line_beginning = ftello(pfp);
933 if (p_max - fillnew < 3) {
934 /* assume blank lines got chopped */
935 strlcpy(buf, " \n", buf_size);
937 fatal("unexpected end of file in patch\n");
940 if (*buf == '\t' || *buf == '\n') {
941 ch = ' '; /* assume the space got eaten */
945 s = savestr(buf + 1);
948 while (--fillnew > p_ptrn_lines)
949 free(p_line[fillnew]);
955 if (fillold > p_ptrn_lines) {
960 p_char[fillold] = ch;
962 p_len[fillold++] = strlen(s);
963 if (fillold > p_ptrn_lines) {
964 if (remove_special_line()) {
965 p_len[fillold - 1] -= 1;
966 s[p_len[fillold - 1]] = 0;
974 if (fillold > p_ptrn_lines) {
976 while (--fillnew > p_ptrn_lines)
977 free(p_line[fillnew]);
982 p_char[fillold] = ch;
984 p_len[fillold++] = strlen(s);
987 while (--fillnew > p_ptrn_lines)
988 free(p_line[fillnew]);
992 if (fillold > p_ptrn_lines) {
993 if (remove_special_line()) {
994 p_len[fillold - 1] -= 1;
995 s[p_len[fillold - 1]] = 0;
1000 if (fillnew > p_end) {
1002 while (--fillnew > p_ptrn_lines)
1003 free(p_line[fillnew]);
1004 p_end = fillold - 1;
1007 p_char[fillnew] = ch;
1008 p_line[fillnew] = s;
1009 p_len[fillnew++] = strlen(s);
1010 if (fillold > p_ptrn_lines) {
1011 if (remove_special_line()) {
1012 p_len[fillnew - 1] -= 1;
1013 s[p_len[fillnew - 1]] = 0;
1021 if (ch != ' ' && context > 0) {
1022 if (context < p_context)
1023 p_context = context;
1027 } else { /* normal diff--fake it up */
1032 line_beginning = ftello(pfp);
1036 if (len == 0 || !isdigit((unsigned char)*buf)) {
1037 next_intuit_at(line_beginning, p_input_line);
1040 p_first = strtolinenum(buf, &s);
1042 p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1043 if (p_ptrn_lines < 0)
1046 p_ptrn_lines = (*s != 'a');
1048 if (hunk_type == 'a')
1049 p_first++; /* do append rather than insert */
1050 min = strtolinenum(s + 1, &s);
1052 max = strtolinenum(s + 1, &s);
1055 if (min < 0 || min > max || max - min == LINENUM_MAX)
1057 if (hunk_type == 'd')
1060 p_repl_lines = max - min + 1;
1061 if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1062 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1064 p_end = p_ptrn_lines + p_repl_lines + 1;
1065 if (p_end > MAXHUNKSIZE)
1066 fatal("hunk too large (%ld lines) at line %ld: %s",
1067 p_end, p_input_line, buf);
1068 while (p_end >= hunkmax)
1070 snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1071 p_first + p_ptrn_lines - 1);
1072 p_line[0] = savestr(buf);
1078 for (i = 1; i <= p_ptrn_lines; i++) {
1082 fatal("unexpected end of file in patch at line %ld\n",
1085 fatal("< expected at line %ld of patch\n",
1087 p_line[i] = savestr(buf + 2);
1092 p_len[i] = strlen(p_line[i]);
1096 if (remove_special_line()) {
1098 (p_line[i - 1])[p_len[i - 1]] = 0;
1100 if (hunk_type == 'c') {
1104 fatal("unexpected end of file in patch at line %ld\n",
1107 fatal("--- expected at line %ld of patch\n",
1110 snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1111 p_line[i] = savestr(buf);
1117 for (i++; i <= p_end; i++) {
1121 fatal("unexpected end of file in patch at line %ld\n",
1124 fatal("> expected at line %ld of patch\n",
1126 p_line[i] = savestr(buf + 2);
1131 p_len[i] = strlen(p_line[i]);
1135 if (remove_special_line()) {
1137 (p_line[i - 1])[p_len[i - 1]] = 0;
1140 if (reverse) /* backwards patch? */
1142 say("Not enough memory to swap next hunk!\n");
1148 for (i = 0; i <= p_end; i++) {
1149 if (i == p_ptrn_lines)
1153 fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1154 special, p_line[i]);
1159 if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1160 p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
1165 * Input a line from the patch file.
1166 * Worry about indentation if do_indent is true.
1167 * The line is read directly into the buf global variable which
1168 * is resized if necessary in order to hold the complete line.
1169 * Returns the number of characters read including the terminating
1173 pgets(bool do_indent)
1177 int indent = 0, skipped = 0;
1179 line = fgetln(pfp, &len);
1181 if (len + 1 > buf_size) {
1182 while (len + 1 > buf_size)
1185 buf = malloc(buf_size);
1187 fatal("out of memory\n");
1189 if (do_indent == 1 && p_indent) {
1191 indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1192 line++, skipped++) {
1194 indent += 8 - (indent %7);
1199 memcpy(buf, line, len - skipped);
1200 buf[len - skipped] = '\0';
1207 * Reverse the old and new portions of the current hunk.
1212 char **tp_line; /* the text of the hunk */
1213 unsigned short *tp_len;/* length of each line */
1214 char *tp_char; /* +, -, and ! */
1217 bool blankline = false;
1221 p_first = p_newfirst;
1224 /* make a scratch copy */
1229 p_line = NULL; /* force set_hunkmax to allocate again */
1233 if (p_line == NULL || p_len == NULL || p_char == NULL) {
1241 return false; /* not enough memory to swap hunk! */
1243 /* now turn the new into the old */
1245 i = p_ptrn_lines + 1;
1246 if (tp_char[i] == '\n') { /* account for possible blank line */
1250 if (p_efake >= 0) { /* fix non-freeable ptr range */
1258 for (n = 0; i <= p_end; i++, n++) {
1259 p_line[n] = tp_line[i];
1260 p_char[n] = tp_char[i];
1261 if (p_char[n] == '+')
1263 p_len[n] = tp_len[i];
1266 i = p_ptrn_lines + 1;
1267 p_line[n] = tp_line[i];
1268 p_char[n] = tp_char[i];
1269 p_len[n] = tp_len[i];
1272 if (p_char[0] != '=')
1273 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1274 p_input_line, p_char[0]);
1276 for (s = p_line[0]; *s; s++)
1280 /* now turn the old into the new */
1282 if (p_char[0] != '*')
1283 fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1284 p_input_line, p_char[0]);
1286 for (s = tp_line[0]; *s; s++)
1289 for (i = 0; n <= p_end; i++, n++) {
1290 p_line[n] = tp_line[i];
1291 p_char[n] = tp_char[i];
1292 if (p_char[n] == '-')
1294 p_len[n] = tp_len[i];
1297 if (i != p_ptrn_lines + 1)
1298 fatal("Malformed patch at line %ld: expected %ld lines, "
1300 p_input_line, p_ptrn_lines + 1, i);
1303 p_ptrn_lines = p_repl_lines;
1314 * Return the specified line position in the old file of the old context.
1323 * Return the number of lines of old context.
1326 pch_ptrn_lines(void)
1328 return p_ptrn_lines;
1332 * Return the probable line position in the new file of the first line.
1341 * Return the number of lines in the replacement text including context.
1344 pch_repl_lines(void)
1346 return p_repl_lines;
1350 * Return the number of lines in the whole hunk.
1359 * Return the number of context lines before the first changed line.
1368 * Return the length of a particular patch line.
1371 pch_line_len(LINENUM line)
1377 * Return the control character (+, -, *, !, etc) for a patch line.
1380 pch_char(LINENUM line)
1382 return p_char[line];
1386 * Return a pointer to a particular patch line.
1389 pfetch(LINENUM line)
1391 return p_line[line];
1395 * Return where in the patch file this hunk began, for error messages.
1404 * Apply an ed script by feeding ed itself.
1410 off_t beginning_of_this_line;
1411 FILE *pipefp = NULL;
1414 if (!skip_rest_of_patch) {
1415 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1417 fatal("can't create temp file %s", TMPOUTNAME);
1419 snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1420 verbose ? " " : " -s ", TMPOUTNAME);
1421 pipefp = popen(buf, "w");
1424 beginning_of_this_line = ftello(pfp);
1425 if (pgets(true) == 0) {
1426 next_intuit_at(beginning_of_this_line, p_input_line);
1430 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1432 /* POSIX defines allowed commands as {a,c,d,i,s} */
1433 if (isdigit((unsigned char)*buf) &&
1434 (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1440 t = strchr(buf, '\0') - 1;
1441 while (--t >= buf && *t == '\\')
1442 continuation = !continuation;
1443 if (!continuation ||
1449 } else if (*t != 'd') {
1450 while (pgets(true)) {
1454 if (strEQ(buf, ".\n"))
1459 next_intuit_at(beginning_of_this_line, p_input_line);
1465 fprintf(pipefp, "w\n");
1466 fprintf(pipefp, "q\n");
1471 if (move_file(TMPOUTNAME, outname) < 0) {
1473 chmod(TMPOUTNAME, filemode);
1475 chmod(outname, filemode);
1481 * Choose the name of the file to be patched based on POSIX rules.
1482 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1483 * if the user specified --posix or set POSIXLY_CORRECT.
1486 posix_name(const struct file_name *names, bool assume_exists)
1492 * POSIX states that the filename will be chosen from one
1493 * of the old, new and index names (in that order) if
1494 * the file exists relative to CWD after -p stripping.
1496 for (i = 0; i < MAX_FILE; i++) {
1497 if (names[i].path != NULL && names[i].exists) {
1498 path = names[i].path;
1502 if (path == NULL && !assume_exists) {
1504 * No files found, look for something we can checkout from
1505 * RCS/SCCS dirs. Same order as above.
1507 for (i = 0; i < MAX_FILE; i++) {
1508 if (names[i].path != NULL &&
1509 (path = checked_in(names[i].path)) != NULL)
1513 * Still no match? Check to see if the diff could be creating
1516 if (path == NULL && ok_to_create_file &&
1517 names[NEW_FILE].path != NULL)
1518 path = names[NEW_FILE].path;
1521 return path ? xstrdup(path) : NULL;
1525 compare_names(const struct file_name *names, bool assume_exists, int phase)
1527 size_t min_components, min_baselen, min_len, tmp;
1533 * The "best" name is the one with the fewest number of path
1534 * components, the shortest basename length, and the shortest
1535 * overall length (in that order). We only use the Index: file
1536 * if neither of the old or new files could be intuited from
1539 min_components = min_baselen = min_len = SIZE_MAX;
1540 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1541 path = names[i].path;
1543 (phase == 1 && !names[i].exists && !assume_exists) ||
1544 (phase == 2 && checked_in(path) == NULL))
1546 if ((tmp = num_components(path)) > min_components)
1548 if (tmp < min_components) {
1549 min_components = tmp;
1552 if ((tmp = strlen(basename(path))) > min_baselen)
1554 if (tmp < min_baselen) {
1558 if ((tmp = strlen(path)) > min_len)
1567 * Choose the name of the file to be patched based the "best" one
1571 best_name(const struct file_name *names, bool assume_exists)
1575 best = compare_names(names, assume_exists, 1);
1577 best = compare_names(names, assume_exists, 2);
1579 * Still no match? Check to see if the diff could be creating
1582 if (best == NULL && ok_to_create_file &&
1583 names[NEW_FILE].path != NULL)
1584 best = names[NEW_FILE].path;
1587 return best ? xstrdup(best) : NULL;
1591 num_components(const char *path)
1596 for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1598 cp++; /* skip consecutive slashes */
1604 * Convert number at NPTR into LINENUM and save address of first
1605 * character that is not a digit in ENDPTR. If conversion is not
1606 * possible, call fatal.
1609 strtolinenum(char *nptr, char **endptr)
1616 for (p = nptr; isdigit((unsigned char)*p); p++)
1625 rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1627 fatal("invalid line number at line %ld: `%s' is %s\n",
1628 p_input_line, nptr, errstr);