2 * Copyright 1986, Larry Wall
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following condition is met:
6 * 1. Redistributions of source code must retain the above copyright notice,
7 * this condition and the following disclaimer.
9 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
10 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
11 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
13 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
15 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
16 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
17 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
21 * patch - a program to apply diffs to original files
23 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
26 * $OpenBSD: patch.c,v 1.54 2014/12/13 10:31:07 tobias Exp $
30 #include <sys/types.h>
46 #include "backupfile.h"
47 #include "pathnames.h"
49 mode_t filemode = 0644;
51 char *buf; /* general purpose buffer */
52 size_t buf_size; /* size of the general purpose buffer */
54 bool using_plan_a = true; /* try to keep everything in memory */
55 bool out_of_mem = false; /* ran out of memory in plan a */
56 bool nonempty_patchf_seen = false; /* seen nonempty patch file? */
60 char *filearg[MAXFILEC];
61 bool ok_to_create_file = false;
63 char *origprae = NULL;
68 bool toutkeep = false;
69 bool trejkeep = false;
70 bool warn_on_invalid_line;
71 bool last_line_missing_eol;
81 bool noreverse = false;
82 bool skip_rest_of_patch = false;
84 bool canonicalize = false;
85 bool check_only = false;
87 char *revision = NULL; /* prerequisite revision, if any */
88 LINENUM input_lines = 0; /* how long is input file in lines */
89 int posix = 0; /* strict POSIX mode? */
91 static void reinitialize_almost_everything(void);
92 static void get_some_switches(void);
93 static LINENUM locate_hunk(LINENUM);
94 static void abort_context_hunk(void);
95 static void rej_line(int, LINENUM);
96 static void abort_hunk(void);
97 static void apply_hunk(LINENUM);
98 static void init_output(const char *);
99 static void init_reject(const char *);
100 static void copy_till(LINENUM, bool);
101 static bool spew_output(void);
102 static void dump_line(LINENUM, bool);
103 static bool patch_match(LINENUM, LINENUM, LINENUM);
104 static bool similar(const char *, const char *, int);
105 static void usage(void);
106 static bool handle_creation(bool, bool *);
108 /* true if -E was specified on command line. */
109 static bool remove_empty_files = false;
111 /* true if -R was specified on command line. */
112 static bool reverse_flag_specified = false;
114 static bool Vflag = false;
116 /* buffer holding the name of the rejected patch file. */
117 static char rejname[PATH_MAX];
119 /* how many input lines have been irretractibly output */
120 static LINENUM last_frozen_line = 0;
122 static int Argc; /* guess */
124 static int Argc_last; /* for restarting plan_b */
125 static char **Argv_last;
127 static FILE *ofp = NULL; /* output file pointer */
128 static FILE *rejfp = NULL; /* reject file pointer */
130 static int filec = 0; /* how many file arguments? */
131 static LINENUM last_offset = 0;
132 static LINENUM maxfuzz = 2;
134 /* patch using ifdef, ifndef, etc. */
135 static bool do_defines = false;
137 static char if_defined[128];
139 static char not_defined[128];
141 static const char else_defined[] = "#else\n";
143 static char end_defined[128];
146 /* Apply a set of diffs as appropriate. */
149 main(int argc, char *argv[])
152 int error = 0, hunk, failed, i, fd;
153 bool out_creating, out_existed, patch_seen, remove_file;
155 LINENUM where = 0, newwhere, fuzz, mymaxfuzz;
159 setvbuf(stdout, NULL, _IOLBF, 0);
160 setvbuf(stderr, NULL, _IOLBF, 0);
161 for (i = 0; i < MAXFILEC; i++)
164 buf_size = INITLINELEN;
165 buf = malloc((unsigned)(buf_size));
167 fatal("out of memory\n");
169 /* Cons up the names of the temporary files. */
170 if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
172 for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--)
175 if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1)
176 fatal("cannot allocate memory");
177 if ((fd = mkstemp(TMPOUTNAME)) < 0)
178 pfatal("can't create %s", TMPOUTNAME);
181 if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1)
182 fatal("cannot allocate memory");
183 if ((fd = mkstemp(TMPINNAME)) < 0)
184 pfatal("can't create %s", TMPINNAME);
187 if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1)
188 fatal("cannot allocate memory");
189 if ((fd = mkstemp(TMPREJNAME)) < 0)
190 pfatal("can't create %s", TMPREJNAME);
193 if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1)
194 fatal("cannot allocate memory");
195 if ((fd = mkstemp(TMPPATNAME)) < 0)
196 pfatal("can't create %s", TMPPATNAME);
199 v = getenv("SIMPLE_BACKUP_SUFFIX");
201 simple_backup_suffix = v;
203 simple_backup_suffix = ORIGEXT;
211 if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
212 v = getenv("VERSION_CONTROL");
213 if (v != NULL || !posix)
214 backup_type = get_version(v); /* OK to pass NULL. */
217 /* make sure we clean up /tmp in case of disaster */
221 for (open_patch_file(filearg[1]); there_is_another_patch();
222 reinitialize_almost_everything()) {
223 /* for each patch in patch file */
225 if (source_file != NULL && (diff_type == CONTEXT_DIFF ||
226 diff_type == NEW_CONTEXT_DIFF ||
227 diff_type == UNI_DIFF))
228 out_creating = strcmp(source_file, _PATH_DEVNULL) == 0;
230 out_creating = false;
233 warn_on_invalid_line = true;
236 outname = xstrdup(filearg[0]);
239 * At this point, we know if we're supposed to be creating the
240 * file and we know if we should be trying to handle a conflict
241 * between the patch and the file already existing. We defer
242 * handling it until hunk processing because we want to swap
243 * the hunk if they opt to reverse it, but we want to make sure
244 * we *can* swap the hunk without running into memory issues
245 * before we offer it. We also want to be verbose if flags or
246 * user decision cause us to skip -- this is explained a little
249 out_existed = stat(outname, &statbuf) == 0;
251 /* for ed script just up and do it and exit */
252 if (diff_type == ED_DIFF) {
256 /* initialize the patched file */
257 if (!skip_rest_of_patch)
258 init_output(TMPOUTNAME);
260 /* initialize reject file */
261 init_reject(TMPREJNAME);
263 /* find out where all the lines are */
264 if (!skip_rest_of_patch)
265 scan_input(filearg[0]);
268 * from here on, open no standard i/o files, because
269 * malloc might misfire and we can't catch it easily
272 /* apply each hunk of patch */
275 reverse_seen = false;
278 while (another_hunk()) {
279 assert(!out_creating || hunk == 0);
284 * There are only three cases in handle_creation() that
285 * results in us skipping hunk location, in order:
287 * 1.) Potentially reversed but -f/--force'd,
288 * 2.) Potentially reversed but -N/--forward'd
289 * 3.) Reversed and the user's opted to not apply it.
291 * In all three cases, we still want to inform the user
292 * that we're ignoring it in the standard way, which is
293 * also tied to this hunk processing loop.
296 reverse_seen = handle_creation(out_existed,
299 mymaxfuzz = pch_context();
300 if (maxfuzz < mymaxfuzz)
302 if (!skip_rest_of_patch) {
304 where = locate_hunk(fuzz);
305 if (hunk == 1 && where == 0 && !force && !reverse_seen) {
306 /* dwim for reversed patch? */
309 say("Not enough memory to try swapped hunk! Assuming unswapped.\n");
314 where = locate_hunk(fuzz);
316 /* didn't find it swapped */
318 /* put it back to normal */
319 fatal("lost hunk on alloc error!\n");
321 } else if (noreverse) {
323 /* put it back to normal */
324 fatal("lost hunk on alloc error!\n");
326 say("Ignoring previously applied (or reversed) patch.\n");
327 skip_rest_of_patch = true;
330 say("%seversed (or previously applied) patch detected! %s -R.",
331 reverse ? "R" : "Unr",
332 reverse ? "Assuming" : "Ignoring");
334 ask("%seversed (or previously applied) patch detected! %s -R? [y] ",
335 reverse ? "R" : "Unr",
336 reverse ? "Assume" : "Ignore");
338 ask("Apply anyway? [n] ");
340 skip_rest_of_patch = true;
346 /* put it back to normal */
347 fatal("lost hunk on alloc error!\n");
351 } while (!skip_rest_of_patch && where == 0 &&
352 ++fuzz <= mymaxfuzz);
354 if (skip_rest_of_patch) { /* just got decided */
355 if (ferror(ofp) || fclose(ofp)) {
356 say("Error writing %s\n",
363 newwhere = pch_newfirst() + last_offset;
364 if (skip_rest_of_patch) {
368 say("Hunk #%d ignored at %ld.\n",
370 } else if (where == 0) {
374 say("Hunk #%d failed at %ld.\n",
379 say("Hunk #%d succeeded at %ld",
382 say(" with fuzz %ld", fuzz);
384 say(" (offset %ld line%s)",
386 last_offset == 1L ? "" : "s");
392 if (out_of_mem && using_plan_a) {
395 say("\n\nRan out of memory using Plan A--trying again...\n\n");
405 fatal("Internal error: hunk should not be 0\n");
407 /* finish spewing out the new file */
408 if (!skip_rest_of_patch && !spew_output()) {
409 say("Can't write %s\n", TMPOUTNAME);
413 /* and put the output where desired */
415 if (!skip_rest_of_patch) {
416 char *realout = outname;
419 if (move_file(TMPOUTNAME, outname) < 0) {
421 realout = TMPOUTNAME;
422 chmod(TMPOUTNAME, filemode);
424 chmod(outname, filemode);
427 * remove_file is a per-patch flag indicating
428 * whether it's OK to remove the empty file.
429 * This is specifically set when we're reversing
430 * the creation of a file and it ends up empty.
431 * This is an exception to the global policy
432 * (remove_empty_files) because the user would
433 * likely not expect the reverse of file
434 * creation to leave an empty file laying
437 if ((remove_empty_files || remove_file) &&
438 stat(realout, &statbuf) == 0 &&
439 statbuf.st_size == 0) {
441 say("Removing %s (empty after patching).\n",
447 if (ferror(rejfp) || fclose(rejfp)) {
448 say("Error writing %s\n", rejname);
454 if (*rejname == '\0') {
455 if (strlcpy(rejname, outname,
456 sizeof(rejname)) >= sizeof(rejname))
457 fatal("filename %s is too long\n", outname);
458 if (strlcat(rejname, REJEXT,
459 sizeof(rejname)) >= sizeof(rejname))
460 fatal("filename %s is too long\n", outname);
463 say("%d out of %d hunks %s--saving rejects to %s\n",
464 failed, hunk, skip_rest_of_patch ? "ignored" : "failed", rejname);
465 else if (filearg[0] != NULL)
466 say("%d out of %d hunks %s while patching %s\n",
467 failed, hunk, skip_rest_of_patch ? "ignored" : "failed", filearg[0]);
469 /* File prompt ignored, just note # hunks. */
470 say("%d out of %d hunks %s\n",
471 failed, hunk, skip_rest_of_patch ? "ignored" : "failed");
472 if (!check_only && move_file(TMPREJNAME, rejname) < 0)
478 if (!patch_seen && nonempty_patchf_seen)
485 /* Prepare to find the next patch to do in the patch file. */
488 reinitialize_almost_everything(void)
494 last_frozen_line = 0;
514 reverse = reverse_flag_specified;
515 skip_rest_of_patch = false;
520 /* Process switches and filenames. */
523 get_some_switches(void)
525 const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
526 static struct option longopts[] = {
527 {"backup", no_argument, 0, 'b'},
528 {"batch", no_argument, 0, 't'},
529 {"check", no_argument, 0, 'C'},
530 {"context", no_argument, 0, 'c'},
531 {"debug", required_argument, 0, 'x'},
532 {"directory", required_argument, 0, 'd'},
533 {"dry-run", no_argument, 0, 'C'},
534 {"ed", no_argument, 0, 'e'},
535 {"force", no_argument, 0, 'f'},
536 {"forward", no_argument, 0, 'N'},
537 {"fuzz", required_argument, 0, 'F'},
538 {"ifdef", required_argument, 0, 'D'},
539 {"input", required_argument, 0, 'i'},
540 {"ignore-whitespace", no_argument, 0, 'l'},
541 {"normal", no_argument, 0, 'n'},
542 {"output", required_argument, 0, 'o'},
543 {"prefix", required_argument, 0, 'B'},
544 {"quiet", no_argument, 0, 's'},
545 {"reject-file", required_argument, 0, 'r'},
546 {"remove-empty-files", no_argument, 0, 'E'},
547 {"reverse", no_argument, 0, 'R'},
548 {"silent", no_argument, 0, 's'},
549 {"strip", required_argument, 0, 'p'},
550 {"suffix", required_argument, 0, 'z'},
551 {"unified", no_argument, 0, 'u'},
552 {"version", no_argument, 0, 'v'},
553 {"version-control", required_argument, 0, 'V'},
554 {"posix", no_argument, &posix, 1},
564 optreset = optind = 1;
565 while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
568 if (backup_type == none)
569 backup_type = numbered_existing;
573 say("Warning, the ``-b suffix'' option has been"
574 " obsoleted by the -z option.\n");
577 /* must directly follow 'b' case for backwards compat */
578 simple_backup_suffix = xstrdup(optarg);
581 origprae = xstrdup(optarg);
584 diff_type = CONTEXT_DIFF;
590 if (chdir(optarg) < 0)
591 pfatal("can't cd to %s", optarg);
595 if (!isalpha((unsigned char)*optarg) && *optarg != '_')
596 fatal("argument to -D is not an identifier\n");
597 snprintf(if_defined, sizeof if_defined,
598 "#ifdef %s\n", optarg);
599 snprintf(not_defined, sizeof not_defined,
600 "#ifndef %s\n", optarg);
601 snprintf(end_defined, sizeof end_defined,
602 "#endif /* %s */\n", optarg);
608 remove_empty_files = true;
614 maxfuzz = atoi(optarg);
617 if (++filec == MAXFILEC)
618 fatal("too many file arguments\n");
619 filearg[filec] = xstrdup(optarg);
625 diff_type = NORMAL_DIFF;
631 outname = xstrdup(optarg);
634 strippath = atoi(optarg);
637 if (strlcpy(rejname, optarg,
638 sizeof(rejname)) >= sizeof(rejname))
639 fatal("argument for -r is too long\n");
643 reverse_flag_specified = true;
652 diff_type = UNI_DIFF;
658 backup_type = get_version(optarg);
663 debug = atoi(optarg);
676 filearg[0] = xstrdup(*Argv++);
679 if (++filec == MAXFILEC)
680 fatal("too many file arguments\n");
681 filearg[filec] = xstrdup(*Argv++);
686 if (getenv("POSIXLY_CORRECT") != NULL)
694 "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
695 " [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
696 " [-r rej-name] [-V t | nil | never | none] [-x number]\n"
697 " [-z backup-ext] [--posix] [origfile [patchfile]]\n"
698 " patch <patchfile\n");
699 my_exit(EXIT_FAILURE);
703 * Attempt to find the right place to apply this hunk of patch.
706 locate_hunk(LINENUM fuzz)
708 LINENUM first_guess = pch_first() + last_offset;
710 LINENUM pat_lines = pch_ptrn_lines();
711 LINENUM max_pos_offset = input_lines - first_guess - pat_lines + 1;
712 LINENUM max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
714 if (pat_lines == 0) { /* null range matches always */
715 if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
716 || diff_type == NEW_CONTEXT_DIFF
717 || diff_type == UNI_DIFF)) {
718 say("Empty context always matches.\n");
720 return (first_guess);
722 if (max_neg_offset >= first_guess) /* do not try lines < 0 */
723 max_neg_offset = first_guess - 1;
724 if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
726 for (offset = 1; ; offset++) {
727 bool check_after = (offset <= max_pos_offset);
728 bool check_before = (offset <= max_neg_offset);
730 if (check_after && patch_match(first_guess, offset, fuzz)) {
733 say("Offset changing from %ld to %ld\n",
734 last_offset, offset);
736 last_offset = offset;
737 return first_guess + offset;
738 } else if (check_before && patch_match(first_guess, -offset, fuzz)) {
741 say("Offset changing from %ld to %ld\n",
742 last_offset, -offset);
744 last_offset = -offset;
745 return first_guess - offset;
746 } else if (!check_before && !check_after)
751 /* We did not find the pattern, dump out the hunk so they can handle it. */
754 abort_context_hunk(void)
757 const LINENUM pat_end = pch_end();
759 * add in last_offset to guess the same as the previous successful
762 const LINENUM oldfirst = pch_first() + last_offset;
763 const LINENUM newfirst = pch_newfirst() + last_offset;
764 const LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
765 const LINENUM newlast = newfirst + pch_repl_lines() - 1;
766 const char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
767 const char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
769 fprintf(rejfp, "***************\n");
770 for (i = 0; i <= pat_end; i++) {
771 switch (pch_char(i)) {
773 if (oldlast < oldfirst)
774 fprintf(rejfp, "*** 0%s\n", stars);
775 else if (oldlast == oldfirst)
776 fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
778 fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
782 if (newlast < newfirst)
783 fprintf(rejfp, "--- 0%s\n", minuses);
784 else if (newlast == newfirst)
785 fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
787 fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
791 fprintf(rejfp, "%s", pfetch(i));
797 fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
800 fatal("fatal internal error in abort_context_hunk\n");
806 rej_line(int ch, LINENUM i)
809 const char *line = pfetch(i);
813 fprintf(rejfp, "%c%s", ch, line);
814 if (len == 0 || line[len - 1] != '\n') {
815 if (len >= USHRT_MAX)
816 fprintf(rejfp, "\n\\ Line too long\n");
818 fprintf(rejfp, "\n\\ No newline at end of line\n");
827 const LINENUM pat_end = pch_end();
828 const LINENUM oldfirst = pch_first() + last_offset;
829 const LINENUM newfirst = pch_newfirst() + last_offset;
831 if (diff_type != UNI_DIFF) {
832 abort_context_hunk();
836 for (i = 0; i <= pat_end; i++) {
837 if (pch_char(i) == '=') {
843 fprintf(rejfp, "malformed hunk: no split found\n");
848 fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
849 pch_ptrn_lines() ? oldfirst : 0,
850 pch_ptrn_lines(), newfirst, pch_repl_lines());
851 while (i < split || j <= pat_end) {
852 ch1 = i < split ? pch_char(i) : -1;
853 ch2 = j <= pat_end ? pch_char(j) : -1;
857 } else if (ch1 == ' ' && ch2 == ' ') {
861 } else if (ch1 == '!' && ch2 == '!') {
862 while (i < split && ch1 == '!') {
865 ch1 = i < split ? pch_char(i) : -1;
867 while (j <= pat_end && ch2 == '!') {
870 ch2 = j <= pat_end ? pch_char(j) : -1;
872 } else if (ch1 == '*') {
874 } else if (ch2 == '+' || ch2 == ' ') {
878 fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
887 /* We found where to apply it (we hope), so do it. */
890 apply_hunk(LINENUM where)
893 const LINENUM lastline = pch_ptrn_lines();
894 LINENUM new = lastline + 1;
899 int def_state = OUTSIDE;
900 const LINENUM pat_end = pch_end();
903 while (pch_char(new) == '=' || pch_char(new) == '\n')
906 while (old <= lastline) {
907 if (pch_char(old) == '-') {
908 copy_till(where + old - 1, false);
910 if (def_state == OUTSIDE) {
911 fputs(not_defined, ofp);
912 def_state = IN_IFNDEF;
913 } else if (def_state == IN_IFDEF) {
914 fputs(else_defined, ofp);
917 fputs(pfetch(old), ofp);
921 } else if (new > pat_end) {
923 } else if (pch_char(new) == '+') {
924 copy_till(where + old - 1, false);
926 if (def_state == IN_IFNDEF) {
927 fputs(else_defined, ofp);
929 } else if (def_state == OUTSIDE) {
930 fputs(if_defined, ofp);
931 def_state = IN_IFDEF;
934 fputs(pfetch(new), ofp);
936 } else if (pch_char(new) != pch_char(old)) {
937 say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
938 pch_hunk_beg() + old,
939 pch_hunk_beg() + new);
941 say("oldchar = '%c', newchar = '%c'\n",
942 pch_char(old), pch_char(new));
945 } else if (pch_char(new) == '!') {
946 copy_till(where + old - 1, false);
948 fputs(not_defined, ofp);
949 def_state = IN_IFNDEF;
951 while (pch_char(old) == '!') {
953 fputs(pfetch(old), ofp);
959 fputs(else_defined, ofp);
962 while (pch_char(new) == '!') {
963 fputs(pfetch(new), ofp);
967 if (pch_char(new) != ' ')
968 fatal("Internal error: expected ' '\n");
971 if (do_defines && def_state != OUTSIDE) {
972 fputs(end_defined, ofp);
977 if (new <= pat_end && pch_char(new) == '+') {
978 copy_till(where + old - 1, false);
980 if (def_state == OUTSIDE) {
981 fputs(if_defined, ofp);
982 def_state = IN_IFDEF;
983 } else if (def_state == IN_IFNDEF) {
984 fputs(else_defined, ofp);
988 while (new <= pat_end && pch_char(new) == '+') {
989 fputs(pfetch(new), ofp);
993 if (do_defines && def_state != OUTSIDE) {
994 fputs(end_defined, ofp);
1002 init_output(const char *name)
1004 ofp = fopen(name, "w");
1006 pfatal("can't create %s", name);
1010 * Open a file to put hunks we can't locate.
1013 init_reject(const char *name)
1015 rejfp = fopen(name, "w");
1017 pfatal("can't create %s", name);
1021 * Copy input file to output, up to wherever hunk is to be applied.
1022 * If endoffile is true, treat the last line specially since it may
1026 copy_till(LINENUM lastline, bool endoffile)
1028 if (last_frozen_line > lastline)
1029 fatal("misordered hunks! output would be garbled\n");
1030 while (last_frozen_line < lastline) {
1031 if (++last_frozen_line == lastline && endoffile)
1032 dump_line(last_frozen_line, !last_line_missing_eol);
1034 dump_line(last_frozen_line, true);
1039 * Finish copying the input file to the output file.
1048 say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
1051 copy_till(input_lines, true); /* dump remainder of file */
1052 rv = ferror(ofp) == 0 && fclose(ofp) == 0;
1058 * Copy one line from input to output.
1061 dump_line(LINENUM line, bool write_newline)
1065 s = ifetch(line, 0);
1068 /* Note: string is not NUL terminated. */
1069 for (; *s != '\n'; s++)
1076 * Does the patch pattern match at line base+offset?
1079 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
1081 LINENUM pline = 1 + fuzz;
1083 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
1084 const char *ilineptr;
1085 const char *plineptr;
1086 unsigned short plinelen;
1088 /* Patch does not match if we don't have any more context to use */
1089 if (pline > pat_lines)
1091 for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
1092 ilineptr = ifetch(iline, offset >= 0);
1093 if (ilineptr == NULL)
1095 plineptr = pfetch(pline);
1096 plinelen = pch_line_len(pline);
1098 if (!similar(ilineptr, plineptr, plinelen))
1100 } else if (strnNE(ilineptr, plineptr, plinelen))
1102 if (iline == input_lines) {
1104 * We are looking at the last line of the file.
1105 * If the file has no eol, the patch line should
1106 * not have one either and vice-versa. Note that
1109 if (last_line_missing_eol) {
1110 if (plineptr[plinelen - 1] == '\n')
1113 if (plineptr[plinelen - 1] != '\n')
1122 * Do two lines match with canonicalized white space?
1125 similar(const char *a, const char *b, int len)
1128 if (isspace((unsigned char)*b)) { /* whitespace (or \n) to match? */
1129 if (!isspace((unsigned char)*a)) /* no corresponding whitespace? */
1131 while (len && isspace((unsigned char)*b) && *b != '\n')
1132 b++, len--; /* skip pattern whitespace */
1133 while (isspace((unsigned char)*a) && *a != '\n')
1134 a++; /* skip target whitespace */
1135 if (*a == '\n' || *b == '\n')
1136 return (*a == *b); /* should end in sync */
1137 } else if (*a++ != *b++) /* match non-whitespace chars */
1140 len--; /* probably not necessary */
1142 return true; /* actually, this is not reached */
1143 /* since there is always a \n */
1147 handle_creation(bool out_existed, bool *remove)
1151 reverse_seen = false;
1152 if (reverse && out_existed) {
1154 * If the patch creates the file and we're reversing the patch,
1155 * then we need to indicate to the patch processor that it's OK
1156 * to remove this file.
1159 } else if (!reverse && out_existed) {
1161 * Otherwise, we need to blow the horn because the patch appears
1162 * to be reversed/already applied. For non-batch jobs, we'll
1163 * prompt to figure out what we should be trying to do to raise
1164 * awareness of the issue. batch (-t) processing suppresses the
1165 * questions and just assumes that we're reversed if it looks
1166 * like we are, which is always the case if we've reached this
1170 skip_rest_of_patch = true;
1174 /* If -N is supplied, however, we bail out/ignore. */
1175 say("Ignoring previously applied (or reversed) patch.\n");
1176 skip_rest_of_patch = true;
1180 /* Unreversed... suspicious if the file existed. */
1182 fatal("lost hunk on alloc error!\n");
1188 say("Patch creates file that already exists, %s %seversed",
1189 reverse ? "Assuming" : "Ignoring",
1190 reverse ? "R" : "Unr");
1192 ask("Patch creates file that already exists! %s -R? [y] ",
1193 reverse ? "Assume" : "Ignore");
1196 ask("Apply anyway? [n]");
1198 /* Don't apply; error out. */
1199 skip_rest_of_patch = true;
1201 /* Attempt to apply. */
1202 reverse_seen = true;
1205 fatal("lost hunk on alloc error!\n");
1208 * They've opted to assume -R; effectively the
1209 * same as the first branch in this function,
1210 * but the decision is here rather than in a
1211 * prior patch/hunk as in that branch.
1219 * The return value indicates if we offered a chance to reverse but the
1220 * user declined. This keeps the main patch processor in the loop since
1221 * we've taken this out of the normal flow of hunk processing to
1222 * simplify logic a little bit.
1224 return (reverse_seen);