3 * Copyright 1986, Larry Wall
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following condition is met:
7 * 1. Redistributions of source code must retain the above copyright notice,
8 * this condition and the following disclaimer.
10 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
11 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
12 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
13 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
14 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
15 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
16 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
17 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
19 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
22 * patch - a program to apply diffs to original files
24 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
27 * $OpenBSD: pch.c,v 1.39 2012/04/11 08:07:13 ajacoutot Exp $
28 * $FreeBSD: head/usr.bin/patch/pch.c 255232 2013-09-05 05:51:15Z se $
31 #include <sys/types.h>
45 #include "pathnames.h"
47 /* Patch (diff listing) abstract type. */
49 static long 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 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 LINENUM p_base; /* where to intuit this time */
64 static LINENUM p_bline; /* line # of p_base */
65 static LINENUM 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(LINENUM, LINENUM);
76 static void skip_to(LINENUM, 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 *);
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 fstat(fileno(pfp), &filestat);
123 p_filesize = filestat.st_size;
124 next_intuit_at(0L, 1L); /* start at the beginning */
129 * Make sure our dynamically realloced tables are malloced to begin with.
135 p_line = calloc((size_t) hunkmax, sizeof(char *));
137 p_len = calloc((size_t) hunkmax, sizeof(short));
139 p_char = calloc((size_t) hunkmax, sizeof(char));
143 * Enlarge the arrays containing the current hunk of patch.
153 new_hunkmax = hunkmax * 2;
155 if (p_line == NULL || p_len == NULL || p_char == NULL)
156 fatal("Internal memory allocation error\n");
158 new_p_line = realloc(p_line, new_hunkmax * sizeof(char *));
159 if (new_p_line == NULL)
162 new_p_len = realloc(p_len, new_hunkmax * sizeof(short));
163 if (new_p_len == NULL)
166 new_p_char = realloc(p_char, new_hunkmax * sizeof(char));
167 if (new_p_char == NULL)
174 if (p_line != NULL && p_len != NULL && p_char != NULL) {
175 hunkmax = new_hunkmax;
180 fatal("out of memory\n");
181 out_of_mem = true; /* whatever is null will be allocated again */
182 /* from within plan_a(), of all places */
185 /* True if the remainder of the patch file contains a diff of some sort. */
188 there_is_another_patch(void)
192 if (p_base != 0L && p_base >= p_filesize) {
199 diff_type = intuit_diff_type();
203 say(" Ignoring the trailing garbage.\ndone\n");
205 say(" I can't seem to find a patch in there anywhere.\n");
209 say(" %sooks like %s to me...\n",
210 (p_base == 0L ? "L" : "The next patch l"),
211 diff_type == UNI_DIFF ? "a unified diff" :
212 diff_type == CONTEXT_DIFF ? "a context diff" :
213 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
214 diff_type == NORMAL_DIFF ? "a normal diff" :
216 if (p_indent && verbose)
217 say("(Patch is indented %d space%s.)\n", p_indent,
218 p_indent == 1 ? "" : "s");
219 skip_to(p_start, p_sline);
220 while (filearg[0] == NULL) {
221 if (force || batch) {
222 say("No file to patch. Skipping...\n");
223 filearg[0] = savestr(bestguess);
224 skip_rest_of_patch = true;
227 ask("File to patch: ");
230 bestguess = savestr(buf);
231 filearg[0] = fetchname(buf, &exists, 0);
234 ask("No file found--skip this patch? [n] ");
238 say("Skipping patch...\n");
240 filearg[0] = fetchname(bestguess, &exists, 0);
241 skip_rest_of_patch = true;
249 p4_fetchname(struct file_name *name, char *str)
253 /* Skip leading whitespace. */
254 while (isspace((unsigned char)*str))
257 /* Remove the file revision number. */
258 for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
264 name->path = fetchname(str, &name->exists, strippath);
267 /* Determine what kind of diff is in the remaining part of the patch file. */
270 intuit_diff_type(void)
272 long this_line = 0, previous_line;
273 long first_command_line = -1;
274 LINENUM fcl_line = -1;
275 bool last_line_was_command = false, this_is_a_command = false;
276 bool stars_last_line = false, stars_this_line = false;
279 struct file_name names[MAX_FILE];
281 memset(names, 0, sizeof(names));
282 ok_to_create_file = false;
283 fseek(pfp, p_base, SEEK_SET);
284 p_input_line = p_bline - 1;
286 previous_line = this_line;
287 last_line_was_command = this_is_a_command;
288 stars_last_line = stars_this_line;
289 this_line = ftell(pfp);
292 if (pgets(false) == 0) {
293 if (first_command_line >= 0L) {
294 /* nothing but deletes!? */
295 p_start = first_command_line;
301 p_sline = p_input_line;
306 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
308 indent += 8 - (indent % 8);
312 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
314 this_is_a_command = (isdigit((unsigned char)*s) &&
315 (*t == 'd' || *t == 'c' || *t == 'a'));
316 if (first_command_line < 0L && this_is_a_command) {
317 first_command_line = this_line;
318 fcl_line = p_input_line;
319 p_indent = indent; /* assume this for now */
321 if (!stars_last_line && strnEQ(s, "*** ", 4))
322 names[OLD_FILE].path = fetchname(s + 4,
323 &names[OLD_FILE].exists, strippath);
324 else if (strnEQ(s, "--- ", 4))
325 names[NEW_FILE].path = fetchname(s + 4,
326 &names[NEW_FILE].exists, strippath);
327 else if (strnEQ(s, "+++ ", 4))
328 /* pretend it is the old name */
329 names[OLD_FILE].path = fetchname(s + 4,
330 &names[OLD_FILE].exists, strippath);
331 else if (strnEQ(s, "Index:", 6))
332 names[INDEX_FILE].path = fetchname(s + 6,
333 &names[INDEX_FILE].exists, strippath);
334 else if (strnEQ(s, "Prereq:", 7)) {
335 for (t = s + 7; isspace((unsigned char)*t); t++)
337 revision = savestr(t);
338 for (t = revision; *t && !isspace((unsigned char)*t); t++)
341 if (*revision == '\0') {
345 } else if (strnEQ(s, "==== ", 5)) {
346 /* Perforce-style diffs. */
347 if ((t = strstr(s + 5, " - ")) != NULL)
348 p4_fetchname(&names[NEW_FILE], t + 3);
349 p4_fetchname(&names[OLD_FILE], s + 5);
351 if ((!diff_type || diff_type == ED_DIFF) &&
352 first_command_line >= 0L &&
355 p_start = first_command_line;
360 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
361 if (strnEQ(s + 4, "0,0", 3))
362 ok_to_create_file = true;
365 p_sline = p_input_line;
369 stars_this_line = strnEQ(s, "********", 8);
370 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
371 strnEQ(s, "*** ", 4)) {
372 if (atol(s + 4) == 0)
373 ok_to_create_file = true;
375 * If this is a new context diff the character just
376 * before the newline is a '*'.
381 p_start = previous_line;
382 p_sline = p_input_line - 1;
383 retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
386 if ((!diff_type || diff_type == NORMAL_DIFF) &&
387 last_line_was_command &&
388 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
389 p_start = previous_line;
390 p_sline = p_input_line - 1;
392 retval = NORMAL_DIFF;
397 if (retval == UNI_DIFF) {
398 /* unswap old and new */
399 struct file_name tmp = names[OLD_FILE];
400 names[OLD_FILE] = names[NEW_FILE];
401 names[NEW_FILE] = tmp;
403 if (filearg[0] == NULL) {
405 filearg[0] = posix_name(names, ok_to_create_file);
407 /* Ignore the Index: name for context diffs, like GNU */
408 if (names[OLD_FILE].path != NULL ||
409 names[NEW_FILE].path != NULL) {
410 free(names[INDEX_FILE].path);
411 names[INDEX_FILE].path = NULL;
413 filearg[0] = best_name(names, ok_to_create_file);
419 if (filearg[0] != NULL)
420 bestguess = savestr(filearg[0]);
421 else if (!ok_to_create_file) {
423 * We don't want to create a new file but we need a
424 * filename to set bestguess. Avoid setting filearg[0]
425 * so the file is not created automatically.
428 bestguess = posix_name(names, true);
430 bestguess = best_name(names, true);
432 free(names[OLD_FILE].path);
433 free(names[NEW_FILE].path);
434 free(names[INDEX_FILE].path);
439 * Remember where this patch ends so we know where to start up again.
442 next_intuit_at(LINENUM file_pos, LINENUM file_line)
449 * Basically a verbose fseek() to the actual diff listing.
452 skip_to(LINENUM file_pos, LINENUM file_line)
456 if (p_base > file_pos)
457 fatal("Internal error: seek %ld>%ld\n", p_base, file_pos);
458 if (verbose && p_base < file_pos) {
459 fseek(pfp, p_base, SEEK_SET);
460 say("The text leading up to this was:\n--------------------------\n");
461 while (ftell(pfp) < file_pos) {
464 fatal("Unexpected end of file\n");
467 say("--------------------------\n");
469 fseek(pfp, file_pos, SEEK_SET);
470 p_input_line = file_line - 1;
473 /* Make this a function for better debugging. */
477 fatal("malformed patch at line %ld: %s", p_input_line, buf);
478 /* about as informative as "Syntax error" in C */
482 * True if the line has been discarded (i.e. it is a line saying
483 * "\ No newline at end of file".)
486 remove_special_line(void)
494 } while (c != EOF && c != '\n');
499 fseek(pfp, -1L, SEEK_CUR);
505 * True if there is more of the current diff listing to process.
510 long line_beginning; /* file pos of the current line */
511 LINENUM repl_beginning; /* index of --- line */
512 LINENUM fillcnt; /* #lines of missing ptrn or repl */
513 LINENUM fillsrc; /* index of first line to copy */
514 LINENUM filldst; /* index of first missing line */
515 bool ptrn_spaces_eaten; /* ptrn was slightly misformed */
516 bool repl_could_be_missing; /* no + or ! lines in this hunk */
517 bool repl_missing; /* we are now backtracking */
518 long repl_backtrack_position; /* file pos of first repl line */
519 LINENUM repl_patch_line; /* input line number for same */
520 LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
526 if (p_end == p_efake)
527 p_end = p_bfake; /* don't free twice */
534 p_max = hunkmax; /* gets reduced when --- found */
535 if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
536 line_beginning = ftell(pfp);
541 ptrn_spaces_eaten = false;
542 repl_could_be_missing = true;
543 repl_missing = false;
544 repl_backtrack_position = 0;
550 if (len == 0 || strnNE(buf, "********", 8)) {
551 next_intuit_at(line_beginning, p_input_line);
555 p_hunk_beg = p_input_line + 1;
556 while (p_end < p_max) {
557 line_beginning = ftell(pfp);
561 if (p_max - p_end < 4) {
562 /* assume blank lines got chopped */
563 strlcpy(buf, " \n", buf_size);
565 if (repl_beginning && repl_could_be_missing) {
569 fatal("unexpected end of file in patch\n");
573 if (p_end >= hunkmax)
574 fatal("Internal error: hunk larger than hunk "
576 p_char[p_end] = *buf;
577 p_line[p_end] = NULL;
580 if (strnEQ(buf, "********", 8)) {
581 if (repl_beginning && repl_could_be_missing) {
585 fatal("unexpected end of hunk "
590 if (repl_beginning && repl_could_be_missing) {
594 fatal("unexpected *** at line %ld: %s",
598 p_line[p_end] = savestr(buf);
603 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
607 if (strnEQ(s, "0,0", 3))
608 memmove(s, s + 2, strlen(s + 2) + 1);
609 p_first = (LINENUM) atol(s);
610 while (isdigit((unsigned char)*s))
613 for (; *s && !isdigit((unsigned char)*s); s++)
617 p_ptrn_lines = ((LINENUM) atol(s)) - p_first + 1;
625 /* we need this much at least */
626 p_max = p_ptrn_lines + 6;
627 while (p_max >= hunkmax)
633 if (repl_beginning ||
634 (p_end != p_ptrn_lines + 1 +
635 (p_char[p_end - 1] == '\n'))) {
638 * `old' lines were omitted;
639 * set up to fill them in
640 * from 'new' context lines.
642 p_end = p_ptrn_lines + 1;
645 fillcnt = p_ptrn_lines;
647 if (repl_beginning) {
648 if (repl_could_be_missing) {
652 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
653 p_input_line, p_hunk_beg + repl_beginning);
655 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
656 (p_end <= p_ptrn_lines
659 p_input_line, p_hunk_beg);
663 repl_beginning = p_end;
664 repl_backtrack_position = ftell(pfp);
665 repl_patch_line = p_input_line;
666 p_line[p_end] = savestr(buf);
672 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
676 p_newfirst = (LINENUM) atol(s);
677 while (isdigit((unsigned char)*s))
680 for (; *s && !isdigit((unsigned char)*s); s++)
684 p_repl_lines = ((LINENUM) atol(s)) -
686 } else if (p_newfirst)
692 p_max = p_repl_lines + p_end;
693 if (p_max > MAXHUNKSIZE)
694 fatal("hunk too large (%ld lines) at line %ld: %s",
695 p_max, p_input_line, buf);
696 while (p_max >= hunkmax)
698 if (p_repl_lines != ptrn_copiable &&
699 (p_context != 0 || p_repl_lines != 1))
700 repl_could_be_missing = false;
706 repl_could_be_missing = false;
708 if (buf[1] == '\n' && canonicalize)
709 strlcpy(buf + 1, " \n", buf_size - 1);
710 if (!isspace((unsigned char)buf[1]) && buf[1] != '>' &&
712 repl_beginning && repl_could_be_missing) {
717 if (context < p_context)
721 p_line[p_end] = savestr(buf + 2);
726 if (p_end == p_ptrn_lines) {
727 if (remove_special_line()) {
730 l = strlen(p_line[p_end]) - 1;
731 (p_line[p_end])[l] = 0;
736 case '\n': /* assume the 2 spaces got eaten */
737 if (repl_beginning && repl_could_be_missing &&
738 (!ptrn_spaces_eaten ||
739 diff_type == NEW_CONTEXT_DIFF)) {
743 p_line[p_end] = savestr(buf);
748 if (p_end != p_ptrn_lines + 1) {
749 ptrn_spaces_eaten |= (repl_beginning != 0);
757 if (!isspace((unsigned char)buf[1]) &&
758 repl_beginning && repl_could_be_missing) {
765 p_line[p_end] = savestr(buf + 2);
772 if (repl_beginning && repl_could_be_missing) {
778 /* set up p_len for strncmp() so we don't have to */
779 /* assume null termination */
781 p_len[p_end] = strlen(p_line[p_end]);
787 if (p_end >= 0 && !repl_beginning)
788 fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
792 /* reset state back to just after --- */
793 p_input_line = repl_patch_line;
794 for (p_end--; p_end > repl_beginning; p_end--)
796 fseek(pfp, repl_backtrack_position, SEEK_SET);
798 /* redundant 'new' context lines were omitted - set */
799 /* up to fill them in from the old file context */
800 if (!p_context && p_repl_lines == 1) {
805 filldst = repl_beginning + 1;
806 fillcnt = p_repl_lines;
808 } else if (!p_context && fillcnt == 1) {
809 /* the first hunk was a null hunk with no context */
810 /* and we were expecting one line -- fix it up. */
811 while (filldst < p_end) {
812 p_line[filldst] = p_line[filldst + 1];
813 p_char[filldst] = p_char[filldst + 1];
814 p_len[filldst] = p_len[filldst + 1];
818 repl_beginning--; /* this doesn't need to be fixed */
821 p_first++; /* do append rather than insert */
825 if (diff_type == CONTEXT_DIFF &&
826 (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
829 "(Fascinating--this is really a new-style context diff but without",
830 "the telltale extra asterisks on the *** line that usually indicate",
831 "the new style...)");
832 diff_type = NEW_CONTEXT_DIFF;
834 /* if there were omitted context lines, fill them in now */
836 p_bfake = filldst; /* remember where not to free() */
837 p_efake = filldst + fillcnt - 1;
838 while (fillcnt-- > 0) {
839 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
842 fatal("replacement text or line numbers mangled in hunk at line %ld\n",
844 p_line[filldst] = p_line[fillsrc];
845 p_char[filldst] = p_char[fillsrc];
846 p_len[filldst] = p_len[fillsrc];
850 while (fillsrc <= p_end && fillsrc != repl_beginning &&
851 p_char[fillsrc] != ' ')
855 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
856 fillsrc, filldst, repl_beginning, p_end + 1);
858 if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
860 if (filldst != p_end + 1 && filldst != repl_beginning)
863 if (p_line[p_end] != NULL) {
864 if (remove_special_line()) {
866 (p_line[p_end])[p_len[p_end]] = 0;
869 } else if (diff_type == UNI_DIFF) {
870 LINENUM fillold; /* index of old lines */
871 LINENUM fillnew; /* index of new lines */
874 line_beginning = ftell(pfp); /* file pos of the current line */
877 if (len == 0 || strnNE(buf, "@@ -", 4)) {
878 next_intuit_at(line_beginning, p_input_line);
884 p_first = (LINENUM) atol(s);
885 while (isdigit((unsigned char)*s))
888 p_ptrn_lines = (LINENUM) atol(++s);
889 while (isdigit((unsigned char)*s))
895 if (*s != '+' || !*++s)
897 p_newfirst = (LINENUM) atol(s);
898 while (isdigit((unsigned char)*s))
901 p_repl_lines = (LINENUM) atol(++s);
902 while (isdigit((unsigned char)*s))
911 p_first++; /* do append rather than insert */
912 p_max = p_ptrn_lines + p_repl_lines + 1;
913 while (p_max >= hunkmax)
916 fillnew = fillold + p_ptrn_lines;
917 p_end = fillnew + p_repl_lines;
918 snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
919 p_first + p_ptrn_lines - 1);
920 p_line[0] = savestr(buf);
926 snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
927 p_newfirst + p_repl_lines - 1);
928 p_line[fillnew] = savestr(buf);
933 p_char[fillnew++] = '=';
936 p_hunk_beg = p_input_line + 1;
937 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
938 line_beginning = ftell(pfp);
942 if (p_max - fillnew < 3) {
943 /* assume blank lines got chopped */
944 strlcpy(buf, " \n", buf_size);
946 fatal("unexpected end of file in patch\n");
949 if (*buf == '\t' || *buf == '\n') {
950 ch = ' '; /* assume the space got eaten */
954 s = savestr(buf + 1);
957 while (--fillnew > p_ptrn_lines)
958 free(p_line[fillnew]);
964 if (fillold > p_ptrn_lines) {
969 p_char[fillold] = ch;
971 p_len[fillold++] = strlen(s);
972 if (fillold > p_ptrn_lines) {
973 if (remove_special_line()) {
974 p_len[fillold - 1] -= 1;
975 s[p_len[fillold - 1]] = 0;
983 if (fillold > p_ptrn_lines) {
985 while (--fillnew > p_ptrn_lines)
986 free(p_line[fillnew]);
991 p_char[fillold] = ch;
993 p_len[fillold++] = strlen(s);
996 while (--fillnew > p_ptrn_lines)
997 free(p_line[fillnew]);
1001 if (fillold > p_ptrn_lines) {
1002 if (remove_special_line()) {
1003 p_len[fillold - 1] -= 1;
1004 s[p_len[fillold - 1]] = 0;
1009 if (fillnew > p_end) {
1011 while (--fillnew > p_ptrn_lines)
1012 free(p_line[fillnew]);
1013 p_end = fillold - 1;
1016 p_char[fillnew] = ch;
1017 p_line[fillnew] = s;
1018 p_len[fillnew++] = strlen(s);
1019 if (fillold > p_ptrn_lines) {
1020 if (remove_special_line()) {
1021 p_len[fillnew - 1] -= 1;
1022 s[p_len[fillnew - 1]] = 0;
1030 if (ch != ' ' && context > 0) {
1031 if (context < p_context)
1032 p_context = context;
1036 } else { /* normal diff--fake it up */
1041 line_beginning = ftell(pfp);
1045 if (len == 0 || !isdigit((unsigned char)*buf)) {
1046 next_intuit_at(line_beginning, p_input_line);
1049 p_first = (LINENUM) atol(buf);
1050 for (s = buf; isdigit((unsigned char)*s); s++)
1053 p_ptrn_lines = (LINENUM) atol(++s) - p_first + 1;
1054 while (isdigit((unsigned char)*s))
1057 p_ptrn_lines = (*s != 'a');
1059 if (hunk_type == 'a')
1060 p_first++; /* do append rather than insert */
1061 min = (LINENUM) atol(++s);
1062 for (; isdigit((unsigned char)*s); s++)
1065 max = (LINENUM) atol(++s);
1068 if (hunk_type == 'd')
1070 p_end = p_ptrn_lines + 1 + max - min + 1;
1071 if (p_end > MAXHUNKSIZE)
1072 fatal("hunk too large (%ld lines) at line %ld: %s",
1073 p_end, p_input_line, buf);
1074 while (p_end >= hunkmax)
1077 p_repl_lines = max - min + 1;
1078 snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1079 p_first + p_ptrn_lines - 1);
1080 p_line[0] = savestr(buf);
1086 for (i = 1; i <= p_ptrn_lines; i++) {
1090 fatal("unexpected end of file in patch at line %ld\n",
1093 fatal("< expected at line %ld of patch\n",
1095 p_line[i] = savestr(buf + 2);
1100 p_len[i] = strlen(p_line[i]);
1104 if (remove_special_line()) {
1106 (p_line[i - 1])[p_len[i - 1]] = 0;
1108 if (hunk_type == 'c') {
1112 fatal("unexpected end of file in patch at line %ld\n",
1115 fatal("--- expected at line %ld of patch\n",
1118 snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1119 p_line[i] = savestr(buf);
1125 for (i++; i <= p_end; i++) {
1129 fatal("unexpected end of file in patch at line %ld\n",
1132 fatal("> expected at line %ld of patch\n",
1134 p_line[i] = savestr(buf + 2);
1139 p_len[i] = strlen(p_line[i]);
1143 if (remove_special_line()) {
1145 (p_line[i - 1])[p_len[i - 1]] = 0;
1148 if (reverse) /* backwards patch? */
1150 say("Not enough memory to swap next hunk!\n");
1156 for (i = 0; i <= p_end; i++) {
1157 if (i == p_ptrn_lines)
1161 fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1162 special, p_line[i]);
1167 if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1168 p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
1173 * Input a line from the patch file.
1174 * Worry about indentation if do_indent is true.
1175 * The line is read directly into the buf global variable which
1176 * is resized if necessary in order to hold the complete line.
1177 * Returns the number of characters read including the terminating
1181 pgets(bool do_indent)
1185 int indent = 0, skipped = 0;
1187 line = fgetln(pfp, &len);
1189 if (len + 1 > buf_size) {
1190 while (len + 1 > buf_size)
1193 buf = malloc(buf_size);
1195 fatal("out of memory\n");
1197 if (do_indent == 1 && p_indent) {
1199 indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1200 line++, skipped++) {
1202 indent += 8 - (indent %7);
1207 memcpy(buf, line, len - skipped);
1208 buf[len - skipped] = '\0';
1215 * Reverse the old and new portions of the current hunk.
1220 char **tp_line; /* the text of the hunk */
1221 short *tp_len; /* length of each line */
1222 char *tp_char; /* +, -, and ! */
1225 bool blankline = false;
1229 p_first = p_newfirst;
1232 /* make a scratch copy */
1237 p_line = NULL; /* force set_hunkmax to allocate again */
1241 if (p_line == NULL || p_len == NULL || p_char == NULL) {
1249 return false; /* not enough memory to swap hunk! */
1251 /* now turn the new into the old */
1253 i = p_ptrn_lines + 1;
1254 if (tp_char[i] == '\n') { /* account for possible blank line */
1258 if (p_efake >= 0) { /* fix non-freeable ptr range */
1266 for (n = 0; i <= p_end; i++, n++) {
1267 p_line[n] = tp_line[i];
1268 p_char[n] = tp_char[i];
1269 if (p_char[n] == '+')
1271 p_len[n] = tp_len[i];
1274 i = p_ptrn_lines + 1;
1275 p_line[n] = tp_line[i];
1276 p_char[n] = tp_char[i];
1277 p_len[n] = tp_len[i];
1280 if (p_char[0] != '=')
1281 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1282 p_input_line, p_char[0]);
1284 for (s = p_line[0]; *s; s++)
1288 /* now turn the old into the new */
1290 if (p_char[0] != '*')
1291 fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1292 p_input_line, p_char[0]);
1294 for (s = tp_line[0]; *s; s++)
1297 for (i = 0; n <= p_end; i++, n++) {
1298 p_line[n] = tp_line[i];
1299 p_char[n] = tp_char[i];
1300 if (p_char[n] == '-')
1302 p_len[n] = tp_len[i];
1305 if (i != p_ptrn_lines + 1)
1306 fatal("Malformed patch at line %ld: expected %ld lines, "
1308 p_input_line, p_ptrn_lines + 1, i);
1311 p_ptrn_lines = p_repl_lines;
1322 * Return the specified line position in the old file of the old context.
1331 * Return the number of lines of old context.
1334 pch_ptrn_lines(void)
1336 return p_ptrn_lines;
1340 * Return the probable line position in the new file of the first line.
1349 * Return the number of lines in the replacement text including context.
1352 pch_repl_lines(void)
1354 return p_repl_lines;
1358 * Return the number of lines in the whole hunk.
1367 * Return the number of context lines before the first changed line.
1376 * Return the length of a particular patch line.
1379 pch_line_len(LINENUM line)
1385 * Return the control character (+, -, *, !, etc) for a patch line.
1388 pch_char(LINENUM line)
1390 return p_char[line];
1394 * Return a pointer to a particular patch line.
1397 pfetch(LINENUM line)
1399 return p_line[line];
1403 * Return where in the patch file this hunk began, for error messages.
1412 * Apply an ed script by feeding ed itself.
1418 long beginning_of_this_line;
1419 FILE *pipefp = NULL;
1421 if (!skip_rest_of_patch) {
1422 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1424 fatal("can't create temp file %s", TMPOUTNAME);
1426 snprintf(buf, buf_size, "%s%s%s", _PATH_ED,
1427 verbose ? " " : " -s ", TMPOUTNAME);
1428 pipefp = popen(buf, "w");
1431 beginning_of_this_line = ftell(pfp);
1432 if (pgets(true) == 0) {
1433 next_intuit_at(beginning_of_this_line, p_input_line);
1437 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1439 /* POSIX defines allowed commands as {a,c,d,i,s} */
1440 if (isdigit((unsigned char)*buf) && (*t == 'a' || *t == 'c' ||
1441 *t == 'd' || *t == 'i' || *t == 's')) {
1445 while (pgets(true)) {
1449 if (strEQ(buf, ".\n"))
1454 next_intuit_at(beginning_of_this_line, p_input_line);
1460 fprintf(pipefp, "w\n");
1461 fprintf(pipefp, "q\n");
1466 if (move_file(TMPOUTNAME, outname) < 0) {
1468 chmod(TMPOUTNAME, filemode);
1470 chmod(outname, filemode);
1476 * Choose the name of the file to be patched based on POSIX rules.
1477 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1478 * if the user specified --posix or set POSIXLY_CORRECT.
1481 posix_name(const struct file_name *names, bool assume_exists)
1487 * POSIX states that the filename will be chosen from one
1488 * of the old, new and index names (in that order) if
1489 * the file exists relative to CWD after -p stripping.
1491 for (i = 0; i < MAX_FILE; i++) {
1492 if (names[i].path != NULL && names[i].exists) {
1493 path = names[i].path;
1497 if (path == NULL && !assume_exists) {
1499 * No files found, look for something we can checkout from
1500 * RCS/SCCS dirs. Same order as above.
1502 for (i = 0; i < MAX_FILE; i++) {
1503 if (names[i].path != NULL &&
1504 (path = checked_in(names[i].path)) != NULL)
1508 * Still no match? Check to see if the diff could be creating
1511 if (path == NULL && ok_to_create_file &&
1512 names[NEW_FILE].path != NULL)
1513 path = names[NEW_FILE].path;
1516 return path ? savestr(path) : NULL;
1520 compare_names(const struct file_name *names, bool assume_exists, int phase)
1522 size_t min_components, min_baselen, min_len, tmp;
1528 * The "best" name is the one with the fewest number of path
1529 * components, the shortest basename length, and the shortest
1530 * overall length (in that order). We only use the Index: file
1531 * if neither of the old or new files could be intuited from
1534 min_components = min_baselen = min_len = SIZE_MAX;
1535 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1536 path = names[i].path;
1538 (phase == 1 && !names[i].exists && !assume_exists) ||
1539 (phase == 2 && checked_in(path) == NULL))
1541 if ((tmp = num_components(path)) > min_components)
1543 if (tmp < min_components) {
1544 min_components = tmp;
1547 if ((tmp = strlen(basename(path))) > min_baselen)
1549 if (tmp < min_baselen) {
1553 if ((tmp = strlen(path)) > min_len)
1562 * Choose the name of the file to be patched based the "best" one
1566 best_name(const struct file_name *names, bool assume_exists)
1570 best = compare_names(names, assume_exists, 1);
1572 best = compare_names(names, assume_exists, 2);
1574 * Still no match? Check to see if the diff could be creating
1577 if (best == NULL && ok_to_create_file &&
1578 names[NEW_FILE].path != NULL)
1579 best = names[NEW_FILE].path;
1582 return best ? savestr(best) : NULL;
1586 num_components(const char *path)
1591 for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1593 cp++; /* skip consecutive slashes */