home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / patch / patch.c < prev    next >
C/C++ Source or Header  |  1989-12-27  |  22KB  |  878 lines

  1. char rcsid[] =
  2.     "$Header: patch.c,v 2.0.1.6 88/06/22 20:46:39 lwall Locked $";
  3.  
  4. /* patch - a program to apply diffs to original files
  5.  *
  6.  * Copyright 1986, Larry Wall
  7.  *
  8.  * This program may be copied as long as you don't try to make any
  9.  * money off of it, or pretend that you wrote it.
  10.  *
  11.  * $Log:    patch.c,v $
  12.  * Revision 2.0.1.6  88/06/22  20:46:39  lwall
  13.  * patch12: rindex() wasn't declared
  14.  *
  15.  * Revision 2.0.1.5  88/06/03  15:09:37  lwall
  16.  * patch10: exit code improved.
  17.  * patch10: better support for non-flexfilenames.
  18.  *
  19.  * Revision 2.0.1.4  87/02/16  14:00:04  lwall
  20.  * Short replacement caused spurious "Out of sync" message.
  21.  *
  22.  * Revision 2.0.1.3  87/01/30  22:45:50  lwall
  23.  * Improved diagnostic on sync error.
  24.  * Moved do_ed_script() to pch.c.
  25.  *
  26.  * Revision 2.0.1.2  86/11/21  09:39:15  lwall
  27.  * Fuzz factor caused offset of installed lines.
  28.  *
  29.  * Revision 2.0.1.1  86/10/29  13:10:22  lwall
  30.  * Backwards search could terminate prematurely.
  31.  *
  32.  * Revision 2.0  86/09/17  15:37:32  lwall
  33.  * Baseline for netwide release.
  34.  *
  35.  * Revision 1.5  86/08/01  20:53:24  lwall
  36.  * Changed some %d's to %ld's.
  37.  * Linted.
  38.  *
  39.  * Revision 1.4  86/08/01  19:17:29  lwall
  40.  * Fixes for machines that can't vararg.
  41.  * Added fuzz factor.
  42.  * Generalized -p.
  43.  * General cleanup.
  44.  *
  45.  * 85/08/15 van%ucbmonet@berkeley
  46.  * Changes for 4.3bsd diff -c.
  47.  *
  48.  * Revision 1.3  85/03/26  15:07:43  lwall
  49.  * Frozen.
  50.  *
  51.  * Revision 1.2.1.9  85/03/12  17:03:35  lwall
  52.  * Changed pfp->_file to fileno(pfp).
  53.  *
  54.  * Revision 1.2.1.8  85/03/12  16:30:43  lwall
  55.  * Check i_ptr and i_womp to make sure they aren't null before freeing.
  56.  * Also allow ed output to be suppressed.
  57.  *
  58.  * Revision 1.2.1.7  85/03/12  15:56:13  lwall
  59.  * Added -p option from jromine@uci-750a.
  60.  *
  61.  * Revision 1.2.1.6  85/03/12  12:12:51  lwall
  62.  * Now checks for normalness of file to patch.
  63.  *
  64.  * Revision 1.2.1.5  85/03/12  11:52:12  lwall
  65.  * Added -D (#ifdef) option from joe@fluke.
  66.  *
  67.  * Revision 1.2.1.4  84/12/06  11:14:15  lwall
  68.  * Made smarter about SCCS subdirectories.
  69.  *
  70.  * Revision 1.2.1.3  84/12/05  11:18:43  lwall
  71.  * Added -l switch to do loose string comparison.
  72.  *
  73.  * Revision 1.2.1.2  84/12/04  09:47:13  lwall
  74.  * Failed hunk count not reset on multiple patch file.
  75.  *
  76.  * Revision 1.2.1.1  84/12/04  09:42:37  lwall
  77.  * Branch for sdcrdcf changes.
  78.  *
  79.  * Revision 1.2  84/11/29  13:29:51  lwall
  80.  * Linted.  Identifiers uniqified.  Fixed i_ptr malloc() bug.  Fixed
  81.  * multiple calls to mktemp().  Will now work on machines that can only
  82.  * read 32767 chars.  Added -R option for diffs with new and old swapped.
  83.  * Various cosmetic changes.
  84.  *
  85.  * Revision 1.1  84/11/09  17:03:58  lwall
  86.  * Initial revision
  87.  *
  88.  */
  89.  
  90. #include "INTERN.h"
  91. #include "common.h"
  92. #include "EXTERN.h"
  93. #include "version.h"
  94. #include "util.h"
  95. #include "pch.h"
  96. #include "inp.h"
  97.  
  98. /* procedures */
  99.  
  100. void reinitialize_almost_everything();
  101. void get_some_switches();
  102. LINENUM locate_hunk();
  103. void abort_hunk();
  104. void apply_hunk();
  105. void init_output();
  106. void init_reject();
  107. void copy_till();
  108. void spew_output();
  109. void dump_line();
  110. bool patch_match();
  111. bool similar();
  112. void re_input();
  113. void my_exit();
  114. char *strchr();
  115.  
  116. static char *myname;
  117.  
  118. /* Apply a set of diffs as appropriate. */
  119.  
  120. main(argc,argv)
  121. int argc;
  122. char **argv;
  123. {
  124.     LINENUM where;
  125.     LINENUM newwhere;
  126.     LINENUM fuzz;
  127.     LINENUM mymaxfuzz;
  128.     int hunk = 0;
  129.     int failed = 0;
  130.     int failtotal = 0;
  131.     int i;
  132.     char *s;
  133.  
  134. #ifdef MSDOS
  135.     stderr = fopen("con", "w");
  136. #endif
  137.     setbuf(stderr, serrbuf);
  138.  
  139.     for (i = 0; i<MAXFILEC; i++)
  140.     filearg[i] = Nullch;
  141.     Mktemp(TMPOUTNAME);
  142.     Mktemp(TMPINNAME);
  143.     Mktemp(TMPREJNAME);
  144.     Mktemp(TMPPATNAME);
  145.  
  146.     /* parse switches */
  147.     Argc = argc;
  148.     Argv = argv;
  149.     myname = argv[0];
  150.     get_some_switches();
  151.  
  152.     /* make sure we clean up /tmp in case of disaster */
  153.     set_signals(0);
  154.  
  155.     for (
  156.     open_patch_file(filearg[1]);
  157.     there_is_another_patch();
  158.     reinitialize_almost_everything()
  159.     ) {                    /* for each patch in patch file */
  160.  
  161.     if (outname == Nullch)
  162.         outname = savestr(filearg[0]);
  163.  
  164.     /* initialize the patched file */
  165.     if (!skip_rest_of_patch)
  166.         init_output(TMPOUTNAME);
  167.  
  168.     /* for ed script just up and do it and exit */
  169.     if (diff_type == ED_DIFF) {
  170.         do_ed_script();
  171.         continue;
  172.     }
  173.  
  174.     /* initialize reject file */
  175.     init_reject(TMPREJNAME);
  176.  
  177.     /* find out where all the lines are */
  178.     if (!skip_rest_of_patch)
  179.         scan_input(filearg[0]);
  180.  
  181.     /* from here on, open no standard i/o files, because malloc */
  182.     /* might misfire and we can't catch it easily */
  183.  
  184.     /* apply each hunk of patch */
  185.     hunk = 0;
  186.     failed = 0;
  187.     out_of_mem = FALSE;
  188.     while (another_hunk()) {
  189.         hunk++;
  190.         fuzz = Nulline;
  191.         mymaxfuzz = pch_context();
  192.         if (maxfuzz < mymaxfuzz)
  193.         mymaxfuzz = maxfuzz;
  194.         if (!skip_rest_of_patch) {
  195.         do {
  196.             where = locate_hunk(fuzz);
  197.             if (hunk == 1 && where == Nulline && !force) {
  198.                         /* dwim for reversed patch? */
  199.             if (!pch_swap()) {
  200.                 if (fuzz == Nulline)
  201.                 say1(
  202. "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
  203.                 continue;
  204.             }
  205.             reverse = !reverse;
  206.             where = locate_hunk(fuzz);  /* try again */
  207.             if (where == Nulline) {        /* didn't find it swapped */
  208.                 if (!pch_swap())         /* put it back to normal */
  209.                 fatal1("Lost hunk on alloc error!\n");
  210.                 reverse = !reverse;
  211.             }
  212.             else if (noreverse) {
  213.                 if (!pch_swap())         /* put it back to normal */
  214.                 fatal1("Lost hunk on alloc error!\n");
  215.                 reverse = !reverse;
  216.                 say1(
  217. "Ignoring previously applied (or reversed) patch.\n");
  218.                 skip_rest_of_patch = TRUE;
  219.             }
  220.             else {
  221.                 ask3(
  222. "%seversed (or previously applied) patch detected!  %s -R? [y] ",
  223.                 reverse ? "R" : "Unr",
  224.                 reverse ? "Assume" : "Ignore");
  225.                 if (*buf == 'n') {
  226.                 ask1("Apply anyway? [n] ");
  227.                 if (*buf != 'y')
  228.                     skip_rest_of_patch = TRUE;
  229.                 where = Nulline;
  230.                 reverse = !reverse;
  231.                 if (!pch_swap())  /* put it back to normal */
  232.                     fatal1("Lost hunk on alloc error!\n");
  233.                 }
  234.             }
  235.             }
  236.         } while (!skip_rest_of_patch && where == Nulline &&
  237.             ++fuzz <= mymaxfuzz);
  238.  
  239.         if (skip_rest_of_patch) {        /* just got decided */
  240.             Fclose(ofp);
  241.             ofp = Nullfp;
  242.         }
  243.         }
  244.  
  245.         newwhere = pch_newfirst() + last_offset;
  246.         if (skip_rest_of_patch) {
  247.         abort_hunk();
  248.         failed++;
  249.         if (verbose)
  250.             say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
  251.         }
  252.         else if (where == Nulline) {
  253.         abort_hunk();
  254.         failed++;
  255.         if (verbose)
  256.             say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
  257.         }
  258.         else {
  259.         apply_hunk(where);
  260.         if (verbose) {
  261.             say3("Hunk #%d succeeded at %ld", hunk, newwhere);
  262.             if (fuzz)
  263.             say2(" with fuzz %ld", fuzz);
  264.             if (last_offset)
  265.             say3(" (offset %ld line%s)",
  266.                 last_offset, last_offset==1L?"":"s");
  267.             say1(".\n");
  268.         }
  269.         }
  270.     }
  271.  
  272.     if (out_of_mem && using_plan_a) {
  273.         Argc = Argc_last;
  274.         Argv = Argv_last;
  275.         say1("\n\nRan out of memory using Plan A--trying again...\n\n");
  276.         continue;
  277.     }
  278.  
  279.     assert(hunk);
  280.  
  281.     /* finish spewing out the new file */
  282.     if (!skip_rest_of_patch)
  283.         spew_output();
  284.     
  285.     /* and put the output where desired */
  286.     ignore_signals();
  287.     if (!skip_rest_of_patch) {
  288.         if (move_file(TMPOUTNAME, outname) < 0) {
  289.         toutkeep = TRUE;
  290.         chmod(TMPOUTNAME, filemode);
  291.         }
  292.         else
  293.         chmod(outname, filemode);
  294.     }
  295.     Fclose(rejfp);
  296.     rejfp = Nullfp;
  297.     if (failed) {
  298.         failtotal += failed;
  299.         if (!*rejname) {
  300.         Strcpy(rejname, outname);
  301. #ifndef FLEXFILENAMES
  302.         {
  303.             char *rindex();
  304.             char *s = rindex(rejname,'/');
  305.  
  306.             if (!s)
  307.             s = rejname;
  308.             if (strlen(s) > 13)
  309.             if (s[12] == '.')    /* try to preserve difference */
  310.                 s[12] = s[13];    /* between .h, .c, .y, etc. */
  311.             s[13] = '\0';
  312.                 }
  313. #else
  314. #ifdef MSDOS
  315.                 if ((s=strchr(rejname,'.'))!=NULL)
  316.                   *s=0;
  317. #endif
  318. #endif
  319.         Strcat(rejname, REJEXT);
  320.         }
  321.         if (skip_rest_of_patch) {
  322.         say4("%d out of %d hunks ignored--saving rejects to %s\n",
  323.             failed, hunk, rejname);
  324.         }
  325.         else {
  326.         say4("%d out of %d hunks failed--saving rejects to %s\n",
  327.             failed, hunk, rejname);
  328.         }
  329.         if (move_file(TMPREJNAME, rejname) < 0)
  330.         trejkeep = TRUE;
  331.     }
  332.     set_signals(1);
  333.     }
  334.     my_exit(failtotal);
  335. }
  336.  
  337. /* Prepare to find the next patch to do in the patch file. */
  338.  
  339. void
  340. reinitialize_almost_everything()
  341. {
  342.     re_patch();
  343.     re_input();
  344.  
  345.     input_lines = 0;
  346.     last_frozen_line = 0;
  347.  
  348.     filec = 0;
  349.     if (filearg[0] != Nullch && !out_of_mem) {
  350.     free(filearg[0]);
  351.     filearg[0] = Nullch;
  352.     }
  353.  
  354.     if (outname != Nullch) {
  355.     free(outname);
  356.     outname = Nullch;
  357.     }
  358.  
  359.     last_offset = 0;
  360.  
  361.     diff_type = 0;
  362.  
  363.     if (revision != Nullch) {
  364.     free(revision);
  365.     revision = Nullch;
  366.     }
  367.  
  368.     reverse = FALSE;
  369.     skip_rest_of_patch = FALSE;
  370.  
  371.     get_some_switches();
  372.  
  373.     if (filec >= 2)
  374.     fatal1("You may not change to a different patch file.\n");
  375. }
  376.  
  377. /* Process switches and filenames up to next '+' or end of list. */
  378.  
  379. void
  380. get_some_switches()
  381. {
  382.     Reg1 char *s;
  383.  
  384.     rejname[0] = '\0';
  385.     Argc_last = Argc;
  386.     Argv_last = Argv;
  387.     if (!Argc)
  388.     return;
  389.     for (Argc--,Argv++; Argc; Argc--,Argv++) {
  390.     s = Argv[0];
  391.     if (strEQ(s, "+")) {
  392.         return;            /* + will be skipped by for loop */
  393.     }
  394.     if (*s != '-' || !s[1]) {
  395.         if (filec == MAXFILEC)
  396.         fatal1("Too many file arguments.\n");
  397.         filearg[filec++] = savestr(s);
  398.     }
  399.     else {
  400.         switch (*++s) {
  401.         case 'b':
  402.         origext = savestr(Argv[1]);
  403.         Argc--,Argv++;
  404.         break;
  405.         case 'B':
  406.         origprae = savestr(Argv[1]);
  407.         Argc--,Argv++;
  408.         break;
  409.         case 'c':
  410.         diff_type = CONTEXT_DIFF;
  411.         break;
  412.         case 'd':
  413.         if (!*++s) {
  414.             Argc--,Argv++;
  415.             s = Argv[0];
  416.         }
  417.         if (chdir(s) < 0)
  418.             fatal2("Can't cd to %s.\n", s);
  419.         break;
  420.         case 'D':
  421.             do_defines = TRUE;
  422.         if (!*++s) {
  423.             Argc--,Argv++;
  424.             s = Argv[0];
  425.         }
  426.         if (!isalpha(*s))
  427.             fatal1("Argument to -D not an identifier.\n");
  428.         Sprintf(if_defined, "#ifdef %s\n", s);
  429.         Sprintf(not_defined, "#ifndef %s\n", s);
  430.         Sprintf(end_defined, "#endif /* %s */\n", s);
  431.         break;
  432.         case 'e':
  433.         diff_type = ED_DIFF;
  434.         break;
  435.         case 'f':
  436.         force = TRUE;
  437.         break;
  438.         case 'F':
  439.         if (*++s == '=')
  440.             s++;
  441.         maxfuzz = atoi(s);
  442.         break;
  443.         case 'l':
  444.         canonicalize = TRUE;
  445.         break;
  446.         case 'n':
  447.         diff_type = NORMAL_DIFF;
  448.         break;
  449.         case 'N':
  450.         noreverse = TRUE;
  451.         break;
  452.         case 'o':
  453.         outname = savestr(Argv[1]);
  454.         Argc--,Argv++;
  455.         break;
  456.         case 'p':
  457.         if (*++s == '=')
  458.             s++;
  459.         strippath = atoi(s);
  460.         break;
  461.         case 'r':
  462.         Strcpy(rejname, Argv[1]);
  463.         Argc--,Argv++;
  464.         break;
  465.         case 'R':
  466.         reverse = TRUE;
  467.         break;
  468.         case 's':
  469.         verbose = FALSE;
  470.         break;
  471.         case 'S':
  472.         skip_rest_of_patch = TRUE;
  473.         break;
  474.         case 'v':
  475.         version();
  476.         break;
  477.             case 'h':
  478.                 Usage();
  479.                 exit(0);
  480.         break;
  481. #ifdef DEBUGGING
  482.         case 'x':
  483.         debug = atoi(s+1);
  484.         break;
  485. #endif
  486.         default:
  487.                 /*fatal2("Unrecognized switch: %s\n", Argv[0]);*/
  488.                 printf("\nUnrecognized switch: %s.\n", Argv[0]);
  489.                 Usage();
  490.                 exit(1);
  491.                 break;
  492.         }
  493.     }
  494.     }
  495. }
  496.  
  497.  
  498. Usage()
  499. {
  500.   printf("\nUsage: %s [options] orig patchfile [+ [options] orig]\n\n", myname);
  501.   printf("-b   next argument is the extension to be used in place of '.orig'\n");
  502.   printf("-c   forces patch to interpret the patch file as a context diff\n");
  503.   printf("-d   next argument is a directory, cd to it before doing anything else\n");
  504.   printf("-D   next argument is the symbol for '#ifdef...#endif' to mark changes\n");
  505.   printf("-e   forces patch to interpret the patch file as an ed script\n");
  506.   printf("-f   do not ask any questions\n");
  507.   printf("-l   more loosely whitespace matching\n");
  508.   printf("-n   forces patch to interpret the patch file as a normal diff\n");
  509.   printf("-N   ignore patches that are reversed or already applied, see -R\n");
  510.   printf("-o   next argument is the output file name\n");
  511.   printf("-r   next argument is the reject file name\n");
  512.   printf("-R   patch was created with the old and new files swapped\n");
  513.   printf("-s   makes patch do its work silently, unless an error occurs\n");
  514.   printf("-S   ignore this patch from the patch file\n");
  515.   printf("-v   print out revision header and patch level\n\n");
  516.   printf("-F<number>    maximum fuzz factor for context diffs (default 2)\n");
  517.   printf("-p<number>    sets the pathname strip count\n");
  518.   printf("-x<number>    set internal debugging flags\n");
  519. }
  520.  
  521.  
  522. /* Attempt to find the right place to apply this hunk of patch. */
  523.  
  524. LINENUM
  525. locate_hunk(fuzz)
  526. LINENUM fuzz;
  527. {
  528.     Reg1 LINENUM first_guess = pch_first() + last_offset;
  529.     Reg2 LINENUM offset;
  530.     LINENUM pat_lines = pch_ptrn_lines();
  531.     Reg3 LINENUM max_pos_offset = input_lines - first_guess
  532.                 - pat_lines + 1;
  533.     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
  534.                 + pch_context();
  535.  
  536.     if (!pat_lines)            /* null range matches always */
  537.     return first_guess;
  538.     if (max_neg_offset >= first_guess)    /* do not try lines < 0 */
  539.     max_neg_offset = first_guess - 1;
  540.     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
  541.     return first_guess;
  542.     for (offset = 1; ; offset++) {
  543.     Reg5 bool check_after = (offset <= max_pos_offset);
  544.     Reg6 bool check_before = (offset <= max_neg_offset);
  545.  
  546.     if (check_after && patch_match(first_guess, offset, fuzz)) {
  547. #ifdef DEBUGGING
  548.         if (debug & 1)
  549.         say3("Offset changing from %ld to %ld\n", last_offset, offset);
  550. #endif
  551.         last_offset = offset;
  552.         return first_guess+offset;
  553.     }
  554.     else if (check_before && patch_match(first_guess, -offset, fuzz)) {
  555. #ifdef DEBUGGING
  556.         if (debug & 1)
  557.         say3("Offset changing from %ld to %ld\n", last_offset, -offset);
  558. #endif
  559.         last_offset = -offset;
  560.         return first_guess-offset;
  561.     }
  562.     else if (!check_before && !check_after)
  563.         return Nulline;
  564.     }
  565. }
  566.  
  567. /* We did not find the pattern, dump out the hunk so they can handle it. */
  568.  
  569. void
  570. abort_hunk()
  571. {
  572.     Reg1 LINENUM i;
  573.     Reg2 LINENUM pat_end = pch_end();
  574.     /* add in last_offset to guess the same as the previous successful hunk */
  575.     LINENUM oldfirst = pch_first() + last_offset;
  576.     LINENUM newfirst = pch_newfirst() + last_offset;
  577.     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
  578.     LINENUM newlast = newfirst + pch_repl_lines() - 1;
  579.     char *stars = (diff_type == NEW_CONTEXT_DIFF ? " ****" : "");
  580.     char *minuses = (diff_type == NEW_CONTEXT_DIFF ? " ----" : " -----");
  581.  
  582.     fprintf(rejfp, "***************\n");
  583.     for (i=0; i<=pat_end; i++) {
  584.     switch (pch_char(i)) {
  585.     case '*':
  586.         if (oldlast < oldfirst)
  587.         fprintf(rejfp, "*** 0%s\n", stars);
  588.         else if (oldlast == oldfirst)
  589.         fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
  590.         else
  591.         fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
  592.         break;
  593.     case '=':
  594.         if (newlast < newfirst)
  595.         fprintf(rejfp, "--- 0%s\n", minuses);
  596.         else if (newlast == newfirst)
  597.         fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
  598.         else
  599.         fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
  600.         break;
  601.     case '\n':
  602.         fprintf(rejfp, "%s", pfetch(i));
  603.         break;
  604.     case ' ': case '-': case '+': case '!':
  605.         fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
  606.         break;
  607.     default:
  608.         say1("Fatal internal error in abort_hunk().\n");
  609.         abort();
  610.     }
  611.     }
  612. }
  613.  
  614. /* We found where to apply it (we hope), so do it. */
  615.  
  616. void
  617. apply_hunk(where)
  618. LINENUM where;
  619. {
  620.     Reg1 LINENUM old = 1;
  621.     Reg2 LINENUM lastline = pch_ptrn_lines();
  622.     Reg3 LINENUM new = lastline+1;
  623. #define OUTSIDE 0
  624. #define IN_IFNDEF 1
  625. #define IN_IFDEF 2
  626. #define IN_ELSE 3
  627.     Reg4 int def_state = OUTSIDE;
  628.     Reg5 bool R_do_defines = do_defines;
  629.     Reg6 LINENUM pat_end = pch_end();
  630.  
  631.     where--;
  632.     while (pch_char(new) == '=' || pch_char(new) == '\n')
  633.     new++;
  634.  
  635.     while (old <= lastline) {
  636.     if (pch_char(old) == '-') {
  637.         copy_till(where + old - 1);
  638.         if (R_do_defines) {
  639.         if (def_state == OUTSIDE) {
  640.             fputs(not_defined, ofp);
  641.             def_state = IN_IFNDEF;
  642.         }
  643.         else if (def_state == IN_IFDEF) {
  644.             fputs(else_defined, ofp);
  645.             def_state = IN_ELSE;
  646.         }
  647.         fputs(pfetch(old), ofp);
  648.         }
  649.         last_frozen_line++;
  650.         old++;
  651.     }
  652.     else if (new > pat_end)
  653.         break;
  654.     else if (pch_char(new) == '+') {
  655.         copy_till(where + old - 1);
  656.         if (R_do_defines) {
  657.         if (def_state == IN_IFNDEF) {
  658.             fputs(else_defined, ofp);
  659.             def_state = IN_ELSE;
  660.         }
  661.         else if (def_state == OUTSIDE) {
  662.             fputs(if_defined, ofp);
  663.             def_state = IN_IFDEF;
  664.         }
  665.         }
  666.         fputs(pfetch(new), ofp);
  667.         new++;
  668.     }
  669.     else {
  670.         if (pch_char(new) != pch_char(old)) {
  671.         say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
  672.             pch_hunk_beg() + old,
  673.             pch_hunk_beg() + new);
  674. #ifdef DEBUGGING
  675.         say3("oldchar = '%c', newchar = '%c'\n",
  676.             pch_char(old), pch_char(new));
  677. #endif
  678.         my_exit(1);
  679.         }
  680.         if (pch_char(new) == '!') {
  681.         copy_till(where + old - 1);
  682.         if (R_do_defines) {
  683.            fputs(not_defined, ofp);
  684.            def_state = IN_IFNDEF;
  685.         }
  686.         while (pch_char(old) == '!') {
  687.             if (R_do_defines) {
  688.             fputs(pfetch(old), ofp);
  689.             }
  690.             last_frozen_line++;
  691.             old++;
  692.         }
  693.         if (R_do_defines) {
  694.             fputs(else_defined, ofp);
  695.             def_state = IN_ELSE;
  696.         }
  697.         while (pch_char(new) == '!') {
  698.             fputs(pfetch(new), ofp);
  699.             new++;
  700.         }
  701.         if (R_do_defines) {
  702.             fputs(end_defined, ofp);
  703.             def_state = OUTSIDE;
  704.         }
  705.         }
  706.         else {
  707.         assert(pch_char(new) == ' ');
  708.         old++;
  709.         new++;
  710.         }
  711.     }
  712.     }
  713.     if (new <= pat_end && pch_char(new) == '+') {
  714.     copy_till(where + old - 1);
  715.     if (R_do_defines) {
  716.         if (def_state == OUTSIDE) {
  717.             fputs(if_defined, ofp);
  718.         def_state = IN_IFDEF;
  719.         }
  720.         else if (def_state == IN_IFNDEF) {
  721.         fputs(else_defined, ofp);
  722.         def_state = IN_ELSE;
  723.         }
  724.     }
  725.     while (new <= pat_end && pch_char(new) == '+') {
  726.         fputs(pfetch(new), ofp);
  727.         new++;
  728.     }
  729.     }
  730.     if (R_do_defines && def_state != OUTSIDE) {
  731.     fputs(end_defined, ofp);
  732.     }
  733. }
  734.  
  735. /* Open the new file. */
  736.  
  737. void
  738. init_output(name)
  739. char *name;
  740. {
  741.     ofp = fopen(name, "w");
  742.     if (ofp == Nullfp)
  743.     fatal2("patch: can't create %s.\n", name);
  744. }
  745.  
  746. /* Open a file to put hunks we can't locate. */
  747.  
  748. void
  749. init_reject(name)
  750. char *name;
  751. {
  752.     rejfp = fopen(name, "w");
  753.     if (rejfp == Nullfp)
  754.     fatal2("patch: can't create %s.\n", name);
  755. }
  756.  
  757. /* Copy input file to output, up to wherever hunk is to be applied. */
  758.  
  759. void
  760. copy_till(lastline)
  761. Reg1 LINENUM lastline;
  762. {
  763.     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
  764.  
  765.     if (R_last_frozen_line > lastline)
  766.     say1("patch: misordered hunks! output will be garbled.\n");
  767.     while (R_last_frozen_line < lastline) {
  768.     dump_line(++R_last_frozen_line);
  769.     }
  770.     last_frozen_line = R_last_frozen_line;
  771. }
  772.  
  773. /* Finish copying the input file to the output file. */
  774.  
  775. void
  776. spew_output()
  777. {
  778. #ifdef DEBUGGING
  779.     if (debug & 256)
  780.     say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
  781. #endif
  782.     if (input_lines)
  783.     copy_till(input_lines);        /* dump remainder of file */
  784.     Fclose(ofp);
  785.     ofp = Nullfp;
  786. }
  787.  
  788. /* Copy one line from input to output. */
  789.  
  790. void
  791. dump_line(line)
  792. LINENUM line;
  793. {
  794.     Reg1 char *s;
  795.     Reg2 char R_newline = '\n';
  796.  
  797.     /* Note: string is not null terminated. */
  798.     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
  799. }
  800.  
  801. /* Does the patch pattern match at line base+offset? */
  802.  
  803. bool
  804. patch_match(base, offset, fuzz)
  805. LINENUM base;
  806. LINENUM offset;
  807. LINENUM fuzz;
  808. {
  809.     Reg1 LINENUM pline = 1 + fuzz;
  810.     Reg2 LINENUM iline;
  811.     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
  812.  
  813.     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
  814.     if (canonicalize) {
  815.         if (!similar(ifetch(iline, (offset >= 0)),
  816.              pfetch(pline),
  817.              pch_line_len(pline) ))
  818.         return FALSE;
  819.     }
  820.     else if (strnNE(ifetch(iline, (offset >= 0)),
  821.            pfetch(pline),
  822.            pch_line_len(pline) ))
  823.         return FALSE;
  824.     }
  825.     return TRUE;
  826. }
  827.  
  828. /* Do two lines match with canonicalized white space? */
  829.  
  830. bool
  831. similar(a,b,len)
  832. Reg1 char *a;
  833. Reg2 char *b;
  834. Reg3 int len;
  835. {
  836.     while (len) {
  837.     if (isspace(*b)) {        /* whitespace (or \n) to match? */
  838.         if (!isspace(*a))        /* no corresponding whitespace? */
  839.         return FALSE;
  840.         while (len && isspace(*b) && *b != '\n')
  841.         b++,len--;        /* skip pattern whitespace */
  842.         while (isspace(*a) && *a != '\n')
  843.         a++;            /* skip target whitespace */
  844.         if (*a == '\n' || *b == '\n')
  845.         return (*a == *b);    /* should end in sync */
  846.     }
  847.     else if (*a++ != *b++)        /* match non-whitespace chars */
  848.         return FALSE;
  849.     else
  850.         len--;            /* probably not necessary */
  851.     }
  852.     return TRUE;            /* actually, this is not reached */
  853.                     /* since there is always a \n */
  854. }
  855.  
  856. /* Exit with cleanup. */
  857.  
  858. void
  859. my_exit(status)
  860. int status;
  861. {
  862.     Unlink(TMPINNAME);
  863.     if (!toutkeep) {
  864.     Unlink(TMPOUTNAME);
  865.     }
  866.     if (!trejkeep) {
  867.     Unlink(TMPREJNAME);
  868.     }
  869.  
  870.     if ( pfp != NULL )
  871.     {
  872.       Fclose(pfp);
  873.       Unlink(TMPPATNAME);
  874.     }
  875.  
  876.     exit(status);
  877. }
  878.