1
/* patch - a program to apply diffs to original files */
3
/* $Id: patch.c,v 1.44 2003/05/20 13:55:03 eggert Exp $ */
5
/* Copyright (C) 1984, 1985, 1986, 1987, 1988 Larry Wall
7
Copyright (C) 1989, 1990, 1991, 1992, 1993, 1997, 1998, 1999, 2002,
8
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. */
30
#include <backupfile.h>
42
/* Some nonstandard hosts don't declare this structure even in <utime.h>. */
43
#if ! HAVE_STRUCT_UTIMBUF
51
/* Output stream state. */
61
static FILE *create_output_file (char const *, int);
62
static LINENUM locate_hunk (LINENUM);
63
static bool apply_hunk (struct outstate *, LINENUM);
64
static bool copy_till (struct outstate *, LINENUM);
65
static bool patch_match (LINENUM, LINENUM, LINENUM, LINENUM);
66
static bool similar (char const *, size_t, char const *, size_t);
67
static bool spew_output (struct outstate *);
68
static char const *make_temp (char);
69
static int numeric_string (char const *, bool, char const *);
70
static void abort_hunk (void);
71
static void cleanup (void);
72
static void get_some_switches (void);
73
static void init_output (char const *, int, struct outstate *);
74
static void init_reject (void);
75
static void reinitialize_almost_everything (void);
76
static void remove_if_needed (char const *, int volatile *);
77
static void usage (FILE *, int) __attribute__((noreturn));
79
static bool make_backups;
80
static bool backup_if_mismatch;
81
static char const *version_control;
82
static char const *version_control_context;
83
static bool remove_empty_files;
85
/* true if -R was specified on command line. */
86
static bool reverse_flag_specified;
88
/* how many input lines have been irretractably output */
89
static LINENUM last_frozen_line;
91
static char const *do_defines; /* symbol to patch using ifdef, ifndef, etc. */
92
static char const if_defined[] = "\n#ifdef %s\n";
93
static char const not_defined[] = "\n#ifndef %s\n";
94
static char const else_defined[] = "\n#else\n";
95
static char const end_defined[] = "\n#endif\n";
98
static char * const *Argv;
100
static FILE *rejfp; /* reject file pointer */
102
static char const *patchname;
103
static char *rejname;
104
static char const * volatile TMPREJNAME;
105
static int volatile TMPREJNAME_needs_removal;
107
static LINENUM last_offset;
108
static LINENUM maxfuzz = 2;
110
static char serrbuf[BUFSIZ];
112
/* Apply a set of diffs as appropriate. */
115
main (int argc, char **argv)
118
bool somefailed = false;
119
struct outstate outstate;
120
char numbuf[LINENUM_LENGTH_BOUND + 1];
122
xalloc_exit_failure = 2;
123
program_name = argv[0];
126
setbuf(stderr, serrbuf);
128
xalloc_fail_func = memory_fatal;
130
buf = xmalloc (bufsize);
134
val = getenv ("QUOTING_STYLE");
136
int i = val ? argmatch (val, quoting_style_args, 0, 0) : -1;
137
set_quoting_style ((struct quoting_options *) 0,
138
i < 0 ? shell_quoting_style : (enum quoting_style) i);
141
posixly_correct = getenv ("POSIXLY_CORRECT") != 0;
142
backup_if_mismatch = ! posixly_correct;
143
patch_get = ((val = getenv ("PATCH_GET"))
144
? numeric_string (val, true, "PATCH_GET value")
145
: posixly_correct - 1);
147
val = getenv ("SIMPLE_BACKUP_SUFFIX");
148
simple_backup_suffix = val && *val ? val : ".orig";
150
if ((version_control = getenv ("PATCH_VERSION_CONTROL")))
151
version_control_context = "$PATCH_VERSION_CONTROL";
152
else if ((version_control = getenv ("VERSION_CONTROL")))
153
version_control_context = "$VERSION_CONTROL";
155
/* Cons up the names of the global temporary files.
156
Do this before `cleanup' can possibly be called (e.g. by `pfatal'). */
157
TMPOUTNAME = make_temp ('o');
158
TMPINNAME = make_temp ('i');
159
TMPREJNAME = make_temp ('r');
160
TMPPATNAME = make_temp ('p');
167
if (make_backups | backup_if_mismatch)
168
backup_type = get_version (version_control_context, version_control);
170
init_output (outfile, 0, &outstate);
172
/* Make sure we clean up in case of disaster. */
176
open_patch_file (patchname);
177
there_is_another_patch();
178
reinitialize_almost_everything()
179
) { /* for each patch in patch file */
182
bool mismatch = false;
183
char *outname = outfile ? outfile : inname;
185
if (!skip_rest_of_patch)
186
get_input_file (inname, outname);
188
if (diff_type == ED_DIFF) {
189
outstate.zero_output = false;
190
somefailed |= skip_rest_of_patch;
191
do_ed_script (outstate.ofp);
192
if (! dry_run && ! outfile && ! skip_rest_of_patch)
195
if (stat (TMPOUTNAME, &statbuf) != 0)
196
pfatal ("%s", TMPOUTNAME);
197
outstate.zero_output = statbuf.st_size == 0;
201
bool apply_anyway = false;
203
/* initialize the patched file */
204
if (! skip_rest_of_patch && ! outfile)
206
int exclusive = TMPOUTNAME_needs_removal ? 0 : O_EXCL;
207
TMPOUTNAME_needs_removal = 1;
208
init_output (TMPOUTNAME, exclusive, &outstate);
211
/* initialize reject file */
214
/* find out where all the lines are */
215
if (!skip_rest_of_patch)
218
/* from here on, open no standard i/o files, because malloc */
219
/* might misfire and we can't catch it easily */
221
/* apply each hunk of patch */
222
while (0 < (got_hunk = another_hunk (diff_type, reverse))) {
223
LINENUM where = 0; /* Pacify `gcc -Wall'. */
226
LINENUM prefix_context = pch_prefix_context ();
227
LINENUM suffix_context = pch_suffix_context ();
228
LINENUM context = (prefix_context < suffix_context
229
? suffix_context : prefix_context);
230
LINENUM mymaxfuzz = (maxfuzz < context ? maxfuzz : context);
232
if (!skip_rest_of_patch) {
234
where = locate_hunk(fuzz);
235
if (! where || fuzz || last_offset)
237
if (hunk == 1 && ! where && ! (force | apply_anyway)
238
&& reverse == reverse_flag_specified) {
239
/* dwim for reversed patch? */
242
"Not enough memory to try swapped hunk! Assuming unswapped.\n");
246
where = locate_hunk (fuzz);
249
("%s patch detected!",
252
: "Reversed (or previously applied)"))))
256
/* Put it back to normal. */
258
fatal ("lost hunk on alloc error!");
262
fuzz--; /* Undo `++fuzz' below. */
267
} while (!skip_rest_of_patch && !where
268
&& ++fuzz <= mymaxfuzz);
270
if (skip_rest_of_patch) { /* just got decided */
271
if (outstate.ofp && ! outfile)
273
fclose (outstate.ofp);
279
newwhere = pch_newfirst() + last_offset;
280
if (skip_rest_of_patch) {
283
if (verbosity == VERBOSE)
284
say ("Hunk #%d ignored at %s.\n", hunk,
285
format_linenum (numbuf, newwhere));
288
|| (where == 1 && pch_says_nonexistent (reverse) == 2
289
&& instat.st_size)) {
292
say ("Patch attempted to create file %s, which already exists.\n",
297
if (verbosity != SILENT)
298
say ("Hunk #%d FAILED at %s.\n", hunk,
299
format_linenum (numbuf, newwhere));
301
else if (! apply_hunk (&outstate, where)) {
304
if (verbosity != SILENT)
305
say ("Hunk #%d FAILED at %s.\n", hunk,
306
format_linenum (numbuf, newwhere));
308
if (verbosity == VERBOSE
309
|| (verbosity != SILENT && (fuzz || last_offset))) {
310
say ("Hunk #%d succeeded at %s", hunk,
311
format_linenum (numbuf, newwhere));
313
say (" with fuzz %s", format_linenum (numbuf, fuzz));
315
say (" (offset %s line%s)",
316
format_linenum (numbuf, last_offset),
317
"s" + (last_offset == 1));
323
if (!skip_rest_of_patch)
325
if (got_hunk < 0 && using_plan_a)
328
fatal ("out of memory using Plan A");
329
say ("\n\nRan out of memory using Plan A -- trying again...\n\n");
332
fclose (outstate.ofp);
339
/* Finish spewing out the new file. */
341
if (! spew_output (&outstate))
343
say ("Skipping patch.\n");
344
skip_rest_of_patch = true;
349
/* and put the output where desired */
351
if (! skip_rest_of_patch && ! outfile) {
352
if (outstate.zero_output
353
&& (remove_empty_files
354
|| (pch_says_nonexistent (! reverse) == 2
355
&& ! posixly_correct)))
357
if (verbosity == VERBOSE)
358
say ("Removing file %s%s\n", quotearg (outname),
359
dry_run ? " and any empty ancestor directories" : "");
362
move_file ((char *) 0, (int *) 0, outname, (mode_t) 0,
364
|| (backup_if_mismatch && (mismatch | failed))));
365
removedirs (outname);
370
if (! outstate.zero_output
371
&& pch_says_nonexistent (! reverse))
374
if (verbosity != SILENT)
375
say ("File %s is not empty after patch, as expected\n",
383
move_file (TMPOUTNAME, &TMPOUTNAME_needs_removal,
384
outname, instat.st_mode,
386
|| (backup_if_mismatch && (mismatch | failed))));
388
if ((set_time | set_utc)
389
&& (t = pch_timestamp (! reverse)) != (time_t) -1)
391
struct utimbuf utimbuf;
392
utimbuf.actime = utimbuf.modtime = t;
394
if (! force && ! inerrno
395
&& pch_says_nonexistent (reverse) != 2
396
&& (t = pch_timestamp (reverse)) != (time_t) -1
397
&& t != instat.st_mtime)
398
say ("Not setting time of file %s (time mismatch)\n",
400
else if (! force && (mismatch | failed))
401
say ("Not setting time of file %s (contents mismatch)\n",
403
else if (utime (outname, &utimbuf) != 0)
404
pfatal ("Can't set timestamp on file %s",
408
if (! inerrno && chmod (outname, instat.st_mode) != 0)
409
pfatal ("Can't set permissions on file %s",
414
if (diff_type != ED_DIFF) {
415
if (fclose (rejfp) != 0)
419
say ("%d out of %d hunk%s %s", failed, hunk, "s" + (hunk == 1),
420
skip_rest_of_patch ? "ignored" : "FAILED");
424
rej = xmalloc (strlen (outname) + 5);
425
strcpy (rej, outname);
426
addext (rej, ".rej", '#');
428
say (" -- saving rejects to file %s", quotearg (rej));
431
move_file (TMPREJNAME, &TMPREJNAME_needs_removal,
432
rej, instat.st_mode, false);
434
&& (chmod (rej, (instat.st_mode
435
& ~(S_IXUSR|S_IXGRP|S_IXOTH)))
437
pfatal ("can't set permissions on file %s",
448
if (outstate.ofp && (ferror (outstate.ofp) || fclose (outstate.ofp) != 0))
456
/* Prepare to find the next patch to do in the patch file. */
459
reinitialize_almost_everything (void)
465
last_frozen_line = 0;
481
reverse = reverse_flag_specified;
482
skip_rest_of_patch = false;
485
static char const shortopts[] = "bB:cd:D:eEfF:g:i:lnNo:p:r:RstTuvV:x:Y:z:Z";
486
static struct option const longopts[] =
488
{"backup", no_argument, NULL, 'b'},
489
{"prefix", required_argument, NULL, 'B'},
490
{"context", no_argument, NULL, 'c'},
491
{"directory", required_argument, NULL, 'd'},
492
{"ifdef", required_argument, NULL, 'D'},
493
{"ed", no_argument, NULL, 'e'},
494
{"remove-empty-files", no_argument, NULL, 'E'},
495
{"force", no_argument, NULL, 'f'},
496
{"fuzz", required_argument, NULL, 'F'},
497
{"get", no_argument, NULL, 'g'},
498
{"input", required_argument, NULL, 'i'},
499
{"ignore-whitespace", no_argument, NULL, 'l'},
500
{"normal", no_argument, NULL, 'n'},
501
{"forward", no_argument, NULL, 'N'},
502
{"output", required_argument, NULL, 'o'},
503
{"strip", required_argument, NULL, 'p'},
504
{"reject-file", required_argument, NULL, 'r'},
505
{"reverse", no_argument, NULL, 'R'},
506
{"quiet", no_argument, NULL, 's'},
507
{"silent", no_argument, NULL, 's'},
508
{"batch", no_argument, NULL, 't'},
509
{"set-time", no_argument, NULL, 'T'},
510
{"unified", no_argument, NULL, 'u'},
511
{"version", no_argument, NULL, 'v'},
512
{"version-control", required_argument, NULL, 'V'},
513
{"debug", required_argument, NULL, 'x'},
514
{"basename-prefix", required_argument, NULL, 'Y'},
515
{"suffix", required_argument, NULL, 'z'},
516
{"set-utc", no_argument, NULL, 'Z'},
517
{"dry-run", no_argument, NULL, CHAR_MAX + 1},
518
{"verbose", no_argument, NULL, CHAR_MAX + 2},
519
{"binary", no_argument, NULL, CHAR_MAX + 3},
520
{"help", no_argument, NULL, CHAR_MAX + 4},
521
{"backup-if-mismatch", no_argument, NULL, CHAR_MAX + 5},
522
{"no-backup-if-mismatch", no_argument, NULL, CHAR_MAX + 6},
523
{"posix", no_argument, NULL, CHAR_MAX + 7},
524
{"quoting-style", required_argument, NULL, CHAR_MAX + 8},
525
{NULL, no_argument, NULL, 0}
528
static char const *const option_help[] =
532
" -p NUM --strip=NUM Strip NUM leading components from file names.",
533
" -F LINES --fuzz LINES Set the fuzz factor to LINES for inexact matching.",
534
" -l --ignore-whitespace Ignore white space changes between patch and input.",
536
" -c --context Interpret the patch as a context difference.",
537
" -e --ed Interpret the patch as an ed script.",
538
" -n --normal Interpret the patch as a normal difference.",
539
" -u --unified Interpret the patch as a unified difference.",
541
" -N --forward Ignore patches that appear to be reversed or already applied.",
542
" -R --reverse Assume patches were created with old and new files swapped.",
544
" -i PATCHFILE --input=PATCHFILE Read patch from PATCHFILE instead of stdin.",
548
" -o FILE --output=FILE Output patched files to FILE.",
549
" -r FILE --reject-file=FILE Output rejects to FILE.",
551
" -D NAME --ifdef=NAME Make merged if-then-else output using NAME.",
552
" -E --remove-empty-files Remove output files that are empty after patching.",
554
" -Z --set-utc Set times of patched files, assuming diff uses UTC (GMT).",
555
" -T --set-time Likewise, assuming local time.",
557
" --quoting-style=WORD output file names using quoting style WORD.",
558
" Valid WORDs are: literal, shell, shell-always, c, escape.",
559
" Default is taken from QUOTING_STYLE env variable, or 'shell' if unset.",
561
"Backup and version control options:",
563
" -b --backup Back up the original contents of each file.",
564
" --backup-if-mismatch Back up if the patch does not match exactly.",
565
" --no-backup-if-mismatch Back up mismatches only if otherwise requested.",
567
" -V STYLE --version-control=STYLE Use STYLE version control.",
568
" STYLE is either 'simple', 'numbered', or 'existing'.",
569
" -B PREFIX --prefix=PREFIX Prepend PREFIX to backup file names.",
570
" -Y PREFIX --basename-prefix=PREFIX Prepend PREFIX to backup file basenames.",
571
" -z SUFFIX --suffix=SUFFIX Append SUFFIX to backup file names.",
573
" -g NUM --get=NUM Get files from RCS etc. if positive; ask if negative.",
575
"Miscellaneous options:",
577
" -t --batch Ask no questions; skip bad-Prereq patches; assume reversed.",
578
" -f --force Like -t, but ignore bad-Prereq patches, and assume unreversed.",
579
" -s --quiet --silent Work silently unless an error occurs.",
580
" --verbose Output extra information about the work being done.",
581
" --dry-run Do not actually change any files; just print what would happen.",
582
" --posix Conform to the POSIX standard.",
584
" -d DIR --directory=DIR Change the working directory to DIR first.",
586
" --binary Read and write data in binary mode.",
588
" --binary Read and write data in binary mode (no effect on this platform).",
591
" -v --version Output version info.",
592
" --help Output this help.",
594
"Report bugs to <" PACKAGE_BUGREPORT ">.",
599
usage (FILE *stream, int status)
601
char const * const *p;
605
fprintf (stream, "%s: Try `%s --help' for more information.\n",
606
program_name, Argv[0]);
610
fprintf (stream, "Usage: %s [OPTION]... [ORIGFILE [PATCHFILE]]\n\n",
612
for (p = option_help; *p; p++)
613
fprintf (stream, "%s\n", *p);
619
/* Process switches and filenames. */
622
get_some_switches (void)
631
while ((optc = getopt_long (Argc, Argv, shortopts, longopts, (int *) 0))
636
/* Special hack for backward compatibility with CVS 1.9.
637
If the last 4 args are `-b SUFFIX ORIGFILE PATCHFILE',
638
treat `-b' as if it were `-b -z'. */
639
if (Argc - optind == 3
640
&& strcmp (Argv[optind - 1], "-b") == 0
641
&& ! (Argv[optind + 0][0] == '-' && Argv[optind + 0][1])
642
&& ! (Argv[optind + 1][0] == '-' && Argv[optind + 1][1])
643
&& ! (Argv[optind + 2][0] == '-' && Argv[optind + 2][1]))
645
optarg = Argv[optind++];
646
if (verbosity != SILENT)
647
say ("warning: the `-b %s' option is obsolete; use `-b -z %s' instead\n",
654
fatal ("backup prefix is empty");
655
origprae = savestr (optarg);
658
diff_type = CONTEXT_DIFF;
661
if (chdir(optarg) < 0)
662
pfatal ("Can't change to directory %s", quotearg (optarg));
665
do_defines = savestr (optarg);
671
remove_empty_files = true;
677
maxfuzz = numeric_string (optarg, false, "fuzz factor");
680
patch_get = numeric_string (optarg, true, "get option value");
683
patchname = savestr (optarg);
689
diff_type = NORMAL_DIFF;
695
if (strcmp (optarg, "-") == 0)
696
fatal ("can't output patches to standard output");
697
outfile = savestr (optarg);
700
strippath = numeric_string (optarg, false, "strip count");
703
rejname = savestr (optarg);
707
reverse_flag_specified = true;
719
diff_type = UNI_DIFF;
726
version_control = optarg;
727
version_control_context = "--version-control or -V option";
731
debug = numeric_string (optarg, true, "debugging option");
736
fatal ("backup basename prefix is empty");
737
origbase = savestr (optarg);
742
fatal ("backup suffix is empty");
743
simple_backup_suffix = savestr (optarg);
756
binary_transput = O_BINARY;
762
backup_if_mismatch = true;
765
backup_if_mismatch = false;
768
posixly_correct = true;
772
int i = argmatch (optarg, quoting_style_args, 0, 0);
775
invalid_arg ("quoting style", optarg, i);
778
set_quoting_style ((struct quoting_options *) 0,
779
(enum quoting_style) i);
787
/* Process any filename args. */
790
inname = savestr (Argv[optind++]);
794
patchname = savestr (Argv[optind++]);
797
fprintf (stderr, "%s: %s: extra operand\n",
798
program_name, quotearg (Argv[optind]));
805
/* Handle STRING (possibly negative if NEGATIVE_ALLOWED is nonzero)
806
of type ARGTYPE_MSGID by converting it to an integer,
807
returning the result. */
809
numeric_string (char const *string,
810
bool negative_allowed,
811
char const *argtype_msgid)
814
char const *p = string;
815
int sign = *p == '-' ? -1 : 1;
817
p += *p == '-' || *p == '+';
821
int v10 = value * 10;
822
int digit = *p - '0';
823
int signed_digit = sign * digit;
824
int next_value = v10 + signed_digit;
826
if (9 < (unsigned) digit)
827
fatal ("%s %s is not a number", argtype_msgid, quotearg (string));
829
if (v10 / 10 != value || (next_value < v10) != (signed_digit < 0))
830
fatal ("%s %s is too large", argtype_msgid, quotearg (string));
836
if (value < 0 && ! negative_allowed)
837
fatal ("%s %s is negative", argtype_msgid, quotearg (string));
842
/* Attempt to find the right place to apply this hunk of patch. */
845
locate_hunk (LINENUM fuzz)
847
register LINENUM first_guess = pch_first () + last_offset;
848
register LINENUM offset;
849
LINENUM pat_lines = pch_ptrn_lines();
850
LINENUM prefix_context = pch_prefix_context ();
851
LINENUM suffix_context = pch_suffix_context ();
852
LINENUM context = (prefix_context < suffix_context
853
? suffix_context : prefix_context);
854
LINENUM prefix_fuzz = fuzz + prefix_context - context;
855
LINENUM suffix_fuzz = fuzz + suffix_context - context;
856
LINENUM max_where = input_lines - (pat_lines - suffix_fuzz) + 1;
857
LINENUM min_where = last_frozen_line + 1 - (prefix_context - prefix_fuzz);
858
LINENUM max_pos_offset = max_where - first_guess;
859
LINENUM max_neg_offset = first_guess - min_where;
860
LINENUM max_offset = (max_pos_offset < max_neg_offset
861
? max_neg_offset : max_pos_offset);
863
if (!pat_lines) /* null range matches always */
866
/* Do not try lines <= 0. */
867
if (first_guess <= max_neg_offset)
868
max_neg_offset = first_guess - 1;
872
/* Can only match start of file. */
875
/* Can only match entire file. */
876
if (pat_lines != input_lines || prefix_context < last_frozen_line)
879
offset = 1 - first_guess;
880
if (last_frozen_line <= prefix_context
881
&& offset <= max_pos_offset
882
&& patch_match (first_guess, offset, (LINENUM) 0, suffix_fuzz))
884
last_offset += offset;
885
return first_guess + offset;
893
/* Can only match end of file. */
894
offset = first_guess - (input_lines - pat_lines + 1);
895
if (offset <= max_neg_offset
896
&& patch_match (first_guess, -offset, prefix_fuzz, (LINENUM) 0))
898
last_offset -= offset;
899
return first_guess - offset;
905
for (offset = 0; offset <= max_offset; offset++) {
906
char numbuf0[LINENUM_LENGTH_BOUND + 1];
907
char numbuf1[LINENUM_LENGTH_BOUND + 1];
908
if (offset <= max_pos_offset
909
&& patch_match (first_guess, offset, prefix_fuzz, suffix_fuzz)) {
911
say ("Offset changing from %s to %s\n",
912
format_linenum (numbuf0, last_offset),
913
format_linenum (numbuf1, last_offset + offset));
914
last_offset += offset;
915
return first_guess+offset;
917
if (0 < offset && offset <= max_neg_offset
918
&& patch_match (first_guess, -offset, prefix_fuzz, suffix_fuzz)) {
920
say ("Offset changing from %s to %s\n",
921
format_linenum (numbuf0, last_offset),
922
format_linenum (numbuf1, last_offset - offset));
923
last_offset -= offset;
924
return first_guess-offset;
930
/* We did not find the pattern, dump out the hunk so they can handle it. */
936
register LINENUM pat_end = pch_end ();
937
/* add in last_offset to guess the same as the previous successful hunk */
938
LINENUM oldfirst = pch_first() + last_offset;
939
LINENUM newfirst = pch_newfirst() + last_offset;
940
LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
941
LINENUM newlast = newfirst + pch_repl_lines() - 1;
943
(int) NEW_CONTEXT_DIFF <= (int) diff_type ? " ****" : "";
944
char const *minuses =
945
(int) NEW_CONTEXT_DIFF <= (int) diff_type ? " ----" : " -----";
947
fprintf(rejfp, "***************\n");
948
for (i=0; i<=pat_end; i++) {
949
char numbuf0[LINENUM_LENGTH_BOUND + 1];
950
char numbuf1[LINENUM_LENGTH_BOUND + 1];
951
switch (pch_char(i)) {
953
if (oldlast < oldfirst)
954
fprintf(rejfp, "*** 0%s\n", stars);
955
else if (oldlast == oldfirst)
956
fprintf (rejfp, "*** %s%s\n",
957
format_linenum (numbuf0, oldfirst), stars);
959
fprintf (rejfp, "*** %s,%s%s\n",
960
format_linenum (numbuf0, oldfirst),
961
format_linenum (numbuf1, oldlast), stars);
964
if (newlast < newfirst)
965
fprintf(rejfp, "--- 0%s\n", minuses);
966
else if (newlast == newfirst)
967
fprintf (rejfp, "--- %s%s\n",
968
format_linenum (numbuf0, newfirst), minuses);
970
fprintf (rejfp, "--- %s,%s%s\n",
971
format_linenum (numbuf0, newfirst),
972
format_linenum (numbuf1, newlast), minuses);
974
case ' ': case '-': case '+': case '!':
975
fprintf (rejfp, "%c ", pch_char (i));
978
pch_write_line (i, rejfp);
981
fatal ("fatal internal error in abort_hunk");
988
/* We found where to apply it (we hope), so do it. */
991
apply_hunk (struct outstate *outstate, LINENUM where)
993
register LINENUM old = 1;
994
register LINENUM lastline = pch_ptrn_lines ();
995
register LINENUM new = lastline+1;
996
register enum {OUTSIDE, IN_IFNDEF, IN_IFDEF, IN_ELSE} def_state = OUTSIDE;
997
register char const *R_do_defines = do_defines;
998
register LINENUM pat_end = pch_end ();
999
register FILE *fp = outstate->ofp;
1002
while (pch_char(new) == '=' || pch_char(new) == '\n')
1005
while (old <= lastline) {
1006
if (pch_char(old) == '-') {
1007
assert (outstate->after_newline);
1008
if (! copy_till (outstate, where + old - 1))
1011
if (def_state == OUTSIDE) {
1012
fprintf (fp, outstate->after_newline + not_defined,
1014
def_state = IN_IFNDEF;
1016
else if (def_state == IN_IFDEF) {
1017
fprintf (fp, outstate->after_newline + else_defined);
1018
def_state = IN_ELSE;
1022
outstate->after_newline = pch_write_line (old, fp);
1023
outstate->zero_output = false;
1028
else if (new > pat_end) {
1031
else if (pch_char(new) == '+') {
1032
if (! copy_till (outstate, where + old - 1))
1035
if (def_state == IN_IFNDEF) {
1036
fprintf (fp, outstate->after_newline + else_defined);
1037
def_state = IN_ELSE;
1039
else if (def_state == OUTSIDE) {
1040
fprintf (fp, outstate->after_newline + if_defined,
1042
def_state = IN_IFDEF;
1047
outstate->after_newline = pch_write_line (new, fp);
1048
outstate->zero_output = false;
1051
else if (pch_char(new) != pch_char(old)) {
1052
char numbuf0[LINENUM_LENGTH_BOUND + 1];
1053
char numbuf1[LINENUM_LENGTH_BOUND + 1];
1055
say ("oldchar = '%c', newchar = '%c'\n",
1056
pch_char (old), pch_char (new));
1057
fatal ("Out-of-sync patch, lines %s,%s -- mangled text or line numbers, maybe?",
1058
format_linenum (numbuf0, pch_hunk_beg() + old),
1059
format_linenum (numbuf1, pch_hunk_beg() + new));
1061
else if (pch_char(new) == '!') {
1062
assert (outstate->after_newline);
1063
if (! copy_till (outstate, where + old - 1))
1065
assert (outstate->after_newline);
1067
fprintf (fp, 1 + not_defined, R_do_defines);
1070
def_state = IN_IFNDEF;
1076
outstate->after_newline = pch_write_line (old, fp);
1081
while (pch_char (old) == '!');
1084
fprintf (fp, outstate->after_newline + else_defined);
1087
def_state = IN_ELSE;
1092
outstate->after_newline = pch_write_line (new, fp);
1095
while (pch_char (new) == '!');
1096
outstate->zero_output = false;
1099
assert(pch_char(new) == ' ');
1102
if (R_do_defines && def_state != OUTSIDE) {
1103
fprintf (fp, outstate->after_newline + end_defined);
1106
outstate->after_newline = true;
1107
def_state = OUTSIDE;
1111
if (new <= pat_end && pch_char(new) == '+') {
1112
if (! copy_till (outstate, where + old - 1))
1115
if (def_state == OUTSIDE) {
1116
fprintf (fp, outstate->after_newline + if_defined,
1118
def_state = IN_IFDEF;
1120
else if (def_state == IN_IFNDEF) {
1121
fprintf (fp, outstate->after_newline + else_defined);
1122
def_state = IN_ELSE;
1126
outstate->zero_output = false;
1131
if (! outstate->after_newline && putc ('\n', fp) == EOF)
1133
outstate->after_newline = pch_write_line (new, fp);
1134
outstate->zero_output = false;
1137
while (new <= pat_end && pch_char (new) == '+');
1139
if (R_do_defines && def_state != OUTSIDE) {
1140
fprintf (fp, outstate->after_newline + end_defined);
1143
outstate->after_newline = true;
1148
/* Create an output file. */
1151
create_output_file (char const *name, int open_flags)
1153
int fd = create_file (name, O_WRONLY | binary_transput | open_flags,
1155
FILE *f = fdopen (fd, binary_transput ? "wb" : "w");
1157
pfatal ("Can't create file %s", quotearg (name));
1161
/* Open the new file. */
1164
init_output (char const *name, int open_flags, struct outstate *outstate)
1166
outstate->ofp = name ? create_output_file (name, open_flags) : (FILE *) 0;
1167
outstate->after_newline = true;
1168
outstate->zero_output = true;
1171
/* Open a file to put hunks we can't locate. */
1176
int exclusive = TMPREJNAME_needs_removal ? 0 : O_EXCL;
1177
TMPREJNAME_needs_removal = 1;
1178
rejfp = create_output_file (TMPREJNAME, exclusive);
1181
/* Copy input file to output, up to wherever hunk is to be applied. */
1184
copy_till (register struct outstate *outstate, register LINENUM lastline)
1186
register LINENUM R_last_frozen_line = last_frozen_line;
1187
register FILE *fp = outstate->ofp;
1188
register char const *s;
1191
if (R_last_frozen_line > lastline)
1193
say ("misordered hunks! output would be garbled\n");
1196
while (R_last_frozen_line < lastline)
1198
s = ifetch (++R_last_frozen_line, false, &size);
1201
if ((! outstate->after_newline && putc ('\n', fp) == EOF)
1202
|| ! fwrite (s, sizeof *s, size, fp))
1204
outstate->after_newline = s[size - 1] == '\n';
1205
outstate->zero_output = false;
1208
last_frozen_line = R_last_frozen_line;
1212
/* Finish copying the input file to the output file. */
1215
spew_output (struct outstate *outstate)
1219
char numbuf0[LINENUM_LENGTH_BOUND + 1];
1220
char numbuf1[LINENUM_LENGTH_BOUND + 1];
1221
say ("il=%s lfl=%s\n",
1222
format_linenum (numbuf0, input_lines),
1223
format_linenum (numbuf1, last_frozen_line));
1226
if (last_frozen_line < input_lines)
1227
if (! copy_till (outstate, input_lines))
1230
if (outstate->ofp && ! outfile)
1232
if (fclose (outstate->ofp) != 0)
1240
/* Does the patch pattern match at line base+offset? */
1243
patch_match (LINENUM base, LINENUM offset,
1244
LINENUM prefix_fuzz, LINENUM suffix_fuzz)
1246
register LINENUM pline = 1 + prefix_fuzz;
1247
register LINENUM iline;
1248
register LINENUM pat_lines = pch_ptrn_lines () - suffix_fuzz;
1250
register char const *p;
1252
for (iline=base+offset+prefix_fuzz; pline <= pat_lines; pline++,iline++) {
1253
p = ifetch (iline, offset >= 0, &size);
1255
if (!similar(p, size,
1257
pch_line_len(pline) ))
1260
else if (size != pch_line_len (pline)
1261
|| memcmp (p, pfetch (pline), size) != 0)
1267
/* Do two lines match with canonicalized white space? */
1270
similar (register char const *a, register size_t alen,
1271
register char const *b, register size_t blen)
1273
/* Ignore presence or absence of trailing newlines. */
1274
alen -= alen && a[alen - 1] == '\n';
1275
blen -= blen && b[blen - 1] == '\n';
1279
if (!blen || (*b == ' ' || *b == '\t'))
1281
while (blen && (*b == ' ' || *b == '\t'))
1285
if (!(*a == ' ' || *a == '\t'))
1288
while (alen && (*a == ' ' || *a == '\t'));
1291
return alen == blen;
1293
else if (!alen || *a++ != *b++)
1300
/* Make a temporary file. */
1302
#if HAVE_MKTEMP && ! HAVE_DECL_MKTEMP && ! defined mktemp
1303
char *mktemp (char *);
1307
#define TMPDIR "/tmp"
1311
make_temp (char letter)
1315
char const *tmpdir = getenv ("TMPDIR"); /* Unix tradition */
1316
if (!tmpdir) tmpdir = getenv ("TMP"); /* DOS tradition */
1317
if (!tmpdir) tmpdir = getenv ("TEMP"); /* another DOS tradition */
1318
if (!tmpdir) tmpdir = TMPDIR;
1319
r = xmalloc (strlen (tmpdir) + 10);
1320
sprintf (r, "%s/p%cXXXXXX", tmpdir, letter);
1322
/* It is OK to use mktemp here, since the rest of the code always
1323
opens temp files with O_EXCL. It might be better to use mkstemp
1324
to avoid some DoS problems, but simply substituting mkstemp for
1325
mktemp here will not fix the DoS problems; a more extensive
1326
change would be needed. */
1332
r = xmalloc (L_tmpnam);
1333
if (! (tmpnam (r) == r && *r))
1339
/* Fatal exit with cleanup. */
1342
fatal_exit (int sig)
1347
exit_with_signal (sig);
1353
remove_if_needed (char const *name, int volatile *needs_removal)
1365
remove_if_needed (TMPINNAME, &TMPINNAME_needs_removal);
1366
remove_if_needed (TMPOUTNAME, &TMPOUTNAME_needs_removal);
1367
remove_if_needed (TMPPATNAME, &TMPPATNAME_needs_removal);
1368
remove_if_needed (TMPREJNAME, &TMPREJNAME_needs_removal);