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>
44 #include "pathnames.h"
46 /* Patch (diff listing) abstract type. */
48 static off_t 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 off_t p_base; /* where to intuit this time */
63 static LINENUM p_bline; /* line # of p_base */
64 static off_t 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(off_t, LINENUM);
75 static void skip_to(off_t, 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 *);
80 static LINENUM strtolinenum(char *, char **);
83 * Prepare to look for the next patch in the patch file.
92 p_end = (LINENUM) - 1;
98 * Open the patch file at the beginning of time.
101 open_patch_file(const char *filename)
103 struct stat filestat;
106 if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
107 pfp = fopen(TMPPATNAME, "w");
109 pfatal("can't create %s", TMPPATNAME);
110 while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
111 nw = fwrite(buf, 1, nr, pfp);
113 pfatal("write error to %s", TMPPATNAME);
115 if (ferror(pfp) || fclose(pfp))
116 pfatal("can't write %s", TMPPATNAME);
117 filename = TMPPATNAME;
119 pfp = fopen(filename, "r");
121 pfatal("patch file %s not found", filename);
122 if (fstat(fileno(pfp), &filestat))
123 pfatal("can't stat %s", filename);
124 p_filesize = filestat.st_size;
125 next_intuit_at(0, 1L); /* start at the beginning */
130 * Make sure our dynamically realloced tables are malloced to begin with.
136 p_line = malloc(hunkmax * sizeof(char *));
138 p_len = malloc(hunkmax * sizeof(unsigned short));
140 p_char = malloc(hunkmax * sizeof(char));
144 * Enlarge the arrays containing the current hunk of patch.
149 int new_hunkmax = hunkmax * 2;
151 if (p_line == NULL || p_len == NULL || p_char == NULL)
152 fatal("Internal memory allocation error\n");
154 p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
155 p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
156 p_char = reallocf(p_char, new_hunkmax * sizeof(char));
158 if (p_line != NULL && p_len != NULL && p_char != NULL) {
159 hunkmax = new_hunkmax;
164 fatal("out of memory\n");
165 out_of_mem = true; /* whatever is null will be allocated again */
166 /* from within plan_a(), of all places */
169 /* True if the remainder of the patch file contains a diff of some sort. */
172 there_is_another_patch(void)
176 if (p_base != 0 && p_base >= p_filesize) {
183 diff_type = intuit_diff_type();
187 say(" Ignoring the trailing garbage.\ndone\n");
189 say(" I can't seem to find a patch in there anywhere.\n");
193 say(" %sooks like %s to me...\n",
194 (p_base == 0 ? "L" : "The next patch l"),
195 diff_type == UNI_DIFF ? "a unified diff" :
196 diff_type == CONTEXT_DIFF ? "a context diff" :
197 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
198 diff_type == NORMAL_DIFF ? "a normal diff" :
200 if (p_indent && verbose)
201 say("(Patch is indented %d space%s.)\n", p_indent,
202 p_indent == 1 ? "" : "s");
203 skip_to(p_start, p_sline);
204 while (filearg[0] == NULL) {
205 if (force || batch) {
206 say("No file to patch. Skipping...\n");
207 filearg[0] = xstrdup(bestguess);
208 skip_rest_of_patch = true;
211 ask("File to patch: ");
214 bestguess = xstrdup(buf);
215 filearg[0] = fetchname(buf, &exists, 0);
218 ask("No file found--skip this patch? [n] ");
222 say("Skipping patch...\n");
224 filearg[0] = fetchname(bestguess, &exists, 0);
225 skip_rest_of_patch = true;
233 p4_fetchname(struct file_name *name, char *str)
237 /* Skip leading whitespace. */
238 while (isspace((unsigned char)*str))
241 /* Remove the file revision number. */
242 for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
248 name->path = fetchname(str, &name->exists, strippath);
251 /* Determine what kind of diff is in the remaining part of the patch file. */
254 intuit_diff_type(void)
256 off_t this_line = 0, previous_line;
257 off_t first_command_line = -1;
258 LINENUM fcl_line = -1;
259 bool last_line_was_command = false, this_is_a_command = false;
260 bool stars_last_line = false, stars_this_line = false;
263 struct file_name names[MAX_FILE];
265 memset(names, 0, sizeof(names));
266 ok_to_create_file = false;
267 fseeko(pfp, p_base, SEEK_SET);
268 p_input_line = p_bline - 1;
270 previous_line = this_line;
271 last_line_was_command = this_is_a_command;
272 stars_last_line = stars_this_line;
273 this_line = ftello(pfp);
276 if (pgets(false) == 0) {
277 if (first_command_line >= 0) {
278 /* nothing but deletes!? */
279 p_start = first_command_line;
285 p_sline = p_input_line;
290 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
292 indent += 8 - (indent % 8);
296 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
298 this_is_a_command = (isdigit((unsigned char)*s) &&
299 (*t == 'd' || *t == 'c' || *t == 'a'));
300 if (first_command_line < 0 && this_is_a_command) {
301 first_command_line = this_line;
302 fcl_line = p_input_line;
303 p_indent = indent; /* assume this for now */
305 if (!stars_last_line && strnEQ(s, "*** ", 4))
306 names[OLD_FILE].path = fetchname(s + 4,
307 &names[OLD_FILE].exists, strippath);
308 else if (strnEQ(s, "--- ", 4))
309 names[NEW_FILE].path = fetchname(s + 4,
310 &names[NEW_FILE].exists, strippath);
311 else if (strnEQ(s, "+++ ", 4))
312 /* pretend it is the old name */
313 names[OLD_FILE].path = fetchname(s + 4,
314 &names[OLD_FILE].exists, strippath);
315 else if (strnEQ(s, "Index:", 6))
316 names[INDEX_FILE].path = fetchname(s + 6,
317 &names[INDEX_FILE].exists, strippath);
318 else if (strnEQ(s, "Prereq:", 7)) {
319 for (t = s + 7; isspace((unsigned char)*t); t++)
321 revision = xstrdup(t);
323 *t && !isspace((unsigned char)*t); t++)
326 if (*revision == '\0') {
330 } else if (strnEQ(s, "==== ", 5)) {
331 /* Perforce-style diffs. */
332 if ((t = strstr(s + 5, " - ")) != NULL)
333 p4_fetchname(&names[NEW_FILE], t + 3);
334 p4_fetchname(&names[OLD_FILE], s + 5);
336 if ((!diff_type || diff_type == ED_DIFF) &&
337 first_command_line >= 0 &&
340 p_start = first_command_line;
345 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
346 if (strnEQ(s + 4, "0,0", 3))
347 ok_to_create_file = true;
350 p_sline = p_input_line;
354 stars_this_line = strnEQ(s, "********", 8);
355 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
356 strnEQ(s, "*** ", 4)) {
357 if (strtolinenum(s + 4, &s) == 0)
358 ok_to_create_file = true;
360 * If this is a new context diff the character just
361 * at the end of the line is a '*'.
363 while (*s && *s != '\n')
366 p_start = previous_line;
367 p_sline = p_input_line - 1;
368 retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
371 if ((!diff_type || diff_type == NORMAL_DIFF) &&
372 last_line_was_command &&
373 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
374 p_start = previous_line;
375 p_sline = p_input_line - 1;
377 retval = NORMAL_DIFF;
382 if (retval == UNI_DIFF) {
383 /* unswap old and new */
384 struct file_name tmp = names[OLD_FILE];
385 names[OLD_FILE] = names[NEW_FILE];
386 names[NEW_FILE] = tmp;
388 if (filearg[0] == NULL) {
390 filearg[0] = posix_name(names, ok_to_create_file);
392 /* Ignore the Index: name for context diffs, like GNU */
393 if (names[OLD_FILE].path != NULL ||
394 names[NEW_FILE].path != NULL) {
395 free(names[INDEX_FILE].path);
396 names[INDEX_FILE].path = NULL;
398 filearg[0] = best_name(names, ok_to_create_file);
404 if (filearg[0] != NULL)
405 bestguess = xstrdup(filearg[0]);
406 else if (!ok_to_create_file) {
408 * We don't want to create a new file but we need a
409 * filename to set bestguess. Avoid setting filearg[0]
410 * so the file is not created automatically.
413 bestguess = posix_name(names, true);
415 bestguess = best_name(names, true);
417 free(names[OLD_FILE].path);
418 free(names[NEW_FILE].path);
419 free(names[INDEX_FILE].path);
424 * Remember where this patch ends so we know where to start up again.
427 next_intuit_at(off_t file_pos, LINENUM file_line)
434 * Basically a verbose fseeko() to the actual diff listing.
437 skip_to(off_t file_pos, LINENUM file_line)
441 if (p_base > file_pos)
442 fatal("Internal error: seek %lld>%lld\n",
443 (long long)p_base, (long long)file_pos);
444 if (verbose && p_base < file_pos) {
445 fseeko(pfp, p_base, SEEK_SET);
446 say("The text leading up to this was:\n--------------------------\n");
447 while (ftello(pfp) < file_pos) {
450 fatal("Unexpected end of file\n");
453 say("--------------------------\n");
455 fseeko(pfp, file_pos, SEEK_SET);
456 p_input_line = file_line - 1;
459 /* Make this a function for better debugging. */
463 fatal("malformed patch at line %ld: %s", p_input_line, buf);
464 /* about as informative as "Syntax error" in C */
468 * True if the line has been discarded (i.e. it is a line saying
469 * "\ No newline at end of file".)
472 remove_special_line(void)
480 } while (c != EOF && c != '\n');
485 fseeko(pfp, -1, SEEK_CUR);
491 * True if there is more of the current diff listing to process.
496 off_t line_beginning; /* file pos of the current line */
497 LINENUM repl_beginning; /* index of --- line */
498 LINENUM fillcnt; /* #lines of missing ptrn or repl */
499 LINENUM fillsrc; /* index of first line to copy */
500 LINENUM filldst; /* index of first missing line */
501 bool ptrn_spaces_eaten; /* ptrn was slightly misformed */
502 bool repl_could_be_missing; /* no + or ! lines in this hunk */
503 bool repl_missing; /* we are now backtracking */
504 off_t repl_backtrack_position; /* file pos of first repl line */
505 LINENUM repl_patch_line; /* input line number for same */
506 LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
512 if (p_end == p_efake)
513 p_end = p_bfake; /* don't free twice */
520 p_max = hunkmax; /* gets reduced when --- found */
521 if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
522 line_beginning = ftello(pfp);
527 ptrn_spaces_eaten = false;
528 repl_could_be_missing = true;
529 repl_missing = false;
530 repl_backtrack_position = 0;
536 if (len == 0 || strnNE(buf, "********", 8)) {
537 next_intuit_at(line_beginning, p_input_line);
541 p_hunk_beg = p_input_line + 1;
542 while (p_end < p_max) {
543 line_beginning = ftello(pfp);
547 if (p_max - p_end < 4) {
548 /* assume blank lines got chopped */
549 strlcpy(buf, " \n", buf_size);
551 if (repl_beginning && repl_could_be_missing) {
555 fatal("unexpected end of file in patch\n");
559 if (p_end >= hunkmax)
560 fatal("Internal error: hunk larger than hunk "
562 p_char[p_end] = *buf;
563 p_line[p_end] = NULL;
566 if (strnEQ(buf, "********", 8)) {
567 if (repl_beginning && repl_could_be_missing) {
571 fatal("unexpected end of hunk "
576 if (repl_beginning && repl_could_be_missing) {
580 fatal("unexpected *** at line %ld: %s",
584 p_line[p_end] = savestr(buf);
590 *s && !isdigit((unsigned char)*s); s++)
594 if (strnEQ(s, "0,0", 3))
595 memmove(s, s + 2, strlen(s + 2) + 1);
596 p_first = strtolinenum(s, &s);
599 *s && !isdigit((unsigned char)*s); s++)
603 p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
604 if (p_ptrn_lines < 0)
612 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
613 p_ptrn_lines >= LINENUM_MAX - 6)
616 /* we need this much at least */
617 p_max = p_ptrn_lines + 6;
618 while (p_max >= hunkmax)
624 if (repl_beginning ||
625 (p_end != p_ptrn_lines + 1 +
626 (p_char[p_end - 1] == '\n'))) {
629 * `old' lines were omitted;
630 * set up to fill them in
631 * from 'new' context lines.
633 p_end = p_ptrn_lines + 1;
636 fillcnt = p_ptrn_lines;
638 if (repl_beginning) {
639 if (repl_could_be_missing) {
643 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
644 p_input_line, p_hunk_beg + repl_beginning);
646 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
647 (p_end <= p_ptrn_lines
650 p_input_line, p_hunk_beg);
654 repl_beginning = p_end;
655 repl_backtrack_position = ftello(pfp);
656 repl_patch_line = p_input_line;
657 p_line[p_end] = savestr(buf);
663 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
667 p_newfirst = strtolinenum(s, &s);
669 for (; *s && !isdigit((unsigned char)*s); s++)
673 p_repl_lines = strtolinenum(s, &s) -
675 if (p_repl_lines < 0)
677 } else if (p_newfirst)
683 if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
684 p_repl_lines >= LINENUM_MAX - p_end)
686 p_max = p_repl_lines + p_end;
687 if (p_max > MAXHUNKSIZE)
688 fatal("hunk too large (%ld lines) at line %ld: %s",
689 p_max, p_input_line, buf);
690 while (p_max >= hunkmax)
692 if (p_repl_lines != ptrn_copiable &&
693 (p_context != 0 || p_repl_lines != 1))
694 repl_could_be_missing = false;
700 repl_could_be_missing = false;
702 if (buf[1] == '\n' && canonicalize)
703 strlcpy(buf + 1, " \n", buf_size - 1);
704 if (!isspace((unsigned char)buf[1]) &&
705 buf[1] != '>' && buf[1] != '<' &&
706 repl_beginning && repl_could_be_missing) {
711 if (context < p_context)
715 p_line[p_end] = savestr(buf + 2);
720 if (p_end == p_ptrn_lines) {
721 if (remove_special_line()) {
724 l = strlen(p_line[p_end]) - 1;
725 (p_line[p_end])[l] = 0;
730 case '\n': /* assume the 2 spaces got eaten */
731 if (repl_beginning && repl_could_be_missing &&
732 (!ptrn_spaces_eaten ||
733 diff_type == NEW_CONTEXT_DIFF)) {
737 p_line[p_end] = savestr(buf);
742 if (p_end != p_ptrn_lines + 1) {
743 ptrn_spaces_eaten |= (repl_beginning != 0);
751 if (!isspace((unsigned char)buf[1]) &&
752 repl_beginning && repl_could_be_missing) {
759 p_line[p_end] = savestr(buf + 2);
766 if (repl_beginning && repl_could_be_missing) {
772 /* set up p_len for strncmp() so we don't have to */
773 /* assume null termination */
775 p_len[p_end] = strlen(p_line[p_end]);
781 if (p_end >= 0 && !repl_beginning)
782 fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
786 /* reset state back to just after --- */
787 p_input_line = repl_patch_line;
788 for (p_end--; p_end > repl_beginning; p_end--)
790 fseeko(pfp, repl_backtrack_position, SEEK_SET);
792 /* redundant 'new' context lines were omitted - set */
793 /* up to fill them in from the old file context */
794 if (!p_context && p_repl_lines == 1) {
799 filldst = repl_beginning + 1;
800 fillcnt = p_repl_lines;
802 } else if (!p_context && fillcnt == 1) {
803 /* the first hunk was a null hunk with no context */
804 /* and we were expecting one line -- fix it up. */
805 while (filldst < p_end) {
806 p_line[filldst] = p_line[filldst + 1];
807 p_char[filldst] = p_char[filldst + 1];
808 p_len[filldst] = p_len[filldst + 1];
812 repl_beginning--; /* this doesn't need to be fixed */
815 p_first++; /* do append rather than insert */
819 if (diff_type == CONTEXT_DIFF &&
820 (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
823 "(Fascinating--this is really a new-style context diff but without",
824 "the telltale extra asterisks on the *** line that usually indicate",
825 "the new style...)");
826 diff_type = NEW_CONTEXT_DIFF;
828 /* if there were omitted context lines, fill them in now */
830 p_bfake = filldst; /* remember where not to free() */
831 p_efake = filldst + fillcnt - 1;
832 while (fillcnt-- > 0) {
833 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
836 fatal("replacement text or line numbers mangled in hunk at line %ld\n",
838 p_line[filldst] = p_line[fillsrc];
839 p_char[filldst] = p_char[fillsrc];
840 p_len[filldst] = p_len[fillsrc];
844 while (fillsrc <= p_end && fillsrc != repl_beginning &&
845 p_char[fillsrc] != ' ')
849 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
850 fillsrc, filldst, repl_beginning, p_end + 1);
852 if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
854 if (filldst != p_end + 1 && filldst != repl_beginning)
857 if (p_line[p_end] != NULL) {
858 if (remove_special_line()) {
860 (p_line[p_end])[p_len[p_end]] = 0;
863 } else if (diff_type == UNI_DIFF) {
864 LINENUM fillold; /* index of old lines */
865 LINENUM fillnew; /* index of new lines */
868 line_beginning = ftello(pfp); /* file pos of the current line */
871 if (len == 0 || strnNE(buf, "@@ -", 4)) {
872 next_intuit_at(line_beginning, p_input_line);
878 p_first = strtolinenum(s, &s);
880 p_ptrn_lines = strtolinenum(s + 1, &s);
885 if (*s != '+' || !*++s)
887 p_newfirst = strtolinenum(s, &s);
889 p_repl_lines = strtolinenum(s + 1, &s);
896 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
897 p_newfirst > LINENUM_MAX - p_repl_lines ||
898 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
901 p_first++; /* do append rather than insert */
902 p_max = p_ptrn_lines + p_repl_lines + 1;
903 while (p_max >= hunkmax)
906 fillnew = fillold + p_ptrn_lines;
907 p_end = fillnew + p_repl_lines;
908 snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
909 p_first + p_ptrn_lines - 1);
910 p_line[0] = savestr(buf);
916 snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
917 p_newfirst + p_repl_lines - 1);
918 p_line[fillnew] = savestr(buf);
923 p_char[fillnew++] = '=';
926 p_hunk_beg = p_input_line + 1;
927 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
928 line_beginning = ftello(pfp);
932 if (p_max - fillnew < 3) {
933 /* assume blank lines got chopped */
934 strlcpy(buf, " \n", buf_size);
936 fatal("unexpected end of file in patch\n");
939 if (*buf == '\t' || *buf == '\n') {
940 ch = ' '; /* assume the space got eaten */
944 s = savestr(buf + 1);
947 while (--fillnew > p_ptrn_lines)
948 free(p_line[fillnew]);
954 if (fillold > p_ptrn_lines) {
959 p_char[fillold] = ch;
961 p_len[fillold++] = strlen(s);
962 if (fillold > p_ptrn_lines) {
963 if (remove_special_line()) {
964 p_len[fillold - 1] -= 1;
965 s[p_len[fillold - 1]] = 0;
973 if (fillold > p_ptrn_lines) {
975 while (--fillnew > p_ptrn_lines)
976 free(p_line[fillnew]);
981 p_char[fillold] = ch;
983 p_len[fillold++] = strlen(s);
986 while (--fillnew > p_ptrn_lines)
987 free(p_line[fillnew]);
991 if (fillold > p_ptrn_lines) {
992 if (remove_special_line()) {
993 p_len[fillold - 1] -= 1;
994 s[p_len[fillold - 1]] = 0;
999 if (fillnew > p_end) {
1001 while (--fillnew > p_ptrn_lines)
1002 free(p_line[fillnew]);
1003 p_end = fillold - 1;
1006 p_char[fillnew] = ch;
1007 p_line[fillnew] = s;
1008 p_len[fillnew++] = strlen(s);
1009 if (fillold > p_ptrn_lines) {
1010 if (remove_special_line()) {
1011 p_len[fillnew - 1] -= 1;
1012 s[p_len[fillnew - 1]] = 0;
1020 if (ch != ' ' && context > 0) {
1021 if (context < p_context)
1022 p_context = context;
1026 } else { /* normal diff--fake it up */
1031 line_beginning = ftello(pfp);
1035 if (len == 0 || !isdigit((unsigned char)*buf)) {
1036 next_intuit_at(line_beginning, p_input_line);
1039 p_first = strtolinenum(buf, &s);
1041 p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1042 if (p_ptrn_lines < 0)
1045 p_ptrn_lines = (*s != 'a');
1047 if (hunk_type == 'a')
1048 p_first++; /* do append rather than insert */
1049 min = strtolinenum(s + 1, &s);
1051 max = strtolinenum(s + 1, &s);
1054 if (min < 0 || min > max || max - min == LINENUM_MAX)
1056 if (hunk_type == 'd')
1059 p_repl_lines = max - min + 1;
1060 if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1061 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1063 p_end = p_ptrn_lines + p_repl_lines + 1;
1064 if (p_end > MAXHUNKSIZE)
1065 fatal("hunk too large (%ld lines) at line %ld: %s",
1066 p_end, p_input_line, buf);
1067 while (p_end >= hunkmax)
1069 snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1070 p_first + p_ptrn_lines - 1);
1071 p_line[0] = savestr(buf);
1077 for (i = 1; i <= p_ptrn_lines; i++) {
1081 fatal("unexpected end of file in patch at line %ld\n",
1084 fatal("< expected at line %ld of patch\n",
1086 p_line[i] = savestr(buf + 2);
1091 p_len[i] = strlen(p_line[i]);
1095 if (remove_special_line()) {
1097 (p_line[i - 1])[p_len[i - 1]] = 0;
1099 if (hunk_type == 'c') {
1103 fatal("unexpected end of file in patch at line %ld\n",
1106 fatal("--- expected at line %ld of patch\n",
1109 snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1110 p_line[i] = savestr(buf);
1116 for (i++; i <= p_end; i++) {
1120 fatal("unexpected end of file in patch at line %ld\n",
1123 fatal("> expected at line %ld of patch\n",
1125 p_line[i] = savestr(buf + 2);
1130 p_len[i] = strlen(p_line[i]);
1134 if (remove_special_line()) {
1136 (p_line[i - 1])[p_len[i - 1]] = 0;
1139 if (reverse) /* backwards patch? */
1141 say("Not enough memory to swap next hunk!\n");
1147 for (i = 0; i <= p_end; i++) {
1148 if (i == p_ptrn_lines)
1152 fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1153 special, p_line[i]);
1158 if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1159 p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
1164 * Input a line from the patch file.
1165 * Worry about indentation if do_indent is true.
1166 * The line is read directly into the buf global variable which
1167 * is resized if necessary in order to hold the complete line.
1168 * Returns the number of characters read including the terminating
1172 pgets(bool do_indent)
1176 int indent = 0, skipped = 0;
1178 line = fgetln(pfp, &len);
1180 if (len + 1 > buf_size) {
1181 while (len + 1 > buf_size)
1184 buf = malloc(buf_size);
1186 fatal("out of memory\n");
1188 if (do_indent == 1 && p_indent) {
1190 indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1191 line++, skipped++) {
1193 indent += 8 - (indent %7);
1198 memcpy(buf, line, len - skipped);
1199 buf[len - skipped] = '\0';
1206 * Reverse the old and new portions of the current hunk.
1211 char **tp_line; /* the text of the hunk */
1212 unsigned short *tp_len;/* length of each line */
1213 char *tp_char; /* +, -, and ! */
1216 bool blankline = false;
1220 p_first = p_newfirst;
1223 /* make a scratch copy */
1228 p_line = NULL; /* force set_hunkmax to allocate again */
1232 if (p_line == NULL || p_len == NULL || p_char == NULL) {
1240 return false; /* not enough memory to swap hunk! */
1242 /* now turn the new into the old */
1244 i = p_ptrn_lines + 1;
1245 if (tp_char[i] == '\n') { /* account for possible blank line */
1249 if (p_efake >= 0) { /* fix non-freeable ptr range */
1257 for (n = 0; i <= p_end; i++, n++) {
1258 p_line[n] = tp_line[i];
1259 p_char[n] = tp_char[i];
1260 if (p_char[n] == '+')
1262 p_len[n] = tp_len[i];
1265 i = p_ptrn_lines + 1;
1266 p_line[n] = tp_line[i];
1267 p_char[n] = tp_char[i];
1268 p_len[n] = tp_len[i];
1271 if (p_char[0] != '=')
1272 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1273 p_input_line, p_char[0]);
1275 for (s = p_line[0]; *s; s++)
1279 /* now turn the old into the new */
1281 if (p_char[0] != '*')
1282 fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1283 p_input_line, p_char[0]);
1285 for (s = tp_line[0]; *s; s++)
1288 for (i = 0; n <= p_end; i++, n++) {
1289 p_line[n] = tp_line[i];
1290 p_char[n] = tp_char[i];
1291 if (p_char[n] == '-')
1293 p_len[n] = tp_len[i];
1296 if (i != p_ptrn_lines + 1)
1297 fatal("Malformed patch at line %ld: expected %ld lines, "
1299 p_input_line, p_ptrn_lines + 1, i);
1302 p_ptrn_lines = p_repl_lines;
1313 * Return the specified line position in the old file of the old context.
1322 * Return the number of lines of old context.
1325 pch_ptrn_lines(void)
1327 return p_ptrn_lines;
1331 * Return the probable line position in the new file of the first line.
1340 * Return the number of lines in the replacement text including context.
1343 pch_repl_lines(void)
1345 return p_repl_lines;
1349 * Return the number of lines in the whole hunk.
1358 * Return the number of context lines before the first changed line.
1367 * Return the length of a particular patch line.
1370 pch_line_len(LINENUM line)
1376 * Return the control character (+, -, *, !, etc) for a patch line.
1379 pch_char(LINENUM line)
1381 return p_char[line];
1385 * Return a pointer to a particular patch line.
1388 pfetch(LINENUM line)
1390 return p_line[line];
1394 * Return where in the patch file this hunk began, for error messages.
1403 * Apply an ed script by feeding ed itself.
1409 off_t beginning_of_this_line;
1410 FILE *pipefp = NULL;
1413 if (!skip_rest_of_patch) {
1414 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1416 fatal("can't create temp file %s", TMPOUTNAME);
1418 snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1419 verbose ? " " : " -s ", TMPOUTNAME);
1420 pipefp = popen(buf, "w");
1423 beginning_of_this_line = ftello(pfp);
1424 if (pgets(true) == 0) {
1425 next_intuit_at(beginning_of_this_line, p_input_line);
1429 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1431 /* POSIX defines allowed commands as {a,c,d,i,s} */
1432 if (isdigit((unsigned char)*buf) &&
1433 (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1439 t = strchr(buf, '\0') - 1;
1440 while (--t >= buf && *t == '\\')
1441 continuation = !continuation;
1442 if (!continuation ||
1448 } else if (*t != 'd') {
1449 while (pgets(true)) {
1453 if (strEQ(buf, ".\n"))
1458 next_intuit_at(beginning_of_this_line, p_input_line);
1464 fprintf(pipefp, "w\n");
1465 fprintf(pipefp, "q\n");
1470 if (move_file(TMPOUTNAME, outname) < 0) {
1472 chmod(TMPOUTNAME, filemode);
1474 chmod(outname, filemode);
1480 * Choose the name of the file to be patched based on POSIX rules.
1481 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1482 * if the user specified --posix or set POSIXLY_CORRECT.
1485 posix_name(const struct file_name *names, bool assume_exists)
1491 * POSIX states that the filename will be chosen from one
1492 * of the old, new and index names (in that order) if
1493 * the file exists relative to CWD after -p stripping.
1495 for (i = 0; i < MAX_FILE; i++) {
1496 if (names[i].path != NULL && names[i].exists) {
1497 path = names[i].path;
1501 if (path == NULL && !assume_exists) {
1503 * No files found, look for something we can checkout from
1504 * RCS/SCCS dirs. Same order as above.
1506 for (i = 0; i < MAX_FILE; i++) {
1507 if (names[i].path != NULL &&
1508 (path = checked_in(names[i].path)) != NULL)
1512 * Still no match? Check to see if the diff could be creating
1515 if (path == NULL && ok_to_create_file &&
1516 names[NEW_FILE].path != NULL)
1517 path = names[NEW_FILE].path;
1520 return path ? xstrdup(path) : NULL;
1524 compare_names(const struct file_name *names, bool assume_exists, int phase)
1526 size_t min_components, min_baselen, min_len, tmp;
1532 * The "best" name is the one with the fewest number of path
1533 * components, the shortest basename length, and the shortest
1534 * overall length (in that order). We only use the Index: file
1535 * if neither of the old or new files could be intuited from
1538 min_components = min_baselen = min_len = SIZE_MAX;
1539 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1540 path = names[i].path;
1542 (phase == 1 && !names[i].exists && !assume_exists) ||
1543 (phase == 2 && checked_in(path) == NULL))
1545 if ((tmp = num_components(path)) > min_components)
1547 if (tmp < min_components) {
1548 min_components = tmp;
1551 if ((tmp = strlen(basename(path))) > min_baselen)
1553 if (tmp < min_baselen) {
1557 if ((tmp = strlen(path)) > min_len)
1566 * Choose the name of the file to be patched based the "best" one
1570 best_name(const struct file_name *names, bool assume_exists)
1574 best = compare_names(names, assume_exists, 1);
1576 best = compare_names(names, assume_exists, 2);
1578 * Still no match? Check to see if the diff could be creating
1581 if (best == NULL && ok_to_create_file &&
1582 names[NEW_FILE].path != NULL)
1583 best = names[NEW_FILE].path;
1586 return best ? xstrdup(best) : NULL;
1590 num_components(const char *path)
1595 for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1597 cp++; /* skip consecutive slashes */
1603 * Convert number at NPTR into LINENUM and save address of first
1604 * character that is not a digit in ENDPTR. If conversion is not
1605 * possible, call fatal.
1608 strtolinenum(char *nptr, char **endptr)
1615 for (p = nptr; isdigit((unsigned char)*p); p++)
1624 rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1626 fatal("invalid line number at line %ld: `%s' is %s\n",
1627 p_input_line, nptr, errstr);