3
/* $Id: pch.c,v 1.45 2003/07/02 22:19:21 eggert Exp $ */
5
/* Copyright (C) 1986, 1987, 1988 Larry Wall
7
Copyright (C) 1990, 1991, 1992, 1993, 1997, 1998, 1999, 2000, 2001,
8
2002, 2003 Free Software Foundation, Inc.
10
This program is free software; you can redistribute it and/or modify
11
it under the terms of the GNU General Public License as published by
12
the Free Software Foundation; either version 2, or (at your option)
15
This program is distributed in the hope that it will be useful,
16
but WITHOUT ANY WARRANTY; without even the implied warranty of
17
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18
GNU General Public License for more details.
20
You should have received a copy of the GNU General Public License
21
along with this program; see the file COPYING.
22
If not, write to the Free Software Foundation,
23
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
27
#include <backupfile.h>
36
#define INITHUNKMAX 125 /* initial dynamic allocation size */
38
/* Patch (diff listing) abstract type. */
40
static FILE *pfp; /* patch file pointer */
41
static int p_says_nonexistent[2]; /* [0] for old file, [1] for new:
42
0 for existent and nonempty,
43
1 for existent and probably (but not necessarily) empty,
45
static int p_rfc934_nesting; /* RFC 934 nesting level */
46
static time_t p_timestamp[2]; /* timestamps in patch headers */
47
static off_t p_filesize; /* size of the patch file */
48
static LINENUM p_first; /* 1st line number */
49
static LINENUM p_newfirst; /* 1st line number of replacement */
50
static LINENUM p_ptrn_lines; /* # lines in pattern */
51
static LINENUM p_repl_lines; /* # lines in replacement text */
52
static LINENUM p_end = -1; /* last line in hunk */
53
static LINENUM p_max; /* max allowed value of p_end */
54
static LINENUM p_prefix_context; /* # of prefix context lines */
55
static LINENUM p_suffix_context; /* # of suffix context lines */
56
static LINENUM p_input_line; /* current line # from patch file */
57
static char **p_line; /* the text of the hunk */
58
static size_t *p_len; /* line length including \n if any */
59
static char *p_Char; /* +, -, and ! */
60
static LINENUM hunkmax = INITHUNKMAX; /* size of above arrays */
61
static int p_indent; /* indent to patch */
62
static bool p_strip_trailing_cr; /* true if stripping trailing \r */
63
static bool p_pass_comments_through; /* true if not ignoring # lines */
64
static file_offset p_base; /* where to intuit this time */
65
static LINENUM p_bline; /* line # of p_base */
66
static file_offset 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 */
72
enum nametype { OLD, NEW, INDEX, NONE };
74
static char *scan_linenum (char *, LINENUM *);
75
static enum diff intuit_diff_type (void);
76
static enum nametype best_name (char * const *, int const *);
77
static int prefix_components (char *, bool);
78
static size_t pget_line (int, int, bool, bool);
79
static size_t get_line (void);
80
static bool incomplete_line (void);
81
static bool grow_hunkmax (void);
82
static void malformed (void) __attribute__ ((noreturn));
83
static void next_intuit_at (file_offset, LINENUM);
84
static void skip_to (file_offset, LINENUM);
85
static char get_ed_command_letter (char const *);
87
/* Prepare to look for the next patch in the patch file. */
99
p_strip_trailing_cr = false;
102
/* Open the patch file at the beginning of time. */
105
open_patch_file (char const *filename)
107
file_offset file_pos = 0;
109
if (!filename || !*filename || strEQ (filename, "-"))
111
file_offset stdin_pos;
115
if (isatty (STDIN_FILENO))
116
fatal ("cannot read binary data from tty on this platform");
117
setmode (STDIN_FILENO, O_BINARY);
120
if (fstat (STDIN_FILENO, &st) != 0)
122
if (S_ISREG (st.st_mode) && (stdin_pos = file_tell (stdin)) != -1)
125
file_pos = stdin_pos;
130
int exclusive = TMPPATNAME_needs_removal ? 0 : O_EXCL;
131
TMPPATNAME_needs_removal = 1;
132
pfp = fdopen (create_file (TMPPATNAME,
133
O_RDWR | O_BINARY | exclusive,
137
pfatal ("Can't open stream for file %s", quotearg (TMPPATNAME));
139
(charsread = fread (buf, 1, bufsize, stdin)) != 0;
140
st.st_size += charsread)
141
if (fwrite (buf, 1, charsread, pfp) != charsread)
143
if (ferror (stdin) || fclose (stdin) != 0)
145
if (fflush (pfp) != 0
146
|| file_seek (pfp, (file_offset) 0, SEEK_SET) != 0)
152
pfp = fopen (filename, binary_transput ? "rb" : "r");
154
pfatal ("Can't open patch file %s", quotearg (filename));
155
if (fstat (fileno (pfp), &st) != 0)
158
p_filesize = st.st_size;
159
if (p_filesize != (file_offset) p_filesize)
160
fatal ("patch file is too long");
161
next_intuit_at (file_pos, (LINENUM) 1);
165
/* Make sure our dynamically realloced tables are malloced to begin with. */
171
p_line = (char **) malloc (hunkmax * sizeof *p_line);
173
p_len = (size_t *) malloc (hunkmax * sizeof *p_len);
175
p_Char = malloc (hunkmax * sizeof *p_Char);
178
/* Enlarge the arrays containing the current hunk of patch. */
184
assert (p_line && p_len && p_Char);
185
if ((p_line = (char **) realloc (p_line, hunkmax * sizeof (*p_line)))
186
&& (p_len = (size_t *) realloc (p_len, hunkmax * sizeof (*p_len)))
187
&& (p_Char = realloc (p_Char, hunkmax * sizeof (*p_Char))))
191
/* Don't free previous values of p_line etc.,
192
since some broken implementations free them for us.
193
Whatever is null will be allocated again from within plan_a (),
198
/* True if the remainder of the patch file contains a diff of some sort. */
201
there_is_another_patch (void)
203
if (p_base != 0 && p_base >= p_filesize) {
204
if (verbosity == VERBOSE)
208
if (verbosity == VERBOSE)
210
diff_type = intuit_diff_type();
211
if (diff_type == NO_DIFF) {
212
if (verbosity == VERBOSE)
214
? " Ignoring the trailing garbage.\ndone\n"
215
: " I can't seem to find a patch in there anywhere.\n");
216
if (! p_base && p_filesize)
217
fatal ("Only garbage was found in the patch input.");
220
if (skip_rest_of_patch)
222
Fseek (pfp, p_start, SEEK_SET);
223
p_input_line = p_sline - 1;
226
if (verbosity == VERBOSE)
227
say (" %sooks like %s to me...\n",
228
(p_base == 0 ? "L" : "The next patch l"),
229
diff_type == UNI_DIFF ? "a unified diff" :
230
diff_type == CONTEXT_DIFF ? "a context diff" :
231
diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
232
diff_type == NORMAL_DIFF ? "a normal diff" :
235
if (verbosity != SILENT)
238
say ("(Patch is indented %d space%s.)\n", p_indent, p_indent==1?"":"s");
239
if (p_strip_trailing_cr)
240
say ("(Stripping trailing CRs from patch.)\n");
243
char numbuf[LINENUM_LENGTH_BOUND + 1];
244
say ("can't find file to patch at input line %s\n",
245
format_linenum (numbuf, p_sline));
246
if (diff_type != ED_DIFF)
248
? "Perhaps you should have used the -p or --strip option?\n"
249
: "Perhaps you used the wrong -p or --strip option?\n");
253
skip_to(p_start,p_sline);
256
say ("No file to patch. Skipping patch.\n");
257
skip_rest_of_patch = true;
260
ask ("File to patch: ");
261
inname = fetchname (buf, 0, (time_t *) 0);
264
if (stat (inname, &instat) == 0)
278
ask ("Skip this patch? [y] ");
280
if (verbosity != SILENT)
281
say ("Skipping patch.\n");
282
skip_rest_of_patch = true;
290
/* Determine what kind of diff is in the remaining part of the patch file. */
293
intuit_diff_type (void)
295
register file_offset this_line = 0;
296
register file_offset first_command_line = -1;
297
char first_ed_command_letter = 0;
298
LINENUM fcl_line = 0; /* Pacify `gcc -W'. */
299
register bool this_is_a_command = false;
300
register bool stars_this_line = false;
305
int version_controlled[3];
306
register enum diff retval;
308
name[OLD] = name[NEW] = name[INDEX] = 0;
309
version_controlled[OLD] = -1;
310
version_controlled[NEW] = -1;
311
version_controlled[INDEX] = -1;
312
p_rfc934_nesting = 0;
313
p_timestamp[OLD] = p_timestamp[NEW] = (time_t) -1;
314
p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0;
315
Fseek (pfp, p_base, SEEK_SET);
316
p_input_line = p_bline - 1;
320
register file_offset previous_line = this_line;
321
register bool last_line_was_command = this_is_a_command;
322
register bool stars_last_line = stars_this_line;
323
register int indent = 0;
324
char ed_command_letter;
325
bool strip_trailing_cr;
328
this_line = file_tell (pfp);
329
chars_read = pget_line (0, 0, false, false);
330
if (chars_read == (size_t) -1)
333
if (first_ed_command_letter) {
334
/* nothing but deletes!? */
335
p_start = first_command_line;
342
p_sline = p_input_line;
346
strip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\r';
347
for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
349
indent = (indent + 8) & ~7;
353
for (t = s; ISDIGIT (*t) || *t == ','; t++)
355
this_is_a_command = (ISDIGIT (*s) &&
356
(*t == 'd' || *t == 'c' || *t == 'a') );
357
if (first_command_line < 0
358
&& ((ed_command_letter = get_ed_command_letter (s))
359
|| this_is_a_command)) {
360
first_command_line = this_line;
361
first_ed_command_letter = ed_command_letter;
362
fcl_line = p_input_line;
363
p_indent = indent; /* assume this for now */
364
p_strip_trailing_cr = strip_trailing_cr;
366
if (!stars_last_line && strnEQ(s, "*** ", 4))
367
name[OLD] = fetchname (s+4, strippath, &p_timestamp[OLD]);
368
else if (strnEQ(s, "+++ ", 4))
370
/* Swap with NEW below. */
371
name[OLD] = fetchname (s+4, strippath, &p_timestamp[OLD]);
372
p_strip_trailing_cr = strip_trailing_cr;
374
else if (strnEQ(s, "Index:", 6))
376
name[INDEX] = fetchname (s+6, strippath, (time_t *) 0);
377
p_strip_trailing_cr = strip_trailing_cr;
379
else if (strnEQ(s, "Prereq:", 7)) {
380
for (t = s + 7; ISSPACE ((unsigned char) *t); t++)
383
for (t = revision; *t; t++)
384
if (ISSPACE ((unsigned char) *t))
387
for (u = t + 1; ISSPACE ((unsigned char) *u); u++)
391
char numbuf[LINENUM_LENGTH_BOUND + 1];
392
say ("Prereq: with multiple words at line %s of patch\n",
393
format_linenum (numbuf, this_line));
402
revision = savestr (revision);
407
for (t = s; t[0] == '-' && t[1] == ' '; t += 2)
409
if (strnEQ(t, "--- ", 4))
411
time_t timestamp = (time_t) -1;
412
name[NEW] = fetchname (t+4, strippath, ×tamp);
413
if (timestamp != (time_t) -1)
415
p_timestamp[NEW] = timestamp;
416
p_rfc934_nesting = (t - s) >> 1;
418
p_strip_trailing_cr = strip_trailing_cr;
421
if ((diff_type == NO_DIFF || diff_type == ED_DIFF) &&
422
first_command_line >= 0 &&
424
p_start = first_command_line;
429
if ((diff_type == NO_DIFF || diff_type == UNI_DIFF)
430
&& strnEQ(s, "@@ -", 4)) {
432
/* `name' and `p_timestamp' are backwards; swap them. */
433
time_t ti = p_timestamp[OLD];
434
p_timestamp[OLD] = p_timestamp[NEW];
435
p_timestamp[NEW] = ti;
437
name[OLD] = name[NEW];
441
if (s[0] == '0' && !ISDIGIT (s[1]))
442
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD];
443
while (*s != ' ' && *s != '\n')
447
if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2]))
448
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW];
451
p_sline = p_input_line;
453
if (! ((name[OLD] || ! p_timestamp[OLD])
454
&& (name[NEW] || ! p_timestamp[NEW]))
457
char numbuf[LINENUM_LENGTH_BOUND + 1];
458
say ("missing header for unified diff at line %s of patch\n",
459
format_linenum (numbuf, p_sline));
463
stars_this_line = strnEQ(s, "********", 8);
464
if ((diff_type == NO_DIFF
465
|| diff_type == CONTEXT_DIFF
466
|| diff_type == NEW_CONTEXT_DIFF)
467
&& stars_last_line && strnEQ (s, "*** ", 4)) {
469
if (s[0] == '0' && !ISDIGIT (s[1]))
470
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD];
471
/* if this is a new context diff the character just before */
472
/* the newline is a '*'. */
476
p_strip_trailing_cr = strip_trailing_cr;
477
p_start = previous_line;
478
p_sline = p_input_line - 1;
479
retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
482
/* Scan the first hunk to see whether the file contents
483
appear to have been deleted. */
484
file_offset saved_p_base = p_base;
485
LINENUM saved_p_bline = p_bline;
486
Fseek (pfp, previous_line, SEEK_SET);
488
if (another_hunk (retval, false)
489
&& ! p_repl_lines && p_newfirst == 1)
490
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW];
491
next_intuit_at (saved_p_base, saved_p_bline);
494
if (! ((name[OLD] || ! p_timestamp[OLD])
495
&& (name[NEW] || ! p_timestamp[NEW]))
498
char numbuf[LINENUM_LENGTH_BOUND + 1];
499
say ("missing header for context diff at line %s of patch\n",
500
format_linenum (numbuf, p_sline));
504
if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) &&
505
last_line_was_command &&
506
(strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) {
507
p_start = previous_line;
508
p_sline = p_input_line - 1;
510
p_strip_trailing_cr = strip_trailing_cr;
511
retval = NORMAL_DIFF;
518
/* To intuit `inname', the name of the file to patch,
519
use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599
520
(with some modifications if posixly_correct is zero):
522
- Take the old and new names from the context header if present,
523
and take the index name from the `Index:' line if present and
524
if either the old and new names are both absent
525
or posixly_correct is nonzero.
526
Consider the file names to be in the order (old, new, index).
527
- If some named files exist, use the first one if posixly_correct
528
is nonzero, the best one otherwise.
529
- If patch_get is nonzero, and no named files exist,
530
but an RCS or SCCS master file exists,
531
use the first named file with an RCS or SCCS master.
532
- If no named files exist, no RCS or SCCS master was found,
533
some names are given, posixly_correct is zero,
534
and the patch appears to create a file, then use the best name
535
requiring the creation of the fewest directories.
536
- Otherwise, report failure by setting `inname' to 0;
537
this causes our invoker to ask the user for a file name. */
543
enum nametype i0 = NONE;
545
if (! posixly_correct && (name[OLD] || name[NEW]) && name[INDEX])
551
for (i = OLD; i <= INDEX; i++)
554
if (i0 != NONE && strcmp (name[i0], name[i]) == 0)
556
/* It's the same name as before; reuse stat results. */
557
stat_errno[i] = stat_errno[i0];
561
else if (stat (name[i], &st[i]) != 0)
562
stat_errno[i] = errno;
572
if (! posixly_correct)
576
i = best_name (name, stat_errno);
578
if (i == NONE && patch_get)
580
enum nametype nope = NONE;
582
for (i = OLD; i <= INDEX; i++)
588
bool readonly = (outfile
589
&& strcmp (outfile, name[i]) != 0);
591
if (nope == NONE || strcmp (name[nope], name[i]) != 0)
593
cs = (version_controller
594
(name[i], readonly, (struct stat *) 0,
596
version_controlled[i] = !! cs;
599
if (version_get (name[i], cs, false, readonly,
603
version_controlled[i] = 0;
618
is_empty = i == NONE || st[i].st_size == 0;
619
if ((! is_empty) < p_says_nonexistent[reverse ^ is_empty])
624
("The next patch%s would %s the file %s,\nwhich %s!",
625
reverse ? ", when reversed," : "",
626
(i == NONE ? "delete"
627
: st[i].st_size == 0 ? "empty out"
629
quotearg (name[i == NONE || st[i].st_size == 0 ? i0 : i]),
630
(i == NONE ? "does not exist"
631
: st[i].st_size == 0 ? "is already empty"
632
: "already exists"));
635
if (i == NONE && p_says_nonexistent[reverse])
638
int newdirs_min = INT_MAX;
639
int distance_from_minimum[3];
641
for (i = OLD; i <= INDEX; i++)
644
newdirs[i] = (prefix_components (name[i], false)
645
- prefix_components (name[i], true));
646
if (newdirs[i] < newdirs_min)
647
newdirs_min = newdirs[i];
650
for (i = OLD; i <= INDEX; i++)
652
distance_from_minimum[i] = newdirs[i] - newdirs_min;
654
i = best_name (name, distance_from_minimum);
665
inerrno = stat_errno[i];
666
invc = version_controlled[i];
670
for (i = OLD; i <= INDEX; i++)
677
/* Count the path name components in FILENAME's prefix.
678
If CHECKDIRS is true, count only existing directories. */
680
prefix_components (char *filename, bool checkdirs)
683
struct stat stat_buf;
685
char *f = filename + FILESYSTEM_PREFIX_LEN (filename);
689
if (ISSLASH (f[0]) && ! ISSLASH (f[-1]))
694
stat_result = stat (filename, &stat_buf);
696
if (! (stat_result == 0 && S_ISDIR (stat_buf.st_mode)))
706
/* Return the index of the best of NAME[OLD], NAME[NEW], and NAME[INDEX].
707
Ignore null names, and ignore NAME[i] if IGNORE[i] is nonzero.
708
Return NONE if all names are ignored. */
710
best_name (char *const *name, int const *ignore)
714
int components_min = INT_MAX;
715
size_t basename_len[3];
716
size_t basename_len_min = SIZE_MAX;
718
size_t len_min = SIZE_MAX;
720
for (i = OLD; i <= INDEX; i++)
721
if (name[i] && !ignore[i])
723
/* Take the names with the fewest prefix components. */
724
components[i] = prefix_components (name[i], false);
725
if (components_min < components[i])
727
components_min = components[i];
729
/* Of those, take the names with the shortest basename. */
730
basename_len[i] = strlen (base_name (name[i]));
731
if (basename_len_min < basename_len[i])
733
basename_len_min = basename_len[i];
735
/* Of those, take the shortest names. */
736
len[i] = strlen (name[i]);
737
if (len_min < len[i])
742
/* Of those, take the first name. */
743
for (i = OLD; i <= INDEX; i++)
744
if (name[i] && !ignore[i]
745
&& components[i] == components_min
746
&& basename_len[i] == basename_len_min
747
&& len[i] == len_min)
753
/* Remember where this patch ends so we know where to start up again. */
756
next_intuit_at (file_offset file_pos, LINENUM file_line)
762
/* Basically a verbose fseek() to the actual diff listing. */
765
skip_to (file_offset file_pos, LINENUM file_line)
767
register FILE *i = pfp;
768
register FILE *o = stdout;
771
assert(p_base <= file_pos);
772
if ((verbosity == VERBOSE || !inname) && p_base < file_pos) {
773
Fseek (i, p_base, SEEK_SET);
774
say ("The text leading up to this was:\n--------------------------\n");
776
while (file_tell (i) < file_pos)
781
if ((c = getc (i)) == EOF)
788
say ("--------------------------\n");
791
Fseek (i, file_pos, SEEK_SET);
792
p_input_line = file_line - 1;
795
/* Make this a function for better debugging. */
799
char numbuf[LINENUM_LENGTH_BOUND + 1];
800
fatal ("malformed patch at line %s: %s",
801
format_linenum (numbuf, p_input_line), buf);
802
/* about as informative as "Syntax error" in C */
805
/* Parse a line number from a string.
806
Return the address of the first char after the number. */
808
scan_linenum (char *s0, LINENUM *linenum)
812
bool overflow = false;
813
char numbuf[LINENUM_LENGTH_BOUND + 1];
815
for (s = s0; ISDIGIT (*s); s++)
817
LINENUM new_n = 10 * n + (*s - '0');
818
overflow |= new_n / 10 != n;
823
fatal ("missing line number at line %s: %s",
824
format_linenum (numbuf, p_input_line), buf);
827
fatal ("line number %.*s is too large at line %s: %s",
828
(int) (s - s0), s0, format_linenum (numbuf, p_input_line), buf);
834
/* 1 if there is more of the current diff listing to process;
835
0 if not; -1 if ran out of memory. */
838
another_hunk (enum diff difftype, bool rev)
841
register LINENUM context = 0;
842
register size_t chars_read;
843
char numbuf0[LINENUM_LENGTH_BOUND + 1];
844
char numbuf1[LINENUM_LENGTH_BOUND + 1];
845
char numbuf2[LINENUM_LENGTH_BOUND + 1];
846
char numbuf3[LINENUM_LENGTH_BOUND + 1];
849
if (p_end == p_efake)
850
p_end = p_bfake; /* don't free twice */
858
p_max = hunkmax; /* gets reduced when --- found */
859
if (difftype == CONTEXT_DIFF || difftype == NEW_CONTEXT_DIFF) {
860
file_offset line_beginning = file_tell (pfp);
861
/* file pos of the current line */
862
LINENUM repl_beginning = 0; /* index of --- line */
863
register LINENUM fillcnt = 0; /* #lines of missing ptrn or repl */
864
register LINENUM fillsrc; /* index of first line to copy */
865
register LINENUM filldst; /* index of first missing line */
866
bool ptrn_spaces_eaten = false; /* ptrn was slightly misformed */
867
bool some_context = false; /* (perhaps internal) context seen */
868
register bool repl_could_be_missing = true;
869
bool ptrn_missing = false; /* The pattern was missing. */
870
bool repl_missing = false; /* Likewise for replacement. */
871
file_offset repl_backtrack_position = 0;
872
/* file pos of first repl line */
873
LINENUM repl_patch_line; /* input line number for same */
874
LINENUM repl_context; /* context for same */
875
LINENUM ptrn_prefix_context = -1; /* lines in pattern prefix context */
876
LINENUM ptrn_suffix_context = -1; /* lines in pattern suffix context */
877
LINENUM repl_prefix_context = -1; /* lines in replac. prefix context */
878
LINENUM ptrn_copiable = 0; /* # of copiable lines in ptrn */
879
LINENUM repl_copiable = 0; /* Likewise for replacement. */
881
/* Pacify `gcc -Wall'. */
882
fillsrc = filldst = repl_patch_line = repl_context = 0;
884
chars_read = get_line ();
885
if (chars_read == (size_t) -1
887
|| strncmp (buf, "********", 8) != 0) {
888
next_intuit_at(line_beginning,p_input_line);
889
return chars_read == (size_t) -1 ? -1 : 0;
891
p_hunk_beg = p_input_line + 1;
892
while (p_end < p_max) {
893
chars_read = get_line ();
894
if (chars_read == (size_t) -1)
897
if (repl_beginning && repl_could_be_missing) {
901
if (p_max - p_end < 4) {
902
strcpy (buf, " \n"); /* assume blank lines got chopped */
905
fatal ("unexpected end of file in patch");
909
if (p_end == hunkmax)
910
fatal ("unterminated hunk starting at line %s; giving up at line %s: %s",
911
format_linenum (numbuf0, pch_hunk_beg ()),
912
format_linenum (numbuf1, p_input_line), buf);
913
assert(p_end < hunkmax);
914
p_Char[p_end] = *buf;
919
if (strnEQ(buf, "********", 8)) {
920
if (repl_beginning && repl_could_be_missing) {
925
fatal ("unexpected end of hunk at line %s",
926
format_linenum (numbuf0, p_input_line));
929
if (repl_beginning && repl_could_be_missing) {
933
fatal ("unexpected `***' at line %s: %s",
934
format_linenum (numbuf0, p_input_line), buf);
937
p_len[p_end] = strlen (buf);
938
if (! (p_line[p_end] = savestr (buf))) {
942
for (s = buf; *s && !ISDIGIT (*s); s++)
944
if (strnEQ(s,"0,0",3))
945
remove_prefix (s, 2);
946
s = scan_linenum (s, &p_first);
948
while (*s && !ISDIGIT (*s))
950
scan_linenum (s, &p_ptrn_lines);
951
p_ptrn_lines += 1 - p_first;
959
p_max = p_ptrn_lines + 6; /* we need this much at least */
960
while (p_max >= hunkmax)
961
if (! grow_hunkmax ())
968
if (ptrn_prefix_context == -1)
969
ptrn_prefix_context = context;
970
ptrn_suffix_context = context;
973
!= p_ptrn_lines + 1 + (p_Char[p_end - 1] == '\n')))
977
/* `Old' lines were omitted. Set up to fill
978
them in from `new' context lines. */
980
p_end = p_ptrn_lines + 1;
981
ptrn_prefix_context = ptrn_suffix_context = -1;
984
fillcnt = p_ptrn_lines;
986
else if (! repl_beginning)
987
fatal ("%s `---' at line %s; check line numbers at line %s",
988
(p_end <= p_ptrn_lines
991
format_linenum (numbuf0, p_input_line),
992
format_linenum (numbuf1, p_hunk_beg));
993
else if (! repl_could_be_missing)
994
fatal ("duplicate `---' at line %s; check line numbers at line %s",
995
format_linenum (numbuf0, p_input_line),
996
format_linenum (numbuf1,
997
p_hunk_beg + repl_beginning));
1000
repl_missing = true;
1004
repl_beginning = p_end;
1005
repl_backtrack_position = file_tell (pfp);
1006
repl_patch_line = p_input_line;
1007
repl_context = context;
1008
p_len[p_end] = strlen (buf);
1009
if (! (p_line[p_end] = savestr (buf)))
1014
p_Char[p_end] = '=';
1015
for (s = buf; *s && ! ISDIGIT (*s); s++)
1017
s = scan_linenum (s, &p_newfirst);
1025
while (! ISDIGIT (*s));
1026
scan_linenum (s, &p_repl_lines);
1027
p_repl_lines += 1 - p_newfirst;
1029
else if (p_newfirst)
1036
p_max = p_repl_lines + p_end;
1037
while (p_max >= hunkmax)
1038
if (! grow_hunkmax ())
1040
if (p_repl_lines != ptrn_copiable
1041
&& (p_prefix_context != 0
1043
|| p_repl_lines != 1))
1044
repl_could_be_missing = false;
1048
repl_could_be_missing = false;
1052
if (*s == '\n' && canonicalize) {
1056
if (*s == ' ' || *s == '\t') {
1059
} else if (repl_beginning && repl_could_be_missing) {
1060
repl_missing = true;
1063
if (! repl_beginning)
1065
if (ptrn_prefix_context == -1)
1066
ptrn_prefix_context = context;
1070
if (repl_prefix_context == -1)
1071
repl_prefix_context = context;
1075
&& p_end == (repl_beginning ? p_max : p_ptrn_lines)
1076
&& incomplete_line ());
1077
p_len[p_end] = chars_read;
1078
if (! (p_line[p_end] = savebuf (s, chars_read))) {
1084
case '\t': case '\n': /* assume spaces got eaten */
1090
if (repl_beginning && repl_could_be_missing &&
1091
(!ptrn_spaces_eaten || difftype == NEW_CONTEXT_DIFF) ) {
1092
repl_missing = true;
1097
&& p_end == (repl_beginning ? p_max : p_ptrn_lines)
1098
&& incomplete_line ());
1099
p_len[p_end] = chars_read;
1100
if (! (p_line[p_end] = savebuf (buf, chars_read))) {
1104
if (p_end != p_ptrn_lines + 1) {
1105
ptrn_spaces_eaten |= (repl_beginning != 0);
1106
some_context = true;
1112
p_Char[p_end] = ' ';
1118
if (*s == '\n' && canonicalize) {
1122
if (*s == ' ' || *s == '\t') {
1125
} else if (repl_beginning && repl_could_be_missing) {
1126
repl_missing = true;
1129
some_context = true;
1137
&& p_end == (repl_beginning ? p_max : p_ptrn_lines)
1138
&& incomplete_line ());
1139
p_len[p_end] = chars_read;
1140
if (! (p_line[p_end] = savebuf (buf + 2, chars_read))) {
1146
if (repl_beginning && repl_could_be_missing) {
1147
repl_missing = true;
1155
if (p_end >=0 && !repl_beginning)
1156
fatal ("no `---' found in patch at line %s",
1157
format_linenum (numbuf0, pch_hunk_beg ()));
1161
/* reset state back to just after --- */
1162
p_input_line = repl_patch_line;
1163
context = repl_context;
1164
for (p_end--; p_end > repl_beginning; p_end--)
1165
free(p_line[p_end]);
1166
Fseek (pfp, repl_backtrack_position, SEEK_SET);
1168
/* redundant 'new' context lines were omitted - set */
1169
/* up to fill them in from the old file context */
1171
filldst = repl_beginning+1;
1172
fillcnt = p_repl_lines;
1175
else if (! ptrn_missing && ptrn_copiable != repl_copiable)
1176
fatal ("context mangled in hunk at line %s",
1177
format_linenum (numbuf0, p_hunk_beg));
1178
else if (!some_context && fillcnt == 1) {
1179
/* the first hunk was a null hunk with no context */
1180
/* and we were expecting one line -- fix it up. */
1181
while (filldst < p_end) {
1182
p_line[filldst] = p_line[filldst+1];
1183
p_Char[filldst] = p_Char[filldst+1];
1184
p_len[filldst] = p_len[filldst+1];
1188
repl_beginning--; /* this doesn't need to be fixed */
1191
p_first++; /* do append rather than insert */
1196
p_prefix_context = ((repl_prefix_context == -1
1197
|| (ptrn_prefix_context != -1
1198
&& ptrn_prefix_context < repl_prefix_context))
1199
? ptrn_prefix_context : repl_prefix_context);
1200
p_suffix_context = ((ptrn_suffix_context != -1
1201
&& ptrn_suffix_context < context)
1202
? ptrn_suffix_context : context);
1203
assert (p_prefix_context != -1 && p_suffix_context != -1);
1205
if (difftype == CONTEXT_DIFF
1208
&& p_prefix_context + p_suffix_context < ptrn_copiable))) {
1209
if (verbosity == VERBOSE)
1210
say ("%s\n%s\n%s\n",
1211
"(Fascinating -- this is really a new-style context diff but without",
1212
"the telltale extra asterisks on the *** line that usually indicate",
1213
"the new style...)");
1214
diff_type = difftype = NEW_CONTEXT_DIFF;
1217
/* if there were omitted context lines, fill them in now */
1219
p_bfake = filldst; /* remember where not to free() */
1220
p_efake = filldst + fillcnt - 1;
1221
while (fillcnt-- > 0) {
1222
while (fillsrc <= p_end && fillsrc != repl_beginning
1223
&& p_Char[fillsrc] != ' ')
1225
if (p_end < fillsrc || fillsrc == repl_beginning)
1227
fatal ("replacement text or line numbers mangled in hunk at line %s",
1228
format_linenum (numbuf0, p_hunk_beg));
1230
p_line[filldst] = p_line[fillsrc];
1231
p_Char[filldst] = p_Char[fillsrc];
1232
p_len[filldst] = p_len[fillsrc];
1233
fillsrc++; filldst++;
1235
while (fillsrc <= p_end && fillsrc != repl_beginning)
1237
if (p_Char[fillsrc] == ' ')
1238
fatal ("replacement text or line numbers mangled in hunk at line %s",
1239
format_linenum (numbuf0, p_hunk_beg));
1243
printf ("fillsrc %s, filldst %s, rb %s, e+1 %s\n",
1244
format_linenum (numbuf0, fillsrc),
1245
format_linenum (numbuf1, filldst),
1246
format_linenum (numbuf2, repl_beginning),
1247
format_linenum (numbuf3, p_end + 1));
1248
assert(fillsrc==p_end+1 || fillsrc==repl_beginning);
1249
assert(filldst==p_end+1 || filldst==repl_beginning);
1252
else if (difftype == UNI_DIFF) {
1253
file_offset line_beginning = file_tell (pfp);
1254
/* file pos of the current line */
1255
register LINENUM fillsrc; /* index of old lines */
1256
register LINENUM filldst; /* index of new lines */
1259
chars_read = get_line ();
1260
if (chars_read == (size_t) -1
1262
|| strncmp (buf, "@@ -", 4) != 0) {
1263
next_intuit_at(line_beginning,p_input_line);
1264
return chars_read == (size_t) -1 ? -1 : 0;
1266
s = scan_linenum (buf + 4, &p_first);
1268
s = scan_linenum (s + 1, &p_ptrn_lines);
1274
s = scan_linenum (s + 1, &p_newfirst);
1276
s = scan_linenum (s + 1, &p_repl_lines);
1283
p_first++; /* do append rather than insert */
1286
p_max = p_ptrn_lines + p_repl_lines + 1;
1287
while (p_max >= hunkmax)
1288
if (! grow_hunkmax ())
1291
filldst = fillsrc + p_ptrn_lines;
1292
p_end = filldst + p_repl_lines;
1293
sprintf (buf, "*** %s,%s ****\n",
1294
format_linenum (numbuf0, p_first),
1295
format_linenum (numbuf1, p_first + p_ptrn_lines - 1));
1296
p_len[0] = strlen (buf);
1297
if (! (p_line[0] = savestr (buf))) {
1302
sprintf (buf, "--- %s,%s ----\n",
1303
format_linenum (numbuf0, p_newfirst),
1304
format_linenum (numbuf1, p_newfirst + p_repl_lines - 1));
1305
p_len[filldst] = strlen (buf);
1306
if (! (p_line[filldst] = savestr (buf))) {
1310
p_Char[filldst++] = '=';
1311
p_prefix_context = -1;
1312
p_hunk_beg = p_input_line + 1;
1313
while (fillsrc <= p_ptrn_lines || filldst <= p_end) {
1314
chars_read = get_line ();
1316
if (p_max - filldst < 3) {
1317
strcpy (buf, " \n"); /* assume blank lines got chopped */
1320
fatal ("unexpected end of file in patch");
1323
if (chars_read == (size_t) -1)
1325
else if (*buf == '\t' || *buf == '\n') {
1326
ch = ' '; /* assume the space got eaten */
1327
s = savebuf (buf, chars_read);
1331
s = savebuf (buf+1, --chars_read);
1334
while (--filldst > p_ptrn_lines)
1335
free(p_line[filldst]);
1341
if (fillsrc > p_ptrn_lines) {
1346
chars_read -= fillsrc == p_ptrn_lines && incomplete_line ();
1347
p_Char[fillsrc] = ch;
1348
p_line[fillsrc] = s;
1349
p_len[fillsrc++] = chars_read;
1355
if (fillsrc > p_ptrn_lines) {
1357
while (--filldst > p_ptrn_lines)
1358
free(p_line[filldst]);
1363
chars_read -= fillsrc == p_ptrn_lines && incomplete_line ();
1364
p_Char[fillsrc] = ch;
1365
p_line[fillsrc] = s;
1366
p_len[fillsrc++] = chars_read;
1367
s = savebuf (s, chars_read);
1369
while (--filldst > p_ptrn_lines)
1370
free(p_line[filldst]);
1376
if (filldst > p_end) {
1378
while (--filldst > p_ptrn_lines)
1379
free(p_line[filldst]);
1383
chars_read -= filldst == p_end && incomplete_line ();
1384
p_Char[filldst] = ch;
1385
p_line[filldst] = s;
1386
p_len[filldst++] = chars_read;
1393
if (p_prefix_context == -1)
1394
p_prefix_context = context;
1398
if (p_prefix_context == -1)
1400
p_suffix_context = context;
1402
else { /* normal diff--fake it up */
1406
file_offset line_beginning = file_tell (pfp);
1408
p_prefix_context = p_suffix_context = 0;
1409
chars_read = get_line ();
1410
if (chars_read == (size_t) -1 || !chars_read || !ISDIGIT (*buf)) {
1411
next_intuit_at(line_beginning,p_input_line);
1412
return chars_read == (size_t) -1 ? -1 : 0;
1414
s = scan_linenum (buf, &p_first);
1416
s = scan_linenum (s + 1, &p_ptrn_lines);
1417
p_ptrn_lines += 1 - p_first;
1420
p_ptrn_lines = (*s != 'a');
1422
if (hunk_type == 'a')
1423
p_first++; /* do append rather than insert */
1424
s = scan_linenum (s + 1, &min);
1426
scan_linenum (s + 1, &max);
1429
if (hunk_type == 'd')
1431
p_end = p_ptrn_lines + 1 + max - min + 1;
1432
while (p_end >= hunkmax)
1433
if (! grow_hunkmax ())
1439
p_repl_lines = max - min + 1;
1440
sprintf (buf, "*** %s,%s\n",
1441
format_linenum (numbuf0, p_first),
1442
format_linenum (numbuf1, p_first + p_ptrn_lines - 1));
1443
p_len[0] = strlen (buf);
1444
if (! (p_line[0] = savestr (buf))) {
1449
for (i=1; i<=p_ptrn_lines; i++) {
1450
chars_read = get_line ();
1451
if (chars_read == (size_t) -1)
1457
fatal ("unexpected end of file in patch at line %s",
1458
format_linenum (numbuf0, p_input_line));
1459
if (buf[0] != '<' || (buf[1] != ' ' && buf[1] != '\t'))
1460
fatal ("`<' expected at line %s of patch",
1461
format_linenum (numbuf0, p_input_line));
1462
chars_read -= 2 + (i == p_ptrn_lines && incomplete_line ());
1463
p_len[i] = chars_read;
1464
if (! (p_line[i] = savebuf (buf + 2, chars_read))) {
1470
if (hunk_type == 'c') {
1471
chars_read = get_line ();
1472
if (chars_read == (size_t) -1)
1478
fatal ("unexpected end of file in patch at line %s",
1479
format_linenum (numbuf0, p_input_line));
1481
fatal ("`---' expected at line %s of patch",
1482
format_linenum (numbuf0, p_input_line));
1484
sprintf (buf, "--- %s,%s\n",
1485
format_linenum (numbuf0, min),
1486
format_linenum (numbuf1, max));
1487
p_len[i] = strlen (buf);
1488
if (! (p_line[i] = savestr (buf))) {
1493
for (i++; i<=p_end; i++) {
1494
chars_read = get_line ();
1495
if (chars_read == (size_t) -1)
1501
fatal ("unexpected end of file in patch at line %s",
1502
format_linenum (numbuf0, p_input_line));
1503
if (buf[0] != '>' || (buf[1] != ' ' && buf[1] != '\t'))
1504
fatal ("`>' expected at line %s of patch",
1505
format_linenum (numbuf0, p_input_line));
1506
chars_read -= 2 + (i == p_end && incomplete_line ());
1507
p_len[i] = chars_read;
1508
if (! (p_line[i] = savebuf (buf + 2, chars_read))) {
1515
if (rev) /* backwards patch? */
1517
say ("Not enough memory to swap next hunk!\n");
1522
for (i=0; i <= p_end; i++) {
1523
if (i == p_ptrn_lines)
1527
fprintf (stderr, "%s %c %c ", format_linenum (numbuf0, i),
1528
p_Char[i], special);
1529
pch_write_line (i, stderr);
1533
if (p_end+1 < hunkmax) /* paranoia reigns supreme... */
1534
p_Char[p_end+1] = '^'; /* add a stopper for apply_hunk */
1541
return pget_line (p_indent, p_rfc934_nesting, p_strip_trailing_cr,
1542
p_pass_comments_through);
1545
/* Input a line from the patch file, worrying about indentation.
1546
Strip up to INDENT characters' worth of leading indentation.
1547
Then remove up to RFC934_NESTING instances of leading "- ".
1548
If STRIP_TRAILING_CR is true, remove any trailing carriage-return.
1549
Unless PASS_COMMENTS_THROUGH is true, ignore any resulting lines
1550
that begin with '#'; they're comments.
1551
Ignore any partial lines at end of input, but warn about them.
1552
Succeed if a line was read; it is terminated by "\n\0" for convenience.
1553
Return the number of characters read, including '\n' but not '\0'.
1554
Return -1 if we ran out of memory. */
1557
pget_line (int indent, int rfc934_nesting, bool strip_trailing_cr,
1558
bool pass_comments_through)
1560
register FILE *fp = pfp;
1580
if (c == ' ' || c == 'X')
1591
while (c == '-' && 0 <= --rfc934_nesting)
1595
goto patch_ends_in_middle_of_line;
1604
goto patch_ends_in_middle_of_line;
1629
goto patch_ends_in_middle_of_line;
1634
while (*b == '#' && !pass_comments_through);
1636
if (strip_trailing_cr && 2 <= i && b[i - 2] == '\r')
1641
patch_ends_in_middle_of_line:
1644
say ("patch unexpectedly ends in middle of line\n");
1649
incomplete_line (void)
1651
register FILE *fp = pfp;
1653
register file_offset line_beginning = file_tell (fp);
1655
if (getc (fp) == '\\')
1657
while ((c = getc (fp)) != '\n' && c != EOF)
1663
/* We don't trust ungetc. */
1664
Fseek (pfp, line_beginning, SEEK_SET);
1669
/* Reverse the old and new portions of the current hunk. */
1674
char **tp_line; /* the text of the hunk */
1675
size_t *tp_len; /* length of each line */
1676
char *tp_char; /* +, -, and ! */
1679
bool blankline = false;
1683
p_first = p_newfirst;
1686
/* make a scratch copy */
1691
p_line = 0; /* force set_hunkmax to allocate again */
1695
if (!p_line || !p_len || !p_Char) {
1705
return false; /* not enough memory to swap hunk! */
1708
/* now turn the new into the old */
1710
i = p_ptrn_lines + 1;
1711
if (tp_char[i] == '\n') { /* account for possible blank line */
1715
if (p_efake >= 0) { /* fix non-freeable ptr range */
1723
for (n=0; i <= p_end; i++,n++) {
1724
p_line[n] = tp_line[i];
1725
p_Char[n] = tp_char[i];
1726
if (p_Char[n] == '+')
1728
p_len[n] = tp_len[i];
1731
i = p_ptrn_lines + 1;
1732
p_line[n] = tp_line[i];
1733
p_Char[n] = tp_char[i];
1734
p_len[n] = tp_len[i];
1737
assert(p_Char[0] == '=');
1739
for (s=p_line[0]; *s; s++)
1743
/* now turn the old into the new */
1745
assert(tp_char[0] == '*');
1747
for (s=tp_line[0]; *s; s++)
1750
for (i=0; n <= p_end; i++,n++) {
1751
p_line[n] = tp_line[i];
1752
p_Char[n] = tp_char[i];
1753
if (p_Char[n] == '-')
1755
p_len[n] = tp_len[i];
1757
assert(i == p_ptrn_lines + 1);
1759
p_ptrn_lines = p_repl_lines;
1770
/* Return whether file WHICH (false = old, true = new) appears to nonexistent.
1771
Return 1 for empty, 2 for nonexistent. */
1774
pch_says_nonexistent (bool which)
1776
return p_says_nonexistent[which];
1779
/* Return timestamp of patch header for file WHICH (false = old, true = new),
1780
or -1 if there was no timestamp or an error in the timestamp. */
1783
pch_timestamp (bool which)
1785
return p_timestamp[which];
1788
/* Return the specified line position in the old file of the old context. */
1796
/* Return the number of lines of old context. */
1799
pch_ptrn_lines (void)
1801
return p_ptrn_lines;
1804
/* Return the probable line position in the new file of the first line. */
1812
/* Return the number of lines in the replacement text including context. */
1815
pch_repl_lines (void)
1817
return p_repl_lines;
1820
/* Return the number of lines in the whole hunk. */
1828
/* Return the number of context lines before the first changed line. */
1831
pch_prefix_context (void)
1833
return p_prefix_context;
1836
/* Return the number of context lines after the last changed line. */
1839
pch_suffix_context (void)
1841
return p_suffix_context;
1844
/* Return the length of a particular patch line. */
1847
pch_line_len (LINENUM line)
1852
/* Return the control character (+, -, *, !, etc) for a patch line. */
1855
pch_char (LINENUM line)
1857
return p_Char[line];
1860
/* Return a pointer to a particular patch line. */
1863
pfetch (LINENUM line)
1865
return p_line[line];
1868
/* Output a patch line. */
1871
pch_write_line (LINENUM line, FILE *file)
1873
bool after_newline = p_line[line][p_len[line] - 1] == '\n';
1874
if (! fwrite (p_line[line], sizeof (*p_line[line]), p_len[line], file))
1876
return after_newline;
1879
/* Return where in the patch file this hunk began, for error messages. */
1887
/* Is the newline-terminated line a valid `ed' command for patch
1888
input? If so, return the command character; if not, return 0.
1889
This accepts accepts just a subset of the valid commands, but it's
1890
good enough in practice. */
1893
get_ed_command_letter (char const *line)
1895
char const *p = line;
1900
while (ISDIGIT (*++p))
1904
if (! ISDIGIT (*++p))
1906
while (ISDIGIT (*++p))
1925
if (strncmp (p, "/.//", 4) != 0)
1934
while (*p == ' ' || *p == '\t')
1941
/* Apply an ed script by feeding ed itself. */
1944
do_ed_script (FILE *ofp)
1946
static char const ed_program[] = ed_PROGRAM;
1948
register file_offset beginning_of_this_line;
1949
register FILE *pipefp = 0;
1950
register size_t chars_read;
1952
if (! dry_run && ! skip_rest_of_patch) {
1953
int exclusive = TMPOUTNAME_needs_removal ? 0 : O_EXCL;
1955
TMPOUTNAME_needs_removal = 1;
1956
copy_file (inname, TMPOUTNAME, exclusive, instat.st_mode);
1957
sprintf (buf, "%s %s%s", ed_program, verbosity == VERBOSE ? "" : "- ",
1960
pipefp = popen(buf, binary_transput ? "wb" : "w");
1962
pfatal ("Can't open pipe to %s", quotearg (buf));
1965
char ed_command_letter;
1966
beginning_of_this_line = file_tell (pfp);
1967
chars_read = get_line ();
1969
next_intuit_at(beginning_of_this_line,p_input_line);
1972
ed_command_letter = get_ed_command_letter (buf);
1973
if (ed_command_letter) {
1975
if (! fwrite (buf, sizeof *buf, chars_read, pipefp))
1977
if (ed_command_letter != 'd' && ed_command_letter != 's') {
1978
p_pass_comments_through = true;
1979
while ((chars_read = get_line ()) != 0) {
1981
if (! fwrite (buf, sizeof *buf, chars_read, pipefp))
1983
if (chars_read == 2 && strEQ (buf, ".\n"))
1986
p_pass_comments_through = false;
1990
next_intuit_at(beginning_of_this_line,p_input_line);
1996
if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, pipefp) == 0
1997
|| fflush (pipefp) != 0)
1999
if (pclose (pipefp) != 0)
2000
fatal ("%s FAILED", ed_program);
2004
FILE *ifp = fopen (TMPOUTNAME, binary_transput ? "rb" : "r");
2007
pfatal ("can't open `%s'", TMPOUTNAME);
2008
while ((c = getc (ifp)) != EOF)
2009
if (putc (c, ofp) == EOF)
2011
if (ferror (ifp) || fclose (ifp) != 0)