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.43 2014/11/18 17:03:35 tobias Exp $
31 #include <sys/types.h>
46 #include "pathnames.h"
48 /* Patch (diff listing) abstract type. */
50 static off_t p_filesize; /* size of the patch file */
51 static LINENUM p_first; /* 1st line number */
52 static LINENUM p_newfirst; /* 1st line number of replacement */
53 static LINENUM p_ptrn_lines; /* # lines in pattern */
54 static LINENUM p_repl_lines; /* # lines in replacement text */
55 static LINENUM p_end = -1; /* last line in hunk */
56 static LINENUM p_max; /* max allowed value of p_end */
57 static LINENUM p_context = 3; /* # of context lines */
58 static LINENUM p_input_line = 0; /* current line # from patch file */
59 static char **p_line = NULL;/* the text of the hunk */
60 static unsigned short *p_len = NULL; /* length of each line */
61 static char *p_char = NULL; /* +, -, and ! */
62 static int hunkmax = INITHUNKMAX; /* size of above arrays to begin with */
63 static int p_indent; /* indent to patch */
64 static off_t p_base; /* where to intuit this time */
65 static LINENUM p_bline; /* line # of p_base */
66 static off_t p_start; /* where intuit found a patch */
67 static LINENUM p_sline; /* and the line number for it */
68 static LINENUM p_hunk_beg; /* line number of current hunk */
69 static LINENUM p_efake = -1; /* end of faked up lines--don't free */
70 static LINENUM p_bfake = -1; /* beg of faked up lines */
71 static FILE *pfp = NULL; /* patch file pointer */
72 static char *bestguess = NULL; /* guess at correct filename */
74 static void grow_hunkmax(void);
75 static int intuit_diff_type(void);
76 static void next_intuit_at(off_t, LINENUM);
77 static void skip_to(off_t, LINENUM);
78 static size_t pgets(bool _do_indent);
79 static char *best_name(const struct file_name *, bool);
80 static char *posix_name(const struct file_name *, bool);
81 static size_t num_components(const char *);
82 static LINENUM strtolinenum(char *, char **);
85 * Prepare to look for the next patch in the patch file.
94 p_end = (LINENUM) - 1;
100 * Open the patch file at the beginning of time.
103 open_patch_file(const char *filename)
105 struct stat filestat;
108 if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
109 pfp = fopen(TMPPATNAME, "w");
111 pfatal("can't create %s", TMPPATNAME);
112 while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
113 nw = fwrite(buf, 1, nr, pfp);
115 pfatal("write error to %s", TMPPATNAME);
117 if (ferror(pfp) || fclose(pfp))
118 pfatal("can't write %s", TMPPATNAME);
119 filename = TMPPATNAME;
121 pfp = fopen(filename, "r");
123 pfatal("patch file %s not found", filename);
124 if (fstat(fileno(pfp), &filestat))
125 pfatal("can't stat %s", filename);
126 p_filesize = filestat.st_size;
127 next_intuit_at(0, 1L); /* start at the beginning */
132 * Make sure our dynamically realloced tables are malloced to begin with.
138 p_line = malloc(hunkmax * sizeof(char *));
140 p_len = malloc(hunkmax * sizeof(unsigned short));
142 p_char = malloc(hunkmax * sizeof(char));
146 * Enlarge the arrays containing the current hunk of patch.
151 int new_hunkmax = hunkmax * 2;
153 if (p_line == NULL || p_len == NULL || p_char == NULL)
154 fatal("Internal memory allocation error\n");
156 p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
157 p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
158 p_char = reallocf(p_char, new_hunkmax * sizeof(char));
160 if (p_line != NULL && p_len != NULL && p_char != NULL) {
161 hunkmax = new_hunkmax;
166 fatal("out of memory\n");
167 out_of_mem = true; /* whatever is null will be allocated again */
168 /* from within plan_a(), of all places */
171 /* True if the remainder of the patch file contains a diff of some sort. */
174 there_is_another_patch(void)
178 if (p_base != 0 && p_base >= p_filesize) {
185 diff_type = intuit_diff_type();
189 say(" Ignoring the trailing garbage.\ndone\n");
191 say(" I can't seem to find a patch in there anywhere.\n");
195 say(" %sooks like %s to me...\n",
196 (p_base == 0 ? "L" : "The next patch l"),
197 diff_type == UNI_DIFF ? "a unified diff" :
198 diff_type == CONTEXT_DIFF ? "a context diff" :
199 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
200 diff_type == NORMAL_DIFF ? "a normal diff" :
202 if (p_indent && verbose)
203 say("(Patch is indented %d space%s.)\n", p_indent,
204 p_indent == 1 ? "" : "s");
205 skip_to(p_start, p_sline);
206 while (filearg[0] == NULL) {
207 if (force || batch) {
208 say("No file to patch. Skipping...\n");
209 filearg[0] = xstrdup(bestguess);
210 skip_rest_of_patch = true;
213 ask("File to patch: ");
216 bestguess = xstrdup(buf);
217 filearg[0] = fetchname(buf, &exists, 0);
220 ask("No file found--skip this patch? [n] ");
224 say("Skipping patch...\n");
226 filearg[0] = fetchname(bestguess, &exists, 0);
227 skip_rest_of_patch = true;
235 p4_fetchname(struct file_name *name, char *str)
239 /* Skip leading whitespace. */
240 while (isspace((unsigned char)*str))
243 /* Remove the file revision number. */
244 for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
250 name->path = fetchname(str, &name->exists, strippath);
253 /* Determine what kind of diff is in the remaining part of the patch file. */
256 intuit_diff_type(void)
258 off_t this_line = 0, previous_line;
259 off_t first_command_line = -1;
260 LINENUM fcl_line = -1;
261 bool last_line_was_command = false, this_is_a_command = false;
262 bool stars_last_line = false, stars_this_line = false;
265 struct file_name names[MAX_FILE];
267 memset(names, 0, sizeof(names));
268 ok_to_create_file = false;
269 fseeko(pfp, p_base, SEEK_SET);
270 p_input_line = p_bline - 1;
272 previous_line = this_line;
273 last_line_was_command = this_is_a_command;
274 stars_last_line = stars_this_line;
275 this_line = ftello(pfp);
278 if (pgets(false) == 0) {
279 if (first_command_line >= 0) {
280 /* nothing but deletes!? */
281 p_start = first_command_line;
287 p_sline = p_input_line;
292 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
294 indent += 8 - (indent % 8);
298 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
300 this_is_a_command = (isdigit((unsigned char)*s) &&
301 (*t == 'd' || *t == 'c' || *t == 'a'));
302 if (first_command_line < 0 && this_is_a_command) {
303 first_command_line = this_line;
304 fcl_line = p_input_line;
305 p_indent = indent; /* assume this for now */
307 if (!stars_last_line && strnEQ(s, "*** ", 4))
308 names[OLD_FILE].path = fetchname(s + 4,
309 &names[OLD_FILE].exists, strippath);
310 else if (strnEQ(s, "--- ", 4))
311 names[NEW_FILE].path = fetchname(s + 4,
312 &names[NEW_FILE].exists, strippath);
313 else if (strnEQ(s, "+++ ", 4))
314 /* pretend it is the old name */
315 names[OLD_FILE].path = fetchname(s + 4,
316 &names[OLD_FILE].exists, strippath);
317 else if (strnEQ(s, "Index:", 6))
318 names[INDEX_FILE].path = fetchname(s + 6,
319 &names[INDEX_FILE].exists, strippath);
320 else if (strnEQ(s, "Prereq:", 7)) {
321 for (t = s + 7; isspace((unsigned char)*t); t++)
323 revision = xstrdup(t);
325 *t && !isspace((unsigned char)*t); t++)
328 if (*revision == '\0') {
332 } else if (strnEQ(s, "==== ", 5)) {
333 /* Perforce-style diffs. */
334 if ((t = strstr(s + 5, " - ")) != NULL)
335 p4_fetchname(&names[NEW_FILE], t + 3);
336 p4_fetchname(&names[OLD_FILE], s + 5);
338 if ((!diff_type || diff_type == ED_DIFF) &&
339 first_command_line >= 0 &&
342 p_start = first_command_line;
347 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
348 if (strnEQ(s + 4, "0,0", 3))
349 ok_to_create_file = true;
352 p_sline = p_input_line;
356 stars_this_line = strnEQ(s, "********", 8);
357 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
358 strnEQ(s, "*** ", 4)) {
359 if (strtolinenum(s + 4, &s) == 0)
360 ok_to_create_file = true;
362 * If this is a new context diff the character just
363 * at the end of the line is a '*'.
365 while (*s && *s != '\n')
368 p_start = previous_line;
369 p_sline = p_input_line - 1;
370 retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
373 if ((!diff_type || diff_type == NORMAL_DIFF) &&
374 last_line_was_command &&
375 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
376 p_start = previous_line;
377 p_sline = p_input_line - 1;
379 retval = NORMAL_DIFF;
384 if (retval == UNI_DIFF) {
385 /* unswap old and new */
386 struct file_name tmp = names[OLD_FILE];
387 names[OLD_FILE] = names[NEW_FILE];
388 names[NEW_FILE] = tmp;
390 if (filearg[0] == NULL) {
392 filearg[0] = posix_name(names, ok_to_create_file);
394 /* Ignore the Index: name for context diffs, like GNU */
395 if (names[OLD_FILE].path != NULL ||
396 names[NEW_FILE].path != NULL) {
397 free(names[INDEX_FILE].path);
398 names[INDEX_FILE].path = NULL;
400 filearg[0] = best_name(names, ok_to_create_file);
406 if (filearg[0] != NULL)
407 bestguess = xstrdup(filearg[0]);
408 else if (!ok_to_create_file) {
410 * We don't want to create a new file but we need a
411 * filename to set bestguess. Avoid setting filearg[0]
412 * so the file is not created automatically.
415 bestguess = posix_name(names, true);
417 bestguess = best_name(names, true);
419 free(names[OLD_FILE].path);
420 free(names[NEW_FILE].path);
421 free(names[INDEX_FILE].path);
426 * Remember where this patch ends so we know where to start up again.
429 next_intuit_at(off_t file_pos, LINENUM file_line)
436 * Basically a verbose fseeko() to the actual diff listing.
439 skip_to(off_t file_pos, LINENUM file_line)
443 if (p_base > file_pos)
444 fatal("Internal error: seek %lld>%lld\n",
445 (long long)p_base, (long long)file_pos);
446 if (verbose && p_base < file_pos) {
447 fseeko(pfp, p_base, SEEK_SET);
448 say("The text leading up to this was:\n--------------------------\n");
449 while (ftello(pfp) < file_pos) {
452 fatal("Unexpected end of file\n");
455 say("--------------------------\n");
457 fseeko(pfp, file_pos, SEEK_SET);
458 p_input_line = file_line - 1;
461 /* Make this a function for better debugging. */
465 fatal("malformed patch at line %ld: %s", p_input_line, buf);
466 /* about as informative as "Syntax error" in C */
470 * True if the line has been discarded (i.e. it is a line saying
471 * "\ No newline at end of file".)
474 remove_special_line(void)
482 } while (c != EOF && c != '\n');
487 fseeko(pfp, -1, SEEK_CUR);
493 * True if there is more of the current diff listing to process.
498 off_t line_beginning; /* file pos of the current line */
499 LINENUM repl_beginning; /* index of --- line */
500 LINENUM fillcnt; /* #lines of missing ptrn or repl */
501 LINENUM fillsrc; /* index of first line to copy */
502 LINENUM filldst; /* index of first missing line */
503 bool ptrn_spaces_eaten; /* ptrn was slightly misformed */
504 bool repl_could_be_missing; /* no + or ! lines in this hunk */
505 bool repl_missing; /* we are now backtracking */
506 off_t repl_backtrack_position; /* file pos of first repl line */
507 LINENUM repl_patch_line; /* input line number for same */
508 LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
514 if (p_end == p_efake)
515 p_end = p_bfake; /* don't free twice */
522 p_max = hunkmax; /* gets reduced when --- found */
523 if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
524 line_beginning = ftello(pfp);
529 ptrn_spaces_eaten = false;
530 repl_could_be_missing = true;
531 repl_missing = false;
532 repl_backtrack_position = 0;
538 if (len == 0 || strnNE(buf, "********", 8)) {
539 next_intuit_at(line_beginning, p_input_line);
543 p_hunk_beg = p_input_line + 1;
544 while (p_end < p_max) {
545 line_beginning = ftello(pfp);
549 if (p_max - p_end < 4) {
550 /* assume blank lines got chopped */
551 strlcpy(buf, " \n", buf_size);
553 if (repl_beginning && repl_could_be_missing) {
557 fatal("unexpected end of file in patch\n");
561 if (p_end >= hunkmax)
562 fatal("Internal error: hunk larger than hunk "
564 p_char[p_end] = *buf;
565 p_line[p_end] = NULL;
568 if (strnEQ(buf, "********", 8)) {
569 if (repl_beginning && repl_could_be_missing) {
573 fatal("unexpected end of hunk "
578 if (repl_beginning && repl_could_be_missing) {
582 fatal("unexpected *** at line %ld: %s",
586 p_line[p_end] = savestr(buf);
592 *s && !isdigit((unsigned char)*s); s++)
596 if (strnEQ(s, "0,0", 3))
597 memmove(s, s + 2, strlen(s + 2) + 1);
598 p_first = strtolinenum(s, &s);
601 *s && !isdigit((unsigned char)*s); s++)
605 p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
606 if (p_ptrn_lines < 0)
614 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
615 p_ptrn_lines >= LINENUM_MAX - 6)
618 /* we need this much at least */
619 p_max = p_ptrn_lines + 6;
620 while (p_max >= hunkmax)
626 if (repl_beginning ||
627 (p_end != p_ptrn_lines + 1 +
628 (p_char[p_end - 1] == '\n'))) {
631 * `old' lines were omitted;
632 * set up to fill them in
633 * from 'new' context lines.
635 p_end = p_ptrn_lines + 1;
638 fillcnt = p_ptrn_lines;
640 if (repl_beginning) {
641 if (repl_could_be_missing) {
645 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
646 p_input_line, p_hunk_beg + repl_beginning);
648 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
649 (p_end <= p_ptrn_lines
652 p_input_line, p_hunk_beg);
656 repl_beginning = p_end;
657 repl_backtrack_position = ftello(pfp);
658 repl_patch_line = p_input_line;
659 p_line[p_end] = savestr(buf);
665 for (s = buf; *s && !isdigit((unsigned char)*s); s++)
669 p_newfirst = strtolinenum(s, &s);
671 for (; *s && !isdigit((unsigned char)*s); s++)
675 p_repl_lines = strtolinenum(s, &s) -
677 if (p_repl_lines < 0)
679 } else if (p_newfirst)
685 if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
686 p_repl_lines >= LINENUM_MAX - p_end)
688 p_max = p_repl_lines + p_end;
689 if (p_max > MAXHUNKSIZE)
690 fatal("hunk too large (%ld lines) at line %ld: %s",
691 p_max, p_input_line, buf);
692 while (p_max >= hunkmax)
694 if (p_repl_lines != ptrn_copiable &&
695 (p_context != 0 || p_repl_lines != 1))
696 repl_could_be_missing = false;
702 repl_could_be_missing = false;
704 if (buf[1] == '\n' && canonicalize)
705 strlcpy(buf + 1, " \n", buf_size - 1);
706 if (!isspace((unsigned char)buf[1]) &&
707 buf[1] != '>' && buf[1] != '<' &&
708 repl_beginning && repl_could_be_missing) {
713 if (context < p_context)
717 p_line[p_end] = savestr(buf + 2);
722 if (p_end == p_ptrn_lines) {
723 if (remove_special_line()) {
726 l = strlen(p_line[p_end]) - 1;
727 (p_line[p_end])[l] = 0;
732 case '\n': /* assume the 2 spaces got eaten */
733 if (repl_beginning && repl_could_be_missing &&
734 (!ptrn_spaces_eaten ||
735 diff_type == NEW_CONTEXT_DIFF)) {
739 p_line[p_end] = savestr(buf);
744 if (p_end != p_ptrn_lines + 1) {
745 ptrn_spaces_eaten |= (repl_beginning != 0);
753 if (!isspace((unsigned char)buf[1]) &&
754 repl_beginning && repl_could_be_missing) {
761 p_line[p_end] = savestr(buf + 2);
768 if (repl_beginning && repl_could_be_missing) {
774 /* set up p_len for strncmp() so we don't have to */
775 /* assume null termination */
777 p_len[p_end] = strlen(p_line[p_end]);
783 if (p_end >= 0 && !repl_beginning)
784 fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
788 /* reset state back to just after --- */
789 p_input_line = repl_patch_line;
790 for (p_end--; p_end > repl_beginning; p_end--)
792 fseeko(pfp, repl_backtrack_position, SEEK_SET);
794 /* redundant 'new' context lines were omitted - set */
795 /* up to fill them in from the old file context */
796 if (!p_context && p_repl_lines == 1) {
801 filldst = repl_beginning + 1;
802 fillcnt = p_repl_lines;
804 } else if (!p_context && fillcnt == 1) {
805 /* the first hunk was a null hunk with no context */
806 /* and we were expecting one line -- fix it up. */
807 while (filldst < p_end) {
808 p_line[filldst] = p_line[filldst + 1];
809 p_char[filldst] = p_char[filldst + 1];
810 p_len[filldst] = p_len[filldst + 1];
814 repl_beginning--; /* this doesn't need to be fixed */
817 p_first++; /* do append rather than insert */
821 if (diff_type == CONTEXT_DIFF &&
822 (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
825 "(Fascinating--this is really a new-style context diff but without",
826 "the telltale extra asterisks on the *** line that usually indicate",
827 "the new style...)");
828 diff_type = NEW_CONTEXT_DIFF;
830 /* if there were omitted context lines, fill them in now */
832 p_bfake = filldst; /* remember where not to free() */
833 p_efake = filldst + fillcnt - 1;
834 while (fillcnt-- > 0) {
835 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
838 fatal("replacement text or line numbers mangled in hunk at line %ld\n",
840 p_line[filldst] = p_line[fillsrc];
841 p_char[filldst] = p_char[fillsrc];
842 p_len[filldst] = p_len[fillsrc];
846 while (fillsrc <= p_end && fillsrc != repl_beginning &&
847 p_char[fillsrc] != ' ')
851 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
852 fillsrc, filldst, repl_beginning, p_end + 1);
854 if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
856 if (filldst != p_end + 1 && filldst != repl_beginning)
859 if (p_line[p_end] != NULL) {
860 if (remove_special_line()) {
862 (p_line[p_end])[p_len[p_end]] = 0;
865 } else if (diff_type == UNI_DIFF) {
866 LINENUM fillold; /* index of old lines */
867 LINENUM fillnew; /* index of new lines */
870 line_beginning = ftello(pfp); /* file pos of the current line */
873 if (len == 0 || strnNE(buf, "@@ -", 4)) {
874 next_intuit_at(line_beginning, p_input_line);
880 p_first = strtolinenum(s, &s);
882 p_ptrn_lines = strtolinenum(s + 1, &s);
887 if (*s != '+' || !*++s)
889 p_newfirst = strtolinenum(s, &s);
891 p_repl_lines = strtolinenum(s + 1, &s);
898 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
899 p_newfirst > LINENUM_MAX - p_repl_lines ||
900 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
903 p_first++; /* do append rather than insert */
904 p_max = p_ptrn_lines + p_repl_lines + 1;
905 while (p_max >= hunkmax)
908 fillnew = fillold + p_ptrn_lines;
909 p_end = fillnew + p_repl_lines;
910 snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
911 p_first + p_ptrn_lines - 1);
912 p_line[0] = savestr(buf);
918 snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
919 p_newfirst + p_repl_lines - 1);
920 p_line[fillnew] = savestr(buf);
925 p_char[fillnew++] = '=';
928 p_hunk_beg = p_input_line + 1;
929 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
930 line_beginning = ftello(pfp);
934 if (p_max - fillnew < 3) {
935 /* assume blank lines got chopped */
936 strlcpy(buf, " \n", buf_size);
938 fatal("unexpected end of file in patch\n");
941 if (*buf == '\t' || *buf == '\n') {
942 ch = ' '; /* assume the space got eaten */
946 s = savestr(buf + 1);
949 while (--fillnew > p_ptrn_lines)
950 free(p_line[fillnew]);
956 if (fillold > p_ptrn_lines) {
961 p_char[fillold] = ch;
963 p_len[fillold++] = strlen(s);
964 if (fillold > p_ptrn_lines) {
965 if (remove_special_line()) {
966 p_len[fillold - 1] -= 1;
967 s[p_len[fillold - 1]] = 0;
975 if (fillold > p_ptrn_lines) {
977 while (--fillnew > p_ptrn_lines)
978 free(p_line[fillnew]);
983 p_char[fillold] = ch;
985 p_len[fillold++] = strlen(s);
988 while (--fillnew > p_ptrn_lines)
989 free(p_line[fillnew]);
993 if (fillold > p_ptrn_lines) {
994 if (remove_special_line()) {
995 p_len[fillold - 1] -= 1;
996 s[p_len[fillold - 1]] = 0;
1001 if (fillnew > p_end) {
1003 while (--fillnew > p_ptrn_lines)
1004 free(p_line[fillnew]);
1005 p_end = fillold - 1;
1008 p_char[fillnew] = ch;
1009 p_line[fillnew] = s;
1010 p_len[fillnew++] = strlen(s);
1011 if (fillold > p_ptrn_lines) {
1012 if (remove_special_line()) {
1013 p_len[fillnew - 1] -= 1;
1014 s[p_len[fillnew - 1]] = 0;
1022 if (ch != ' ' && context > 0) {
1023 if (context < p_context)
1024 p_context = context;
1028 } else { /* normal diff--fake it up */
1033 line_beginning = ftello(pfp);
1037 if (len == 0 || !isdigit((unsigned char)*buf)) {
1038 next_intuit_at(line_beginning, p_input_line);
1041 p_first = strtolinenum(buf, &s);
1043 p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1044 if (p_ptrn_lines < 0)
1047 p_ptrn_lines = (*s != 'a');
1049 if (hunk_type == 'a')
1050 p_first++; /* do append rather than insert */
1051 min = strtolinenum(s + 1, &s);
1053 max = strtolinenum(s + 1, &s);
1056 if (min < 0 || min > max || max - min == LINENUM_MAX)
1058 if (hunk_type == 'd')
1061 p_repl_lines = max - min + 1;
1062 if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1063 p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1065 p_end = p_ptrn_lines + p_repl_lines + 1;
1066 if (p_end > MAXHUNKSIZE)
1067 fatal("hunk too large (%ld lines) at line %ld: %s",
1068 p_end, p_input_line, buf);
1069 while (p_end >= hunkmax)
1071 snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1072 p_first + p_ptrn_lines - 1);
1073 p_line[0] = savestr(buf);
1079 for (i = 1; i <= p_ptrn_lines; i++) {
1083 fatal("unexpected end of file in patch at line %ld\n",
1086 fatal("< expected at line %ld of patch\n",
1088 p_line[i] = savestr(buf + 2);
1093 p_len[i] = strlen(p_line[i]);
1097 if (remove_special_line()) {
1099 (p_line[i - 1])[p_len[i - 1]] = 0;
1101 if (hunk_type == 'c') {
1105 fatal("unexpected end of file in patch at line %ld\n",
1108 fatal("--- expected at line %ld of patch\n",
1111 snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1112 p_line[i] = savestr(buf);
1118 for (i++; i <= p_end; i++) {
1122 fatal("unexpected end of file in patch at line %ld\n",
1125 fatal("> expected at line %ld of patch\n",
1127 p_line[i] = savestr(buf + 2);
1132 p_len[i] = strlen(p_line[i]);
1136 if (remove_special_line()) {
1138 (p_line[i - 1])[p_len[i - 1]] = 0;
1141 if (reverse) /* backwards patch? */
1143 say("Not enough memory to swap next hunk!\n");
1149 for (i = 0; i <= p_end; i++) {
1150 if (i == p_ptrn_lines)
1154 fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1155 special, p_line[i]);
1160 if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1161 p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
1166 * Input a line from the patch file.
1167 * Worry about indentation if do_indent is true.
1168 * The line is read directly into the buf global variable which
1169 * is resized if necessary in order to hold the complete line.
1170 * Returns the number of characters read including the terminating
1174 pgets(bool do_indent)
1178 int indent = 0, skipped = 0;
1180 line = fgetln(pfp, &len);
1182 if (len + 1 > buf_size) {
1183 while (len + 1 > buf_size)
1186 buf = malloc(buf_size);
1188 fatal("out of memory\n");
1190 if (do_indent == 1 && p_indent) {
1192 indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1193 line++, skipped++) {
1195 indent += 8 - (indent %7);
1200 memcpy(buf, line, len - skipped);
1201 buf[len - skipped] = '\0';
1208 * Reverse the old and new portions of the current hunk.
1213 char **tp_line; /* the text of the hunk */
1214 unsigned short *tp_len;/* length of each line */
1215 char *tp_char; /* +, -, and ! */
1218 bool blankline = false;
1222 p_first = p_newfirst;
1225 /* make a scratch copy */
1230 p_line = NULL; /* force set_hunkmax to allocate again */
1234 if (p_line == NULL || p_len == NULL || p_char == NULL) {
1242 return false; /* not enough memory to swap hunk! */
1244 /* now turn the new into the old */
1246 i = p_ptrn_lines + 1;
1247 if (tp_char[i] == '\n') { /* account for possible blank line */
1251 if (p_efake >= 0) { /* fix non-freeable ptr range */
1259 for (n = 0; i <= p_end; i++, n++) {
1260 p_line[n] = tp_line[i];
1261 p_char[n] = tp_char[i];
1262 if (p_char[n] == '+')
1264 p_len[n] = tp_len[i];
1267 i = p_ptrn_lines + 1;
1268 p_line[n] = tp_line[i];
1269 p_char[n] = tp_char[i];
1270 p_len[n] = tp_len[i];
1273 if (p_char[0] != '=')
1274 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1275 p_input_line, p_char[0]);
1277 for (s = p_line[0]; *s; s++)
1281 /* now turn the old into the new */
1283 if (p_char[0] != '*')
1284 fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1285 p_input_line, p_char[0]);
1287 for (s = tp_line[0]; *s; s++)
1290 for (i = 0; n <= p_end; i++, n++) {
1291 p_line[n] = tp_line[i];
1292 p_char[n] = tp_char[i];
1293 if (p_char[n] == '-')
1295 p_len[n] = tp_len[i];
1298 if (i != p_ptrn_lines + 1)
1299 fatal("Malformed patch at line %ld: expected %ld lines, "
1301 p_input_line, p_ptrn_lines + 1, i);
1304 p_ptrn_lines = p_repl_lines;
1315 * Return the specified line position in the old file of the old context.
1324 * Return the number of lines of old context.
1327 pch_ptrn_lines(void)
1329 return p_ptrn_lines;
1333 * Return the probable line position in the new file of the first line.
1342 * Return the number of lines in the replacement text including context.
1345 pch_repl_lines(void)
1347 return p_repl_lines;
1351 * Return the number of lines in the whole hunk.
1360 * Return the number of context lines before the first changed line.
1369 * Return the length of a particular patch line.
1372 pch_line_len(LINENUM line)
1378 * Return the control character (+, -, *, !, etc) for a patch line.
1381 pch_char(LINENUM line)
1383 return p_char[line];
1387 * Return a pointer to a particular patch line.
1390 pfetch(LINENUM line)
1392 return p_line[line];
1396 * Return where in the patch file this hunk began, for error messages.
1405 * Apply an ed script by feeding ed itself.
1411 off_t beginning_of_this_line;
1412 FILE *pipefp = NULL;
1414 if (!skip_rest_of_patch) {
1415 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1417 fatal("can't create temp file %s", TMPOUTNAME);
1419 snprintf(buf, buf_size, "%s%s%s", _PATH_ED,
1420 verbose ? " " : " -s ", TMPOUTNAME);
1421 pipefp = popen(buf, "w");
1424 beginning_of_this_line = ftello(pfp);
1425 if (pgets(true) == 0) {
1426 next_intuit_at(beginning_of_this_line, p_input_line);
1430 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1432 /* POSIX defines allowed commands as {a,c,d,i,s} */
1433 if (isdigit((unsigned char)*buf) &&
1434 (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1438 while (pgets(true)) {
1442 if (strEQ(buf, ".\n"))
1447 next_intuit_at(beginning_of_this_line, p_input_line);
1453 fprintf(pipefp, "w\n");
1454 fprintf(pipefp, "q\n");
1459 if (move_file(TMPOUTNAME, outname) < 0) {
1461 chmod(TMPOUTNAME, filemode);
1463 chmod(outname, filemode);
1469 * Choose the name of the file to be patched based on POSIX rules.
1470 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1471 * if the user specified --posix or set POSIXLY_CORRECT.
1474 posix_name(const struct file_name *names, bool assume_exists)
1480 * POSIX states that the filename will be chosen from one
1481 * of the old, new and index names (in that order) if
1482 * the file exists relative to CWD after -p stripping.
1484 for (i = 0; i < MAX_FILE; i++) {
1485 if (names[i].path != NULL && names[i].exists) {
1486 path = names[i].path;
1490 if (path == NULL && !assume_exists) {
1492 * No files found, look for something we can checkout from
1493 * RCS/SCCS dirs. Same order as above.
1495 for (i = 0; i < MAX_FILE; i++) {
1496 if (names[i].path != NULL &&
1497 (path = checked_in(names[i].path)) != NULL)
1501 * Still no match? Check to see if the diff could be creating
1504 if (path == NULL && ok_to_create_file &&
1505 names[NEW_FILE].path != NULL)
1506 path = names[NEW_FILE].path;
1509 return path ? xstrdup(path) : NULL;
1513 compare_names(const struct file_name *names, bool assume_exists, int phase)
1515 size_t min_components, min_baselen, min_len, tmp;
1521 * The "best" name is the one with the fewest number of path
1522 * components, the shortest basename length, and the shortest
1523 * overall length (in that order). We only use the Index: file
1524 * if neither of the old or new files could be intuited from
1527 min_components = min_baselen = min_len = SIZE_MAX;
1528 for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1529 path = names[i].path;
1531 (phase == 1 && !names[i].exists && !assume_exists) ||
1532 (phase == 2 && checked_in(path) == NULL))
1534 if ((tmp = num_components(path)) > min_components)
1536 if (tmp < min_components) {
1537 min_components = tmp;
1540 if ((tmp = strlen(basename(path))) > min_baselen)
1542 if (tmp < min_baselen) {
1546 if ((tmp = strlen(path)) > min_len)
1555 * Choose the name of the file to be patched based the "best" one
1559 best_name(const struct file_name *names, bool assume_exists)
1563 best = compare_names(names, assume_exists, 1);
1565 best = compare_names(names, assume_exists, 2);
1567 * Still no match? Check to see if the diff could be creating
1570 if (best == NULL && ok_to_create_file &&
1571 names[NEW_FILE].path != NULL)
1572 best = names[NEW_FILE].path;
1575 return best ? xstrdup(best) : NULL;
1579 num_components(const char *path)
1584 for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1586 cp++; /* skip consecutive slashes */
1592 * Convert number at NPTR into LINENUM and save address of first
1593 * character that is not a digit in ENDPTR. If conversion is not
1594 * possible, call fatal.
1597 strtolinenum(char *nptr, char **endptr)
1604 for (p = nptr; isdigit((unsigned char)*p); p++)
1613 rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1615 fatal("invalid line number at line %ld: `%s' is %s\n",
1616 p_input_line, nptr, errstr);