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 nonempty_patchf_seen = true;
187 diff_type = intuit_diff_type();
191 say(" Ignoring the trailing garbage.\ndone\n");
193 say(" I can't seem to find a patch in there anywhere.\n");
197 say(" %sooks like %s to me...\n",
198 (p_base == 0 ? "L" : "The next patch l"),
199 diff_type == UNI_DIFF ? "a unified diff" :
200 diff_type == CONTEXT_DIFF ? "a context diff" :
201 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
202 diff_type == NORMAL_DIFF ? "a normal diff" :
204 if (p_indent && verbose)
205 say("(Patch is indented %d space%s.)\n", p_indent,
206 p_indent == 1 ? "" : "s");
207 skip_to(p_start, p_sline);
208 while (filearg[0] == NULL) {
209 if (force || batch) {
210 say("No file to patch. Skipping...\n");
211 filearg[0] = xstrdup(bestguess);
212 skip_rest_of_patch = true;
215 ask("File to patch: ");
218 bestguess = xstrdup(buf);
219 filearg[0] = fetchname(buf, &exists, 0);
222 int def_skip = *bestguess == '\0';
223 ask("No file found--skip this patch? [%c] ",
224 def_skip ? 'y' : 'n');
225 if (*buf == 'n' || (!def_skip && *buf != 'y'))
228 say("Skipping patch...\n");
230 filearg[0] = fetchname(bestguess, &exists, 0);
231 skip_rest_of_patch = true;
239 p4_fetchname(struct file_name *name, char *str)
243 /* Skip leading whitespace. */
244 while (isspace((unsigned char)*str))
247 /* Remove the file revision number. */
248 for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
254 name->path = fetchname(str, &name->exists, strippath);
257 /* Determine what kind of diff is in the remaining part of the patch file. */
260 intuit_diff_type(void)
262 off_t this_line = 0, previous_line;
263 off_t first_command_line = -1;
264 LINENUM fcl_line = -1;
265 bool last_line_was_command = false, this_is_a_command = false;
266 bool stars_last_line = false, stars_this_line = false;
269 struct file_name names[MAX_FILE];
270 int piece_of_git = 0;
272 memset(names, 0, sizeof(names));
273 ok_to_create_file = false;
274 fseeko(pfp, p_base, SEEK_SET);
275 p_input_line = p_bline - 1;
277 previous_line = this_line;
278 last_line_was_command = this_is_a_command;
279 stars_last_line = stars_this_line;
280 this_line = ftello(pfp);
283 if (pgets(false) == 0) {
284 if (first_command_line >= 0) {
285 /* nothing but deletes!? */
286 p_start = first_command_line;
292 p_sline = p_input_line;
297 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
299 indent += 8 - (indent % 8);
303 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
305 this_is_a_command = (isdigit((unsigned char)*s) &&
306 (*t == 'd' || *t == 'c' || *t == 'a'));
307 if (first_command_line < 0 && this_is_a_command) {
308 first_command_line = this_line;
309 fcl_line = p_input_line;
310 p_indent = indent; /* assume this for now */
312 if (!stars_last_line && strnEQ(s, "*** ", 4))
313 names[OLD_FILE].path = fetchname(s + 4,
314 &names[OLD_FILE].exists, strippath);
315 else if (strnEQ(s, "--- ", 4)) {
317 if (piece_of_git && strippath == 957 &&
318 strnEQ(s, "--- a/", 6))
320 names[NEW_FILE].path = fetchname(s + off,
321 &names[NEW_FILE].exists, strippath);
322 } else if (strnEQ(s, "+++ ", 4)) {
323 /* pretend it is the old name */
325 if (piece_of_git && strippath == 957 &&
326 strnEQ(s, "+++ b/", 6))
328 names[OLD_FILE].path = fetchname(s + off,
329 &names[OLD_FILE].exists, strippath);
330 } else if (strnEQ(s, "Index:", 6))
331 names[INDEX_FILE].path = fetchname(s + 6,
332 &names[INDEX_FILE].exists, strippath);
333 else if (strnEQ(s, "Prereq:", 7)) {
334 for (t = s + 7; isspace((unsigned char)*t); t++)
336 revision = xstrdup(t);
338 *t && !isspace((unsigned char)*t); t++)
341 if (*revision == '\0') {
345 } else if (strnEQ(s, "diff --git a/", 13)) {
346 /* Git-style diffs. */
348 } else if (strnEQ(s, "==== ", 5)) {
349 /* Perforce-style diffs. */
350 if ((t = strstr(s + 5, " - ")) != NULL)
351 p4_fetchname(&names[NEW_FILE], t + 3);
352 p4_fetchname(&names[OLD_FILE], s + 5);
354 if ((!diff_type || diff_type == ED_DIFF) &&
355 first_command_line >= 0 &&
358 p_start = first_command_line;
363 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
364 if (strnEQ(s + 4, "0,0", 3))
365 ok_to_create_file = true;
368 p_sline = p_input_line;
372 stars_this_line = strnEQ(s, "********", 8);
373 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
374 strnEQ(s, "*** ", 4)) {
375 if (strtolinenum(s + 4, &s) == 0)
376 ok_to_create_file = true;
378 * If this is a new context diff the character just
379 * at the end of the line is a '*'.
381 while (*s && *s != '\n')
384 p_start = previous_line;
385 p_sline = p_input_line - 1;
386 retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
389 if ((!diff_type || diff_type == NORMAL_DIFF) &&
390 last_line_was_command &&
391 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
392 p_start = previous_line;
393 p_sline = p_input_line - 1;
395 retval = NORMAL_DIFF;
400 if (retval == UNI_DIFF) {
401 /* unswap old and new */
402 struct file_name tmp = names[OLD_FILE];
403 names[OLD_FILE] = names[NEW_FILE];
404 names[NEW_FILE] = tmp;
406 if (filearg[0] == NULL) {
408 filearg[0] = posix_name(names, ok_to_create_file);
410 /* Ignore the Index: name for context diffs, like GNU */
411 if (names[OLD_FILE].path != NULL ||
412 names[NEW_FILE].path != NULL) {
413 free(names[INDEX_FILE].path);
414 names[INDEX_FILE].path = NULL;
416 filearg[0] = best_name(names, ok_to_create_file);
422 if (filearg[0] != NULL)
423 bestguess = xstrdup(filearg[0]);
424 else if (!ok_to_create_file) {
426 * We don't want to create a new file but we need a
427 * filename to set bestguess. Avoid setting filearg[0]
428 * so the file is not created automatically.
431 bestguess = posix_name(names, true);
433 bestguess = best_name(names, true);
435 free(names[OLD_FILE].path);
436 free(names[NEW_FILE].path);
437 free(names[INDEX_FILE].path);
442 * Remember where this patch ends so we know where to start up again.
445 next_intuit_at(off_t file_pos, LINENUM file_line)
452 * Basically a verbose fseeko() to the actual diff listing.
455 skip_to(off_t file_pos, LINENUM file_line)
459 if (p_base > file_pos)
460 fatal("Internal error: seek %lld>%lld\n",
461 (long long)p_base, (long long)file_pos);
462 if (verbose && p_base < file_pos) {
463 fseeko(pfp, p_base, SEEK_SET);
464 say("The text leading up to this was:\n--------------------------\n");
465 while (ftello(pfp) < file_pos) {
468 fatal("Unexpected end of file\n");
471 say("--------------------------\n");
473 fseeko(pfp, file_pos, SEEK_SET);
474 p_input_line = file_line - 1;
477 /* Make this a function for better debugging. */
481 fatal("malformed patch at line %ld: %s", p_input_line, buf);
482 /* about as informative as "Syntax error" in C */
486 * True if the line has been discarded (i.e. it is a line saying
487 * "\ No newline at end of file".)
490 remove_special_line(void)
498 } while (c != EOF && c != '\n');
503 fseeko(pfp, -1, SEEK_CUR);
509 * True if there is more of the current diff listing to process.
514 off_t line_beginning; /* file pos of the current line */
515 LINENUM repl_beginning; /* index of --- line */
516 LINENUM fillcnt; /* #lines of missing ptrn or repl */
517 LINENUM fillsrc; /* index of first line to copy */
518 LINENUM filldst; /* index of first missing line */
519 bool ptrn_spaces_eaten; /* ptrn was slightly malformed */
520 bool repl_could_be_missing; /* no + or ! lines in this hunk */
521 bool repl_missing; /* we are now backtracking */
522 off_t repl_backtrack_position; /* file pos of first repl line */
523 LINENUM repl_patch_line; /* input line number for same */
524 LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
530 if (p_end == p_efake)
531 p_end = p_bfake; /* don't free twice */
538 p_max = hunkmax; /* gets reduced when --- found */
539 if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
540 line_beginning = ftello(pfp);
545 ptrn_spaces_eaten = false;
546 repl_could_be_missing = true;
547 repl_missing = false;
548 repl_backtrack_position = 0;
554 if (len == 0 || strnNE(buf, "********", 8)) {
555 next_intuit_at(line_beginning, p_input_line);
559 p_hunk_beg = p_input_line + 1;
560 while (p_end < p_max) {
561 line_beginning = ftello(pfp);
565 if (p_max - p_end < 4) {
566 /* assume blank lines got chopped */
567 strlcpy(buf, " \n", buf_size);
569 if (repl_beginning && repl_could_be_missing) {
573 fatal("unexpected end of file in patch\n");
577 if (p_end >= hunkmax)
578 fatal("Internal error: hunk larger than hunk "
580 p_char[p_end] = *buf;
581 p_line[p_end] = NULL;
584 if (strnEQ(buf, "********", 8)) {
585 if (repl_beginning && repl_could_be_missing) {
589 fatal("unexpected end of hunk "
594 if (repl_beginning && repl_could_be_missing) {
598 fatal("unexpected *** at line %ld: %s",
602 p_line[p_end] = savestr(buf);
608 *s && !isdigit((unsigned char)*s); s++)
612 if (strnEQ(s, "0,0", 3))
613 memmove(s, s + 2, strlen(s + 2) + 1);
614 p_first = strtolinenum(s, &s);
617 *s && !isdigit((unsigned char)*s); s++)
621 p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
622 if (p_ptrn_lines < 0)
630 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
631 p_ptrn_lines >= LINENUM_MAX - 6)
634 /* we need this much at least */
635 p_max = p_ptrn_lines + 6;
636 while (p_max >= hunkmax)
642 if (repl_beginning ||
643 (p_end != p_ptrn_lines + 1 +
644 (p_char[p_end - 1] == '\n'))) {
647 * `old' lines were omitted;
648 * set up to fill them in
649 * from 'new' context lines.
651 p_end = p_ptrn_lines + 1;
654 fillcnt = p_ptrn_lines;
656 if (repl_beginning) {
657 if (repl_could_be_missing) {
661 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
662 p_input_line, p_hunk_beg + repl_beginning);
664 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
665 (p_end <= p_ptrn_lines
668 p_input_line, p_hunk_beg);
672 repl_beginning = p_end;
673 repl_backtrack_position = ftello(pfp);
674 repl_patch_line = p_input_line;
675 p_line[p_end] = savestr(buf);
681 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
685 p_newfirst = strtolinenum(s, &s);
687 for (; *s && !isdigit((unsigned char)*s); s++)
691 p_repl_lines = strtolinenum(s, &s) -
693 if (p_repl_lines < 0)
695 } else if (p_newfirst)
701 if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
702 p_repl_lines >= LINENUM_MAX - p_end)
704 p_max = p_repl_lines + p_end;
705 if (p_max > MAXHUNKSIZE)
706 fatal("hunk too large (%ld lines) at line %ld: %s",
707 p_max, p_input_line, buf);
708 while (p_max >= hunkmax)
710 if (p_repl_lines != ptrn_copiable &&
711 (p_context != 0 || p_repl_lines != 1))
712 repl_could_be_missing = false;
718 repl_could_be_missing = false;
720 if (buf[1] == '\n' && canonicalize)
721 strlcpy(buf + 1, " \n", buf_size - 1);
722 if (!isspace((unsigned char)buf[1]) &&
723 buf[1] != '>' && buf[1] != '<' &&
724 repl_beginning && repl_could_be_missing) {
729 if (context < p_context)
733 p_line[p_end] = savestr(buf + 2);
738 if (p_end == p_ptrn_lines) {
739 if (remove_special_line()) {
742 l = strlen(p_line[p_end]) - 1;
743 (p_line[p_end])[l] = 0;
748 case '\n': /* assume the 2 spaces got eaten */
749 if (repl_beginning && repl_could_be_missing &&
750 (!ptrn_spaces_eaten ||
751 diff_type == NEW_CONTEXT_DIFF)) {
755 p_line[p_end] = savestr(buf);
760 if (p_end != p_ptrn_lines + 1) {
761 ptrn_spaces_eaten |= (repl_beginning != 0);
769 if (!isspace((unsigned char)buf[1]) &&
770 repl_beginning && repl_could_be_missing) {
777 p_line[p_end] = savestr(buf + 2);
784 if (repl_beginning && repl_could_be_missing) {
790 /* set up p_len for strncmp() so we don't have to */
791 /* assume null termination */
793 p_len[p_end] = strlen(p_line[p_end]);
799 if (p_end >= 0 && !repl_beginning)
800 fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
804 /* reset state back to just after --- */
805 p_input_line = repl_patch_line;
806 for (p_end--; p_end > repl_beginning; p_end--)
808 fseeko(pfp, repl_backtrack_position, SEEK_SET);
810 /* redundant 'new' context lines were omitted - set */
811 /* up to fill them in from the old file context */
812 if (!p_context && p_repl_lines == 1) {
817 filldst = repl_beginning + 1;
818 fillcnt = p_repl_lines;
820 } else if (!p_context && fillcnt == 1) {
821 /* the first hunk was a null hunk with no context */
822 /* and we were expecting one line -- fix it up. */
823 while (filldst < p_end) {
824 p_line[filldst] = p_line[filldst + 1];
825 p_char[filldst] = p_char[filldst + 1];
826 p_len[filldst] = p_len[filldst + 1];
830 repl_beginning--; /* this doesn't need to be fixed */
833 p_first++; /* do append rather than insert */
837 if (diff_type == CONTEXT_DIFF &&
838 (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
841 "(Fascinating--this is really a new-style context diff but without",
842 "the telltale extra asterisks on the *** line that usually indicate",
843 "the new style...)");
844 diff_type = NEW_CONTEXT_DIFF;
846 /* if there were omitted context lines, fill them in now */
848 p_bfake = filldst; /* remember where not to free() */
849 p_efake = filldst + fillcnt - 1;
850 while (fillcnt-- > 0) {
851 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
854 fatal("replacement text or line numbers mangled in hunk at line %ld\n",
856 p_line[filldst] = p_line[fillsrc];
857 p_char[filldst] = p_char[fillsrc];
858 p_len[filldst] = p_len[fillsrc];
862 while (fillsrc <= p_end && fillsrc != repl_beginning &&
863 p_char[fillsrc] != ' ')
867 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
868 fillsrc, filldst, repl_beginning, p_end + 1);
870 if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
872 if (filldst != p_end + 1 && filldst != repl_beginning)
875 if (p_line[p_end] != NULL) {
876 if (remove_special_line()) {
878 (p_line[p_end])[p_len[p_end]] = 0;
881 } else if (diff_type == UNI_DIFF) {
882 LINENUM fillold; /* index of old lines */
883 LINENUM fillnew; /* index of new lines */
886 line_beginning = ftello(pfp); /* file pos of the current line */
889 if (len == 0 || strnNE(buf, "@@ -", 4)) {
890 next_intuit_at(line_beginning, p_input_line);
896 p_first = strtolinenum(s, &s);
898 p_ptrn_lines = strtolinenum(s + 1, &s);
903 if (*s != '+' || !*++s)
905 p_newfirst = strtolinenum(s, &s);
907 p_repl_lines = strtolinenum(s + 1, &s);
914 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
915 p_newfirst > LINENUM_MAX - p_repl_lines ||
916 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
919 p_first++; /* do append rather than insert */
920 p_max = p_ptrn_lines + p_repl_lines + 1;
921 while (p_max >= hunkmax)
924 fillnew = fillold + p_ptrn_lines;
925 p_end = fillnew + p_repl_lines;
926 snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
927 p_first + p_ptrn_lines - 1);
928 p_line[0] = savestr(buf);
934 snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
935 p_newfirst + p_repl_lines - 1);
936 p_line[fillnew] = savestr(buf);
941 p_char[fillnew++] = '=';
944 p_hunk_beg = p_input_line + 1;
945 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
946 line_beginning = ftello(pfp);
950 if (p_max - fillnew < 3) {
951 /* assume blank lines got chopped */
952 strlcpy(buf, " \n", buf_size);
954 fatal("unexpected end of file in patch\n");
957 if (*buf == '\t' || *buf == '\n') {
958 ch = ' '; /* assume the space got eaten */
962 s = savestr(buf + 1);
965 while (--fillnew > p_ptrn_lines)
966 free(p_line[fillnew]);
972 if (fillold > p_ptrn_lines) {
977 p_char[fillold] = ch;
979 p_len[fillold++] = strlen(s);
980 if (fillold > p_ptrn_lines) {
981 if (remove_special_line()) {
982 p_len[fillold - 1] -= 1;
983 s[p_len[fillold - 1]] = 0;
991 if (fillold > p_ptrn_lines) {
993 while (--fillnew > p_ptrn_lines)
994 free(p_line[fillnew]);
999 p_char[fillold] = ch;
1000 p_line[fillold] = s;
1001 p_len[fillold++] = strlen(s);
1004 while (--fillnew > p_ptrn_lines)
1005 free(p_line[fillnew]);
1006 p_end = fillold - 1;
1009 if (fillold > p_ptrn_lines) {
1010 if (remove_special_line()) {
1011 p_len[fillold - 1] -= 1;
1012 s[p_len[fillold - 1]] = 0;
1017 if (fillnew > p_end) {
1019 while (--fillnew > p_ptrn_lines)
1020 free(p_line[fillnew]);
1021 p_end = fillold - 1;
1024 p_char[fillnew] = ch;
1025 p_line[fillnew] = s;
1026 p_len[fillnew++] = strlen(s);
1027 if (fillold > p_ptrn_lines) {
1028 if (remove_special_line()) {
1029 p_len[fillnew - 1] -= 1;
1030 s[p_len[fillnew - 1]] = 0;
1038 if (ch != ' ' && context > 0) {
1039 if (context < p_context)
1040 p_context = context;
1044 } else { /* normal diff--fake it up */
1049 line_beginning = ftello(pfp);
1053 if (len == 0 || !isdigit((unsigned char)*buf)) {
1054 next_intuit_at(line_beginning, p_input_line);
1057 p_first = strtolinenum(buf, &s);
1059 p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1060 if (p_ptrn_lines < 0)
1063 p_ptrn_lines = (*s != 'a');
1065 if (hunk_type == 'a')
1066 p_first++; /* do append rather than insert */
1067 min = strtolinenum(s + 1, &s);
1069 max = strtolinenum(s + 1, &s);
1072 if (min < 0 || min > max || max - min == LINENUM_MAX)
1074 if (hunk_type == 'd')
1077 p_repl_lines = max - min + 1;
1078 if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1079 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1081 p_end = p_ptrn_lines + p_repl_lines + 1;
1082 if (p_end > MAXHUNKSIZE)
1083 fatal("hunk too large (%ld lines) at line %ld: %s",
1084 p_end, p_input_line, buf);
1085 while (p_end >= hunkmax)
1087 snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1088 p_first + p_ptrn_lines - 1);
1089 p_line[0] = savestr(buf);
1095 for (i = 1; i <= p_ptrn_lines; i++) {
1099 fatal("unexpected end of file in patch at line %ld\n",
1102 fatal("< expected at line %ld of patch\n",
1104 p_line[i] = savestr(buf + 2);
1109 p_len[i] = strlen(p_line[i]);
1113 if (remove_special_line()) {
1115 (p_line[i - 1])[p_len[i - 1]] = 0;
1117 if (hunk_type == 'c') {
1121 fatal("unexpected end of file in patch at line %ld\n",
1124 fatal("--- expected at line %ld of patch\n",
1127 snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1128 p_line[i] = savestr(buf);
1134 for (i++; i <= p_end; i++) {
1138 fatal("unexpected end of file in patch at line %ld\n",
1141 fatal("> expected at line %ld of patch\n",
1143 /* Don't overrun if we don't have enough line */
1145 p_line[i] = savestr(buf + 2);
1147 p_line[i] = savestr("");
1153 p_len[i] = strlen(p_line[i]);
1157 if (remove_special_line()) {
1159 (p_line[i - 1])[p_len[i - 1]] = 0;
1162 if (reverse) /* backwards patch? */
1164 say("Not enough memory to swap next hunk!\n");
1170 for (i = 0; i <= p_end; i++) {
1171 if (i == p_ptrn_lines)
1175 fprintf(stderr, "%3ld %c %c %s", i, p_char[i],
1176 special, p_line[i]);
1181 if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1182 p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
1187 * Input a line from the patch file.
1188 * Worry about indentation if do_indent is true.
1189 * The line is read directly into the buf global variable which
1190 * is resized if necessary in order to hold the complete line.
1191 * Returns the number of characters read including the terminating
1195 pgets(bool do_indent)
1199 int indent = 0, skipped = 0;
1201 line = fgetln(pfp, &len);
1203 if (len + 1 > buf_size) {
1204 while (len + 1 > buf_size)
1207 buf = malloc(buf_size);
1209 fatal("out of memory\n");
1211 if (do_indent == 1 && p_indent) {
1213 indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1214 line++, skipped++) {
1216 indent += 8 - (indent %7);
1221 memcpy(buf, line, len - skipped);
1222 buf[len - skipped] = '\0';
1229 * Reverse the old and new portions of the current hunk.
1234 char **tp_line; /* the text of the hunk */
1235 unsigned short *tp_len;/* length of each line */
1236 char *tp_char; /* +, -, and ! */
1239 bool blankline = false;
1243 p_first = p_newfirst;
1246 /* make a scratch copy */
1251 p_line = NULL; /* force set_hunkmax to allocate again */
1255 if (p_line == NULL || p_len == NULL || p_char == NULL) {
1263 return false; /* not enough memory to swap hunk! */
1265 /* now turn the new into the old */
1267 i = p_ptrn_lines + 1;
1268 if (tp_char[i] == '\n') { /* account for possible blank line */
1272 if (p_efake >= 0) { /* fix non-freeable ptr range */
1280 for (n = 0; i <= p_end; i++, n++) {
1281 p_line[n] = tp_line[i];
1282 p_char[n] = tp_char[i];
1283 if (p_char[n] == '+')
1285 p_len[n] = tp_len[i];
1288 i = p_ptrn_lines + 1;
1289 p_line[n] = tp_line[i];
1290 p_char[n] = tp_char[i];
1291 p_len[n] = tp_len[i];
1294 if (p_char[0] != '=')
1295 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1296 p_input_line, p_char[0]);
1298 for (s = p_line[0]; *s; s++)
1302 /* now turn the old into the new */
1304 if (p_char[0] != '*')
1305 fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1306 p_input_line, p_char[0]);
1308 for (s = tp_line[0]; *s; s++)
1311 for (i = 0; n <= p_end; i++, n++) {
1312 p_line[n] = tp_line[i];
1313 p_char[n] = tp_char[i];
1314 if (p_char[n] == '-')
1316 p_len[n] = tp_len[i];
1319 if (i != p_ptrn_lines + 1)
1320 fatal("Malformed patch at line %ld: expected %ld lines, "
1322 p_input_line, p_ptrn_lines + 1, i);
1325 p_ptrn_lines = p_repl_lines;
1336 * Return the specified line position in the old file of the old context.
1345 * Return the number of lines of old context.
1348 pch_ptrn_lines(void)
1350 return p_ptrn_lines;
1354 * Return the probable line position in the new file of the first line.
1363 * Return the number of lines in the replacement text including context.
1366 pch_repl_lines(void)
1368 return p_repl_lines;
1372 * Return the number of lines in the whole hunk.
1381 * Return the number of context lines before the first changed line.
1390 * Return the length of a particular patch line.
1393 pch_line_len(LINENUM line)
1399 * Return the control character (+, -, *, !, etc) for a patch line.
1402 pch_char(LINENUM line)
1404 return p_char[line];
1408 * Return a pointer to a particular patch line.
1411 pfetch(LINENUM line)
1413 return p_line[line];
1417 * Return where in the patch file this hunk began, for error messages.
1426 * Apply an ed script by feeding ed itself.
1432 off_t beginning_of_this_line;
1433 FILE *pipefp = NULL;
1436 if (!skip_rest_of_patch) {
1437 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1439 fatal("can't create temp file %s", TMPOUTNAME);
1441 snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1442 verbose ? " " : " -s ", TMPOUTNAME);
1443 pipefp = popen(buf, "w");
1446 beginning_of_this_line = ftello(pfp);
1447 if (pgets(true) == 0) {
1448 next_intuit_at(beginning_of_this_line, p_input_line);
1452 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1454 /* POSIX defines allowed commands as {a,c,d,i,s} */
1455 if (isdigit((unsigned char)*buf) &&
1456 (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1462 t = strchr(buf, '\0') - 1;
1463 while (--t >= buf && *t == '\\')
1464 continuation = !continuation;
1465 if (!continuation ||
1471 } else if (*t != 'd') {
1472 while (pgets(true)) {
1476 if (strEQ(buf, ".\n"))
1481 next_intuit_at(beginning_of_this_line, p_input_line);
1487 fprintf(pipefp, "w\n");
1488 fprintf(pipefp, "q\n");
1493 if (move_file(TMPOUTNAME, outname) < 0) {
1495 chmod(TMPOUTNAME, filemode);
1497 chmod(outname, filemode);
1503 * Choose the name of the file to be patched based on POSIX rules.
1504 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1505 * if the user specified --posix or set POSIXLY_CORRECT.
1508 posix_name(const struct file_name *names, bool assume_exists)
1514 * POSIX states that the filename will be chosen from one
1515 * of the old, new and index names (in that order) if
1516 * the file exists relative to CWD after -p stripping.
1518 for (i = 0; i < MAX_FILE; i++) {
1519 if (names[i].path != NULL && names[i].exists) {
1520 path = names[i].path;
1524 if (path == NULL && !assume_exists) {
1526 * No files found, check to see if the diff could be
1527 * creating a new file.
1529 if (path == NULL && ok_to_create_file &&
1530 names[NEW_FILE].path != NULL)
1531 path = names[NEW_FILE].path;
1534 return path ? xstrdup(path) : NULL;
1538 compare_names(const struct file_name *names, bool assume_exists)
1540 size_t min_components, min_baselen, min_len, tmp;
1546 * The "best" name is the one with the fewest number of path
1547 * components, the shortest basename length, and the shortest
1548 * overall length (in that order). We only use the Index: file
1549 * if neither of the old or new files could be intuited from
1552 min_components = min_baselen = min_len = SIZE_MAX;
1553 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1554 path = names[i].path;
1555 if (path == NULL || (!names[i].exists && !assume_exists))
1557 if ((tmp = num_components(path)) > min_components)
1559 if (tmp < min_components) {
1560 min_components = tmp;
1563 if ((tmp = strlen(basename(path))) > min_baselen)
1565 if (tmp < min_baselen) {
1569 if ((tmp = strlen(path)) > min_len)
1578 * Choose the name of the file to be patched based the "best" one
1582 best_name(const struct file_name *names, bool assume_exists)
1586 best = compare_names(names, assume_exists);
1588 /* No match? Check to see if the diff could be creating a new file. */
1589 if (best == NULL && ok_to_create_file)
1590 best = names[NEW_FILE].path;
1592 return best ? xstrdup(best) : NULL;
1596 num_components(const char *path)
1601 for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1603 cp++; /* skip consecutive slashes */
1609 * Convert number at NPTR into LINENUM and save address of first
1610 * character that is not a digit in ENDPTR. If conversion is not
1611 * possible, call fatal.
1614 strtolinenum(char *nptr, char **endptr)
1621 for (p = nptr; isdigit((unsigned char)*p); p++)
1630 rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1632 fatal("invalid line number at line %ld: `%s' is %s\n",
1633 p_input_line, nptr, errstr);