coverity appeasement
[minix.git] / commands / patch / patch.c
blobb5092d16b7552279a6599b7d75b65612bfda7518
1 /*
2 * $OpenBSD: patch.c,v 1.45 2007/04/18 21:52:24 sobrado Exp $
3 * $DragonFly: src/usr.bin/patch/patch.c,v 1.10 2008/08/10 23:39:56 joerg Exp $
4 * $NetBSD: patch.c,v 1.27 2008/09/19 18:33:34 joerg Exp $
5 */
7 /*
8 * patch - a program to apply diffs to original files
9 *
10 * Copyright 1986, Larry Wall
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following condition is met:
14 * 1. Redistributions of source code must retain the above copyright notice,
15 * this condition and the following disclaimer.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
29 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
30 * behaviour
33 #include <sys/cdefs.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
38 #include <ctype.h>
39 #include <getopt.h>
40 #include <limits.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <stdlib.h>
44 #include <unistd.h>
46 #include "common.h"
47 #include "util.h"
48 #include "pch.h"
49 #include "inp.h"
50 #include "backupfile.h"
51 #include "pathnames.h"
53 mode_t filemode = 0644;
55 char buf[MAXLINELEN]; /* general purpose buffer */
56 size_t buf_len = sizeof(buf);
58 bool using_plan_a = true; /* try to keep everything in memory */
59 bool out_of_mem = false; /* ran out of memory in plan a */
61 #define MAXFILEC 2
63 char *filearg[MAXFILEC];
64 bool ok_to_create_file = false;
65 char *outname = NULL;
66 char *origprae = NULL;
67 char *TMPOUTNAME;
68 char *TMPINNAME;
69 char *TMPREJNAME;
70 char *TMPPATNAME;
71 bool toutkeep = false;
72 bool trejkeep = false;
73 bool warn_on_invalid_line;
74 bool last_line_missing_eol;
76 #ifdef DEBUGGING
77 int debug = 0;
78 #endif
80 bool force = false;
81 bool batch = false;
82 bool verbose = true;
83 bool reverse = false;
84 bool noreverse = false;
85 bool skip_rest_of_patch = false;
86 int strippath = 957;
87 bool canonicalize = false;
88 bool check_only = false;
89 int diff_type = 0;
90 char *revision = NULL; /* prerequisite revision, if any */
91 LINENUM input_lines = 0; /* how long is input file in lines */
92 int posix = 0; /* strict POSIX mode? */
94 static void reinitialize_almost_everything(void);
95 static void get_some_switches(void);
96 static LINENUM locate_hunk(LINENUM);
97 static void abort_context_hunk(void);
98 static void rej_line(int, LINENUM);
99 static void abort_hunk(void);
100 static void apply_hunk(LINENUM);
101 static void init_output(const char *);
102 static void init_reject(const char *);
103 static void copy_till(LINENUM, bool);
104 static bool spew_output(void);
105 static void dump_line(LINENUM, bool);
106 static bool patch_match(LINENUM, LINENUM, LINENUM);
107 static bool similar(const char *, const char *, int);
108 static void usage(void);
110 /* true if -E was specified on command line. */
111 static bool remove_empty_files = false;
113 /* true if -R was specified on command line. */
114 static bool reverse_flag_specified = false;
116 /* buffer holding the name of the rejected patch file. */
117 static char rejname[NAME_MAX + 1];
119 /* buffer for stderr */
120 static char serrbuf[BUFSIZ];
122 /* how many input lines have been irretractibly output */
123 static LINENUM last_frozen_line = 0;
125 static int Argc; /* guess */
126 static char **Argv;
127 static int Argc_last; /* for restarting plan_b */
128 static char **Argv_last;
130 static FILE *ofp = NULL; /* output file pointer */
131 static FILE *rejfp = NULL; /* reject file pointer */
133 static int filec = 0; /* how many file arguments? */
134 static LINENUM last_offset = 0;
135 static LINENUM maxfuzz = 2;
137 /* patch using ifdef, ifndef, etc. */
138 static bool do_defines = false;
139 /* #ifdef xyzzy */
140 static char if_defined[128];
141 /* #ifndef xyzzy */
142 static char not_defined[128];
143 /* #else */
144 static const char else_defined[] = "#else\n";
145 /* #endif xyzzy */
146 static char end_defined[128];
149 /* Apply a set of diffs as appropriate. */
152 main(int argc, char *argv[])
154 int error = 0, hunk, failed, i, fd;
155 LINENUM where = 0, newwhere, fuzz, mymaxfuzz;
156 const char *tmpdir;
157 char *v;
158 int alloclen;
160 setbuf(stderr, serrbuf);
161 for (i = 0; i < MAXFILEC; i++)
162 filearg[i] = NULL;
165 /* Cons up the names of the temporary files. */
166 if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
167 tmpdir = _PATH_TMP;
168 for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--)
170 i++;
172 alloclen = i + 100;
173 #define TMPALLOC(var) if(!(var = malloc(alloclen))) { fatal(#var); exit(1); }
174 TMPALLOC(TMPOUTNAME);
175 TMPALLOC(TMPINNAME);
176 TMPALLOC(TMPREJNAME);
177 TMPALLOC(TMPPATNAME);
179 if (snprintf(TMPOUTNAME, alloclen, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1)
180 fatal("cannot allocate memory");
181 if ((fd = mkstemp(TMPOUTNAME)) < 0)
182 pfatal("can't create %s", TMPOUTNAME);
183 close(fd);
185 if (snprintf(TMPINNAME, alloclen, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1)
186 fatal("cannot allocate memory");
187 if ((fd = mkstemp(TMPINNAME)) < 0)
188 pfatal("can't create %s", TMPINNAME);
189 close(fd);
191 if (snprintf(TMPREJNAME, alloclen, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1)
192 fatal("cannot allocate memory");
193 if ((fd = mkstemp(TMPREJNAME)) < 0)
194 pfatal("can't create %s", TMPREJNAME);
195 close(fd);
197 if (snprintf(TMPPATNAME, alloclen, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1)
198 fatal("cannot allocate memory");
199 if ((fd = mkstemp(TMPPATNAME)) < 0)
200 pfatal("can't create %s", TMPPATNAME);
201 close(fd);
203 v = getenv("SIMPLE_BACKUP_SUFFIX");
204 if (v)
205 simple_backup_suffix = v;
206 else
207 simple_backup_suffix = ORIGEXT;
209 /* parse switches */
210 Argc = argc;
211 Argv = argv;
212 get_some_switches();
214 if (backup_type == none) {
215 if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
216 v = getenv("VERSION_CONTROL");
217 if (v != NULL || !posix)
218 backup_type = get_version(v); /* OK to pass NULL. */
221 /* make sure we clean up /tmp in case of disaster */
222 set_signals(0);
224 for (open_patch_file(filearg[1]); there_is_another_patch();
225 reinitialize_almost_everything()) {
226 /* for each patch in patch file */
228 warn_on_invalid_line = true;
230 if (outname == NULL)
231 outname = savestr(filearg[0]);
233 /* for ed script just up and do it and exit */
234 if (diff_type == ED_DIFF) {
235 do_ed_script();
236 continue;
238 /* initialize the patched file */
239 if (!skip_rest_of_patch)
240 init_output(TMPOUTNAME);
242 /* initialize reject file */
243 init_reject(TMPREJNAME);
245 /* find out where all the lines are */
246 if (!skip_rest_of_patch)
247 scan_input(filearg[0]);
249 /* from here on, open no standard i/o files, because malloc */
250 /* might misfire and we can't catch it easily */
252 /* apply each hunk of patch */
253 hunk = 0;
254 failed = 0;
255 out_of_mem = false;
256 while (another_hunk()) {
257 hunk++;
258 fuzz = 0;
259 mymaxfuzz = pch_context();
260 if (maxfuzz < mymaxfuzz)
261 mymaxfuzz = maxfuzz;
262 if (!skip_rest_of_patch) {
263 do {
264 where = locate_hunk(fuzz);
265 if (hunk == 1 && where == 0 && !force) {
266 /* dwim for reversed patch? */
267 if (!pch_swap()) {
268 if (fuzz == 0)
269 say("Not enough memory to try swapped hunk! Assuming unswapped.\n");
270 continue;
272 reverse = !reverse;
273 /* try again */
274 where = locate_hunk(fuzz);
275 if (where == 0) {
276 /* didn't find it swapped */
277 if (!pch_swap())
278 /* put it back to normal */
279 fatal("lost hunk on alloc error!\n");
280 reverse = !reverse;
281 } else if (noreverse) {
282 if (!pch_swap())
283 /* put it back to normal */
284 fatal("lost hunk on alloc error!\n");
285 reverse = !reverse;
286 say("Ignoring previously applied (or reversed) patch.\n");
287 skip_rest_of_patch = true;
288 } else if (batch) {
289 if (verbose)
290 say("%seversed (or previously applied) patch detected! %s -R.",
291 reverse ? "R" : "Unr",
292 reverse ? "Assuming" : "Ignoring");
293 } else {
294 ask("%seversed (or previously applied) patch detected! %s -R? [y] ",
295 reverse ? "R" : "Unr",
296 reverse ? "Assume" : "Ignore");
297 if (*buf == 'n') {
298 ask("Apply anyway? [n] ");
299 if (*buf != 'y')
300 skip_rest_of_patch = true;
301 where = 0;
302 reverse = !reverse;
303 if (!pch_swap())
304 /* put it back to normal */
305 fatal("lost hunk on alloc error!\n");
309 } while (!skip_rest_of_patch && where == 0 &&
310 ++fuzz <= mymaxfuzz);
312 if (skip_rest_of_patch) { /* just got decided */
313 if (ferror(ofp) || fclose(ofp)) {
314 say("Error writing %s\n",
315 TMPOUTNAME);
316 error = 1;
318 ofp = NULL;
321 newwhere = pch_newfirst() + last_offset;
322 if (skip_rest_of_patch) {
323 abort_hunk();
324 failed++;
325 if (verbose)
326 say("Hunk #%d ignored at %ld.\n",
327 hunk, newwhere);
328 } else if (where == 0) {
329 abort_hunk();
330 failed++;
331 if (verbose)
332 say("Hunk #%d failed at %ld.\n",
333 hunk, newwhere);
334 } else {
335 apply_hunk(where);
336 if (verbose) {
337 say("Hunk #%d succeeded at %ld",
338 hunk, newwhere);
339 if (fuzz != 0)
340 say(" with fuzz %ld", fuzz);
341 if (last_offset)
342 say(" (offset %ld line%s)",
343 last_offset,
344 last_offset == 1L ? "" : "s");
345 say(".\n");
350 if (out_of_mem && using_plan_a) {
351 Argc = Argc_last;
352 Argv = Argv_last;
353 say("\n\nRan out of memory using Plan A--trying again...\n\n");
354 if (ofp)
355 fclose(ofp);
356 ofp = NULL;
357 if (rejfp)
358 fclose(rejfp);
359 rejfp = NULL;
360 continue;
362 if (hunk == 0)
363 fatal("Internal error: hunk should not be 0\n");
365 /* finish spewing out the new file */
366 if (!skip_rest_of_patch && !spew_output()) {
367 say("Can't write %s\n", TMPOUTNAME);
368 error = 1;
371 /* and put the output where desired */
372 ignore_signals();
373 if (!skip_rest_of_patch) {
374 struct stat statbuf;
375 char *realout = outname;
377 if (!check_only) {
378 if (move_file(TMPOUTNAME, outname) < 0) {
379 toutkeep = true;
380 realout = TMPOUTNAME;
381 chmod(TMPOUTNAME, filemode);
382 } else
383 chmod(outname, filemode);
385 if (remove_empty_files &&
386 stat(realout, &statbuf) == 0 &&
387 statbuf.st_size == 0) {
388 if (verbose)
389 say("Removing %s (empty after patching).\n",
390 realout);
391 unlink(realout);
395 if (ferror(rejfp) || fclose(rejfp)) {
396 say("Error writing %s\n", rejname);
397 error = 1;
399 rejfp = NULL;
400 if (failed) {
401 error = 1;
402 if (*rejname == '\0') {
403 if (strlcpy(rejname, outname,
404 sizeof(rejname)) >= sizeof(rejname))
405 fatal("filename %s is too long\n", outname);
406 if (strlcat(rejname, REJEXT,
407 sizeof(rejname)) >= sizeof(rejname))
408 fatal("filename %s is too long\n", outname);
410 if (skip_rest_of_patch) {
411 say("%d out of %d hunks ignored--saving rejects to %s\n",
412 failed, hunk, rejname);
413 } else {
414 say("%d out of %d hunks failed--saving rejects to %s\n",
415 failed, hunk, rejname);
417 if (!check_only && move_file(TMPREJNAME, rejname) < 0)
418 trejkeep = true;
420 set_signals(1);
422 my_exit(error);
423 /* NOTREACHED */
426 /* Prepare to find the next patch to do in the patch file. */
428 static void
429 reinitialize_almost_everything(void)
431 re_patch();
432 re_input();
434 input_lines = 0;
435 last_frozen_line = 0;
437 filec = 0;
438 if (!out_of_mem) {
439 free(filearg[0]);
440 filearg[0] = NULL;
443 free(outname);
444 outname = NULL;
446 last_offset = 0;
447 diff_type = 0;
449 free(revision);
450 revision = NULL;
452 reverse = reverse_flag_specified;
453 skip_rest_of_patch = false;
455 get_some_switches();
458 /* Process switches and filenames. */
460 static void
461 get_some_switches(void)
463 const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
464 static struct option longopts[] = {
465 {"backup", no_argument, 0, 'b'},
466 {"batch", no_argument, 0, 't'},
467 {"check", no_argument, 0, 'C'},
468 {"context", no_argument, 0, 'c'},
469 {"debug", required_argument, 0, 'x'},
470 {"directory", required_argument, 0, 'd'},
471 {"ed", no_argument, 0, 'e'},
472 {"force", no_argument, 0, 'f'},
473 {"forward", no_argument, 0, 'N'},
474 {"fuzz", required_argument, 0, 'F'},
475 {"ifdef", required_argument, 0, 'D'},
476 {"input", required_argument, 0, 'i'},
477 {"ignore-whitespace", no_argument, 0, 'l'},
478 {"normal", no_argument, 0, 'n'},
479 {"output", required_argument, 0, 'o'},
480 {"prefix", required_argument, 0, 'B'},
481 {"quiet", no_argument, 0, 's'},
482 {"reject-file", required_argument, 0, 'r'},
483 {"remove-empty-files", no_argument, 0, 'E'},
484 {"reverse", no_argument, 0, 'R'},
485 {"silent", no_argument, 0, 's'},
486 {"strip", required_argument, 0, 'p'},
487 {"suffix", required_argument, 0, 'z'},
488 {"unified", no_argument, 0, 'u'},
489 {"version", no_argument, 0, 'v'},
490 {"version-control", required_argument, 0, 'V'},
491 {"posix", no_argument, &posix, 1},
492 {NULL, 0, 0, 0}
494 int ch;
496 rejname[0] = '\0';
497 Argc_last = Argc;
498 Argv_last = Argv;
499 if (!Argc)
500 return;
501 optreset = optind = 1;
502 while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
503 switch (ch) {
504 case 'b':
505 if (backup_type == none)
506 backup_type = numbered_existing;
507 if (optarg == NULL)
508 break;
509 if (verbose)
510 say("Warning, the ``-b suffix'' option has been"
511 " obsoleted by the -z option.\n");
512 /* FALLTHROUGH */
513 case 'z':
514 /* must directly follow 'b' case for backwards compat */
515 simple_backup_suffix = savestr(optarg);
516 break;
517 case 'B':
518 origprae = savestr(optarg);
519 break;
520 case 'c':
521 diff_type = CONTEXT_DIFF;
522 break;
523 case 'C':
524 check_only = true;
525 break;
526 case 'd':
527 if (chdir(optarg) < 0)
528 pfatal("can't cd to %s", optarg);
529 break;
530 case 'D':
531 do_defines = true;
532 if (!isalpha((unsigned char)*optarg) && *optarg != '_')
533 fatal("argument to -D is not an identifier\n");
534 snprintf(if_defined, sizeof if_defined,
535 "#ifdef %s\n", optarg);
536 snprintf(not_defined, sizeof not_defined,
537 "#ifndef %s\n", optarg);
538 snprintf(end_defined, sizeof end_defined,
539 "#endif /* %s */\n", optarg);
540 break;
541 case 'e':
542 diff_type = ED_DIFF;
543 break;
544 case 'E':
545 remove_empty_files = true;
546 break;
547 case 'f':
548 force = true;
549 break;
550 case 'F':
551 maxfuzz = atoi(optarg);
552 break;
553 case 'i':
554 if (++filec == MAXFILEC)
555 fatal("too many file arguments\n");
556 filearg[filec] = savestr(optarg);
557 break;
558 case 'l':
559 canonicalize = true;
560 break;
561 case 'n':
562 diff_type = NORMAL_DIFF;
563 break;
564 case 'N':
565 noreverse = true;
566 break;
567 case 'o':
568 outname = savestr(optarg);
569 break;
570 case 'p':
571 strippath = atoi(optarg);
572 break;
573 case 'r':
574 if (strlcpy(rejname, optarg,
575 sizeof(rejname)) >= sizeof(rejname))
576 fatal("argument for -r is too long\n");
577 break;
578 case 'R':
579 reverse = true;
580 reverse_flag_specified = true;
581 break;
582 case 's':
583 verbose = false;
584 break;
585 case 't':
586 batch = true;
587 break;
588 case 'u':
589 diff_type = UNI_DIFF;
590 break;
591 case 'v':
592 version();
593 break;
594 case 'V':
595 backup_type = get_version(optarg);
596 break;
597 #ifdef DEBUGGING
598 case 'x':
599 debug = atoi(optarg);
600 break;
601 #endif
602 default:
603 if (ch != '\0')
604 usage();
605 break;
608 Argc -= optind;
609 Argv += optind;
611 if (Argc > 0) {
612 filearg[0] = savestr(*Argv++);
613 Argc--;
614 while (Argc > 0) {
615 if (++filec == MAXFILEC)
616 fatal("too many file arguments\n");
617 filearg[filec] = savestr(*Argv++);
618 Argc--;
622 if (getenv("POSIXLY_CORRECT") != NULL)
623 posix = 1;
626 static void
627 usage(void)
629 fprintf(stderr,
630 "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
631 " [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
632 " [-r rej-name] [-V t | nil | never] [-x number] [-z backup-ext]\n"
633 " [--posix] [origfile [patchfile]]\n"
634 " patch <patchfile\n");
635 my_exit(EXIT_SUCCESS);
639 * Attempt to find the right place to apply this hunk of patch.
641 static LINENUM
642 locate_hunk(LINENUM fuzz)
644 LINENUM first_guess = pch_first() + last_offset;
645 LINENUM offset;
646 LINENUM pat_lines = pch_ptrn_lines();
647 LINENUM max_pos_offset = input_lines - first_guess - pat_lines + 1;
648 LINENUM max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
650 if (pat_lines == 0) { /* null range matches always */
651 if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
652 || diff_type == NEW_CONTEXT_DIFF
653 || diff_type == UNI_DIFF)) {
654 say("Empty context always matches.\n");
656 return (first_guess);
658 if (max_neg_offset >= first_guess) /* do not try lines < 0 */
659 max_neg_offset = first_guess - 1;
660 if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
661 return first_guess;
662 for (offset = 1; ; offset++) {
663 bool check_after = (offset <= max_pos_offset);
664 bool check_before = (offset <= max_neg_offset);
666 if (check_after && patch_match(first_guess, offset, fuzz)) {
667 #ifdef DEBUGGING
668 if (debug & 1)
669 say("Offset changing from %ld to %ld\n",
670 last_offset, offset);
671 #endif
672 last_offset = offset;
673 return first_guess + offset;
674 } else if (check_before && patch_match(first_guess, -offset, fuzz)) {
675 #ifdef DEBUGGING
676 if (debug & 1)
677 say("Offset changing from %ld to %ld\n",
678 last_offset, -offset);
679 #endif
680 last_offset = -offset;
681 return first_guess - offset;
682 } else if (!check_before && !check_after)
683 return 0;
687 /* We did not find the pattern, dump out the hunk so they can handle it. */
689 static void
690 abort_context_hunk(void)
692 LINENUM i;
693 const LINENUM pat_end = pch_end();
695 * add in last_offset to guess the same as the previous successful
696 * hunk
698 const LINENUM oldfirst = pch_first() + last_offset;
699 const LINENUM newfirst = pch_newfirst() + last_offset;
700 const LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
701 const LINENUM newlast = newfirst + pch_repl_lines() - 1;
702 const char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
703 const char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
705 fprintf(rejfp, "***************\n");
706 for (i = 0; i <= pat_end; i++) {
707 switch (pch_char(i)) {
708 case '*':
709 if (oldlast < oldfirst)
710 fprintf(rejfp, "*** 0%s\n", stars);
711 else if (oldlast == oldfirst)
712 fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
713 else
714 fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
715 oldlast, stars);
716 break;
717 case '=':
718 if (newlast < newfirst)
719 fprintf(rejfp, "--- 0%s\n", minuses);
720 else if (newlast == newfirst)
721 fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
722 else
723 fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
724 newlast, minuses);
725 break;
726 case '\n':
727 fprintf(rejfp, "%s", pfetch(i));
728 break;
729 case ' ':
730 case '-':
731 case '+':
732 case '!':
733 fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
734 break;
735 default:
736 fatal("fatal internal error in abort_context_hunk\n");
741 static void
742 rej_line(int ch, LINENUM i)
744 size_t len;
745 const char *line = pfetch(i);
747 len = strlen(line);
749 fprintf(rejfp, "%c%s", ch, line);
750 if (len == 0 || line[len-1] != '\n')
751 fprintf(rejfp, "\n\\ No newline at end of file\n");
754 static void
755 abort_hunk(void)
757 LINENUM i, j, split;
758 int ch1, ch2;
759 const LINENUM pat_end = pch_end();
760 const LINENUM oldfirst = pch_first() + last_offset;
761 const LINENUM newfirst = pch_newfirst() + last_offset;
763 if (diff_type != UNI_DIFF) {
764 abort_context_hunk();
765 return;
767 split = -1;
768 for (i = 0; i <= pat_end; i++) {
769 if (pch_char(i) == '=') {
770 split = i;
771 break;
774 if (split == -1) {
775 fprintf(rejfp, "malformed hunk: no split found\n");
776 return;
778 i = 0;
779 j = split + 1;
780 fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
781 pch_ptrn_lines() ? oldfirst : 0,
782 pch_ptrn_lines(), newfirst, pch_repl_lines());
783 while (i < split || j <= pat_end) {
784 ch1 = i < split ? pch_char(i) : -1;
785 ch2 = j <= pat_end ? pch_char(j) : -1;
786 if (ch1 == '-') {
787 rej_line('-', i);
788 i++;
789 } else if (ch1 == ' ' && ch2 == ' ') {
790 rej_line(' ', i);
791 i++;
792 j++;
793 } else if (ch1 == '!' && ch2 == '!') {
794 while (i < split && ch1 == '!') {
795 rej_line('-', i);
796 i++;
797 ch1 = i < split ? pch_char(i) : -1;
799 while (j <= pat_end && ch2 == '!') {
800 rej_line('+', j);
801 j++;
802 ch2 = j <= pat_end ? pch_char(j) : -1;
804 } else if (ch1 == '*') {
805 i++;
806 } else if (ch2 == '+' || ch2 == ' ') {
807 rej_line(ch2, j);
808 j++;
809 } else {
810 fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
811 i, split, j);
812 rej_line(ch1, i);
813 rej_line(ch2, j);
814 return;
819 /* We found where to apply it (we hope), so do it. */
821 static void
822 apply_hunk(LINENUM where)
824 LINENUM old = 1;
825 const LINENUM lastline = pch_ptrn_lines();
826 LINENUM new = lastline + 1;
827 #define OUTSIDE 0
828 #define IN_IFNDEF 1
829 #define IN_IFDEF 2
830 #define IN_ELSE 3
831 int def_state = OUTSIDE;
832 const LINENUM pat_end = pch_end();
834 where--;
835 while (pch_char(new) == '=' || pch_char(new) == '\n')
836 new++;
838 while (old <= lastline) {
839 if (pch_char(old) == '-') {
840 copy_till(where + old - 1, false);
841 if (do_defines) {
842 if (def_state == OUTSIDE) {
843 fputs(not_defined, ofp);
844 def_state = IN_IFNDEF;
845 } else if (def_state == IN_IFDEF) {
846 fputs(else_defined, ofp);
847 def_state = IN_ELSE;
849 fputs(pfetch(old), ofp);
851 last_frozen_line++;
852 old++;
853 } else if (new > pat_end) {
854 break;
855 } else if (pch_char(new) == '+') {
856 copy_till(where + old - 1, false);
857 if (do_defines) {
858 if (def_state == IN_IFNDEF) {
859 fputs(else_defined, ofp);
860 def_state = IN_ELSE;
861 } else if (def_state == OUTSIDE) {
862 fputs(if_defined, ofp);
863 def_state = IN_IFDEF;
866 fputs(pfetch(new), ofp);
867 new++;
868 } else if (pch_char(new) != pch_char(old)) {
869 say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
870 pch_hunk_beg() + old,
871 pch_hunk_beg() + new);
872 #ifdef DEBUGGING
873 say("oldchar = '%c', newchar = '%c'\n",
874 pch_char(old), pch_char(new));
875 #endif
876 my_exit(2);
877 } else if (pch_char(new) == '!') {
878 copy_till(where + old - 1, false);
879 if (do_defines) {
880 fputs(not_defined, ofp);
881 def_state = IN_IFNDEF;
883 while (pch_char(old) == '!') {
884 if (do_defines) {
885 fputs(pfetch(old), ofp);
887 last_frozen_line++;
888 old++;
890 if (do_defines) {
891 fputs(else_defined, ofp);
892 def_state = IN_ELSE;
894 while (pch_char(new) == '!') {
895 fputs(pfetch(new), ofp);
896 new++;
898 } else {
899 if (pch_char(new) != ' ')
900 fatal("Internal error: expected ' '\n");
901 old++;
902 new++;
903 if (do_defines && def_state != OUTSIDE) {
904 fputs(end_defined, ofp);
905 def_state = OUTSIDE;
909 if (new <= pat_end && pch_char(new) == '+') {
910 copy_till(where + old - 1, false);
911 if (do_defines) {
912 if (def_state == OUTSIDE) {
913 fputs(if_defined, ofp);
914 def_state = IN_IFDEF;
915 } else if (def_state == IN_IFNDEF) {
916 fputs(else_defined, ofp);
917 def_state = IN_ELSE;
920 while (new <= pat_end && pch_char(new) == '+') {
921 fputs(pfetch(new), ofp);
922 new++;
925 if (do_defines && def_state != OUTSIDE) {
926 fputs(end_defined, ofp);
931 * Open the new file.
933 static void
934 init_output(const char *name)
936 ofp = fopen(name, "w");
937 if (ofp == NULL)
938 pfatal("can't create %s", name);
942 * Open a file to put hunks we can't locate.
944 static void
945 init_reject(const char *name)
947 rejfp = fopen(name, "w");
948 if (rejfp == NULL)
949 pfatal("can't create %s", name);
953 * Copy input file to output, up to wherever hunk is to be applied.
954 * If endoffile is true, treat the last line specially since it may
955 * lack a newline.
957 static void
958 copy_till(LINENUM lastline, bool endoffile)
960 if (last_frozen_line > lastline)
961 fatal("misordered hunks! output would be garbled\n");
962 while (last_frozen_line < lastline) {
963 if (++last_frozen_line == lastline && endoffile)
964 dump_line(last_frozen_line, !last_line_missing_eol);
965 else
966 dump_line(last_frozen_line, true);
971 * Finish copying the input file to the output file.
973 static bool
974 spew_output(void)
976 int rv;
978 #ifdef DEBUGGING
979 if (debug & 256)
980 say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
981 #endif
982 if (input_lines)
983 copy_till(input_lines, true); /* dump remainder of file */
984 rv = ferror(ofp) == 0 && fclose(ofp) == 0;
985 ofp = NULL;
986 return rv;
990 * Copy one line from input to output.
992 static void
993 dump_line(LINENUM line, bool write_newline)
995 char *s;
997 s = ifetch(line, 0);
998 if (s == NULL)
999 return;
1000 /* Note: string is not NUL terminated. */
1001 for (; *s != '\n'; s++)
1002 putc(*s, ofp);
1003 if (write_newline)
1004 putc('\n', ofp);
1008 * Does the patch pattern match at line base+offset?
1010 static bool
1011 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
1013 LINENUM pline = 1 + fuzz;
1014 LINENUM iline;
1015 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
1016 const char *ilineptr;
1017 const char *plineptr;
1018 short plinelen;
1020 for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
1021 ilineptr = ifetch(iline, offset >= 0);
1022 if (ilineptr == NULL)
1023 return false;
1024 plineptr = pfetch(pline);
1025 plinelen = pch_line_len(pline);
1026 if (canonicalize) {
1027 if (!similar(ilineptr, plineptr, plinelen))
1028 return false;
1029 } else if (strnNE(ilineptr, plineptr, plinelen))
1030 return false;
1031 if (iline == input_lines) {
1033 * We are looking at the last line of the file.
1034 * If the file has no eol, the patch line should
1035 * not have one either and vice-versa. Note that
1036 * plinelen > 0.
1038 if (last_line_missing_eol) {
1039 if (plineptr[plinelen - 1] == '\n')
1040 return false;
1041 } else {
1042 if (plineptr[plinelen - 1] != '\n')
1043 return false;
1047 return true;
1051 * Do two lines match with canonicalized white space?
1053 static bool
1054 similar(const char *a, const char *b, int len)
1056 while (len) {
1057 if (isspace((unsigned char)*b)) { /* whitespace (or \n) to match? */
1058 if (!isspace((unsigned char)*a)) /* no corresponding whitespace? */
1059 return false;
1060 while (len && isspace((unsigned char)*b) && *b != '\n')
1061 b++, len--; /* skip pattern whitespace */
1062 while (isspace((unsigned char)*a) && *a != '\n')
1063 a++; /* skip target whitespace */
1064 if (*a == '\n' || *b == '\n')
1065 return (*a == *b); /* should end in sync */
1066 } else if (*a++ != *b++) /* match non-whitespace chars */
1067 return false;
1068 else
1069 len--; /* probably not necessary */
1071 return true; /* actually, this is not reached */
1072 /* since there is always a \n */