3 /* $Id: pch.c,v 1.26 1997/07/21 17:59:46 eggert Exp $ */
6 Copyright 1986, 1987, 1988 Larry Wall
7 Copyright 1990, 1991, 1992, 1993, 1997 Free Software Foundation, Inc.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; see the file COPYING.
21 If not, write to the Free Software Foundation,
22 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 #include <backupfile.h>
34 #define INITHUNKMAX 125 /* initial dynamic allocation size */
36 /* Patch (diff listing) abstract type. */
38 static FILE *pfp; /* patch file pointer */
39 static int p_says_nonexistent[2]; /* [0] for old file, [1] for new;
40 value is 0 for nonempty, 1 for empty, 2 for nonexistent */
41 static int p_rfc934_nesting; /* RFC 934 nesting level */
42 static time_t p_timestamp[2]; /* timestamps in patch headers */
43 static off_t p_filesize; /* size of the patch file */
44 static LINENUM p_first; /* 1st line number */
45 static LINENUM p_newfirst; /* 1st line number of replacement */
46 static LINENUM p_ptrn_lines; /* # lines in pattern */
47 static LINENUM p_repl_lines; /* # lines in replacement text */
48 static LINENUM p_end = -1; /* last line in hunk */
49 static LINENUM p_max; /* max allowed value of p_end */
50 static LINENUM p_prefix_context; /* # of prefix context lines */
51 static LINENUM p_suffix_context; /* # of suffix context lines */
52 static LINENUM p_input_line; /* current line # from patch file */
53 static char **p_line; /* the text of the hunk */
54 static size_t *p_len; /* line length including \n if any */
55 static char *p_Char; /* +, -, and ! */
56 static LINENUM hunkmax = INITHUNKMAX; /* size of above arrays */
57 static int p_indent; /* indent to patch */
58 static file_offset p_base; /* where to intuit this time */
59 static LINENUM p_bline; /* line # of p_base */
60 static file_offset p_start; /* where intuit found a patch */
61 static LINENUM p_sline; /* and the line number for it */
62 static LINENUM p_hunk_beg; /* line number of current hunk */
63 static LINENUM p_efake = -1; /* end of faked up lines--don't free */
64 static LINENUM p_bfake = -1; /* beg of faked up lines */
66 enum nametype { OLD, NEW, INDEX, NONE };
68 static enum diff intuit_diff_type PARAMS ((void));
69 static enum nametype best_name PARAMS ((char * const *, int const *));
70 static int prefix_components PARAMS ((char *, int));
71 static size_t pget_line PARAMS ((int, int));
72 static size_t get_line PARAMS ((void));
73 static bool incomplete_line PARAMS ((void));
74 static bool grow_hunkmax PARAMS ((void));
75 static void malformed PARAMS ((void)) __attribute__ ((noreturn));
76 static void next_intuit_at PARAMS ((file_offset, LINENUM));
77 static void skip_to PARAMS ((file_offset, LINENUM));
79 /* Prepare to look for the next patch in the patch file. */
93 /* Open the patch file at the beginning of time. */
96 open_patch_file(filename)
99 file_offset file_pos = 0;
101 if (!filename || !*filename || strEQ (filename, "-"))
103 file_offset stdin_pos;
107 if (isatty (STDIN_FILENO))
108 fatal ("cannot read binary data from tty on this platform");
109 setmode (STDIN_FILENO, O_BINARY);
112 if (fstat (STDIN_FILENO, &st) != 0)
114 if (S_ISREG (st.st_mode) && (stdin_pos = file_tell (stdin)) != -1)
117 file_pos = stdin_pos;
122 pfp = fopen (TMPPATNAME, "w+b");
124 pfatal ("can't create `%s'", TMPPATNAME);
126 (charsread = fread (buf, 1, bufsize, stdin)) != 0;
127 st.st_size += charsread)
128 if (fwrite (buf, 1, charsread, pfp) != charsread)
130 if (ferror (stdin) || fclose (stdin) != 0)
132 if (fflush (pfp) != 0
133 || file_seek (pfp, (file_offset) 0, SEEK_SET) != 0)
139 pfp = fopen (filename, binary_transput ? "rb" : "r");
141 pfatal ("can't open patch file `%s'", filename);
142 if (fstat (fileno (pfp), &st) != 0)
145 p_filesize = st.st_size;
146 if (p_filesize != (file_offset) p_filesize)
147 fatal ("patch file is too long");
148 next_intuit_at (file_pos, (LINENUM) 1);
152 /* Make sure our dynamically realloced tables are malloced to begin with. */
158 p_line = (char **) malloc (hunkmax * sizeof *p_line);
160 p_len = (size_t *) malloc (hunkmax * sizeof *p_len);
162 p_Char = malloc (hunkmax * sizeof *p_Char);
165 /* Enlarge the arrays containing the current hunk of patch. */
171 assert (p_line && p_len && p_Char);
172 if ((p_line = (char **) realloc (p_line, hunkmax * sizeof (*p_line)))
173 && (p_len = (size_t *) realloc (p_len, hunkmax * sizeof (*p_len)))
174 && (p_Char = realloc (p_Char, hunkmax * sizeof (*p_Char))))
178 /* Don't free previous values of p_line etc.,
179 since some broken implementations free them for us.
180 Whatever is null will be allocated again from within plan_a (),
185 /* True if the remainder of the patch file contains a diff of some sort. */
188 there_is_another_patch()
190 if (p_base != 0 && p_base >= p_filesize) {
191 if (verbosity == VERBOSE)
195 if (verbosity == VERBOSE)
197 diff_type = intuit_diff_type();
198 if (diff_type == NO_DIFF) {
199 if (verbosity == VERBOSE)
201 ? " Ignoring the trailing garbage.\ndone\n"
202 : " I can't seem to find a patch in there anywhere.\n");
203 if (! p_base && p_filesize)
204 fatal ("Only garbage was found in the patch input.");
207 if (skip_rest_of_patch)
209 Fseek (pfp, p_start, SEEK_SET);
210 p_input_line = p_sline - 1;
213 if (verbosity == VERBOSE)
214 say (" %sooks like %s to me...\n",
215 (p_base == 0 ? "L" : "The next patch l"),
216 diff_type == UNI_DIFF ? "a unified diff" :
217 diff_type == CONTEXT_DIFF ? "a context diff" :
218 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
219 diff_type == NORMAL_DIFF ? "a normal diff" :
222 if (verbosity != SILENT)
225 say ("(Patch is indented %d space%s.)\n", p_indent, p_indent==1?"":"s");
228 say ("can't find file to patch at input line %ld\n",
230 say (strippath == INT_MAX
231 ? "Perhaps you should have used the -p or --strip option?\n"
232 : "Perhaps you used the wrong -p or --strip option?\n");
236 skip_to(p_start,p_sline);
238 if (force || batch) {
239 say ("No file to patch. Skipping patch.\n");
240 skip_rest_of_patch = TRUE;
243 ask ("File to patch: ");
244 inname = fetchname (buf, 0, (time_t *) 0);
247 if (stat (inname, &instat) == 0)
260 ask ("Skip this patch? [y] ");
262 if (verbosity != SILENT)
263 say ("Skipping patch.\n");
264 skip_rest_of_patch = TRUE;
272 /* Determine what kind of diff is in the remaining part of the patch file. */
280 register file_offset this_line = 0;
281 register file_offset previous_line;
282 register file_offset first_command_line = -1;
283 LINENUM fcl_line = 0; /* Pacify `gcc -W'. */
284 register bool last_line_was_command = FALSE;
285 register bool this_is_a_command = FALSE;
286 register bool stars_last_line = FALSE;
287 register bool stars_this_line = FALSE;
292 int version_controlled[3];
293 register enum diff retval;
295 name[OLD] = name[NEW] = name[INDEX] = 0;
296 version_controlled[OLD] = -1;
297 version_controlled[NEW] = -1;
298 version_controlled[INDEX] = -1;
299 p_rfc934_nesting = 0;
300 p_timestamp[OLD] = p_timestamp[NEW] = (time_t) -1;
301 p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0;
302 Fseek (pfp, p_base, SEEK_SET);
303 p_input_line = p_bline - 1;
305 previous_line = this_line;
306 last_line_was_command = this_is_a_command;
307 stars_last_line = stars_this_line;
308 this_line = file_tell (pfp);
310 if (! pget_line (0, 0)) {
311 if (first_command_line >= 0) {
312 /* nothing but deletes!? */
313 p_start = first_command_line;
320 p_sline = p_input_line;
324 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
326 indent = (indent + 8) & ~7;
330 for (t = s; ISDIGIT (*t) || *t == ','; t++)
332 this_is_a_command = (ISDIGIT (*s) &&
333 (*t == 'd' || *t == 'c' || *t == 'a') );
334 if (first_command_line < 0 && this_is_a_command) {
335 first_command_line = this_line;
336 fcl_line = p_input_line;
337 p_indent = indent; /* assume this for now */
339 if (!stars_last_line && strnEQ(s, "*** ", 4))
340 name[OLD] = fetchname (s+4, strippath, &p_timestamp[OLD]);
341 else if (strnEQ(s, "+++ ", 4))
342 /* Swap with NEW below. */
343 name[OLD] = fetchname (s+4, strippath, &p_timestamp[OLD]);
344 else if (strnEQ(s, "Index:", 6))
345 name[INDEX] = fetchname (s+6, strippath, (time_t *) 0);
346 else if (strnEQ(s, "Prereq:", 7)) {
347 for (t = s + 7; ISSPACE ((unsigned char) *t); t++)
350 for (t = revision; *t && !ISSPACE ((unsigned char) *t); t++)
357 revision = savestr (revision);
362 for (t = s; t[0] == '-' && t[1] == ' '; t += 2)
364 if (strnEQ(t, "--- ", 4))
366 time_t timestamp = (time_t) -1;
367 name[NEW] = fetchname (t+4, strippath, ×tamp);
368 if (timestamp != (time_t) -1)
370 p_timestamp[NEW] = timestamp;
371 p_rfc934_nesting = (t - s) >> 1;
375 if ((diff_type == NO_DIFF || diff_type == ED_DIFF) &&
376 first_command_line >= 0 &&
379 p_start = first_command_line;
384 if ((diff_type == NO_DIFF || diff_type == UNI_DIFF)
385 && strnEQ(s, "@@ -", 4)) {
387 /* `name' and `p_timestamp' are backwards; swap them. */
388 time_t ti = p_timestamp[OLD];
389 p_timestamp[OLD] = p_timestamp[NEW];
390 p_timestamp[NEW] = ti;
392 name[OLD] = name[NEW];
397 p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD];
398 while (*s != ' ' && *s != '\n')
403 p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW];
406 p_sline = p_input_line;
408 if (! ((name[OLD] || ! p_timestamp[OLD])
409 && (name[NEW] || ! p_timestamp[NEW])))
410 say ("missing header for unified diff at line %ld of patch\n",
414 stars_this_line = strnEQ(s, "********", 8);
415 if ((diff_type == NO_DIFF
416 || diff_type == CONTEXT_DIFF
417 || diff_type == NEW_CONTEXT_DIFF)
418 && stars_last_line && strnEQ (s, "*** ", 4)) {
421 p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD];
422 /* if this is a new context diff the character just before */
423 /* the newline is a '*'. */
427 p_start = previous_line;
428 p_sline = p_input_line - 1;
429 retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
432 /* Scan the first hunk to see whether the file contents
433 appear to have been deleted. */
434 file_offset saved_p_base = p_base;
435 LINENUM saved_p_bline = p_bline;
436 Fseek (pfp, previous_line, SEEK_SET);
438 if (another_hunk (retval, 0)
439 && ! p_repl_lines && p_newfirst == 1)
440 p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW];
441 next_intuit_at (saved_p_base, saved_p_bline);
444 if (! ((name[OLD] || ! p_timestamp[OLD])
445 && (name[NEW] || ! p_timestamp[NEW])))
446 say ("missing header for context diff at line %ld of patch\n",
450 if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) &&
451 last_line_was_command &&
452 (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) {
453 p_start = previous_line;
454 p_sline = p_input_line - 1;
456 retval = NORMAL_DIFF;
463 /* To intuit `inname', the name of the file to patch,
464 use the algorithm specified by POSIX 1003.2b/D11 section 5.22.7.2
465 (with some modifications if posixly_correct is zero):
467 - Take the old and new names from the context header if present,
468 and take the index name from the `Index:' line if present and
469 if either the old and new names are both absent
470 or posixly_correct is nonzero.
471 Consider the file names to be in the order (old, new, index).
472 - If some named files exist, use the first one if posixly_correct
473 is nonzero, the best one otherwise.
474 - If patch_get is nonzero, and no named files exist,
475 but an RCS or SCCS master file exists,
476 use the first named file with an RCS or SCCS master.
477 - If no named files exist, no RCS or SCCS master was found,
478 some names are given, posixly_correct is zero,
479 and the patch appears to create a file, then use the best name
480 requiring the creation of the fewest directories.
481 - Otherwise, report failure by setting `inname' to 0;
482 this causes our invoker to ask the user for a file name. */
488 enum nametype i0 = NONE;
490 if (! posixly_correct && (name[OLD] || name[NEW]) && name[INDEX])
496 for (i = OLD; i <= INDEX; i++)
499 if (i0 != NONE && strcmp (name[i0], name[i]) == 0)
501 /* It's the same name as before; reuse stat results. */
502 stat_errno[i] = stat_errno[i0];
506 else if (stat (name[i], &st[i]) != 0)
507 stat_errno[i] = errno;
517 if (! posixly_correct)
519 i = best_name (name, stat_errno);
521 if (i == NONE && patch_get)
523 enum nametype nope = NONE;
525 for (i = OLD; i <= INDEX; i++)
531 int readonly = outfile && strcmp (outfile, name[i]) != 0;
533 if (nope == NONE || strcmp (name[nope], name[i]) != 0)
535 cs = (version_controller
536 (name[i], readonly, (struct stat *) 0,
538 version_controlled[i] = !! cs;
541 if (version_get (name[i], cs, 0, readonly,
545 version_controlled[i] = 0;
559 if (p_says_nonexistent[reverse ^ (i == NONE || st[i].st_size == 0)])
563 ("The next patch%s would %s the file `%s',\nwhich %s!",
564 reverse ? ", when reversed," : "",
565 (i == NONE ? "delete"
566 : st[i].st_size == 0 ? "empty out"
568 name[i == NONE || st[i].st_size == 0 ? i0 : i],
569 (i == NONE ? "does not exist"
570 : st[i].st_size == 0 ? "is already empty"
571 : "already exists")))
575 if (i == NONE && p_says_nonexistent[reverse])
578 int newdirs_min = INT_MAX;
579 int distance_from_minimum[3];
581 for (i = OLD; i <= INDEX; i++)
584 newdirs[i] = (prefix_components (name[i], 0)
585 - prefix_components (name[i], 1));
586 if (newdirs[i] < newdirs_min)
587 newdirs_min = newdirs[i];
590 for (i = OLD; i <= INDEX; i++)
592 distance_from_minimum[i] = newdirs[i] - newdirs_min;
594 i = best_name (name, distance_from_minimum);
605 inerrno = stat_errno[i];
606 invc = version_controlled[i];
610 for (i = OLD; i <= INDEX; i++)
617 /* Count the path name components in FILENAME's prefix.
618 If CHECKDIRS is nonzero, count only existing directories. */
620 prefix_components (filename, checkdirs)
625 struct stat stat_buf;
627 char *f = filename + FILESYSTEM_PREFIX_LEN (filename);
631 if (ISSLASH (f[0]) && ! ISSLASH (f[-1]))
636 stat_result = stat (filename, &stat_buf);
638 if (! (stat_result == 0 && S_ISDIR (stat_buf.st_mode)))
648 /* Return the index of the best of NAME[OLD], NAME[NEW], and NAME[INDEX].
649 Ignore null names, and ignore NAME[i] if IGNORE[i] is nonzero.
650 Return NONE if all names are ignored. */
652 best_name (name, ignore)
658 int components_min = INT_MAX;
659 size_t basename_len[3];
660 size_t basename_len_min = (size_t) -1;
662 size_t len_min = (size_t) -1;
664 for (i = OLD; i <= INDEX; i++)
665 if (name[i] && !ignore[i])
667 /* Take the names with the fewest prefix components. */
668 components[i] = prefix_components (name[i], 0);
669 if (components_min < components[i])
671 components_min = components[i];
673 /* Of those, take the names with the shortest basename. */
674 basename_len[i] = strlen (base_name (name[i]));
675 if (basename_len_min < basename_len[i])
677 basename_len_min = basename_len[i];
679 /* Of those, take the shortest names. */
680 len[i] = strlen (name[i]);
681 if (len_min < len[i])
686 /* Of those, take the first name. */
687 for (i = OLD; i <= INDEX; i++)
688 if (name[i] && !ignore[i]
689 && components[i] == components_min
690 && basename_len[i] == basename_len_min
691 && len[i] == len_min)
697 /* Remember where this patch ends so we know where to start up again. */
700 next_intuit_at(file_pos,file_line)
701 file_offset file_pos;
708 /* Basically a verbose fseek() to the actual diff listing. */
711 skip_to(file_pos,file_line)
712 file_offset file_pos;
715 register FILE *i = pfp;
716 register FILE *o = stdout;
719 assert(p_base <= file_pos);
720 if ((verbosity == VERBOSE || !inname) && p_base < file_pos) {
721 Fseek (i, p_base, SEEK_SET);
722 say ("The text leading up to this was:\n--------------------------\n");
724 while (file_tell (i) < file_pos)
729 if ((c = getc (i)) == EOF)
736 say ("--------------------------\n");
739 Fseek (i, file_pos, SEEK_SET);
740 p_input_line = file_line - 1;
743 /* Make this a function for better debugging. */
747 fatal ("malformed patch at line %ld: %s", p_input_line, buf);
748 /* about as informative as "Syntax error" in C */
751 /* 1 if there is more of the current diff listing to process;
752 0 if not; -1 if ran out of memory. */
755 another_hunk (difftype, rev)
760 register LINENUM context = 0;
761 register size_t chars_read;
764 if (p_end == p_efake)
765 p_end = p_bfake; /* don't free twice */
773 p_max = hunkmax; /* gets reduced when --- found */
774 if (difftype == CONTEXT_DIFF || difftype == NEW_CONTEXT_DIFF) {
775 file_offset line_beginning = file_tell (pfp);
776 /* file pos of the current line */
777 LINENUM repl_beginning = 0; /* index of --- line */
778 register LINENUM fillcnt = 0; /* #lines of missing ptrn or repl */
779 register LINENUM fillsrc; /* index of first line to copy */
780 register LINENUM filldst; /* index of first missing line */
781 bool ptrn_spaces_eaten = FALSE; /* ptrn was slightly misformed */
782 bool some_context = FALSE; /* (perhaps internal) context seen */
783 register bool repl_could_be_missing = TRUE;
784 bool repl_missing = FALSE; /* we are now backtracking */
785 file_offset repl_backtrack_position = 0;
786 /* file pos of first repl line */
787 LINENUM repl_patch_line; /* input line number for same */
788 LINENUM repl_context; /* context for same */
789 LINENUM ptrn_prefix_context = -1; /* lines in pattern prefix context */
790 LINENUM ptrn_suffix_context = -1; /* lines in pattern suffix context */
791 LINENUM repl_prefix_context = -1; /* lines in replac. prefix context */
792 register LINENUM ptrn_copiable = 0;
793 /* # of copiable lines in ptrn */
795 /* Pacify `gcc -Wall'. */
796 fillsrc = filldst = repl_patch_line = repl_context = 0;
798 chars_read = get_line ();
799 if (chars_read == (size_t) -1
801 || strncmp (buf, "********", 8) != 0) {
802 next_intuit_at(line_beginning,p_input_line);
803 return chars_read == (size_t) -1 ? -1 : 0;
805 p_hunk_beg = p_input_line + 1;
806 while (p_end < p_max) {
807 chars_read = get_line ();
808 if (chars_read == (size_t) -1)
811 if (repl_beginning && repl_could_be_missing) {
815 if (p_max - p_end < 4) {
816 strcpy (buf, " \n"); /* assume blank lines got chopped */
819 fatal ("unexpected end of file in patch");
823 if (p_end == hunkmax)
824 fatal ("unterminated hunk starting at line %ld; giving up at line %ld: %s",
825 pch_hunk_beg (), p_input_line, buf);
826 assert(p_end < hunkmax);
827 p_Char[p_end] = *buf;
832 if (strnEQ(buf, "********", 8)) {
833 if (repl_beginning && repl_could_be_missing) {
838 fatal ("unexpected end of hunk at line %ld",
842 if (repl_beginning && repl_could_be_missing) {
846 fatal ("unexpected `***' at line %ld: %s",
850 p_len[p_end] = strlen (buf);
851 if (! (p_line[p_end] = savestr (buf))) {
855 for (s = buf; *s && !ISDIGIT (*s); s++)
859 if (strnEQ(s,"0,0",3))
860 remove_prefix (s, 2);
861 p_first = (LINENUM) atol(s);
865 while (*s && !ISDIGIT (*s))
869 p_ptrn_lines = ((LINENUM)atol(s)) - p_first + 1;
877 p_max = p_ptrn_lines + 6; /* we need this much at least */
878 while (p_max >= hunkmax)
879 if (! grow_hunkmax ())
886 if (ptrn_prefix_context == -1)
887 ptrn_prefix_context = context;
888 ptrn_suffix_context = context;
891 != p_ptrn_lines + 1 + (p_Char[p_end - 1] == '\n')))
895 /* `Old' lines were omitted. Set up to fill
896 them in from `new' context lines. */
897 p_end = p_ptrn_lines + 1;
898 ptrn_prefix_context = ptrn_suffix_context = -1;
901 fillcnt = p_ptrn_lines;
903 else if (! repl_beginning)
904 fatal ("%s `---' at line %ld; check line numbers at line %ld",
905 (p_end <= p_ptrn_lines
908 p_input_line, p_hunk_beg);
909 else if (! repl_could_be_missing)
910 fatal ("duplicate `---' at line %ld; check line numbers at line %ld",
911 p_input_line, p_hunk_beg + repl_beginning);
918 repl_beginning = p_end;
919 repl_backtrack_position = file_tell (pfp);
920 repl_patch_line = p_input_line;
921 repl_context = context;
922 p_len[p_end] = strlen (buf);
923 if (! (p_line[p_end] = savestr (buf)))
929 for (s = buf; *s && ! ISDIGIT (*s); s++)
933 p_newfirst = (LINENUM) atol (s);
943 while (! ISDIGIT (*s));
944 p_repl_lines = (LINENUM) atol (s) - p_newfirst + 1;
953 p_max = p_repl_lines + p_end;
954 while (p_max >= hunkmax)
955 if (! grow_hunkmax ())
957 if (p_repl_lines != ptrn_copiable
958 && (p_prefix_context != 0
960 || p_repl_lines != 1))
961 repl_could_be_missing = FALSE;
965 repl_could_be_missing = FALSE;
969 if (*s == '\n' && canonicalize) {
973 if (*s == ' ' || *s == '\t') {
976 } else if (repl_beginning && repl_could_be_missing) {
980 if (! repl_beginning)
982 if (ptrn_prefix_context == -1)
983 ptrn_prefix_context = context;
987 if (repl_prefix_context == -1)
988 repl_prefix_context = context;
992 && p_end == (repl_beginning ? p_max : p_ptrn_lines)
993 && incomplete_line ());
994 p_len[p_end] = chars_read;
995 if (! (p_line[p_end] = savebuf (s, chars_read))) {
1001 case '\t': case '\n': /* assume spaces got eaten */
1007 if (repl_beginning && repl_could_be_missing &&
1008 (!ptrn_spaces_eaten || difftype == NEW_CONTEXT_DIFF) ) {
1009 repl_missing = TRUE;
1014 && p_end == (repl_beginning ? p_max : p_ptrn_lines)
1015 && incomplete_line ());
1016 p_len[p_end] = chars_read;
1017 if (! (p_line[p_end] = savebuf (buf, chars_read))) {
1021 if (p_end != p_ptrn_lines + 1) {
1022 ptrn_spaces_eaten |= (repl_beginning != 0);
1023 some_context = TRUE;
1025 if (!repl_beginning)
1027 p_Char[p_end] = ' ';
1033 if (*s == '\n' && canonicalize) {
1037 if (*s == ' ' || *s == '\t') {
1040 } else if (repl_beginning && repl_could_be_missing) {
1041 repl_missing = TRUE;
1044 some_context = TRUE;
1046 if (!repl_beginning)
1050 && p_end == (repl_beginning ? p_max : p_ptrn_lines)
1051 && incomplete_line ());
1052 p_len[p_end] = chars_read;
1053 if (! (p_line[p_end] = savebuf (buf + 2, chars_read))) {
1059 if (repl_beginning && repl_could_be_missing) {
1060 repl_missing = TRUE;
1068 if (p_end >=0 && !repl_beginning)
1069 fatal ("no `---' found in patch at line %ld", pch_hunk_beg ());
1073 /* reset state back to just after --- */
1074 p_input_line = repl_patch_line;
1075 context = repl_context;
1076 for (p_end--; p_end > repl_beginning; p_end--)
1077 free(p_line[p_end]);
1078 Fseek (pfp, repl_backtrack_position, SEEK_SET);
1080 /* redundant 'new' context lines were omitted - set */
1081 /* up to fill them in from the old file context */
1083 filldst = repl_beginning+1;
1084 fillcnt = p_repl_lines;
1087 else if (!some_context && fillcnt == 1) {
1088 /* the first hunk was a null hunk with no context */
1089 /* and we were expecting one line -- fix it up. */
1090 while (filldst < p_end) {
1091 p_line[filldst] = p_line[filldst+1];
1092 p_Char[filldst] = p_Char[filldst+1];
1093 p_len[filldst] = p_len[filldst+1];
1097 repl_beginning--; /* this doesn't need to be fixed */
1100 p_first++; /* do append rather than insert */
1105 p_prefix_context = ((repl_prefix_context == -1
1106 || (ptrn_prefix_context != -1
1107 && ptrn_prefix_context < repl_prefix_context))
1108 ? ptrn_prefix_context : repl_prefix_context);
1109 p_suffix_context = ((ptrn_suffix_context != -1
1110 && ptrn_suffix_context < context)
1111 ? ptrn_suffix_context : context);
1112 assert (p_prefix_context != -1 && p_suffix_context != -1);
1114 if (difftype == CONTEXT_DIFF
1117 && p_prefix_context + p_suffix_context < ptrn_copiable))) {
1118 if (verbosity == VERBOSE)
1119 say ("%s\n%s\n%s\n",
1120 "(Fascinating -- this is really a new-style context diff but without",
1121 "the telltale extra asterisks on the *** line that usually indicate",
1122 "the new style...)");
1123 diff_type = difftype = NEW_CONTEXT_DIFF;
1126 /* if there were omitted context lines, fill them in now */
1128 p_bfake = filldst; /* remember where not to free() */
1129 p_efake = filldst + fillcnt - 1;
1130 while (fillcnt-- > 0) {
1131 while (fillsrc <= p_end && fillsrc != repl_beginning
1132 && p_Char[fillsrc] != ' ')
1134 if (p_end < fillsrc || fillsrc == repl_beginning)
1135 fatal ("replacement text or line numbers mangled in hunk at line %ld",
1137 p_line[filldst] = p_line[fillsrc];
1138 p_Char[filldst] = p_Char[fillsrc];
1139 p_len[filldst] = p_len[fillsrc];
1140 fillsrc++; filldst++;
1142 while (fillsrc <= p_end && fillsrc != repl_beginning)
1144 if (p_Char[fillsrc] == ' ')
1145 fatal ("replacement text or line numbers mangled in hunk at line %ld",
1150 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
1151 fillsrc,filldst,repl_beginning,p_end+1);
1152 assert(fillsrc==p_end+1 || fillsrc==repl_beginning);
1153 assert(filldst==p_end+1 || filldst==repl_beginning);
1156 else if (difftype == UNI_DIFF) {
1157 file_offset line_beginning = file_tell (pfp);
1158 /* file pos of the current line */
1159 register LINENUM fillsrc; /* index of old lines */
1160 register LINENUM filldst; /* index of new lines */
1163 chars_read = get_line ();
1164 if (chars_read == (size_t) -1
1166 || strncmp (buf, "@@ -", 4) != 0) {
1167 next_intuit_at(line_beginning,p_input_line);
1168 return chars_read == (size_t) -1 ? -1 : 0;
1173 p_first = (LINENUM) atol(s);
1174 while (ISDIGIT (*s))
1177 p_ptrn_lines = (LINENUM) atol(++s);
1178 while (ISDIGIT (*s))
1183 if (*s != '+' || !*++s)
1185 p_newfirst = (LINENUM) atol(s);
1186 while (ISDIGIT (*s))
1189 p_repl_lines = (LINENUM) atol(++s);
1190 while (ISDIGIT (*s))
1198 p_first++; /* do append rather than insert */
1201 p_max = p_ptrn_lines + p_repl_lines + 1;
1202 while (p_max >= hunkmax)
1203 if (! grow_hunkmax ())
1206 filldst = fillsrc + p_ptrn_lines;
1207 p_end = filldst + p_repl_lines;
1208 sprintf (buf,"*** %ld,%ld ****\n",p_first,p_first + p_ptrn_lines - 1);
1209 p_len[0] = strlen (buf);
1210 if (! (p_line[0] = savestr (buf))) {
1215 sprintf (buf,"--- %ld,%ld ----\n",p_newfirst,p_newfirst+p_repl_lines-1);
1216 p_len[filldst] = strlen (buf);
1217 if (! (p_line[filldst] = savestr (buf))) {
1221 p_Char[filldst++] = '=';
1222 p_prefix_context = -1;
1223 p_hunk_beg = p_input_line + 1;
1224 while (fillsrc <= p_ptrn_lines || filldst <= p_end) {
1225 chars_read = get_line ();
1227 if (p_max - filldst < 3) {
1228 strcpy (buf, " \n"); /* assume blank lines got chopped */
1231 fatal ("unexpected end of file in patch");
1234 if (chars_read == (size_t) -1)
1236 else if (*buf == '\t' || *buf == '\n') {
1237 ch = ' '; /* assume the space got eaten */
1238 s = savebuf (buf, chars_read);
1242 s = savebuf (buf+1, --chars_read);
1245 while (--filldst > p_ptrn_lines)
1246 free(p_line[filldst]);
1252 if (fillsrc > p_ptrn_lines) {
1257 chars_read -= fillsrc == p_ptrn_lines && incomplete_line ();
1258 p_Char[fillsrc] = ch;
1259 p_line[fillsrc] = s;
1260 p_len[fillsrc++] = chars_read;
1266 if (fillsrc > p_ptrn_lines) {
1268 while (--filldst > p_ptrn_lines)
1269 free(p_line[filldst]);
1274 chars_read -= fillsrc == p_ptrn_lines && incomplete_line ();
1275 p_Char[fillsrc] = ch;
1276 p_line[fillsrc] = s;
1277 p_len[fillsrc++] = chars_read;
1278 s = savebuf (s, chars_read);
1280 while (--filldst > p_ptrn_lines)
1281 free(p_line[filldst]);
1287 if (filldst > p_end) {
1289 while (--filldst > p_ptrn_lines)
1290 free(p_line[filldst]);
1294 chars_read -= filldst == p_end && incomplete_line ();
1295 p_Char[filldst] = ch;
1296 p_line[filldst] = s;
1297 p_len[filldst++] = chars_read;
1304 if (p_prefix_context == -1)
1305 p_prefix_context = context;
1309 if (p_prefix_context == -1)
1311 p_suffix_context = context;
1313 else { /* normal diff--fake it up */
1317 file_offset line_beginning = file_tell (pfp);
1319 p_prefix_context = p_suffix_context = 0;
1320 chars_read = get_line ();
1321 if (chars_read == (size_t) -1 || !chars_read || !ISDIGIT (*buf)) {
1322 next_intuit_at(line_beginning,p_input_line);
1323 return chars_read == (size_t) -1 ? -1 : 0;
1325 p_first = (LINENUM)atol(buf);
1326 for (s = buf; ISDIGIT (*s); s++)
1329 p_ptrn_lines = (LINENUM)atol(++s) - p_first + 1;
1330 while (ISDIGIT (*s))
1334 p_ptrn_lines = (*s != 'a');
1336 if (hunk_type == 'a')
1337 p_first++; /* do append rather than insert */
1338 min = (LINENUM)atol(++s);
1339 while (ISDIGIT (*s))
1342 max = (LINENUM)atol(++s);
1345 if (hunk_type == 'd')
1347 p_end = p_ptrn_lines + 1 + max - min + 1;
1348 while (p_end >= hunkmax)
1349 if (! grow_hunkmax ())
1355 p_repl_lines = max - min + 1;
1356 sprintf (buf, "*** %ld,%ld\n", p_first, p_first + p_ptrn_lines - 1);
1357 p_len[0] = strlen (buf);
1358 if (! (p_line[0] = savestr (buf))) {
1363 for (i=1; i<=p_ptrn_lines; i++) {
1364 chars_read = get_line ();
1365 if (chars_read == (size_t) -1)
1371 fatal ("unexpected end of file in patch at line %ld",
1373 if (buf[0] != '<' || (buf[1] != ' ' && buf[1] != '\t'))
1374 fatal ("`<' expected at line %ld of patch", p_input_line);
1375 chars_read -= 2 + (i == p_ptrn_lines && incomplete_line ());
1376 p_len[i] = chars_read;
1377 if (! (p_line[i] = savebuf (buf + 2, chars_read))) {
1383 if (hunk_type == 'c') {
1384 chars_read = get_line ();
1385 if (chars_read == (size_t) -1)
1391 fatal ("unexpected end of file in patch at line %ld",
1394 fatal ("`---' expected at line %ld of patch", p_input_line);
1396 sprintf (buf, "--- %ld,%ld\n", min, max);
1397 p_len[i] = strlen (buf);
1398 if (! (p_line[i] = savestr (buf))) {
1403 for (i++; i<=p_end; i++) {
1404 chars_read = get_line ();
1405 if (chars_read == (size_t) -1)
1411 fatal ("unexpected end of file in patch at line %ld",
1413 if (buf[0] != '>' || (buf[1] != ' ' && buf[1] != '\t'))
1414 fatal ("`>' expected at line %ld of patch", p_input_line);
1415 chars_read -= 2 + (i == p_end && incomplete_line ());
1416 p_len[i] = chars_read;
1417 if (! (p_line[i] = savebuf (buf + 2, chars_read))) {
1424 if (rev) /* backwards patch? */
1426 say ("Not enough memory to swap next hunk!\n");
1431 for (i=0; i <= p_end; i++) {
1432 if (i == p_ptrn_lines)
1436 fprintf (stderr, "%3ld %c %c ", i, p_Char[i], special);
1437 pch_write_line (i, stderr);
1441 if (p_end+1 < hunkmax) /* paranoia reigns supreme... */
1442 p_Char[p_end+1] = '^'; /* add a stopper for apply_hunk */
1449 return pget_line (p_indent, p_rfc934_nesting);
1452 /* Input a line from the patch file, worrying about indentation.
1453 Strip up to INDENT characters' worth of leading indentation.
1454 Then remove up to RFC934_NESTING instances of leading "- ".
1455 Ignore any partial lines at end of input, but warn about them.
1456 Succeed if a line was read; it is terminated by "\n\0" for convenience.
1457 Return the number of characters read, including '\n' but not '\0'.
1458 Return -1 if we ran out of memory. */
1461 pget_line (indent, rfc934_nesting)
1465 register FILE *fp = pfp;
1482 if (c == ' ' || c == 'X')
1493 while (c == '-' && 0 <= --rfc934_nesting)
1497 goto patch_ends_in_middle_of_line;
1506 goto patch_ends_in_middle_of_line;
1531 goto patch_ends_in_middle_of_line;
1538 patch_ends_in_middle_of_line:
1541 say ("patch unexpectedly ends in middle of line\n");
1548 register FILE *fp = pfp;
1550 register file_offset line_beginning = file_tell (fp);
1552 if (getc (fp) == '\\')
1554 while ((c = getc (fp)) != '\n' && c != EOF)
1560 /* We don't trust ungetc. */
1561 Fseek (pfp, line_beginning, SEEK_SET);
1566 /* Reverse the old and new portions of the current hunk. */
1571 char **tp_line; /* the text of the hunk */
1572 size_t *tp_len; /* length of each line */
1573 char *tp_char; /* +, -, and ! */
1576 bool blankline = FALSE;
1580 p_first = p_newfirst;
1583 /* make a scratch copy */
1588 p_line = 0; /* force set_hunkmax to allocate again */
1592 if (!p_line || !p_len || !p_Char) {
1602 return FALSE; /* not enough memory to swap hunk! */
1605 /* now turn the new into the old */
1607 i = p_ptrn_lines + 1;
1608 if (tp_char[i] == '\n') { /* account for possible blank line */
1612 if (p_efake >= 0) { /* fix non-freeable ptr range */
1620 for (n=0; i <= p_end; i++,n++) {
1621 p_line[n] = tp_line[i];
1622 p_Char[n] = tp_char[i];
1623 if (p_Char[n] == '+')
1625 p_len[n] = tp_len[i];
1628 i = p_ptrn_lines + 1;
1629 p_line[n] = tp_line[i];
1630 p_Char[n] = tp_char[i];
1631 p_len[n] = tp_len[i];
1634 assert(p_Char[0] == '=');
1636 for (s=p_line[0]; *s; s++)
1640 /* now turn the old into the new */
1642 assert(tp_char[0] == '*');
1644 for (s=tp_line[0]; *s; s++)
1647 for (i=0; n <= p_end; i++,n++) {
1648 p_line[n] = tp_line[i];
1649 p_Char[n] = tp_char[i];
1650 if (p_Char[n] == '-')
1652 p_len[n] = tp_len[i];
1654 assert(i == p_ptrn_lines + 1);
1656 p_ptrn_lines = p_repl_lines;
1667 /* Return whether file WHICH (0 = old, 1 = new) appears to nonexistent.
1668 Return 1 for empty, 2 for nonexistent. */
1671 pch_says_nonexistent (which)
1674 return p_says_nonexistent[which];
1677 /* Return timestamp of patch header for file WHICH (0 = old, 1 = new),
1678 or -1 if there was no timestamp or an error in the timestamp. */
1681 pch_timestamp (which)
1684 return p_timestamp[which];
1687 /* Return the specified line position in the old file of the old context. */
1695 /* Return the number of lines of old context. */
1700 return p_ptrn_lines;
1703 /* Return the probable line position in the new file of the first line. */
1711 /* Return the number of lines in the replacement text including context. */
1716 return p_repl_lines;
1719 /* Return the number of lines in the whole hunk. */
1727 /* Return the number of context lines before the first changed line. */
1730 pch_prefix_context ()
1732 return p_prefix_context;
1735 /* Return the number of context lines after the last changed line. */
1738 pch_suffix_context ()
1740 return p_suffix_context;
1743 /* Return the length of a particular patch line. */
1752 /* Return the control character (+, -, *, !, etc) for a patch line. */
1758 return p_Char[line];
1761 /* Return a pointer to a particular patch line. */
1767 return p_line[line];
1770 /* Output a patch line. */
1773 pch_write_line (line, file)
1777 bool after_newline = p_line[line][p_len[line] - 1] == '\n';
1778 if (! fwrite (p_line[line], sizeof (*p_line[line]), p_len[line], file))
1780 return after_newline;
1783 /* Return where in the patch file this hunk began, for error messages. */
1791 /* Apply an ed script by feeding ed itself. */
1797 static char const ed_program[] = ed_PROGRAM;
1800 register file_offset beginning_of_this_line;
1801 register bool this_line_is_command = FALSE;
1802 register FILE *pipefp = 0;
1803 register size_t chars_read;
1805 if (!skip_rest_of_patch) {
1807 copy_file (inname, TMPOUTNAME, instat.st_mode);
1808 sprintf (buf, "%s %s%s", ed_program, verbosity == VERBOSE ? "" : "- ",
1811 pipefp = popen(buf, binary_transput ? "wb" : "w");
1813 pfatal ("can't open pipe to `%s'", buf);
1816 beginning_of_this_line = file_tell (pfp);
1817 chars_read = get_line ();
1819 next_intuit_at(beginning_of_this_line,p_input_line);
1822 for (t = buf; ISDIGIT (*t) || *t == ','; t++)
1824 this_line_is_command = (ISDIGIT (*buf) &&
1825 (*t == 'd' || *t == 'c' || *t == 'a' || *t == 'i' || *t == 's') );
1826 if (this_line_is_command) {
1828 if (! fwrite (buf, sizeof *buf, chars_read, pipefp))
1830 if (*t != 'd' && *t != 's') {
1831 while ((chars_read = get_line ()) != 0) {
1833 if (! fwrite (buf, sizeof *buf, chars_read, pipefp))
1835 if (chars_read == 2 && strEQ (buf, ".\n"))
1841 next_intuit_at(beginning_of_this_line,p_input_line);
1847 if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, pipefp) == 0
1848 || fflush (pipefp) != 0)
1850 if (pclose (pipefp) != 0)
1851 fatal ("%s FAILED", ed_program);
1855 FILE *ifp = fopen (TMPOUTNAME, binary_transput ? "rb" : "r");
1858 pfatal ("can't open `%s'", TMPOUTNAME);
1859 while ((c = getc (ifp)) != EOF)
1860 if (putc (c, ofp) == EOF)
1862 if (ferror (ifp) || fclose (ifp) != 0)