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