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 $
31 #include <sys/types.h>
47 #include "backupfile.h"
48 #include "pathnames.h"
50 mode_t filemode = 0644;
52 char *buf; /* general purpose buffer */
53 size_t buf_size; /* size of the general purpose buffer */
55 bool using_plan_a = true; /* try to keep everything in memory */
56 bool out_of_mem = false; /* ran out of memory in plan a */
57 bool nonempty_patchf_seen = false; /* seen nonempty patch file? */
61 char *filearg[MAXFILEC];
62 bool ok_to_create_file = false;
64 char *origprae = NULL;
69 bool toutkeep = false;
70 bool trejkeep = false;
71 bool warn_on_invalid_line;
72 bool last_line_missing_eol;
82 bool noreverse = false;
83 bool skip_rest_of_patch = false;
85 bool canonicalize = false;
86 bool check_only = false;
88 char *revision = NULL; /* prerequisite revision, if any */
89 LINENUM input_lines = 0; /* how long is input file in lines */
90 int posix = 0; /* strict POSIX mode? */
92 static void reinitialize_almost_everything(void);
93 static void get_some_switches(void);
94 static LINENUM locate_hunk(LINENUM);
95 static void abort_context_hunk(void);
96 static void rej_line(int, LINENUM);
97 static void abort_hunk(void);
98 static void apply_hunk(LINENUM);
99 static void init_output(const char *);
100 static void init_reject(const char *);
101 static void copy_till(LINENUM, bool);
102 static bool spew_output(void);
103 static void dump_line(LINENUM, bool);
104 static bool patch_match(LINENUM, LINENUM, LINENUM);
105 static bool similar(const char *, const char *, int);
106 static void usage(void);
107 static bool handle_creation(bool, bool *);
109 /* true if -E was specified on command line. */
110 static bool remove_empty_files = false;
112 /* true if -R was specified on command line. */
113 static bool reverse_flag_specified = false;
115 static bool Vflag = false;
117 /* buffer holding the name of the rejected patch file. */
118 static char rejname[PATH_MAX];
120 /* how many input lines have been irretractibly output */
121 static LINENUM last_frozen_line = 0;
123 static int Argc; /* guess */
125 static int Argc_last; /* for restarting plan_b */
126 static char **Argv_last;
128 static FILE *ofp = NULL; /* output file pointer */
129 static FILE *rejfp = NULL; /* reject file pointer */
131 static int filec = 0; /* how many file arguments? */
132 static LINENUM last_offset = 0;
133 static LINENUM maxfuzz = 2;
135 /* patch using ifdef, ifndef, etc. */
136 static bool do_defines = false;
138 static char if_defined[128];
140 static char not_defined[128];
142 static const char else_defined[] = "#else\n";
144 static char end_defined[128];
147 /* Apply a set of diffs as appropriate. */
150 main(int argc, char *argv[])
153 int error = 0, hunk, failed, i, fd;
154 bool out_creating, out_existed, patch_seen, remove_file;
156 LINENUM where = 0, newwhere, fuzz, mymaxfuzz;
160 setvbuf(stdout, NULL, _IOLBF, 0);
161 setvbuf(stderr, NULL, _IOLBF, 0);
162 for (i = 0; i < MAXFILEC; i++)
165 buf_size = INITLINELEN;
166 buf = malloc((unsigned)(buf_size));
168 fatal("out of memory\n");
170 /* Cons up the names of the temporary files. */
171 if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
173 for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--)
176 if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1)
177 fatal("cannot allocate memory");
178 if ((fd = mkstemp(TMPOUTNAME)) < 0)
179 pfatal("can't create %s", TMPOUTNAME);
182 if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1)
183 fatal("cannot allocate memory");
184 if ((fd = mkstemp(TMPINNAME)) < 0)
185 pfatal("can't create %s", TMPINNAME);
188 if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1)
189 fatal("cannot allocate memory");
190 if ((fd = mkstemp(TMPREJNAME)) < 0)
191 pfatal("can't create %s", TMPREJNAME);
194 if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1)
195 fatal("cannot allocate memory");
196 if ((fd = mkstemp(TMPPATNAME)) < 0)
197 pfatal("can't create %s", TMPPATNAME);
200 v = getenv("SIMPLE_BACKUP_SUFFIX");
202 simple_backup_suffix = v;
204 simple_backup_suffix = ORIGEXT;
212 if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
213 v = getenv("VERSION_CONTROL");
214 if (v != NULL || !posix)
215 backup_type = get_version(v); /* OK to pass NULL. */
218 /* make sure we clean up /tmp in case of disaster */
222 for (open_patch_file(filearg[1]); there_is_another_patch();
223 reinitialize_almost_everything()) {
224 /* for each patch in patch file */
226 if (source_file != NULL && (diff_type == CONTEXT_DIFF ||
227 diff_type == NEW_CONTEXT_DIFF ||
228 diff_type == UNI_DIFF))
229 out_creating = strcmp(source_file, _PATH_DEVNULL) == 0;
231 out_creating = false;
234 warn_on_invalid_line = true;
237 outname = xstrdup(filearg[0]);
240 * At this point, we know if we're supposed to be creating the
241 * file and we know if we should be trying to handle a conflict
242 * between the patch and the file already existing. We defer
243 * handling it until hunk processing because we want to swap
244 * the hunk if they opt to reverse it, but we want to make sure
245 * we *can* swap the hunk without running into memory issues
246 * before we offer it. We also want to be verbose if flags or
247 * user decision cause us to skip -- this is explained a little
250 out_existed = stat(outname, &statbuf) == 0;
252 /* for ed script just up and do it and exit */
253 if (diff_type == ED_DIFF) {
257 /* initialize the patched file */
258 if (!skip_rest_of_patch)
259 init_output(TMPOUTNAME);
261 /* initialize reject file */
262 init_reject(TMPREJNAME);
264 /* find out where all the lines are */
265 if (!skip_rest_of_patch)
266 scan_input(filearg[0]);
269 * from here on, open no standard i/o files, because
270 * malloc might misfire and we can't catch it easily
273 /* apply each hunk of patch */
276 reverse_seen = false;
279 while (another_hunk()) {
280 assert(!out_creating || hunk == 0);
285 * There are only three cases in handle_creation() that
286 * results in us skipping hunk location, in order:
288 * 1.) Potentially reversed but -f/--force'd,
289 * 2.) Potentially reversed but -N/--forward'd
290 * 3.) Reversed and the user's opted to not apply it.
292 * In all three cases, we still want to inform the user
293 * that we're ignoring it in the standard way, which is
294 * also tied to this hunk processing loop.
297 reverse_seen = handle_creation(out_existed,
300 mymaxfuzz = pch_context();
301 if (maxfuzz < mymaxfuzz)
303 if (!skip_rest_of_patch) {
305 where = locate_hunk(fuzz);
306 if (hunk == 1 && where == 0 && !force && !reverse_seen) {
307 /* dwim for reversed patch? */
310 say("Not enough memory to try swapped hunk! Assuming unswapped.\n");
315 where = locate_hunk(fuzz);
317 /* didn't find it swapped */
319 /* put it back to normal */
320 fatal("lost hunk on alloc error!\n");
322 } else if (noreverse) {
324 /* put it back to normal */
325 fatal("lost hunk on alloc error!\n");
327 say("Ignoring previously applied (or reversed) patch.\n");
328 skip_rest_of_patch = true;
331 say("%seversed (or previously applied) patch detected! %s -R.",
332 reverse ? "R" : "Unr",
333 reverse ? "Assuming" : "Ignoring");
335 ask("%seversed (or previously applied) patch detected! %s -R? [y] ",
336 reverse ? "R" : "Unr",
337 reverse ? "Assume" : "Ignore");
339 ask("Apply anyway? [n] ");
341 skip_rest_of_patch = true;
347 /* put it back to normal */
348 fatal("lost hunk on alloc error!\n");
352 } while (!skip_rest_of_patch && where == 0 &&
353 ++fuzz <= mymaxfuzz);
355 if (skip_rest_of_patch) { /* just got decided */
356 if (ferror(ofp) || fclose(ofp)) {
357 say("Error writing %s\n",
364 newwhere = pch_newfirst() + last_offset;
365 if (skip_rest_of_patch) {
369 say("Hunk #%d ignored at %ld.\n",
371 } else if (where == 0) {
375 say("Hunk #%d failed at %ld.\n",
380 say("Hunk #%d succeeded at %ld",
383 say(" with fuzz %ld", fuzz);
385 say(" (offset %ld line%s)",
387 last_offset == 1L ? "" : "s");
393 if (out_of_mem && using_plan_a) {
396 say("\n\nRan out of memory using Plan A--trying again...\n\n");
406 fatal("Internal error: hunk should not be 0\n");
408 /* finish spewing out the new file */
409 if (!skip_rest_of_patch && !spew_output()) {
410 say("Can't write %s\n", TMPOUTNAME);
414 /* and put the output where desired */
416 if (!skip_rest_of_patch) {
417 char *realout = outname;
420 if (move_file(TMPOUTNAME, outname) < 0) {
422 realout = TMPOUTNAME;
423 chmod(TMPOUTNAME, filemode);
425 chmod(outname, filemode);
428 * remove_file is a per-patch flag indicating
429 * whether it's OK to remove the empty file.
430 * This is specifically set when we're reversing
431 * the creation of a file and it ends up empty.
432 * This is an exception to the global policy
433 * (remove_empty_files) because the user would
434 * likely not expect the reverse of file
435 * creation to leave an empty file laying
438 if ((remove_empty_files || remove_file) &&
439 stat(realout, &statbuf) == 0 &&
440 statbuf.st_size == 0) {
442 say("Removing %s (empty after patching).\n",
448 if (ferror(rejfp) || fclose(rejfp)) {
449 say("Error writing %s\n", rejname);
455 if (*rejname == '\0') {
456 if (strlcpy(rejname, outname,
457 sizeof(rejname)) >= sizeof(rejname))
458 fatal("filename %s is too long\n", outname);
459 if (strlcat(rejname, REJEXT,
460 sizeof(rejname)) >= sizeof(rejname))
461 fatal("filename %s is too long\n", outname);
464 say("%d out of %d hunks %s--saving rejects to %s\n",
465 failed, hunk, skip_rest_of_patch ? "ignored" : "failed", rejname);
466 else if (filearg[0] != NULL)
467 say("%d out of %d hunks %s while patching %s\n",
468 failed, hunk, skip_rest_of_patch ? "ignored" : "failed", filearg[0]);
470 /* File prompt ignored, just note # hunks. */
471 say("%d out of %d hunks %s\n",
472 failed, hunk, skip_rest_of_patch ? "ignored" : "failed");
473 if (!check_only && move_file(TMPREJNAME, rejname) < 0)
479 if (!patch_seen && nonempty_patchf_seen)
486 /* Prepare to find the next patch to do in the patch file. */
489 reinitialize_almost_everything(void)
495 last_frozen_line = 0;
515 reverse = reverse_flag_specified;
516 skip_rest_of_patch = false;
521 /* Process switches and filenames. */
524 get_some_switches(void)
526 const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
527 static struct option longopts[] = {
528 {"backup", no_argument, 0, 'b'},
529 {"batch", no_argument, 0, 't'},
530 {"check", no_argument, 0, 'C'},
531 {"context", no_argument, 0, 'c'},
532 {"debug", required_argument, 0, 'x'},
533 {"directory", required_argument, 0, 'd'},
534 {"dry-run", no_argument, 0, 'C'},
535 {"ed", no_argument, 0, 'e'},
536 {"force", no_argument, 0, 'f'},
537 {"forward", no_argument, 0, 'N'},
538 {"fuzz", required_argument, 0, 'F'},
539 {"ifdef", required_argument, 0, 'D'},
540 {"input", required_argument, 0, 'i'},
541 {"ignore-whitespace", no_argument, 0, 'l'},
542 {"normal", no_argument, 0, 'n'},
543 {"output", required_argument, 0, 'o'},
544 {"prefix", required_argument, 0, 'B'},
545 {"quiet", no_argument, 0, 's'},
546 {"reject-file", required_argument, 0, 'r'},
547 {"remove-empty-files", no_argument, 0, 'E'},
548 {"reverse", no_argument, 0, 'R'},
549 {"silent", no_argument, 0, 's'},
550 {"strip", required_argument, 0, 'p'},
551 {"suffix", required_argument, 0, 'z'},
552 {"unified", no_argument, 0, 'u'},
553 {"version", no_argument, 0, 'v'},
554 {"version-control", required_argument, 0, 'V'},
555 {"posix", no_argument, &posix, 1},
565 optreset = optind = 1;
566 while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
569 if (backup_type == none)
570 backup_type = numbered_existing;
574 say("Warning, the ``-b suffix'' option has been"
575 " obsoleted by the -z option.\n");
578 /* must directly follow 'b' case for backwards compat */
579 simple_backup_suffix = xstrdup(optarg);
582 origprae = xstrdup(optarg);
585 diff_type = CONTEXT_DIFF;
591 if (chdir(optarg) < 0)
592 pfatal("can't cd to %s", optarg);
596 if (!isalpha((unsigned char)*optarg) && *optarg != '_')
597 fatal("argument to -D is not an identifier\n");
598 snprintf(if_defined, sizeof if_defined,
599 "#ifdef %s\n", optarg);
600 snprintf(not_defined, sizeof not_defined,
601 "#ifndef %s\n", optarg);
602 snprintf(end_defined, sizeof end_defined,
603 "#endif /* %s */\n", optarg);
609 remove_empty_files = true;
615 maxfuzz = atoi(optarg);
618 if (++filec == MAXFILEC)
619 fatal("too many file arguments\n");
620 filearg[filec] = xstrdup(optarg);
626 diff_type = NORMAL_DIFF;
632 outname = xstrdup(optarg);
635 strippath = atoi(optarg);
638 if (strlcpy(rejname, optarg,
639 sizeof(rejname)) >= sizeof(rejname))
640 fatal("argument for -r is too long\n");
644 reverse_flag_specified = true;
653 diff_type = UNI_DIFF;
659 backup_type = get_version(optarg);
664 debug = atoi(optarg);
677 filearg[0] = xstrdup(*Argv++);
680 if (++filec == MAXFILEC)
681 fatal("too many file arguments\n");
682 filearg[filec] = xstrdup(*Argv++);
687 if (getenv("POSIXLY_CORRECT") != NULL)
695 "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
696 " [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
697 " [-r rej-name] [-V t | nil | never | none] [-x number]\n"
698 " [-z backup-ext] [--posix] [origfile [patchfile]]\n"
699 " patch <patchfile\n");
700 my_exit(EXIT_FAILURE);
704 * Attempt to find the right place to apply this hunk of patch.
707 locate_hunk(LINENUM fuzz)
709 LINENUM first_guess = pch_first() + last_offset;
711 LINENUM pat_lines = pch_ptrn_lines();
712 LINENUM max_pos_offset = input_lines - first_guess - pat_lines + 1;
713 LINENUM max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
715 if (pat_lines == 0) { /* null range matches always */
716 if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
717 || diff_type == NEW_CONTEXT_DIFF
718 || diff_type == UNI_DIFF)) {
719 say("Empty context always matches.\n");
721 return (first_guess);
723 if (max_neg_offset >= first_guess) /* do not try lines < 0 */
724 max_neg_offset = first_guess - 1;
725 if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
727 for (offset = 1; ; offset++) {
728 bool check_after = (offset <= max_pos_offset);
729 bool check_before = (offset <= max_neg_offset);
731 if (check_after && patch_match(first_guess, offset, fuzz)) {
734 say("Offset changing from %ld to %ld\n",
735 last_offset, offset);
737 last_offset = offset;
738 return first_guess + offset;
739 } else if (check_before && patch_match(first_guess, -offset, fuzz)) {
742 say("Offset changing from %ld to %ld\n",
743 last_offset, -offset);
745 last_offset = -offset;
746 return first_guess - offset;
747 } else if (!check_before && !check_after)
752 /* We did not find the pattern, dump out the hunk so they can handle it. */
755 abort_context_hunk(void)
758 const LINENUM pat_end = pch_end();
760 * add in last_offset to guess the same as the previous successful
763 const LINENUM oldfirst = pch_first() + last_offset;
764 const LINENUM newfirst = pch_newfirst() + last_offset;
765 const LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
766 const LINENUM newlast = newfirst + pch_repl_lines() - 1;
767 const char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
768 const char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
770 fprintf(rejfp, "***************\n");
771 for (i = 0; i <= pat_end; i++) {
772 switch (pch_char(i)) {
774 if (oldlast < oldfirst)
775 fprintf(rejfp, "*** 0%s\n", stars);
776 else if (oldlast == oldfirst)
777 fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
779 fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
783 if (newlast < newfirst)
784 fprintf(rejfp, "--- 0%s\n", minuses);
785 else if (newlast == newfirst)
786 fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
788 fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
792 fprintf(rejfp, "%s", pfetch(i));
798 fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
801 fatal("fatal internal error in abort_context_hunk\n");
807 rej_line(int ch, LINENUM i)
810 const char *line = pfetch(i);
814 fprintf(rejfp, "%c%s", ch, line);
815 if (len == 0 || line[len - 1] != '\n') {
816 if (len >= USHRT_MAX)
817 fprintf(rejfp, "\n\\ Line too long\n");
819 fprintf(rejfp, "\n\\ No newline at end of line\n");
828 const LINENUM pat_end = pch_end();
829 const LINENUM oldfirst = pch_first() + last_offset;
830 const LINENUM newfirst = pch_newfirst() + last_offset;
832 if (diff_type != UNI_DIFF) {
833 abort_context_hunk();
837 for (i = 0; i <= pat_end; i++) {
838 if (pch_char(i) == '=') {
844 fprintf(rejfp, "malformed hunk: no split found\n");
849 fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
850 pch_ptrn_lines() ? oldfirst : 0,
851 pch_ptrn_lines(), newfirst, pch_repl_lines());
852 while (i < split || j <= pat_end) {
853 ch1 = i < split ? pch_char(i) : -1;
854 ch2 = j <= pat_end ? pch_char(j) : -1;
858 } else if (ch1 == ' ' && ch2 == ' ') {
862 } else if (ch1 == '!' && ch2 == '!') {
863 while (i < split && ch1 == '!') {
866 ch1 = i < split ? pch_char(i) : -1;
868 while (j <= pat_end && ch2 == '!') {
871 ch2 = j <= pat_end ? pch_char(j) : -1;
873 } else if (ch1 == '*') {
875 } else if (ch2 == '+' || ch2 == ' ') {
879 fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
888 /* We found where to apply it (we hope), so do it. */
891 apply_hunk(LINENUM where)
894 const LINENUM lastline = pch_ptrn_lines();
895 LINENUM new = lastline + 1;
900 int def_state = OUTSIDE;
901 const LINENUM pat_end = pch_end();
904 while (pch_char(new) == '=' || pch_char(new) == '\n')
907 while (old <= lastline) {
908 if (pch_char(old) == '-') {
909 copy_till(where + old - 1, false);
911 if (def_state == OUTSIDE) {
912 fputs(not_defined, ofp);
913 def_state = IN_IFNDEF;
914 } else if (def_state == IN_IFDEF) {
915 fputs(else_defined, ofp);
918 fputs(pfetch(old), ofp);
922 } else if (new > pat_end) {
924 } else if (pch_char(new) == '+') {
925 copy_till(where + old - 1, false);
927 if (def_state == IN_IFNDEF) {
928 fputs(else_defined, ofp);
930 } else if (def_state == OUTSIDE) {
931 fputs(if_defined, ofp);
932 def_state = IN_IFDEF;
935 fputs(pfetch(new), ofp);
937 } else if (pch_char(new) != pch_char(old)) {
938 say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
939 pch_hunk_beg() + old,
940 pch_hunk_beg() + new);
942 say("oldchar = '%c', newchar = '%c'\n",
943 pch_char(old), pch_char(new));
946 } else if (pch_char(new) == '!') {
947 copy_till(where + old - 1, false);
949 fputs(not_defined, ofp);
950 def_state = IN_IFNDEF;
952 while (pch_char(old) == '!') {
954 fputs(pfetch(old), ofp);
960 fputs(else_defined, ofp);
963 while (pch_char(new) == '!') {
964 fputs(pfetch(new), ofp);
968 if (pch_char(new) != ' ')
969 fatal("Internal error: expected ' '\n");
972 if (do_defines && def_state != OUTSIDE) {
973 fputs(end_defined, ofp);
978 if (new <= pat_end && pch_char(new) == '+') {
979 copy_till(where + old - 1, false);
981 if (def_state == OUTSIDE) {
982 fputs(if_defined, ofp);
983 def_state = IN_IFDEF;
984 } else if (def_state == IN_IFNDEF) {
985 fputs(else_defined, ofp);
989 while (new <= pat_end && pch_char(new) == '+') {
990 fputs(pfetch(new), ofp);
994 if (do_defines && def_state != OUTSIDE) {
995 fputs(end_defined, ofp);
1000 * Open the new file.
1003 init_output(const char *name)
1005 ofp = fopen(name, "w");
1007 pfatal("can't create %s", name);
1011 * Open a file to put hunks we can't locate.
1014 init_reject(const char *name)
1016 rejfp = fopen(name, "w");
1018 pfatal("can't create %s", name);
1022 * Copy input file to output, up to wherever hunk is to be applied.
1023 * If endoffile is true, treat the last line specially since it may
1027 copy_till(LINENUM lastline, bool endoffile)
1029 if (last_frozen_line > lastline)
1030 fatal("misordered hunks! output would be garbled\n");
1031 while (last_frozen_line < lastline) {
1032 if (++last_frozen_line == lastline && endoffile)
1033 dump_line(last_frozen_line, !last_line_missing_eol);
1035 dump_line(last_frozen_line, true);
1040 * Finish copying the input file to the output file.
1049 say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
1052 copy_till(input_lines, true); /* dump remainder of file */
1053 rv = ferror(ofp) == 0 && fclose(ofp) == 0;
1059 * Copy one line from input to output.
1062 dump_line(LINENUM line, bool write_newline)
1066 s = ifetch(line, 0);
1069 /* Note: string is not NUL terminated. */
1070 for (; *s != '\n'; s++)
1077 * Does the patch pattern match at line base+offset?
1080 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
1082 LINENUM pline = 1 + fuzz;
1084 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
1085 const char *ilineptr;
1086 const char *plineptr;
1087 unsigned short plinelen;
1089 /* Patch does not match if we don't have any more context to use */
1090 if (pline > pat_lines)
1092 for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
1093 ilineptr = ifetch(iline, offset >= 0);
1094 if (ilineptr == NULL)
1096 plineptr = pfetch(pline);
1097 plinelen = pch_line_len(pline);
1099 if (!similar(ilineptr, plineptr, plinelen))
1101 } else if (strnNE(ilineptr, plineptr, plinelen))
1103 if (iline == input_lines) {
1105 * We are looking at the last line of the file.
1106 * If the file has no eol, the patch line should
1107 * not have one either and vice-versa. Note that
1110 if (last_line_missing_eol) {
1111 if (plineptr[plinelen - 1] == '\n')
1114 if (plineptr[plinelen - 1] != '\n')
1123 * Do two lines match with canonicalized white space?
1126 similar(const char *a, const char *b, int len)
1129 if (isspace((unsigned char)*b)) { /* whitespace (or \n) to match? */
1130 if (!isspace((unsigned char)*a)) /* no corresponding whitespace? */
1132 while (len && isspace((unsigned char)*b) && *b != '\n')
1133 b++, len--; /* skip pattern whitespace */
1134 while (isspace((unsigned char)*a) && *a != '\n')
1135 a++; /* skip target whitespace */
1136 if (*a == '\n' || *b == '\n')
1137 return (*a == *b); /* should end in sync */
1138 } else if (*a++ != *b++) /* match non-whitespace chars */
1141 len--; /* probably not necessary */
1143 return true; /* actually, this is not reached */
1144 /* since there is always a \n */
1148 handle_creation(bool out_existed, bool *remove)
1152 reverse_seen = false;
1153 if (reverse && out_existed) {
1155 * If the patch creates the file and we're reversing the patch,
1156 * then we need to indicate to the patch processor that it's OK
1157 * to remove this file.
1160 } else if (!reverse && out_existed) {
1162 * Otherwise, we need to blow the horn because the patch appears
1163 * to be reversed/already applied. For non-batch jobs, we'll
1164 * prompt to figure out what we should be trying to do to raise
1165 * awareness of the issue. batch (-t) processing suppresses the
1166 * questions and just assumes that we're reversed if it looks
1167 * like we are, which is always the case if we've reached this
1171 skip_rest_of_patch = true;
1175 /* If -N is supplied, however, we bail out/ignore. */
1176 say("Ignoring previously applied (or reversed) patch.\n");
1177 skip_rest_of_patch = true;
1181 /* Unreversed... suspicious if the file existed. */
1183 fatal("lost hunk on alloc error!\n");
1189 say("Patch creates file that already exists, %s %seversed",
1190 reverse ? "Assuming" : "Ignoring",
1191 reverse ? "R" : "Unr");
1193 ask("Patch creates file that already exists! %s -R? [y] ",
1194 reverse ? "Assume" : "Ignore");
1197 ask("Apply anyway? [n]");
1199 /* Don't apply; error out. */
1200 skip_rest_of_patch = true;
1202 /* Attempt to apply. */
1203 reverse_seen = true;
1206 fatal("lost hunk on alloc error!\n");
1209 * They've opted to assume -R; effectively the
1210 * same as the first branch in this function,
1211 * but the decision is here rather than in a
1212 * prior patch/hunk as in that branch.
1220 * The return value indicates if we offered a chance to reverse but the
1221 * user declined. This keeps the main patch processor in the loop since
1222 * we've taken this out of the normal flow of hunk processing to
1223 * simplify logic a little bit.
1225 return (reverse_seen);