home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / c / library / os2 / rcs / rcs56src / source / patch / patch.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-12-24  |  23.8 KB  |  979 lines

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