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.39 2012/04/11 08:07:13 ajacoutot Exp $
30 #include <sys/types.h>
44 #include "pathnames.h"
46 /* Patch (diff listing) abstract type. */
48 static long p_filesize; /* size of the patch file */
49 static LINENUM p_first; /* 1st line number */
50 static LINENUM p_newfirst; /* 1st line number of replacement */
51 static LINENUM p_ptrn_lines; /* # lines in pattern */
52 static LINENUM p_repl_lines; /* # lines in replacement text */
53 static LINENUM p_end = -1; /* last line in hunk */
54 static LINENUM p_max; /* max allowed value of p_end */
55 static LINENUM p_context = 3; /* # of context lines */
56 static LINENUM p_input_line = 0; /* current line # from patch file */
57 static char **p_line = NULL;/* the text of the hunk */
58 static unsigned short *p_len = NULL; /* length of each line */
59 static char *p_char = NULL; /* +, -, and ! */
60 static int hunkmax = INITHUNKMAX; /* size of above arrays to begin with */
61 static int p_indent; /* indent to patch */
62 static LINENUM p_base; /* where to intuit this time */
63 static LINENUM p_bline; /* line # of p_base */
64 static LINENUM p_start; /* where intuit found a patch */
65 static LINENUM p_sline; /* and the line number for it */
66 static LINENUM p_hunk_beg; /* line number of current hunk */
67 static LINENUM p_efake = -1; /* end of faked up lines--don't free */
68 static LINENUM p_bfake = -1; /* beg of faked up lines */
69 static FILE *pfp = NULL; /* patch file pointer */
70 static char *bestguess = NULL; /* guess at correct filename */
72 static void grow_hunkmax(void);
73 static int intuit_diff_type(void);
74 static void next_intuit_at(LINENUM, LINENUM);
75 static void skip_to(LINENUM, LINENUM);
76 static size_t pgets(bool _do_indent);
77 static char *best_name(const struct file_name *, bool);
78 static char *posix_name(const struct file_name *, bool);
79 static size_t num_components(const char *);
82 * Prepare to look for the next patch in the patch file.
91 p_end = (LINENUM) - 1;
97 * Open the patch file at the beginning of time.
100 open_patch_file(const char *filename)
102 struct stat filestat;
105 if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
106 pfp = fopen(TMPPATNAME, "w");
108 pfatal("can't create %s", TMPPATNAME);
109 while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
110 nw = fwrite(buf, 1, nr, pfp);
112 pfatal("write error to %s", TMPPATNAME);
114 if (ferror(pfp) || fclose(pfp))
115 pfatal("can't write %s", TMPPATNAME);
116 filename = TMPPATNAME;
118 pfp = fopen(filename, "r");
120 pfatal("patch file %s not found", filename);
121 fstat(fileno(pfp), &filestat);
122 p_filesize = filestat.st_size;
123 next_intuit_at(0L, 1L); /* start at the beginning */
128 * Make sure our dynamically realloced tables are malloced to begin with.
134 p_line = malloc(hunkmax * sizeof(char *));
136 p_len = malloc(hunkmax * sizeof(unsigned short));
138 p_char = malloc(hunkmax * sizeof(char));
142 * Enlarge the arrays containing the current hunk of patch.
147 int new_hunkmax = hunkmax * 2;
149 if (p_line == NULL || p_len == NULL || p_char == NULL)
150 fatal("Internal memory allocation error\n");
152 p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
153 p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
154 p_char = reallocf(p_char, new_hunkmax * sizeof(char));
156 if (p_line != NULL && p_len != NULL && p_char != NULL) {
157 hunkmax = new_hunkmax;
162 fatal("out of memory\n");
163 out_of_mem = true; /* whatever is null will be allocated again */
164 /* from within plan_a(), of all places */
167 /* True if the remainder of the patch file contains a diff of some sort. */
170 there_is_another_patch(void)
174 if (p_base != 0L && p_base >= p_filesize) {
181 diff_type = intuit_diff_type();
185 say(" Ignoring the trailing garbage.\ndone\n");
187 say(" I can't seem to find a patch in there anywhere.\n");
191 say(" %sooks like %s to me...\n",
192 (p_base == 0L ? "L" : "The next patch l"),
193 diff_type == UNI_DIFF ? "a unified diff" :
194 diff_type == CONTEXT_DIFF ? "a context diff" :
195 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
196 diff_type == NORMAL_DIFF ? "a normal diff" :
198 if (p_indent && verbose)
199 say("(Patch is indented %d space%s.)\n", p_indent,
200 p_indent == 1 ? "" : "s");
201 skip_to(p_start, p_sline);
202 while (filearg[0] == NULL) {
203 if (force || batch) {
204 say("No file to patch. Skipping...\n");
205 filearg[0] = savestr(bestguess);
206 skip_rest_of_patch = true;
209 ask("File to patch: ");
212 bestguess = savestr(buf);
213 filearg[0] = fetchname(buf, &exists, 0);
216 ask("No file found--skip this patch? [n] ");
220 say("Skipping patch...\n");
222 filearg[0] = fetchname(bestguess, &exists, 0);
223 skip_rest_of_patch = true;
231 p4_fetchname(struct file_name *name, char *str)
235 /* Skip leading whitespace. */
236 while (isspace((unsigned char)*str))
239 /* Remove the file revision number. */
240 for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
246 name->path = fetchname(str, &name->exists, strippath);
249 /* Determine what kind of diff is in the remaining part of the patch file. */
252 intuit_diff_type(void)
254 long this_line = 0, previous_line;
255 long first_command_line = -1;
256 LINENUM fcl_line = -1;
257 bool last_line_was_command = false, this_is_a_command = false;
258 bool stars_last_line = false, stars_this_line = false;
261 struct file_name names[MAX_FILE];
263 memset(names, 0, sizeof(names));
264 ok_to_create_file = false;
265 fseek(pfp, p_base, SEEK_SET);
266 p_input_line = p_bline - 1;
268 previous_line = this_line;
269 last_line_was_command = this_is_a_command;
270 stars_last_line = stars_this_line;
271 this_line = ftell(pfp);
274 if (pgets(false) == 0) {
275 if (first_command_line >= 0L) {
276 /* nothing but deletes!? */
277 p_start = first_command_line;
283 p_sline = p_input_line;
288 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
290 indent += 8 - (indent % 8);
294 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
296 this_is_a_command = (isdigit((unsigned char)*s) &&
297 (*t == 'd' || *t == 'c' || *t == 'a'));
298 if (first_command_line < 0L && this_is_a_command) {
299 first_command_line = this_line;
300 fcl_line = p_input_line;
301 p_indent = indent; /* assume this for now */
303 if (!stars_last_line && strnEQ(s, "*** ", 4))
304 names[OLD_FILE].path = fetchname(s + 4,
305 &names[OLD_FILE].exists, strippath);
306 else if (strnEQ(s, "--- ", 4))
307 names[NEW_FILE].path = fetchname(s + 4,
308 &names[NEW_FILE].exists, strippath);
309 else if (strnEQ(s, "+++ ", 4))
310 /* pretend it is the old name */
311 names[OLD_FILE].path = fetchname(s + 4,
312 &names[OLD_FILE].exists, strippath);
313 else if (strnEQ(s, "Index:", 6))
314 names[INDEX_FILE].path = fetchname(s + 6,
315 &names[INDEX_FILE].exists, strippath);
316 else if (strnEQ(s, "Prereq:", 7)) {
317 for (t = s + 7; isspace((unsigned char)*t); t++)
319 revision = savestr(t);
320 for (t = revision; *t && !isspace((unsigned char)*t); t++)
323 if (*revision == '\0') {
327 } else if (strnEQ(s, "==== ", 5)) {
328 /* Perforce-style diffs. */
329 if ((t = strstr(s + 5, " - ")) != NULL)
330 p4_fetchname(&names[NEW_FILE], t + 3);
331 p4_fetchname(&names[OLD_FILE], s + 5);
333 if ((!diff_type || diff_type == ED_DIFF) &&
334 first_command_line >= 0L &&
337 p_start = first_command_line;
342 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
343 if (strnEQ(s + 4, "0,0", 3))
344 ok_to_create_file = true;
347 p_sline = p_input_line;
351 stars_this_line = strnEQ(s, "********", 8);
352 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
353 strnEQ(s, "*** ", 4)) {
354 if (atol(s + 4) == 0)
355 ok_to_create_file = true;
357 * If this is a new context diff the character just
358 * before the newline is a '*'.
363 p_start = previous_line;
364 p_sline = p_input_line - 1;
365 retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
368 if ((!diff_type || diff_type == NORMAL_DIFF) &&
369 last_line_was_command &&
370 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
371 p_start = previous_line;
372 p_sline = p_input_line - 1;
374 retval = NORMAL_DIFF;
379 if (retval == UNI_DIFF) {
380 /* unswap old and new */
381 struct file_name tmp = names[OLD_FILE];
382 names[OLD_FILE] = names[NEW_FILE];
383 names[NEW_FILE] = tmp;
385 if (filearg[0] == NULL) {
387 filearg[0] = posix_name(names, ok_to_create_file);
389 /* Ignore the Index: name for context diffs, like GNU */
390 if (names[OLD_FILE].path != NULL ||
391 names[NEW_FILE].path != NULL) {
392 free(names[INDEX_FILE].path);
393 names[INDEX_FILE].path = NULL;
395 filearg[0] = best_name(names, ok_to_create_file);
401 if (filearg[0] != NULL)
402 bestguess = savestr(filearg[0]);
403 else if (!ok_to_create_file) {
405 * We don't want to create a new file but we need a
406 * filename to set bestguess. Avoid setting filearg[0]
407 * so the file is not created automatically.
410 bestguess = posix_name(names, true);
412 bestguess = best_name(names, true);
414 free(names[OLD_FILE].path);
415 free(names[NEW_FILE].path);
416 free(names[INDEX_FILE].path);
421 * Remember where this patch ends so we know where to start up again.
424 next_intuit_at(LINENUM file_pos, LINENUM file_line)
431 * Basically a verbose fseek() to the actual diff listing.
434 skip_to(LINENUM file_pos, LINENUM file_line)
438 if (p_base > file_pos)
439 fatal("Internal error: seek %ld>%ld\n", p_base, file_pos);
440 if (verbose && p_base < file_pos) {
441 fseek(pfp, p_base, SEEK_SET);
442 say("The text leading up to this was:\n--------------------------\n");
443 while (ftell(pfp) < file_pos) {
446 fatal("Unexpected end of file\n");
449 say("--------------------------\n");
451 fseek(pfp, file_pos, SEEK_SET);
452 p_input_line = file_line - 1;
455 /* Make this a function for better debugging. */
459 fatal("malformed patch at line %ld: %s", p_input_line, buf);
460 /* about as informative as "Syntax error" in C */
464 * True if the line has been discarded (i.e. it is a line saying
465 * "\ No newline at end of file".)
468 remove_special_line(void)
476 } while (c != EOF && c != '\n');
481 fseek(pfp, -1L, SEEK_CUR);
487 * True if there is more of the current diff listing to process.
492 long line_beginning; /* file pos of the current line */
493 LINENUM repl_beginning; /* index of --- line */
494 LINENUM fillcnt; /* #lines of missing ptrn or repl */
495 LINENUM fillsrc; /* index of first line to copy */
496 LINENUM filldst; /* index of first missing line */
497 bool ptrn_spaces_eaten; /* ptrn was slightly misformed */
498 bool repl_could_be_missing; /* no + or ! lines in this hunk */
499 bool repl_missing; /* we are now backtracking */
500 long repl_backtrack_position; /* file pos of first repl line */
501 LINENUM repl_patch_line; /* input line number for same */
502 LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
508 if (p_end == p_efake)
509 p_end = p_bfake; /* don't free twice */
516 p_max = hunkmax; /* gets reduced when --- found */
517 if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
518 line_beginning = ftell(pfp);
523 ptrn_spaces_eaten = false;
524 repl_could_be_missing = true;
525 repl_missing = false;
526 repl_backtrack_position = 0;
532 if (len == 0 || strnNE(buf, "********", 8)) {
533 next_intuit_at(line_beginning, p_input_line);
537 p_hunk_beg = p_input_line + 1;
538 while (p_end < p_max) {
539 line_beginning = ftell(pfp);
543 if (p_max - p_end < 4) {
544 /* assume blank lines got chopped */
545 strlcpy(buf, " \n", buf_size);
547 if (repl_beginning && repl_could_be_missing) {
551 fatal("unexpected end of file in patch\n");
555 if (p_end >= hunkmax)
556 fatal("Internal error: hunk larger than hunk "
558 p_char[p_end] = *buf;
559 p_line[p_end] = NULL;
562 if (strnEQ(buf, "********", 8)) {
563 if (repl_beginning && repl_could_be_missing) {
567 fatal("unexpected end of hunk "
572 if (repl_beginning && repl_could_be_missing) {
576 fatal("unexpected *** at line %ld: %s",
580 p_line[p_end] = savestr(buf);
585 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
589 if (strnEQ(s, "0,0", 3))
590 memmove(s, s + 2, strlen(s + 2) + 1);
591 p_first = (LINENUM) atol(s);
592 while (isdigit((unsigned char)*s))
595 for (; *s && !isdigit((unsigned char)*s); s++)
599 p_ptrn_lines = ((LINENUM) atol(s)) - p_first + 1;
607 /* we need this much at least */
608 p_max = p_ptrn_lines + 6;
609 while (p_max >= hunkmax)
615 if (repl_beginning ||
616 (p_end != p_ptrn_lines + 1 +
617 (p_char[p_end - 1] == '\n'))) {
620 * `old' lines were omitted;
621 * set up to fill them in
622 * from 'new' context lines.
624 p_end = p_ptrn_lines + 1;
627 fillcnt = p_ptrn_lines;
629 if (repl_beginning) {
630 if (repl_could_be_missing) {
634 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
635 p_input_line, p_hunk_beg + repl_beginning);
637 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
638 (p_end <= p_ptrn_lines
641 p_input_line, p_hunk_beg);
645 repl_beginning = p_end;
646 repl_backtrack_position = ftell(pfp);
647 repl_patch_line = p_input_line;
648 p_line[p_end] = savestr(buf);
654 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
658 p_newfirst = (LINENUM) atol(s);
659 while (isdigit((unsigned char)*s))
662 for (; *s && !isdigit((unsigned char)*s); s++)
666 p_repl_lines = ((LINENUM) atol(s)) -
668 } else if (p_newfirst)
674 p_max = p_repl_lines + p_end;
675 if (p_max > MAXHUNKSIZE)
676 fatal("hunk too large (%ld lines) at line %ld: %s",
677 p_max, p_input_line, buf);
678 while (p_max >= hunkmax)
680 if (p_repl_lines != ptrn_copiable &&
681 (p_context != 0 || p_repl_lines != 1))
682 repl_could_be_missing = false;
688 repl_could_be_missing = false;
690 if (buf[1] == '\n' && canonicalize)
691 strlcpy(buf + 1, " \n", buf_size - 1);
692 if (!isspace((unsigned char)buf[1]) && buf[1] != '>' &&
694 repl_beginning && repl_could_be_missing) {
699 if (context < p_context)
703 p_line[p_end] = savestr(buf + 2);
708 if (p_end == p_ptrn_lines) {
709 if (remove_special_line()) {
712 l = strlen(p_line[p_end]) - 1;
713 (p_line[p_end])[l] = 0;
718 case '\n': /* assume the 2 spaces got eaten */
719 if (repl_beginning && repl_could_be_missing &&
720 (!ptrn_spaces_eaten ||
721 diff_type == NEW_CONTEXT_DIFF)) {
725 p_line[p_end] = savestr(buf);
730 if (p_end != p_ptrn_lines + 1) {
731 ptrn_spaces_eaten |= (repl_beginning != 0);
739 if (!isspace((unsigned char)buf[1]) &&
740 repl_beginning && repl_could_be_missing) {
747 p_line[p_end] = savestr(buf + 2);
754 if (repl_beginning && repl_could_be_missing) {
760 /* set up p_len for strncmp() so we don't have to */
761 /* assume null termination */
763 p_len[p_end] = strlen(p_line[p_end]);
769 if (p_end >= 0 && !repl_beginning)
770 fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
774 /* reset state back to just after --- */
775 p_input_line = repl_patch_line;
776 for (p_end--; p_end > repl_beginning; p_end--)
778 fseek(pfp, repl_backtrack_position, SEEK_SET);
780 /* redundant 'new' context lines were omitted - set */
781 /* up to fill them in from the old file context */
782 if (!p_context && p_repl_lines == 1) {
787 filldst = repl_beginning + 1;
788 fillcnt = p_repl_lines;
790 } else if (!p_context && fillcnt == 1) {
791 /* the first hunk was a null hunk with no context */
792 /* and we were expecting one line -- fix it up. */
793 while (filldst < p_end) {
794 p_line[filldst] = p_line[filldst + 1];
795 p_char[filldst] = p_char[filldst + 1];
796 p_len[filldst] = p_len[filldst + 1];
800 repl_beginning--; /* this doesn't need to be fixed */
803 p_first++; /* do append rather than insert */
807 if (diff_type == CONTEXT_DIFF &&
808 (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
811 "(Fascinating--this is really a new-style context diff but without",
812 "the telltale extra asterisks on the *** line that usually indicate",
813 "the new style...)");
814 diff_type = NEW_CONTEXT_DIFF;
816 /* if there were omitted context lines, fill them in now */
818 p_bfake = filldst; /* remember where not to free() */
819 p_efake = filldst + fillcnt - 1;
820 while (fillcnt-- > 0) {
821 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
824 fatal("replacement text or line numbers mangled in hunk at line %ld\n",
826 p_line[filldst] = p_line[fillsrc];
827 p_char[filldst] = p_char[fillsrc];
828 p_len[filldst] = p_len[fillsrc];
832 while (fillsrc <= p_end && fillsrc != repl_beginning &&
833 p_char[fillsrc] != ' ')
837 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
838 fillsrc, filldst, repl_beginning, p_end + 1);
840 if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
842 if (filldst != p_end + 1 && filldst != repl_beginning)
845 if (p_line[p_end] != NULL) {
846 if (remove_special_line()) {
848 (p_line[p_end])[p_len[p_end]] = 0;
851 } else if (diff_type == UNI_DIFF) {
852 LINENUM fillold; /* index of old lines */
853 LINENUM fillnew; /* index of new lines */
856 line_beginning = ftell(pfp); /* file pos of the current line */
859 if (len == 0 || strnNE(buf, "@@ -", 4)) {
860 next_intuit_at(line_beginning, p_input_line);
866 p_first = (LINENUM) atol(s);
867 while (isdigit((unsigned char)*s))
870 p_ptrn_lines = (LINENUM) atol(++s);
871 while (isdigit((unsigned char)*s))
877 if (*s != '+' || !*++s)
879 p_newfirst = (LINENUM) atol(s);
880 while (isdigit((unsigned char)*s))
883 p_repl_lines = (LINENUM) atol(++s);
884 while (isdigit((unsigned char)*s))
893 p_first++; /* do append rather than insert */
894 p_max = p_ptrn_lines + p_repl_lines + 1;
895 while (p_max >= hunkmax)
898 fillnew = fillold + p_ptrn_lines;
899 p_end = fillnew + p_repl_lines;
900 snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
901 p_first + p_ptrn_lines - 1);
902 p_line[0] = savestr(buf);
908 snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
909 p_newfirst + p_repl_lines - 1);
910 p_line[fillnew] = savestr(buf);
915 p_char[fillnew++] = '=';
918 p_hunk_beg = p_input_line + 1;
919 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
920 line_beginning = ftell(pfp);
924 if (p_max - fillnew < 3) {
925 /* assume blank lines got chopped */
926 strlcpy(buf, " \n", buf_size);
928 fatal("unexpected end of file in patch\n");
931 if (*buf == '\t' || *buf == '\n') {
932 ch = ' '; /* assume the space got eaten */
936 s = savestr(buf + 1);
939 while (--fillnew > p_ptrn_lines)
940 free(p_line[fillnew]);
946 if (fillold > p_ptrn_lines) {
951 p_char[fillold] = ch;
953 p_len[fillold++] = strlen(s);
954 if (fillold > p_ptrn_lines) {
955 if (remove_special_line()) {
956 p_len[fillold - 1] -= 1;
957 s[p_len[fillold - 1]] = 0;
965 if (fillold > p_ptrn_lines) {
967 while (--fillnew > p_ptrn_lines)
968 free(p_line[fillnew]);
973 p_char[fillold] = ch;
975 p_len[fillold++] = strlen(s);
978 while (--fillnew > p_ptrn_lines)
979 free(p_line[fillnew]);
983 if (fillold > p_ptrn_lines) {
984 if (remove_special_line()) {
985 p_len[fillold - 1] -= 1;
986 s[p_len[fillold - 1]] = 0;
991 if (fillnew > p_end) {
993 while (--fillnew > p_ptrn_lines)
994 free(p_line[fillnew]);
998 p_char[fillnew] = ch;
1000 p_len[fillnew++] = strlen(s);
1001 if (fillold > p_ptrn_lines) {
1002 if (remove_special_line()) {
1003 p_len[fillnew - 1] -= 1;
1004 s[p_len[fillnew - 1]] = 0;
1012 if (ch != ' ' && context > 0) {
1013 if (context < p_context)
1014 p_context = context;
1018 } else { /* normal diff--fake it up */
1023 line_beginning = ftell(pfp);
1027 if (len == 0 || !isdigit((unsigned char)*buf)) {
1028 next_intuit_at(line_beginning, p_input_line);
1031 p_first = (LINENUM) atol(buf);
1032 for (s = buf; isdigit((unsigned char)*s); s++)
1035 p_ptrn_lines = (LINENUM) atol(++s) - p_first + 1;
1036 while (isdigit((unsigned char)*s))
1039 p_ptrn_lines = (*s != 'a');
1041 if (hunk_type == 'a')
1042 p_first++; /* do append rather than insert */
1043 min = (LINENUM) atol(++s);
1044 for (; isdigit((unsigned char)*s); s++)
1047 max = (LINENUM) atol(++s);
1050 if (hunk_type == 'd')
1052 p_end = p_ptrn_lines + 1 + max - min + 1;
1053 if (p_end > MAXHUNKSIZE)
1054 fatal("hunk too large (%ld lines) at line %ld: %s",
1055 p_end, p_input_line, buf);
1056 while (p_end >= hunkmax)
1059 p_repl_lines = max - min + 1;
1060 snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1061 p_first + p_ptrn_lines - 1);
1062 p_line[0] = savestr(buf);
1068 for (i = 1; i <= p_ptrn_lines; i++) {
1072 fatal("unexpected end of file in patch at line %ld\n",
1075 fatal("< expected at line %ld of patch\n",
1077 p_line[i] = savestr(buf + 2);
1082 p_len[i] = strlen(p_line[i]);
1086 if (remove_special_line()) {
1088 (p_line[i - 1])[p_len[i - 1]] = 0;
1090 if (hunk_type == 'c') {
1094 fatal("unexpected end of file in patch at line %ld\n",
1097 fatal("--- expected at line %ld of patch\n",
1100 snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1101 p_line[i] = savestr(buf);
1107 for (i++; i <= p_end; i++) {
1111 fatal("unexpected end of file in patch at line %ld\n",
1114 fatal("> expected at line %ld of patch\n",
1116 p_line[i] = savestr(buf + 2);
1121 p_len[i] = strlen(p_line[i]);
1125 if (remove_special_line()) {
1127 (p_line[i - 1])[p_len[i - 1]] = 0;
1130 if (reverse) /* backwards patch? */
1132 say("Not enough memory to swap next hunk!\n");
1138 for (i = 0; i <= p_end; i++) {
1139 if (i == p_ptrn_lines)
1143 fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1144 special, p_line[i]);
1149 if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1150 p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
1155 * Input a line from the patch file.
1156 * Worry about indentation if do_indent is true.
1157 * The line is read directly into the buf global variable which
1158 * is resized if necessary in order to hold the complete line.
1159 * Returns the number of characters read including the terminating
1163 pgets(bool do_indent)
1167 int indent = 0, skipped = 0;
1169 line = fgetln(pfp, &len);
1171 if (len + 1 > buf_size) {
1172 while (len + 1 > buf_size)
1175 buf = malloc(buf_size);
1177 fatal("out of memory\n");
1179 if (do_indent == 1 && p_indent) {
1181 indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1182 line++, skipped++) {
1184 indent += 8 - (indent %7);
1189 memcpy(buf, line, len - skipped);
1190 buf[len - skipped] = '\0';
1197 * Reverse the old and new portions of the current hunk.
1202 char **tp_line; /* the text of the hunk */
1203 unsigned short *tp_len;/* length of each line */
1204 char *tp_char; /* +, -, and ! */
1207 bool blankline = false;
1211 p_first = p_newfirst;
1214 /* make a scratch copy */
1219 p_line = NULL; /* force set_hunkmax to allocate again */
1223 if (p_line == NULL || p_len == NULL || p_char == NULL) {
1231 return false; /* not enough memory to swap hunk! */
1233 /* now turn the new into the old */
1235 i = p_ptrn_lines + 1;
1236 if (tp_char[i] == '\n') { /* account for possible blank line */
1240 if (p_efake >= 0) { /* fix non-freeable ptr range */
1248 for (n = 0; i <= p_end; i++, n++) {
1249 p_line[n] = tp_line[i];
1250 p_char[n] = tp_char[i];
1251 if (p_char[n] == '+')
1253 p_len[n] = tp_len[i];
1256 i = p_ptrn_lines + 1;
1257 p_line[n] = tp_line[i];
1258 p_char[n] = tp_char[i];
1259 p_len[n] = tp_len[i];
1262 if (p_char[0] != '=')
1263 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1264 p_input_line, p_char[0]);
1266 for (s = p_line[0]; *s; s++)
1270 /* now turn the old into the new */
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 = tp_line[0]; *s; s++)
1279 for (i = 0; n <= p_end; i++, n++) {
1280 p_line[n] = tp_line[i];
1281 p_char[n] = tp_char[i];
1282 if (p_char[n] == '-')
1284 p_len[n] = tp_len[i];
1287 if (i != p_ptrn_lines + 1)
1288 fatal("Malformed patch at line %ld: expected %ld lines, "
1290 p_input_line, p_ptrn_lines + 1, i);
1293 p_ptrn_lines = p_repl_lines;
1304 * Return the specified line position in the old file of the old context.
1313 * Return the number of lines of old context.
1316 pch_ptrn_lines(void)
1318 return p_ptrn_lines;
1322 * Return the probable line position in the new file of the first line.
1331 * Return the number of lines in the replacement text including context.
1334 pch_repl_lines(void)
1336 return p_repl_lines;
1340 * Return the number of lines in the whole hunk.
1349 * Return the number of context lines before the first changed line.
1358 * Return the length of a particular patch line.
1361 pch_line_len(LINENUM line)
1367 * Return the control character (+, -, *, !, etc) for a patch line.
1370 pch_char(LINENUM line)
1372 return p_char[line];
1376 * Return a pointer to a particular patch line.
1379 pfetch(LINENUM line)
1381 return p_line[line];
1385 * Return where in the patch file this hunk began, for error messages.
1394 * Apply an ed script by feeding ed itself.
1400 long beginning_of_this_line;
1401 FILE *pipefp = NULL;
1404 if (!skip_rest_of_patch) {
1405 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1407 fatal("can't create temp file %s", TMPOUTNAME);
1409 snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1410 verbose ? " " : " -s ", TMPOUTNAME);
1411 pipefp = popen(buf, "w");
1414 beginning_of_this_line = ftell(pfp);
1415 if (pgets(true) == 0) {
1416 next_intuit_at(beginning_of_this_line, p_input_line);
1420 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1422 /* POSIX defines allowed commands as {a,c,d,i,s} */
1423 if (isdigit((unsigned char)*buf) && (*t == 'a' || *t == 'c' ||
1424 *t == 'd' || *t == 'i' || *t == 's')) {
1430 t = strchr(buf, '\0') - 1;
1431 while (--t >= buf && *t == '\\')
1432 continuation = !continuation;
1433 if (!continuation ||
1439 } else if (*t != 'd') {
1440 while (pgets(true)) {
1444 if (strEQ(buf, ".\n"))
1449 next_intuit_at(beginning_of_this_line, p_input_line);
1455 fprintf(pipefp, "w\n");
1456 fprintf(pipefp, "q\n");
1461 if (move_file(TMPOUTNAME, outname) < 0) {
1463 chmod(TMPOUTNAME, filemode);
1465 chmod(outname, filemode);
1471 * Choose the name of the file to be patched based on POSIX rules.
1472 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1473 * if the user specified --posix or set POSIXLY_CORRECT.
1476 posix_name(const struct file_name *names, bool assume_exists)
1482 * POSIX states that the filename will be chosen from one
1483 * of the old, new and index names (in that order) if
1484 * the file exists relative to CWD after -p stripping.
1486 for (i = 0; i < MAX_FILE; i++) {
1487 if (names[i].path != NULL && names[i].exists) {
1488 path = names[i].path;
1492 if (path == NULL && !assume_exists) {
1494 * No files found, look for something we can checkout from
1495 * RCS/SCCS dirs. Same order as above.
1497 for (i = 0; i < MAX_FILE; i++) {
1498 if (names[i].path != NULL &&
1499 (path = checked_in(names[i].path)) != NULL)
1503 * Still no match? Check to see if the diff could be creating
1506 if (path == NULL && ok_to_create_file &&
1507 names[NEW_FILE].path != NULL)
1508 path = names[NEW_FILE].path;
1511 return path ? savestr(path) : NULL;
1515 compare_names(const struct file_name *names, bool assume_exists, int phase)
1517 size_t min_components, min_baselen, min_len, tmp;
1523 * The "best" name is the one with the fewest number of path
1524 * components, the shortest basename length, and the shortest
1525 * overall length (in that order). We only use the Index: file
1526 * if neither of the old or new files could be intuited from
1529 min_components = min_baselen = min_len = SIZE_MAX;
1530 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1531 path = names[i].path;
1533 (phase == 1 && !names[i].exists && !assume_exists) ||
1534 (phase == 2 && checked_in(path) == NULL))
1536 if ((tmp = num_components(path)) > min_components)
1538 if (tmp < min_components) {
1539 min_components = tmp;
1542 if ((tmp = strlen(basename(path))) > min_baselen)
1544 if (tmp < min_baselen) {
1548 if ((tmp = strlen(path)) > min_len)
1557 * Choose the name of the file to be patched based the "best" one
1561 best_name(const struct file_name *names, bool assume_exists)
1565 best = compare_names(names, assume_exists, 1);
1567 best = compare_names(names, assume_exists, 2);
1569 * Still no match? Check to see if the diff could be creating
1572 if (best == NULL && ok_to_create_file &&
1573 names[NEW_FILE].path != NULL)
1574 best = names[NEW_FILE].path;
1577 return best ? savestr(best) : NULL;
1581 num_components(const char *path)
1586 for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1588 cp++; /* skip consecutive slashes */