home *** CD-ROM | disk | FTP | other *** search
/ rtsi.com / 2014.01.www.rtsi.com.tar / www.rtsi.com / OS9 / TOP / USR / SRC / upatch.t.Z / upatch.t / patch.c < prev    next >
C/C++ Source or Header  |  1988-08-24  |  19KB  |  836 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. int  init_output();
  106. int  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.  
  115. int  inos9, outos9,prjos9,patos9;
  116.  
  117. /* Apply a set of diffs as appropriate. */
  118.  
  119. main(argc,argv)
  120. int argc;
  121. char **argv;
  122. {
  123.     LINENUM where;
  124.     LINENUM newwhere;
  125.     LINENUM fuzz;
  126.     LINENUM mymaxfuzz;
  127.     int hunk = 0;
  128.     int failed = 0;
  129.     int failtotal = 0;
  130.     int i;
  131.  
  132.     setbuf(stderr, serrbuf);
  133.     for (i = 0; i<MAXFILEC; i++)
  134.     filearg[i] = Nullch;
  135.     Mktemp(TMPOUTNAME);
  136.     Mktemp(TMPINNAME);
  137.     Mktemp(TMPREJNAME);
  138.     Mktemp(TMPPATNAME);
  139.  
  140.     /* parse switches */
  141.     Argc = argc;
  142.     Argv = argv;
  143.     get_some_switches();
  144.     
  145. #if OSK
  146.     _siginit();
  147. #endif
  148.     /* make sure we clean up /tmp in case of disaster */
  149.     set_signals(0);
  150.  
  151.     for (
  152.     open_patch_file(filearg[1]);
  153.     there_is_another_patch();
  154.     reinitialize_almost_everything()
  155.     ) {                    /* for each patch in patch file */
  156.  
  157.     if (outname == Nullch)
  158.         outname = savestr(filearg[0]);
  159.     
  160.     /* initialize the patched file */
  161.     if (!skip_rest_of_patch)
  162.         outos9 = init_output(TMPOUTNAME);
  163.     
  164.     /* for ed script just up and do it and exit */
  165.     if (diff_type == ED_DIFF) {
  166.         do_ed_script();
  167.         continue;
  168.     }
  169.     
  170.     /* initialize reject file */
  171.     prjos9 = init_reject(TMPREJNAME);
  172.     
  173.     /* find out where all the lines are */
  174.     if (!skip_rest_of_patch)
  175.         scan_input(filearg[0]);
  176.     
  177.     /* from here on, open no standard i/o files, because malloc */
  178.     /* might misfire and we can't catch it easily */
  179.     
  180.     /* apply each hunk of patch */
  181.     hunk = 0;
  182.     failed = 0;
  183.     out_of_mem = FALSE;
  184.     while (another_hunk()) {
  185.         hunk++;
  186.         fuzz = Nulline;
  187.         mymaxfuzz = pch_context();
  188.         if (maxfuzz < mymaxfuzz)
  189.         mymaxfuzz = maxfuzz;
  190.         if (!skip_rest_of_patch) {
  191.         do {
  192.             where = locate_hunk(fuzz);
  193.             if (hunk == 1 && where == Nulline && !force) {
  194.                         /* dwim for reversed patch? */
  195.             if (!pch_swap()) {
  196.                 if (fuzz == Nulline)
  197.                 say1(
  198. "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
  199.                 continue;
  200.             }
  201.             reverse = !reverse;
  202.             where = locate_hunk(fuzz);  /* try again */
  203.             if (where == Nulline) {        /* didn't find it swapped */
  204.                 if (!pch_swap())         /* put it back to normal */
  205.                 fatal1("Lost hunk on alloc error!\n");
  206.                 reverse = !reverse;
  207.             }
  208.             else if (noreverse) {
  209.                 if (!pch_swap())         /* put it back to normal */
  210.                 fatal1("Lost hunk on alloc error!\n");
  211.                 reverse = !reverse;
  212.                 say1(
  213. "Ignoring previously applied (or reversed) patch.\n");
  214.                 skip_rest_of_patch = TRUE;
  215.             }
  216.             else {
  217.                 ask3(
  218. "%seversed (or previously applied) patch detected!  %s -R? [y] ",
  219.                 reverse ? "R" : "Unr",
  220.                 reverse ? "Assume" : "Ignore");
  221.                 if (*buf == 'n') {
  222.                 ask1("Apply anyway? [n] ");
  223.                 if (*buf != 'y')
  224.                     skip_rest_of_patch = TRUE;
  225.                 where = Nulline;
  226.                 reverse = !reverse;
  227.                 if (!pch_swap())  /* put it back to normal */
  228.                     fatal1("Lost hunk on alloc error!\n");
  229.                 }
  230.             }
  231.             }
  232.         } while (!skip_rest_of_patch && where == Nulline &&
  233.             ++fuzz <= mymaxfuzz);
  234.  
  235.         if (skip_rest_of_patch) {        /* just got decided */
  236.             Fclose(ofp);
  237.             ofp = Nullfp;
  238.         }
  239.         }
  240.  
  241.         newwhere = pch_newfirst() + last_offset;
  242.         if (skip_rest_of_patch) {
  243.         abort_hunk();
  244.         failed++;
  245.         if (verbose)
  246.             say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
  247.         }
  248.         else if (where == Nulline) {
  249.         abort_hunk();
  250.         failed++;
  251.         if (verbose)
  252.             say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
  253.         }
  254.         else {
  255.         apply_hunk(where);
  256.         if (verbose) {
  257.             say3("Hunk #%d succeeded at %ld", hunk, newwhere);
  258.             if (fuzz)
  259.             say2(" with fuzz %ld", fuzz);
  260.             if (last_offset)
  261.             say3(" (offset %ld line%s)",
  262.                 last_offset, last_offset==1L?"":"s");
  263.             say1(".\n");
  264.         }
  265.         }
  266.     }
  267.  
  268.     if (out_of_mem && using_plan_a) {
  269.         Argc = Argc_last;
  270.         Argv = Argv_last;
  271.         say1("\n\nRan out of memory using Plan A--trying again...\n\n");
  272.         continue;
  273.     }
  274.     
  275.     if(!hunk) exit(-1);    /* assert(hunk)    */
  276.     
  277.     /* finish spewing out the new file */
  278.     if (!skip_rest_of_patch)
  279.         spew_output();
  280.     
  281.     /* and put the output where desired */
  282.     ignore_signals();
  283.     if (!skip_rest_of_patch) {
  284.         if (move_file(TMPOUTNAME, outname) < 0) {
  285.         toutkeep = TRUE;
  286.         chmod(TMPOUTNAME, filemode);
  287.         }
  288.         else
  289.         chmod(outname, filemode);
  290.     }
  291.     Fclose(rejfp);
  292.     rejfp = Nullfp;
  293.     if (failed) {
  294.         failtotal += failed;
  295.         if (!*rejname) {
  296.         Strcpy(rejname, outname);
  297. #ifndef FLEXFILENAMES
  298.         {
  299.             char *rindex();
  300.             char *s = rindex(rejname,'/');
  301.  
  302.             if (!s)
  303.             s = rejname;
  304.             if (strlen(s) > 13)
  305.             if (s[12] == '.')    /* try to preserve difference */
  306.                 s[12] = s[13];    /* between .h, .c, .y, etc. */
  307.             s[13] = '\0';
  308.         }
  309. #endif
  310.         Strcat(rejname, REJEXT);
  311.         }
  312.         if (skip_rest_of_patch) {
  313.         say4("%d out of %d hunks ignored--saving rejects to %s\n",
  314.             failed, hunk, rejname);
  315.         }
  316.         else {
  317.         say4("%d out of %d hunks failed--saving rejects to %s\n",
  318.             failed, hunk, rejname);
  319.         }
  320.         if (move_file(TMPREJNAME, rejname) < 0)
  321.         trejkeep = TRUE;
  322.     }
  323.     set_signals(1);
  324.     }
  325.     my_exit(failtotal);
  326. }
  327.  
  328. /* Prepare to find the next patch to do in the patch file. */
  329.  
  330. void
  331. reinitialize_almost_everything()
  332. {
  333.     re_patch();
  334.     re_input();
  335.  
  336.     input_lines = 0;
  337.     last_frozen_line = 0;
  338.  
  339.     filec = 0;
  340.     if (filearg[0] != Nullch && !out_of_mem) {
  341.     free(filearg[0]);
  342.     filearg[0] = Nullch;
  343.     }
  344.  
  345.     if (outname != Nullch) {
  346.     free(outname);
  347.     outname = Nullch;
  348.     }
  349.  
  350.     last_offset = 0;
  351.  
  352.     diff_type = 0;
  353.  
  354.     if (revision != Nullch) {
  355.     free(revision);
  356.     revision = Nullch;
  357.     }
  358.  
  359.     reverse = FALSE;
  360.     skip_rest_of_patch = FALSE;
  361.  
  362.     get_some_switches();
  363.  
  364.     if (filec >= 2)
  365.     fatal1("You may not change to a different patch file.\n");
  366. }
  367.  
  368. /* Process switches and filenames up to next '+' or end of list. */
  369.  
  370. void
  371. get_some_switches()
  372. {
  373.     Reg1 char *s;
  374.  
  375.     rejname[0] = '\0';
  376.     Argc_last = Argc;
  377.     Argv_last = Argv;
  378.     if (!Argc)
  379.     return;
  380.     for (Argc--,Argv++; Argc; Argc--,Argv++) {
  381.     s = Argv[0];
  382.     if (strEQ(s, "+")) {
  383.         return;            /* + will be skipped by for loop */
  384.     }
  385.     if (*s != '-' || !s[1]) {
  386.         if (filec == MAXFILEC)
  387.         fatal1("Too many file arguments.\n");
  388.         filearg[filec++] = savestr(s);
  389.     }
  390.     else {
  391.         switch (*++s) {
  392.         case 'b':
  393.         origext = savestr(Argv[1]);
  394.         Argc--,Argv++;
  395.         break;
  396.         case 'B':
  397.         origprae = savestr(Argv[1]);
  398.         Argc--,Argv++;
  399.         break;
  400.         case 'c':
  401.         diff_type = CONTEXT_DIFF;
  402.         break;
  403.         case 'd':
  404.         if (!*++s) {
  405.             Argc--,Argv++;
  406.             s = Argv[0];
  407.         }
  408.         if (chdir(s) < 0)
  409.             fatal2("Can't cd to %s.\n", s);
  410.         break;
  411.         case 'D':
  412.             do_defines = TRUE;
  413.         if (!*++s) {
  414.             Argc--,Argv++;
  415.             s = Argv[0];
  416.         }
  417.         if (!isalpha(*s))
  418.             fatal1("Argument to -D not an identifier.\n");
  419.         Sprintf(if_defined, "#ifdef %s\n", s);
  420.         Sprintf(not_defined, "#ifndef %s\n", s);
  421.         Sprintf(end_defined, "#endif /* %s */\n", s);
  422.         break;
  423.         case 'e':
  424.         diff_type = ED_DIFF;
  425.         break;
  426.         case 'f':
  427.         force = TRUE;
  428.         break;
  429.         case 'F':
  430.         if (*++s == '=')
  431.             s++;
  432.         maxfuzz = atoi(s);
  433.         break;
  434.         case 'l':
  435.         canonicalize = TRUE;
  436.         break;
  437.         case 'n':
  438.         diff_type = NORMAL_DIFF;
  439.         break;
  440.         case 'N':
  441.         noreverse = TRUE;
  442.         break;
  443.         case 'o':
  444.         outname = savestr(Argv[1]);
  445.         Argc--,Argv++;
  446.         break;
  447.         case 'p':
  448.         if (*++s == '=')
  449.             s++;
  450.          strippath = atoi(s);
  451.         break;
  452.         case 'r':
  453.         Strcpy(rejname, Argv[1]);
  454.         Argc--,Argv++;
  455.         break;
  456.         case 'R':
  457.         reverse = TRUE;
  458.         break;
  459.         case 's':
  460.         verbose = FALSE;
  461.         break;
  462.         case 'S':
  463.         skip_rest_of_patch = TRUE;
  464.         break;
  465.         case 'v':
  466.         version();
  467.         break;
  468. #ifdef DEBUGGING
  469.         case 'x':
  470.         debug = atoi(s+1);
  471.         break;
  472. #endif
  473.         default:
  474.         fatal2("Unrecognized switch: %s\n", Argv[0]);
  475.         }
  476.     }
  477.     }
  478. }
  479.  
  480. /* Attempt to find the right place to apply this hunk of patch. */
  481.  
  482. LINENUM
  483. locate_hunk(fuzz)
  484. LINENUM fuzz;
  485. {
  486.     Reg1 LINENUM first_guess = pch_first() + last_offset;
  487.     Reg2 LINENUM offset;
  488.     LINENUM pat_lines = pch_ptrn_lines();
  489.     Reg3 LINENUM max_pos_offset = input_lines - first_guess
  490.                 - pat_lines + 1; 
  491.     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
  492.                 + pch_context();
  493.  
  494.     if (!pat_lines)            /* null range matches always */
  495.     return first_guess;
  496.     if (max_neg_offset >= first_guess)    /* do not try lines < 0 */
  497.     max_neg_offset = first_guess - 1;
  498.     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
  499.     return first_guess;
  500.     for (offset = 1; ; offset++) {
  501.     Reg5 bool check_after = (offset <= max_pos_offset);
  502.     Reg6 bool check_before = (offset <= max_neg_offset);
  503.  
  504.     if (check_after && patch_match(first_guess, offset, fuzz)) {
  505. #ifdef DEBUGGING
  506.         if (debug & 1)
  507.         say3("Offset changing from %ld to %ld\n", last_offset, offset);
  508. #endif
  509.         last_offset = offset;
  510.         return first_guess+offset;
  511.     }
  512.     else if (check_before && patch_match(first_guess, -offset, fuzz)) {
  513. #ifdef DEBUGGING
  514.         if (debug & 1)
  515.         say3("Offset changing from %ld to %ld\n", last_offset, -offset);
  516. #endif
  517.         last_offset = -offset;
  518.         return first_guess-offset;
  519.     }
  520.     else if (!check_before && !check_after)
  521.         return Nulline;
  522.     }
  523. }
  524.  
  525. /* We did not find the pattern, dump out the hunk so they can handle it. */
  526.  
  527. void
  528. abort_hunk()
  529. {
  530.     Reg1 LINENUM i;
  531.     Reg2 LINENUM pat_end = pch_end();
  532.     /* add in last_offset to guess the same as the previous successful hunk */
  533.     LINENUM oldfirst = pch_first() + last_offset;
  534.     LINENUM newfirst = pch_newfirst() + last_offset;
  535.     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
  536.     LINENUM newlast = newfirst + pch_repl_lines() - 1;
  537.     char *stars = (diff_type == NEW_CONTEXT_DIFF ? " ****" : "");
  538.     char *minuses = (diff_type == NEW_CONTEXT_DIFF ? " ----" : " -----");
  539.  
  540.     fprintf(rejfp, "***************\n");
  541.     for (i=0; i<=pat_end; i++) {
  542.     switch (pch_char(i)) {
  543.     case '*':
  544.         if (oldlast < oldfirst)
  545.         fprintf(rejfp, "*** 0%s\n", stars);
  546.         else if (oldlast == oldfirst)
  547.         fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
  548.         else
  549.         fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
  550.         break;
  551.     case '=':
  552.         if (newlast < newfirst)
  553.         fprintf(rejfp, "--- 0%s\n", minuses);
  554.         else if (newlast == newfirst)
  555.         fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
  556.         else
  557.         fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
  558.         break;
  559.     case '\n':
  560.         fprintf(rejfp, "%s", pfetch(i));
  561.         break;
  562.     case ' ': case '-': case '+': case '!':
  563.         fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
  564.         break;
  565.     default:
  566.         say1("Fatal internal error in abort_hunk().\n"); 
  567.         abort();
  568.     }
  569.     }
  570. }
  571.  
  572. /* We found where to apply it (we hope), so do it. */
  573.  
  574. void
  575. apply_hunk(where)
  576. LINENUM where;
  577. {
  578.     Reg1 LINENUM old = 1;
  579.     Reg2 LINENUM lastline = pch_ptrn_lines();
  580.     Reg3 LINENUM new = lastline+1;
  581. #define OUTSIDE 0
  582. #define IN_IFNDEF 1
  583. #define IN_IFDEF 2
  584. #define IN_ELSE 3
  585.     Reg4 int def_state = OUTSIDE;
  586.     Reg5 bool R_do_defines = do_defines;
  587.     Reg6 LINENUM pat_end = pch_end();
  588.  
  589.     where--;
  590.     while (pch_char(new) == '=' || pch_char(new) == '\n')
  591.     new++;
  592.     
  593.     while (old <= lastline) {
  594.     if (pch_char(old) == '-') {
  595.         copy_till(where + old - 1);
  596.         if (R_do_defines) {
  597.         if (def_state == OUTSIDE) {
  598.             fputs(not_defined, ofp);
  599.             def_state = IN_IFNDEF;
  600.         }
  601.         else if (def_state == IN_IFDEF) {
  602.             fputs(else_defined, ofp);
  603.             def_state = IN_ELSE;
  604.         }
  605.         fputs(pfetch(old), ofp);
  606.         }
  607.         last_frozen_line++;
  608.         old++;
  609.     }
  610.     else if (new > pat_end)
  611.         break;
  612.     else if (pch_char(new) == '+') {
  613.         copy_till(where + old - 1);
  614.         if (R_do_defines) {
  615.         if (def_state == IN_IFNDEF) {
  616.             fputs(else_defined, ofp);
  617.             def_state = IN_ELSE;
  618.         }
  619.         else if (def_state == OUTSIDE) {
  620.             fputs(if_defined, ofp);
  621.             def_state = IN_IFDEF;
  622.         }
  623.         }
  624.         fputs(pfetch(new), ofp);
  625.         new++;
  626.     }
  627.     else {
  628.         if (pch_char(new) != pch_char(old)) {
  629.         say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
  630.             pch_hunk_beg() + old,
  631.             pch_hunk_beg() + new);
  632. #ifdef DEBUGGING
  633.         say3("oldchar = '%c', newchar = '%c'\n",
  634.             pch_char(old), pch_char(new));
  635. #endif
  636.         my_exit(1);
  637.         }
  638.         if (pch_char(new) == '!') {
  639.         copy_till(where + old - 1);
  640.         if (R_do_defines) {
  641.            fputs(not_defined, ofp);
  642.            def_state = IN_IFNDEF;
  643.         }
  644.         while (pch_char(old) == '!') {
  645.             if (R_do_defines) {
  646.             fputs(pfetch(old), ofp);
  647.             }
  648.             last_frozen_line++;
  649.             old++;
  650.         }
  651.         if (R_do_defines) {
  652.             fputs(else_defined, ofp);
  653.             def_state = IN_ELSE;
  654.         }
  655.         while (pch_char(new) == '!') {
  656.             fputs(pfetch(new), ofp);
  657.             new++;
  658.         }
  659.         if (R_do_defines) {
  660.             fputs(end_defined, ofp);
  661.             def_state = OUTSIDE;
  662.         }
  663.         }
  664.         else {
  665.         if(!(pch_char(new) == ' ')) exit(-1); /* assert() */
  666.         old++;
  667.         new++;
  668.         }
  669.     }
  670.     }
  671.     if (new <= pat_end && pch_char(new) == '+') {
  672.     copy_till(where + old - 1);
  673.     if (R_do_defines) {
  674.         if (def_state == OUTSIDE) {
  675.             fputs(if_defined, ofp);
  676.         def_state = IN_IFDEF;
  677.         }
  678.         else if (def_state == IN_IFNDEF) {
  679.         fputs(else_defined, ofp);
  680.         def_state = IN_ELSE;
  681.         }
  682.     }
  683.     while (new <= pat_end && pch_char(new) == '+') {
  684.         fputs(pfetch(new), ofp);
  685.         new++;
  686.     }
  687.     }
  688.     if (R_do_defines && def_state != OUTSIDE) {
  689.     fputs(end_defined, ofp);
  690.     }
  691. }
  692.  
  693. /* Open the new file. */
  694.  
  695. int
  696. init_output(name)
  697. char *name;
  698. {
  699.     ofp = fopen(name, "w");
  700.     if (ofp == Nullfp)
  701.     fatal2("patch: can't create %s.\n", name);
  702.     return(fileno(ofp));
  703. }
  704.  
  705. /* Open a file to put hunks we can't locate. */
  706.  
  707. int
  708. init_reject(name)
  709. char *name;
  710. {
  711.     rejfp = fopen(name, "w");
  712.     if (rejfp == Nullfp)
  713.     fatal2("patch: can't create %s.\n", name);
  714.     return(fileno(rejfp));
  715. }
  716.  
  717. /* Copy input file to output, up to wherever hunk is to be applied. */
  718.  
  719. void
  720. copy_till(lastline)
  721. Reg1 LINENUM lastline;
  722. {
  723.     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
  724.  
  725.     if (R_last_frozen_line > lastline)
  726.     say1("patch: misordered hunks! output will be garbled.\n");
  727.     while (R_last_frozen_line < lastline) {
  728.     dump_line(++R_last_frozen_line);
  729.     }
  730.     last_frozen_line = R_last_frozen_line;
  731. }
  732.  
  733. /* Finish copying the input file to the output file. */
  734.  
  735. void
  736. spew_output()
  737. {
  738. #ifdef DEBUGGING
  739.     if (debug & 256)
  740.     say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
  741. #endif
  742.     if (input_lines)
  743.     copy_till(input_lines);        /* dump remainder of file */
  744.     Fclose(ofp);
  745.     ofp = Nullfp;
  746. }
  747.  
  748. /* Copy one line from input to output. */
  749.  
  750. void
  751. dump_line(line)
  752. LINENUM line;
  753. {
  754.     Reg1 char *s;
  755.     Reg2 char R_newline = '\n';
  756.  
  757.     /* Note: string is not null terminated. */
  758.     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
  759. }
  760.  
  761. /* Does the patch pattern match at line base+offset? */
  762.  
  763. bool
  764. patch_match(base, offset, fuzz)
  765. LINENUM base;
  766. LINENUM offset;
  767. LINENUM fuzz;
  768. {
  769.     Reg1 LINENUM pline = 1 + fuzz;
  770.     Reg2 LINENUM iline;
  771.     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
  772.  
  773.     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
  774.     if (canonicalize) {
  775.         if (!similar(ifetch(iline, (offset >= 0)),
  776.              pfetch(pline),
  777.              pch_line_len(pline) ))
  778.         return FALSE;
  779.     }
  780.     else if (strnNE(ifetch(iline, (offset >= 0)),
  781.            pfetch(pline),
  782.            pch_line_len(pline) ))
  783.         return FALSE;
  784.     }
  785.     return TRUE;
  786. }
  787.  
  788. /* Do two lines match with canonicalized white space? */
  789.  
  790. bool
  791. similar(a,b,len)
  792. Reg1 char *a;
  793. Reg2 char *b;
  794. Reg3 int len;
  795. {
  796.     while (len) {
  797.     if (isspace(*b)) {        /* whitespace (or \n) to match? */
  798.         if (!isspace(*a))        /* no corresponding whitespace? */
  799.         return FALSE;
  800.         while (len && isspace(*b) && *b != '\n')
  801.         b++,len--;        /* skip pattern whitespace */
  802.         while (isspace(*a) && *a != '\n')
  803.         a++;            /* skip target whitespace */
  804.         if (*a == '\n' || *b == '\n')
  805.         return (*a == *b);    /* should end in sync */
  806.     }
  807.     else if (*a++ != *b++)        /* match non-whitespace chars */
  808.         return FALSE;
  809.     else
  810.         len--;            /* probably not necessary */
  811.     }
  812.     return TRUE;            /* actually, this is not reached */
  813.                     /* since there is always a \n */
  814. }
  815.  
  816. /* Exit with cleanup. */
  817.  
  818. void
  819. my_exit(status)
  820. int status;
  821. {
  822.     close(inos9);
  823.     close(outos9);
  824.     close(prjos9);
  825.     close(patos9);
  826.     Unlink(TMPINNAME);
  827.     if (!toutkeep) {
  828.     Unlink(TMPOUTNAME);
  829.     }
  830.     if (!trejkeep) {
  831.     Unlink(TMPREJNAME);
  832.     }
  833.     Unlink(TMPPATNAME);
  834.     exit(status);
  835. }
  836.