2 * Copyright 1986, Larry Wall
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following condition is met:
6 * 1. Redistributions of source code must retain the above copyright notice,
7 * this condition and the following disclaimer.
9 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
10 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
11 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
13 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
15 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
16 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
17 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
21 * patch - a program to apply diffs to original files
23 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
26 * $OpenBSD: pch.c,v 1.43 2014/11/18 17:03:35 tobias Exp $
30 #include <sys/types.h>
45 #include "pathnames.h"
47 /* Patch (diff listing) abstract type. */
49 static off_t p_filesize; /* size of the patch file */
50 static LINENUM p_first; /* 1st line number */
51 static LINENUM p_newfirst; /* 1st line number of replacement */
52 static LINENUM p_ptrn_lines; /* # lines in pattern */
53 static LINENUM p_repl_lines; /* # lines in replacement text */
54 static LINENUM p_end = -1; /* last line in hunk */
55 static LINENUM p_max; /* max allowed value of p_end */
56 static LINENUM p_context = 3; /* # of context lines */
57 static LINENUM p_input_line = 0; /* current line # from patch file */
58 static char **p_line = NULL;/* the text of the hunk */
59 static unsigned short *p_len = NULL; /* length of each line */
60 static char *p_char = NULL; /* +, -, and ! */
61 static int hunkmax = INITHUNKMAX; /* size of above arrays to begin with */
62 static int p_indent; /* indent to patch */
63 static off_t p_base; /* where to intuit this time */
64 static LINENUM p_bline; /* line # of p_base */
65 static off_t p_start; /* where intuit found a patch */
66 static LINENUM p_sline; /* and the line number for it */
67 static LINENUM p_hunk_beg; /* line number of current hunk */
68 static LINENUM p_efake = -1; /* end of faked up lines--don't free */
69 static LINENUM p_bfake = -1; /* beg of faked up lines */
70 static FILE *pfp = NULL; /* patch file pointer */
71 static char *bestguess = NULL; /* guess at correct filename */
75 static void grow_hunkmax(void);
76 static int intuit_diff_type(void);
77 static void next_intuit_at(off_t, LINENUM);
78 static void skip_to(off_t, LINENUM);
79 static size_t pgets(bool _do_indent);
80 static char *best_name(const struct file_name *, bool);
81 static char *posix_name(const struct file_name *, bool);
82 static size_t num_components(const char *);
83 static LINENUM strtolinenum(char *, char **);
86 * Prepare to look for the next patch in the patch file.
95 p_end = (LINENUM) - 1;
101 * Open the patch file at the beginning of time.
104 open_patch_file(const char *filename)
106 struct stat filestat;
109 if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
110 pfp = fopen(TMPPATNAME, "w");
112 pfatal("can't create %s", TMPPATNAME);
113 while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
114 nw = fwrite(buf, 1, nr, pfp);
116 pfatal("write error to %s", TMPPATNAME);
118 if (ferror(pfp) || fclose(pfp))
119 pfatal("can't write %s", TMPPATNAME);
120 filename = TMPPATNAME;
122 pfp = fopen(filename, "r");
124 pfatal("patch file %s not found", filename);
125 if (fstat(fileno(pfp), &filestat))
126 pfatal("can't stat %s", filename);
127 p_filesize = filestat.st_size;
128 next_intuit_at(0, 1L); /* start at the beginning */
133 * Make sure our dynamically realloced tables are malloced to begin with.
139 p_line = malloc(hunkmax * sizeof(char *));
141 p_len = malloc(hunkmax * sizeof(unsigned short));
143 p_char = malloc(hunkmax * sizeof(char));
147 * Enlarge the arrays containing the current hunk of patch.
152 int new_hunkmax = hunkmax * 2;
154 if (p_line == NULL || p_len == NULL || p_char == NULL)
155 fatal("Internal memory allocation error\n");
157 p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
158 p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
159 p_char = reallocf(p_char, new_hunkmax * sizeof(char));
161 if (p_line != NULL && p_len != NULL && p_char != NULL) {
162 hunkmax = new_hunkmax;
167 fatal("out of memory\n");
168 out_of_mem = true; /* whatever is null will be allocated again */
169 /* from within plan_a(), of all places */
172 /* True if the remainder of the patch file contains a diff of some sort. */
175 there_is_another_patch(void)
179 if (p_base != 0 && p_base >= p_filesize) {
186 nonempty_patchf_seen = true;
189 diff_type = intuit_diff_type();
193 say(" Ignoring the trailing garbage.\ndone\n");
195 say(" I can't seem to find a patch in there anywhere.\n");
199 say(" %sooks like %s to me...\n",
200 (p_base == 0 ? "L" : "The next patch l"),
201 diff_type == UNI_DIFF ? "a unified diff" :
202 diff_type == CONTEXT_DIFF ? "a context diff" :
203 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
204 diff_type == NORMAL_DIFF ? "a normal diff" :
206 if (p_indent && verbose)
207 say("(Patch is indented %d space%s.)\n", p_indent,
208 p_indent == 1 ? "" : "s");
209 skip_to(p_start, p_sline);
210 while (filearg[0] == NULL) {
211 if (force || batch) {
212 say("No file to patch. Skipping...\n");
213 filearg[0] = xstrdup(bestguess);
214 skip_rest_of_patch = true;
217 ask("File to patch: ");
220 bestguess = xstrdup(buf);
221 filearg[0] = fetchname(buf, &exists, 0);
224 * fetchname can now return buf = NULL, exists = true, to
225 * indicate to the caller that /dev/null was specified. Retain
226 * previous behavior for now until this can be better evaluted.
228 if (filearg[0] == NULL || !exists) {
229 int def_skip = *bestguess == '\0';
230 ask("No file found--skip this patch? [%c] ",
231 def_skip ? 'y' : 'n');
232 if (*buf == 'n' || (!def_skip && *buf != 'y'))
235 say("Skipping patch...\n");
237 filearg[0] = fetchname(bestguess, &exists, 0);
238 skip_rest_of_patch = true;
246 p4_fetchname(struct file_name *name, char *str)
250 /* Skip leading whitespace. */
251 while (isspace((unsigned char)*str))
254 /* Remove the file revision number. */
255 for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
261 name->path = fetchname(str, &name->exists, strippath);
264 /* Determine what kind of diff is in the remaining part of the patch file. */
267 intuit_diff_type(void)
269 off_t this_line = 0, previous_line;
270 off_t first_command_line = -1;
271 LINENUM fcl_line = -1;
272 bool last_line_was_command = false, this_is_a_command = false;
273 bool stars_last_line = false, stars_this_line = false;
276 struct file_name names[MAX_FILE];
277 int piece_of_git = 0;
279 memset(names, 0, sizeof(names));
280 ok_to_create_file = false;
281 fseeko(pfp, p_base, SEEK_SET);
282 p_input_line = p_bline - 1;
284 previous_line = this_line;
285 last_line_was_command = this_is_a_command;
286 stars_last_line = stars_this_line;
287 this_line = ftello(pfp);
290 if (pgets(false) == 0) {
291 if (first_command_line >= 0) {
292 /* nothing but deletes!? */
293 p_start = first_command_line;
299 p_sline = p_input_line;
304 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
306 indent += 8 - (indent % 8);
310 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
312 this_is_a_command = (isdigit((unsigned char)*s) &&
313 (*t == 'd' || *t == 'c' || *t == 'a'));
314 if (first_command_line < 0 && this_is_a_command) {
315 first_command_line = this_line;
316 fcl_line = p_input_line;
317 p_indent = indent; /* assume this for now */
319 if (!stars_last_line && strnEQ(s, "*** ", 4))
320 names[OLD_FILE].path = fetchname(s + 4,
321 &names[OLD_FILE].exists, strippath);
322 else if (strnEQ(s, "--- ", 4)) {
324 if (piece_of_git && strippath == 957 &&
325 strnEQ(s, "--- a/", 6))
327 names[NEW_FILE].path = fetchname(s + off,
328 &names[NEW_FILE].exists, strippath);
329 } else if (strnEQ(s, "+++ ", 4)) {
330 /* pretend it is the old name */
332 if (piece_of_git && strippath == 957 &&
333 strnEQ(s, "+++ b/", 6))
335 names[OLD_FILE].path = fetchname(s + off,
336 &names[OLD_FILE].exists, strippath);
337 } else if (strnEQ(s, "Index:", 6))
338 names[INDEX_FILE].path = fetchname(s + 6,
339 &names[INDEX_FILE].exists, strippath);
340 else if (strnEQ(s, "Prereq:", 7)) {
341 for (t = s + 7; isspace((unsigned char)*t); t++)
343 revision = xstrdup(t);
345 *t && !isspace((unsigned char)*t); t++)
348 if (*revision == '\0') {
352 } else if (strnEQ(s, "diff --git a/", 13)) {
353 /* Git-style diffs. */
355 } else if (strnEQ(s, "==== ", 5)) {
356 /* Perforce-style diffs. */
357 if ((t = strstr(s + 5, " - ")) != NULL)
358 p4_fetchname(&names[NEW_FILE], t + 3);
359 p4_fetchname(&names[OLD_FILE], s + 5);
361 if ((!diff_type || diff_type == ED_DIFF) &&
362 first_command_line >= 0 &&
365 p_start = first_command_line;
370 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
371 if (strnEQ(s + 4, "0,0", 3))
372 ok_to_create_file = true;
375 p_sline = p_input_line;
379 stars_this_line = strnEQ(s, "********", 8);
380 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
381 strnEQ(s, "*** ", 4)) {
382 if (strtolinenum(s + 4, &s) == 0)
383 ok_to_create_file = true;
385 * If this is a new context diff the character just
386 * at the end of the line is a '*'.
388 while (*s && *s != '\n')
391 p_start = previous_line;
392 p_sline = p_input_line - 1;
393 retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
396 if ((!diff_type || diff_type == NORMAL_DIFF) &&
397 last_line_was_command &&
398 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
399 p_start = previous_line;
400 p_sline = p_input_line - 1;
402 retval = NORMAL_DIFF;
407 if (retval == UNI_DIFF) {
408 /* unswap old and new */
409 struct file_name tmp = names[OLD_FILE];
410 names[OLD_FILE] = names[NEW_FILE];
411 names[NEW_FILE] = tmp;
420 * If we've successfully determined a diff type, stored in
421 * retval, path == NULL means _PATH_DEVNULL if exists is set.
422 * Explicitly specify it here to make it easier to detect later
423 * on that we're actually creating a file and not that we've
424 * just goofed something up.
426 if (names[OLD_FILE].path != NULL)
427 source_file = xstrdup(names[OLD_FILE].path);
428 else if (names[OLD_FILE].exists)
429 source_file = xstrdup(_PATH_DEVNULL);
431 if (filearg[0] == NULL) {
433 filearg[0] = posix_name(names, ok_to_create_file);
435 /* Ignore the Index: name for context diffs, like GNU */
436 if (names[OLD_FILE].path != NULL ||
437 names[NEW_FILE].path != NULL) {
438 free(names[INDEX_FILE].path);
439 names[INDEX_FILE].path = NULL;
441 filearg[0] = best_name(names, ok_to_create_file);
447 if (filearg[0] != NULL)
448 bestguess = xstrdup(filearg[0]);
449 else if (!ok_to_create_file) {
451 * We don't want to create a new file but we need a
452 * filename to set bestguess. Avoid setting filearg[0]
453 * so the file is not created automatically.
456 bestguess = posix_name(names, true);
458 bestguess = best_name(names, true);
460 free(names[OLD_FILE].path);
461 free(names[NEW_FILE].path);
462 free(names[INDEX_FILE].path);
467 * Remember where this patch ends so we know where to start up again.
470 next_intuit_at(off_t file_pos, LINENUM file_line)
477 * Basically a verbose fseeko() to the actual diff listing.
480 skip_to(off_t file_pos, LINENUM file_line)
484 if (p_base > file_pos)
485 fatal("Internal error: seek %lld>%lld\n",
486 (long long)p_base, (long long)file_pos);
487 if (verbose && p_base < file_pos) {
488 fseeko(pfp, p_base, SEEK_SET);
489 say("The text leading up to this was:\n--------------------------\n");
490 while (ftello(pfp) < file_pos) {
493 fatal("Unexpected end of file\n");
496 say("--------------------------\n");
498 fseeko(pfp, file_pos, SEEK_SET);
499 p_input_line = file_line - 1;
502 /* Make this a function for better debugging. */
506 fatal("malformed patch at line %ld: %s", p_input_line, buf);
507 /* about as informative as "Syntax error" in C */
511 * True if the line has been discarded (i.e. it is a line saying
512 * "\ No newline at end of file".)
515 remove_special_line(void)
523 } while (c != EOF && c != '\n');
528 fseeko(pfp, -1, SEEK_CUR);
534 * True if there is more of the current diff listing to process.
539 off_t line_beginning; /* file pos of the current line */
540 LINENUM repl_beginning; /* index of --- line */
541 LINENUM fillcnt; /* #lines of missing ptrn or repl */
542 LINENUM fillsrc; /* index of first line to copy */
543 LINENUM filldst; /* index of first missing line */
544 bool ptrn_spaces_eaten; /* ptrn was slightly malformed */
545 bool repl_could_be_missing; /* no + or ! lines in this hunk */
546 bool repl_missing; /* we are now backtracking */
547 off_t repl_backtrack_position; /* file pos of first repl line */
548 LINENUM repl_patch_line; /* input line number for same */
549 LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
555 if (p_end == p_efake)
556 p_end = p_bfake; /* don't free twice */
563 p_max = hunkmax; /* gets reduced when --- found */
564 if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
565 line_beginning = ftello(pfp);
570 ptrn_spaces_eaten = false;
571 repl_could_be_missing = true;
572 repl_missing = false;
573 repl_backtrack_position = 0;
579 if (len == 0 || strnNE(buf, "********", 8)) {
580 next_intuit_at(line_beginning, p_input_line);
584 p_hunk_beg = p_input_line + 1;
585 while (p_end < p_max) {
586 line_beginning = ftello(pfp);
590 if (p_max - p_end < 4) {
591 /* assume blank lines got chopped */
592 strlcpy(buf, " \n", buf_size);
594 if (repl_beginning && repl_could_be_missing) {
598 fatal("unexpected end of file in patch\n");
602 if (p_end >= hunkmax)
603 fatal("Internal error: hunk larger than hunk "
605 p_char[p_end] = *buf;
606 p_line[p_end] = NULL;
609 if (strnEQ(buf, "********", 8)) {
610 if (repl_beginning && repl_could_be_missing) {
614 fatal("unexpected end of hunk "
619 if (repl_beginning && repl_could_be_missing) {
623 fatal("unexpected *** at line %ld: %s",
627 p_line[p_end] = savestr(buf);
633 *s && !isdigit((unsigned char)*s); s++)
637 if (strnEQ(s, "0,0", 3))
638 memmove(s, s + 2, strlen(s + 2) + 1);
639 p_first = strtolinenum(s, &s);
642 *s && !isdigit((unsigned char)*s); s++)
646 p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
647 if (p_ptrn_lines < 0)
655 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
656 p_ptrn_lines >= LINENUM_MAX - 6)
659 /* we need this much at least */
660 p_max = p_ptrn_lines + 6;
661 while (p_max >= hunkmax)
667 if (repl_beginning ||
668 (p_end != p_ptrn_lines + 1 +
669 (p_char[p_end - 1] == '\n'))) {
672 * `old' lines were omitted;
673 * set up to fill them in
674 * from 'new' context lines.
676 p_end = p_ptrn_lines + 1;
679 fillcnt = p_ptrn_lines;
681 if (repl_beginning) {
682 if (repl_could_be_missing) {
686 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
687 p_input_line, p_hunk_beg + repl_beginning);
689 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
690 (p_end <= p_ptrn_lines
693 p_input_line, p_hunk_beg);
697 repl_beginning = p_end;
698 repl_backtrack_position = ftello(pfp);
699 repl_patch_line = p_input_line;
700 p_line[p_end] = savestr(buf);
706 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
710 p_newfirst = strtolinenum(s, &s);
712 for (; *s && !isdigit((unsigned char)*s); s++)
716 p_repl_lines = strtolinenum(s, &s) -
718 if (p_repl_lines < 0)
720 } else if (p_newfirst)
726 if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
727 p_repl_lines >= LINENUM_MAX - p_end)
729 p_max = p_repl_lines + p_end;
730 if (p_max > MAXHUNKSIZE)
731 fatal("hunk too large (%ld lines) at line %ld: %s",
732 p_max, p_input_line, buf);
733 while (p_max >= hunkmax)
735 if (p_repl_lines != ptrn_copiable &&
736 (p_context != 0 || p_repl_lines != 1))
737 repl_could_be_missing = false;
743 repl_could_be_missing = false;
745 if (buf[1] == '\n' && canonicalize)
746 strlcpy(buf + 1, " \n", buf_size - 1);
747 if (!isspace((unsigned char)buf[1]) &&
748 buf[1] != '>' && buf[1] != '<' &&
749 repl_beginning && repl_could_be_missing) {
754 if (context < p_context)
758 p_line[p_end] = savestr(buf + 2);
763 if (p_end == p_ptrn_lines) {
764 if (remove_special_line()) {
767 l = strlen(p_line[p_end]) - 1;
768 (p_line[p_end])[l] = 0;
773 case '\n': /* assume the 2 spaces got eaten */
774 if (repl_beginning && repl_could_be_missing &&
775 (!ptrn_spaces_eaten ||
776 diff_type == NEW_CONTEXT_DIFF)) {
780 p_line[p_end] = savestr(buf);
785 if (p_end != p_ptrn_lines + 1) {
786 ptrn_spaces_eaten |= (repl_beginning != 0);
794 if (!isspace((unsigned char)buf[1]) &&
795 repl_beginning && repl_could_be_missing) {
802 p_line[p_end] = savestr(buf + 2);
809 if (repl_beginning && repl_could_be_missing) {
815 /* set up p_len for strncmp() so we don't have to */
816 /* assume null termination */
818 p_len[p_end] = strlen(p_line[p_end]);
824 if (p_end >= 0 && !repl_beginning)
825 fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
829 /* reset state back to just after --- */
830 p_input_line = repl_patch_line;
831 for (p_end--; p_end > repl_beginning; p_end--)
833 fseeko(pfp, repl_backtrack_position, SEEK_SET);
835 /* redundant 'new' context lines were omitted - set */
836 /* up to fill them in from the old file context */
837 if (!p_context && p_repl_lines == 1) {
842 filldst = repl_beginning + 1;
843 fillcnt = p_repl_lines;
845 } else if (!p_context && fillcnt == 1) {
846 /* the first hunk was a null hunk with no context */
847 /* and we were expecting one line -- fix it up. */
848 while (filldst < p_end) {
849 p_line[filldst] = p_line[filldst + 1];
850 p_char[filldst] = p_char[filldst + 1];
851 p_len[filldst] = p_len[filldst + 1];
855 repl_beginning--; /* this doesn't need to be fixed */
858 p_first++; /* do append rather than insert */
862 if (diff_type == CONTEXT_DIFF &&
863 (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
866 "(Fascinating--this is really a new-style context diff but without",
867 "the telltale extra asterisks on the *** line that usually indicate",
868 "the new style...)");
869 diff_type = NEW_CONTEXT_DIFF;
871 /* if there were omitted context lines, fill them in now */
873 p_bfake = filldst; /* remember where not to free() */
874 p_efake = filldst + fillcnt - 1;
875 while (fillcnt-- > 0) {
876 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
879 fatal("replacement text or line numbers mangled in hunk at line %ld\n",
881 p_line[filldst] = p_line[fillsrc];
882 p_char[filldst] = p_char[fillsrc];
883 p_len[filldst] = p_len[fillsrc];
887 while (fillsrc <= p_end && fillsrc != repl_beginning &&
888 p_char[fillsrc] != ' ')
892 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
893 fillsrc, filldst, repl_beginning, p_end + 1);
895 if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
897 if (filldst != p_end + 1 && filldst != repl_beginning)
900 if (p_line[p_end] != NULL) {
901 if (remove_special_line()) {
903 (p_line[p_end])[p_len[p_end]] = 0;
906 } else if (diff_type == UNI_DIFF) {
907 LINENUM fillold; /* index of old lines */
908 LINENUM fillnew; /* index of new lines */
911 line_beginning = ftello(pfp); /* file pos of the current line */
914 if (len == 0 || strnNE(buf, "@@ -", 4)) {
915 next_intuit_at(line_beginning, p_input_line);
921 p_first = strtolinenum(s, &s);
923 p_ptrn_lines = strtolinenum(s + 1, &s);
928 if (*s != '+' || !*++s)
930 p_newfirst = strtolinenum(s, &s);
932 p_repl_lines = strtolinenum(s + 1, &s);
939 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
940 p_newfirst > LINENUM_MAX - p_repl_lines ||
941 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
944 p_first++; /* do append rather than insert */
945 p_max = p_ptrn_lines + p_repl_lines + 1;
946 while (p_max >= hunkmax)
949 fillnew = fillold + p_ptrn_lines;
950 p_end = fillnew + p_repl_lines;
951 snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
952 p_first + p_ptrn_lines - 1);
953 p_line[0] = savestr(buf);
959 snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
960 p_newfirst + p_repl_lines - 1);
961 p_line[fillnew] = savestr(buf);
966 p_char[fillnew++] = '=';
969 p_hunk_beg = p_input_line + 1;
970 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
971 line_beginning = ftello(pfp);
975 if (p_max - fillnew < 3) {
976 /* assume blank lines got chopped */
977 strlcpy(buf, " \n", buf_size);
979 fatal("unexpected end of file in patch\n");
982 if (*buf == '\t' || *buf == '\n') {
983 ch = ' '; /* assume the space got eaten */
987 s = savestr(buf + 1);
990 while (--fillnew > p_ptrn_lines)
991 free(p_line[fillnew]);
997 if (fillold > p_ptrn_lines) {
1002 p_char[fillold] = ch;
1003 p_line[fillold] = s;
1004 p_len[fillold++] = strlen(s);
1005 if (fillold > p_ptrn_lines) {
1006 if (remove_special_line()) {
1007 p_len[fillold - 1] -= 1;
1008 s[p_len[fillold - 1]] = 0;
1016 if (fillold > p_ptrn_lines) {
1018 while (--fillnew > p_ptrn_lines)
1019 free(p_line[fillnew]);
1020 p_end = fillold - 1;
1024 p_char[fillold] = ch;
1025 p_line[fillold] = s;
1026 p_len[fillold++] = strlen(s);
1029 while (--fillnew > p_ptrn_lines)
1030 free(p_line[fillnew]);
1031 p_end = fillold - 1;
1034 if (fillold > p_ptrn_lines) {
1035 if (remove_special_line()) {
1036 p_len[fillold - 1] -= 1;
1037 s[p_len[fillold - 1]] = 0;
1042 if (fillnew > p_end) {
1044 while (--fillnew > p_ptrn_lines)
1045 free(p_line[fillnew]);
1046 p_end = fillold - 1;
1049 p_char[fillnew] = ch;
1050 p_line[fillnew] = s;
1051 p_len[fillnew++] = strlen(s);
1052 if (fillold > p_ptrn_lines) {
1053 if (remove_special_line()) {
1054 p_len[fillnew - 1] -= 1;
1055 s[p_len[fillnew - 1]] = 0;
1063 if (ch != ' ' && context > 0) {
1064 if (context < p_context)
1065 p_context = context;
1069 } else { /* normal diff--fake it up */
1074 line_beginning = ftello(pfp);
1078 if (len == 0 || !isdigit((unsigned char)*buf)) {
1079 next_intuit_at(line_beginning, p_input_line);
1082 p_first = strtolinenum(buf, &s);
1084 p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1085 if (p_ptrn_lines < 0)
1088 p_ptrn_lines = (*s != 'a');
1090 if (hunk_type == 'a')
1091 p_first++; /* do append rather than insert */
1092 min = strtolinenum(s + 1, &s);
1094 max = strtolinenum(s + 1, &s);
1097 if (min < 0 || min > max || max - min == LINENUM_MAX)
1099 if (hunk_type == 'd')
1102 p_repl_lines = max - min + 1;
1103 if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1104 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1106 p_end = p_ptrn_lines + p_repl_lines + 1;
1107 if (p_end > MAXHUNKSIZE)
1108 fatal("hunk too large (%ld lines) at line %ld: %s",
1109 p_end, p_input_line, buf);
1110 while (p_end >= hunkmax)
1112 snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1113 p_first + p_ptrn_lines - 1);
1114 p_line[0] = savestr(buf);
1120 for (i = 1; i <= p_ptrn_lines; i++) {
1124 fatal("unexpected end of file in patch at line %ld\n",
1127 fatal("< expected at line %ld of patch\n",
1129 p_line[i] = savestr(buf + 2);
1134 p_len[i] = strlen(p_line[i]);
1138 if (remove_special_line()) {
1140 (p_line[i - 1])[p_len[i - 1]] = 0;
1142 if (hunk_type == 'c') {
1146 fatal("unexpected end of file in patch at line %ld\n",
1149 fatal("--- expected at line %ld of patch\n",
1152 snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1153 p_line[i] = savestr(buf);
1159 for (i++; i <= p_end; i++) {
1163 fatal("unexpected end of file in patch at line %ld\n",
1166 fatal("> expected at line %ld of patch\n",
1168 /* Don't overrun if we don't have enough line */
1170 p_line[i] = savestr(buf + 2);
1172 p_line[i] = savestr("");
1178 p_len[i] = strlen(p_line[i]);
1182 if (remove_special_line()) {
1184 (p_line[i - 1])[p_len[i - 1]] = 0;
1187 if (reverse) /* backwards patch? */
1189 say("Not enough memory to swap next hunk!\n");
1195 for (i = 0; i <= p_end; i++) {
1196 if (i == p_ptrn_lines)
1200 fprintf(stderr, "%3ld %c %c %s", i, p_char[i],
1201 special, p_line[i]);
1206 if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1207 p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
1212 * Input a line from the patch file.
1213 * Worry about indentation if do_indent is true.
1214 * The line is read directly into the buf global variable which
1215 * is resized if necessary in order to hold the complete line.
1216 * Returns the number of characters read including the terminating
1220 pgets(bool do_indent)
1224 int indent = 0, skipped = 0;
1226 line = fgetln(pfp, &len);
1228 if (len + 1 > buf_size) {
1229 while (len + 1 > buf_size)
1232 buf = malloc(buf_size);
1234 fatal("out of memory\n");
1236 if (do_indent == 1 && p_indent) {
1238 indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1239 line++, skipped++) {
1241 indent += 8 - (indent %7);
1246 memcpy(buf, line, len - skipped);
1247 buf[len - skipped] = '\0';
1254 * Reverse the old and new portions of the current hunk.
1259 char **tp_line; /* the text of the hunk */
1260 unsigned short *tp_len;/* length of each line */
1261 char *tp_char; /* +, -, and ! */
1264 bool blankline = false;
1268 p_first = p_newfirst;
1271 /* make a scratch copy */
1276 p_line = NULL; /* force set_hunkmax to allocate again */
1280 if (p_line == NULL || p_len == NULL || p_char == NULL) {
1288 return false; /* not enough memory to swap hunk! */
1290 /* now turn the new into the old */
1292 i = p_ptrn_lines + 1;
1293 if (tp_char[i] == '\n') { /* account for possible blank line */
1297 if (p_efake >= 0) { /* fix non-freeable ptr range */
1305 for (n = 0; i <= p_end; i++, n++) {
1306 p_line[n] = tp_line[i];
1307 p_char[n] = tp_char[i];
1308 if (p_char[n] == '+')
1310 p_len[n] = tp_len[i];
1313 i = p_ptrn_lines + 1;
1314 p_line[n] = tp_line[i];
1315 p_char[n] = tp_char[i];
1316 p_len[n] = tp_len[i];
1319 if (p_char[0] != '=')
1320 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1321 p_input_line, p_char[0]);
1323 for (s = p_line[0]; *s; s++)
1327 /* now turn the old into the new */
1329 if (p_char[0] != '*')
1330 fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1331 p_input_line, p_char[0]);
1333 for (s = tp_line[0]; *s; s++)
1336 for (i = 0; n <= p_end; i++, n++) {
1337 p_line[n] = tp_line[i];
1338 p_char[n] = tp_char[i];
1339 if (p_char[n] == '-')
1341 p_len[n] = tp_len[i];
1344 if (i != p_ptrn_lines + 1)
1345 fatal("Malformed patch at line %ld: expected %ld lines, "
1347 p_input_line, p_ptrn_lines + 1, i);
1350 p_ptrn_lines = p_repl_lines;
1361 * Return the specified line position in the old file of the old context.
1370 * Return the number of lines of old context.
1373 pch_ptrn_lines(void)
1375 return p_ptrn_lines;
1379 * Return the probable line position in the new file of the first line.
1388 * Return the number of lines in the replacement text including context.
1391 pch_repl_lines(void)
1393 return p_repl_lines;
1397 * Return the number of lines in the whole hunk.
1406 * Return the number of context lines before the first changed line.
1415 * Return the length of a particular patch line.
1418 pch_line_len(LINENUM line)
1424 * Return the control character (+, -, *, !, etc) for a patch line.
1427 pch_char(LINENUM line)
1429 return p_char[line];
1433 * Return a pointer to a particular patch line.
1436 pfetch(LINENUM line)
1438 return p_line[line];
1442 * Return where in the patch file this hunk began, for error messages.
1451 * Apply an ed script by feeding ed itself.
1457 off_t beginning_of_this_line;
1458 FILE *pipefp = NULL;
1461 if (!skip_rest_of_patch) {
1462 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1464 fatal("can't create temp file %s", TMPOUTNAME);
1466 snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1467 verbose ? " " : " -s ", TMPOUTNAME);
1468 pipefp = popen(buf, "w");
1471 beginning_of_this_line = ftello(pfp);
1472 if (pgets(true) == 0) {
1473 next_intuit_at(beginning_of_this_line, p_input_line);
1477 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1479 /* POSIX defines allowed commands as {a,c,d,i,s} */
1480 if (isdigit((unsigned char)*buf) &&
1481 (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1487 t = strchr(buf, '\0') - 1;
1488 while (--t >= buf && *t == '\\')
1489 continuation = !continuation;
1490 if (!continuation ||
1496 } else if (*t != 'd') {
1497 while (pgets(true)) {
1501 if (strEQ(buf, ".\n"))
1506 next_intuit_at(beginning_of_this_line, p_input_line);
1512 fprintf(pipefp, "w\n");
1513 fprintf(pipefp, "q\n");
1518 if (move_file(TMPOUTNAME, outname) < 0) {
1520 chmod(TMPOUTNAME, filemode);
1522 chmod(outname, filemode);
1528 * Choose the name of the file to be patched based on POSIX rules.
1529 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1530 * if the user specified --posix or set POSIXLY_CORRECT.
1533 posix_name(const struct file_name *names, bool assume_exists)
1539 * POSIX states that the filename will be chosen from one
1540 * of the old, new and index names (in that order) if
1541 * the file exists relative to CWD after -p stripping.
1543 for (i = 0; i < MAX_FILE; i++) {
1544 if (names[i].path != NULL && names[i].exists) {
1545 path = names[i].path;
1549 if (path == NULL && !assume_exists) {
1551 * No files found, check to see if the diff could be
1552 * creating a new file.
1554 if (path == NULL && ok_to_create_file &&
1555 names[NEW_FILE].path != NULL)
1556 path = names[NEW_FILE].path;
1559 return path ? xstrdup(path) : NULL;
1563 compare_names(const struct file_name *names, bool assume_exists)
1565 size_t min_components, min_baselen, min_len, tmp;
1571 * The "best" name is the one with the fewest number of path
1572 * components, the shortest basename length, and the shortest
1573 * overall length (in that order). We only use the Index: file
1574 * if neither of the old or new files could be intuited from
1577 min_components = min_baselen = min_len = SIZE_MAX;
1578 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1579 path = names[i].path;
1580 if (path == NULL || (!names[i].exists && !assume_exists))
1582 if ((tmp = num_components(path)) > min_components)
1584 if (tmp < min_components) {
1585 min_components = tmp;
1588 if ((tmp = strlen(basename(path))) > min_baselen)
1590 if (tmp < min_baselen) {
1594 if ((tmp = strlen(path)) > min_len)
1603 * Choose the name of the file to be patched based the "best" one
1607 best_name(const struct file_name *names, bool assume_exists)
1611 best = compare_names(names, assume_exists);
1613 /* No match? Check to see if the diff could be creating a new file. */
1614 if (best == NULL && ok_to_create_file)
1615 best = names[NEW_FILE].path;
1617 return best ? xstrdup(best) : NULL;
1621 num_components(const char *path)
1626 for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1628 cp++; /* skip consecutive slashes */
1634 * Convert number at NPTR into LINENUM and save address of first
1635 * character that is not a digit in ENDPTR. If conversion is not
1636 * possible, call fatal.
1639 strtolinenum(char *nptr, char **endptr)
1646 for (p = nptr; isdigit((unsigned char)*p); p++)
1655 rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1657 fatal("invalid line number at line %ld: `%s' is %s\n",
1658 p_input_line, nptr, errstr);