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);
467 say("%d out of %d hunks %s while patching %s\n",
468 failed, hunk, skip_rest_of_patch ? "ignored" : "failed", filearg[0]);
469 if (!check_only && move_file(TMPREJNAME, rejname) < 0)
475 if (!patch_seen && nonempty_patchf_seen)
482 /* Prepare to find the next patch to do in the patch file. */
485 reinitialize_almost_everything(void)
491 last_frozen_line = 0;
511 reverse = reverse_flag_specified;
512 skip_rest_of_patch = false;
517 /* Process switches and filenames. */
520 get_some_switches(void)
522 const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
523 static struct option longopts[] = {
524 {"backup", no_argument, 0, 'b'},
525 {"batch", no_argument, 0, 't'},
526 {"check", no_argument, 0, 'C'},
527 {"context", no_argument, 0, 'c'},
528 {"debug", required_argument, 0, 'x'},
529 {"directory", required_argument, 0, 'd'},
530 {"dry-run", no_argument, 0, 'C'},
531 {"ed", no_argument, 0, 'e'},
532 {"force", no_argument, 0, 'f'},
533 {"forward", no_argument, 0, 'N'},
534 {"fuzz", required_argument, 0, 'F'},
535 {"ifdef", required_argument, 0, 'D'},
536 {"input", required_argument, 0, 'i'},
537 {"ignore-whitespace", no_argument, 0, 'l'},
538 {"normal", no_argument, 0, 'n'},
539 {"output", required_argument, 0, 'o'},
540 {"prefix", required_argument, 0, 'B'},
541 {"quiet", no_argument, 0, 's'},
542 {"reject-file", required_argument, 0, 'r'},
543 {"remove-empty-files", no_argument, 0, 'E'},
544 {"reverse", no_argument, 0, 'R'},
545 {"silent", no_argument, 0, 's'},
546 {"strip", required_argument, 0, 'p'},
547 {"suffix", required_argument, 0, 'z'},
548 {"unified", no_argument, 0, 'u'},
549 {"version", no_argument, 0, 'v'},
550 {"version-control", required_argument, 0, 'V'},
551 {"posix", no_argument, &posix, 1},
561 optreset = optind = 1;
562 while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
565 if (backup_type == none)
566 backup_type = numbered_existing;
570 say("Warning, the ``-b suffix'' option has been"
571 " obsoleted by the -z option.\n");
574 /* must directly follow 'b' case for backwards compat */
575 simple_backup_suffix = xstrdup(optarg);
578 origprae = xstrdup(optarg);
581 diff_type = CONTEXT_DIFF;
587 if (chdir(optarg) < 0)
588 pfatal("can't cd to %s", optarg);
592 if (!isalpha((unsigned char)*optarg) && *optarg != '_')
593 fatal("argument to -D is not an identifier\n");
594 snprintf(if_defined, sizeof if_defined,
595 "#ifdef %s\n", optarg);
596 snprintf(not_defined, sizeof not_defined,
597 "#ifndef %s\n", optarg);
598 snprintf(end_defined, sizeof end_defined,
599 "#endif /* %s */\n", optarg);
605 remove_empty_files = true;
611 maxfuzz = atoi(optarg);
614 if (++filec == MAXFILEC)
615 fatal("too many file arguments\n");
616 filearg[filec] = xstrdup(optarg);
622 diff_type = NORMAL_DIFF;
628 outname = xstrdup(optarg);
631 strippath = atoi(optarg);
634 if (strlcpy(rejname, optarg,
635 sizeof(rejname)) >= sizeof(rejname))
636 fatal("argument for -r is too long\n");
640 reverse_flag_specified = true;
649 diff_type = UNI_DIFF;
655 backup_type = get_version(optarg);
660 debug = atoi(optarg);
673 filearg[0] = xstrdup(*Argv++);
676 if (++filec == MAXFILEC)
677 fatal("too many file arguments\n");
678 filearg[filec] = xstrdup(*Argv++);
683 if (getenv("POSIXLY_CORRECT") != NULL)
691 "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
692 " [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
693 " [-r rej-name] [-V t | nil | never | none] [-x number]\n"
694 " [-z backup-ext] [--posix] [origfile [patchfile]]\n"
695 " patch <patchfile\n");
696 my_exit(EXIT_FAILURE);
700 * Attempt to find the right place to apply this hunk of patch.
703 locate_hunk(LINENUM fuzz)
705 LINENUM first_guess = pch_first() + last_offset;
707 LINENUM pat_lines = pch_ptrn_lines();
708 LINENUM max_pos_offset = input_lines - first_guess - pat_lines + 1;
709 LINENUM max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
711 if (pat_lines == 0) { /* null range matches always */
712 if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
713 || diff_type == NEW_CONTEXT_DIFF
714 || diff_type == UNI_DIFF)) {
715 say("Empty context always matches.\n");
717 return (first_guess);
719 if (max_neg_offset >= first_guess) /* do not try lines < 0 */
720 max_neg_offset = first_guess - 1;
721 if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
723 for (offset = 1; ; offset++) {
724 bool check_after = (offset <= max_pos_offset);
725 bool check_before = (offset <= max_neg_offset);
727 if (check_after && patch_match(first_guess, offset, fuzz)) {
730 say("Offset changing from %ld to %ld\n",
731 last_offset, offset);
733 last_offset = offset;
734 return first_guess + offset;
735 } else if (check_before && patch_match(first_guess, -offset, fuzz)) {
738 say("Offset changing from %ld to %ld\n",
739 last_offset, -offset);
741 last_offset = -offset;
742 return first_guess - offset;
743 } else if (!check_before && !check_after)
748 /* We did not find the pattern, dump out the hunk so they can handle it. */
751 abort_context_hunk(void)
754 const LINENUM pat_end = pch_end();
756 * add in last_offset to guess the same as the previous successful
759 const LINENUM oldfirst = pch_first() + last_offset;
760 const LINENUM newfirst = pch_newfirst() + last_offset;
761 const LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
762 const LINENUM newlast = newfirst + pch_repl_lines() - 1;
763 const char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
764 const char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
766 fprintf(rejfp, "***************\n");
767 for (i = 0; i <= pat_end; i++) {
768 switch (pch_char(i)) {
770 if (oldlast < oldfirst)
771 fprintf(rejfp, "*** 0%s\n", stars);
772 else if (oldlast == oldfirst)
773 fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
775 fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
779 if (newlast < newfirst)
780 fprintf(rejfp, "--- 0%s\n", minuses);
781 else if (newlast == newfirst)
782 fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
784 fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
788 fprintf(rejfp, "%s", pfetch(i));
794 fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
797 fatal("fatal internal error in abort_context_hunk\n");
803 rej_line(int ch, LINENUM i)
806 const char *line = pfetch(i);
810 fprintf(rejfp, "%c%s", ch, line);
811 if (len == 0 || line[len - 1] != '\n') {
812 if (len >= USHRT_MAX)
813 fprintf(rejfp, "\n\\ Line too long\n");
815 fprintf(rejfp, "\n\\ No newline at end of line\n");
824 const LINENUM pat_end = pch_end();
825 const LINENUM oldfirst = pch_first() + last_offset;
826 const LINENUM newfirst = pch_newfirst() + last_offset;
828 if (diff_type != UNI_DIFF) {
829 abort_context_hunk();
833 for (i = 0; i <= pat_end; i++) {
834 if (pch_char(i) == '=') {
840 fprintf(rejfp, "malformed hunk: no split found\n");
845 fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
846 pch_ptrn_lines() ? oldfirst : 0,
847 pch_ptrn_lines(), newfirst, pch_repl_lines());
848 while (i < split || j <= pat_end) {
849 ch1 = i < split ? pch_char(i) : -1;
850 ch2 = j <= pat_end ? pch_char(j) : -1;
854 } else if (ch1 == ' ' && ch2 == ' ') {
858 } else if (ch1 == '!' && ch2 == '!') {
859 while (i < split && ch1 == '!') {
862 ch1 = i < split ? pch_char(i) : -1;
864 while (j <= pat_end && ch2 == '!') {
867 ch2 = j <= pat_end ? pch_char(j) : -1;
869 } else if (ch1 == '*') {
871 } else if (ch2 == '+' || ch2 == ' ') {
875 fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
884 /* We found where to apply it (we hope), so do it. */
887 apply_hunk(LINENUM where)
890 const LINENUM lastline = pch_ptrn_lines();
891 LINENUM new = lastline + 1;
896 int def_state = OUTSIDE;
897 const LINENUM pat_end = pch_end();
900 while (pch_char(new) == '=' || pch_char(new) == '\n')
903 while (old <= lastline) {
904 if (pch_char(old) == '-') {
905 copy_till(where + old - 1, false);
907 if (def_state == OUTSIDE) {
908 fputs(not_defined, ofp);
909 def_state = IN_IFNDEF;
910 } else if (def_state == IN_IFDEF) {
911 fputs(else_defined, ofp);
914 fputs(pfetch(old), ofp);
918 } else if (new > pat_end) {
920 } else if (pch_char(new) == '+') {
921 copy_till(where + old - 1, false);
923 if (def_state == IN_IFNDEF) {
924 fputs(else_defined, ofp);
926 } else if (def_state == OUTSIDE) {
927 fputs(if_defined, ofp);
928 def_state = IN_IFDEF;
931 fputs(pfetch(new), ofp);
933 } else if (pch_char(new) != pch_char(old)) {
934 say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
935 pch_hunk_beg() + old,
936 pch_hunk_beg() + new);
938 say("oldchar = '%c', newchar = '%c'\n",
939 pch_char(old), pch_char(new));
942 } else if (pch_char(new) == '!') {
943 copy_till(where + old - 1, false);
945 fputs(not_defined, ofp);
946 def_state = IN_IFNDEF;
948 while (pch_char(old) == '!') {
950 fputs(pfetch(old), ofp);
956 fputs(else_defined, ofp);
959 while (pch_char(new) == '!') {
960 fputs(pfetch(new), ofp);
964 if (pch_char(new) != ' ')
965 fatal("Internal error: expected ' '\n");
968 if (do_defines && def_state != OUTSIDE) {
969 fputs(end_defined, ofp);
974 if (new <= pat_end && pch_char(new) == '+') {
975 copy_till(where + old - 1, false);
977 if (def_state == OUTSIDE) {
978 fputs(if_defined, ofp);
979 def_state = IN_IFDEF;
980 } else if (def_state == IN_IFNDEF) {
981 fputs(else_defined, ofp);
985 while (new <= pat_end && pch_char(new) == '+') {
986 fputs(pfetch(new), ofp);
990 if (do_defines && def_state != OUTSIDE) {
991 fputs(end_defined, ofp);
999 init_output(const char *name)
1001 ofp = fopen(name, "w");
1003 pfatal("can't create %s", name);
1007 * Open a file to put hunks we can't locate.
1010 init_reject(const char *name)
1012 rejfp = fopen(name, "w");
1014 pfatal("can't create %s", name);
1018 * Copy input file to output, up to wherever hunk is to be applied.
1019 * If endoffile is true, treat the last line specially since it may
1023 copy_till(LINENUM lastline, bool endoffile)
1025 if (last_frozen_line > lastline)
1026 fatal("misordered hunks! output would be garbled\n");
1027 while (last_frozen_line < lastline) {
1028 if (++last_frozen_line == lastline && endoffile)
1029 dump_line(last_frozen_line, !last_line_missing_eol);
1031 dump_line(last_frozen_line, true);
1036 * Finish copying the input file to the output file.
1045 say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
1048 copy_till(input_lines, true); /* dump remainder of file */
1049 rv = ferror(ofp) == 0 && fclose(ofp) == 0;
1055 * Copy one line from input to output.
1058 dump_line(LINENUM line, bool write_newline)
1062 s = ifetch(line, 0);
1065 /* Note: string is not NUL terminated. */
1066 for (; *s != '\n'; s++)
1073 * Does the patch pattern match at line base+offset?
1076 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
1078 LINENUM pline = 1 + fuzz;
1080 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
1081 const char *ilineptr;
1082 const char *plineptr;
1083 unsigned short plinelen;
1085 /* Patch does not match if we don't have any more context to use */
1086 if (pline > pat_lines)
1088 for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
1089 ilineptr = ifetch(iline, offset >= 0);
1090 if (ilineptr == NULL)
1092 plineptr = pfetch(pline);
1093 plinelen = pch_line_len(pline);
1095 if (!similar(ilineptr, plineptr, plinelen))
1097 } else if (strnNE(ilineptr, plineptr, plinelen))
1099 if (iline == input_lines) {
1101 * We are looking at the last line of the file.
1102 * If the file has no eol, the patch line should
1103 * not have one either and vice-versa. Note that
1106 if (last_line_missing_eol) {
1107 if (plineptr[plinelen - 1] == '\n')
1110 if (plineptr[plinelen - 1] != '\n')
1119 * Do two lines match with canonicalized white space?
1122 similar(const char *a, const char *b, int len)
1125 if (isspace((unsigned char)*b)) { /* whitespace (or \n) to match? */
1126 if (!isspace((unsigned char)*a)) /* no corresponding whitespace? */
1128 while (len && isspace((unsigned char)*b) && *b != '\n')
1129 b++, len--; /* skip pattern whitespace */
1130 while (isspace((unsigned char)*a) && *a != '\n')
1131 a++; /* skip target whitespace */
1132 if (*a == '\n' || *b == '\n')
1133 return (*a == *b); /* should end in sync */
1134 } else if (*a++ != *b++) /* match non-whitespace chars */
1137 len--; /* probably not necessary */
1139 return true; /* actually, this is not reached */
1140 /* since there is always a \n */
1144 handle_creation(bool out_existed, bool *remove)
1148 reverse_seen = false;
1149 if (reverse && out_existed) {
1151 * If the patch creates the file and we're reversing the patch,
1152 * then we need to indicate to the patch processor that it's OK
1153 * to remove this file.
1156 } else if (!reverse && out_existed) {
1158 * Otherwise, we need to blow the horn because the patch appears
1159 * to be reversed/already applied. For non-batch jobs, we'll
1160 * prompt to figure out what we should be trying to do to raise
1161 * awareness of the issue. batch (-t) processing suppresses the
1162 * questions and just assumes that we're reversed if it looks
1163 * like we are, which is always the case if we've reached this
1167 skip_rest_of_patch = true;
1171 /* If -N is supplied, however, we bail out/ignore. */
1172 say("Ignoring previously applied (or reversed) patch.\n");
1173 skip_rest_of_patch = true;
1177 /* Unreversed... suspicious if the file existed. */
1179 fatal("lost hunk on alloc error!\n");
1185 say("Patch creates file that already exists, %s %seversed",
1186 reverse ? "Assuming" : "Ignoring",
1187 reverse ? "R" : "Unr");
1189 ask("Patch creates file that already exists! %s -R? [y] ",
1190 reverse ? "Assume" : "Ignore");
1193 ask("Apply anyway? [n]");
1195 /* Don't apply; error out. */
1196 skip_rest_of_patch = true;
1198 /* Attempt to apply. */
1199 reverse_seen = true;
1202 fatal("lost hunk on alloc error!\n");
1205 * They've opted to assume -R; effectively the
1206 * same as the first branch in this function,
1207 * but the decision is here rather than in a
1208 * prior patch/hunk as in that branch.
1216 * The return value indicates if we offered a chance to reverse but the
1217 * user declined. This keeps the main patch processor in the loop since
1218 * we've taken this out of the normal flow of hunk processing to
1219 * simplify logic a little bit.
1221 return (reverse_seen);