Larry Wall's patch v2.0-11 (3 of 3)

egray at fthood.UUCP egray at fthood.UUCP
Wed Jun 8 02:45:00 AEST 1988


This is part 3 of 3 to Larry Wall's patch v2.0-11

Emmet P. Gray				US Army, HQ III Corps & Fort Hood
...!ihnp4!uiucuxc!fthood!egray		Attn: AFZF-DE-ENV
					Directorate of Engineering & Housing
					Environmental Management Office
					Fort Hood, TX 76544-5057

------------------------------------------------------------------------------
#! /bin/sh
# This is a shell archive, meaning:
# 1. Remove everything above the #! /bin/sh line.
# 2. Save the resulting text in a file.
# 3. Execute the file with /bin/sh (not csh) to create:
#	patch.man
#	patchlevel.h
#	pch.c
#	pch.h
#	util.c
# This archive created: Tue Jun  7 11:32:47 1988
export PATH; PATH=/bin:/usr/bin:$PATH
echo shar: "extracting 'patch.man'" '(14363 characters)'
if test -f 'patch.man'
then
	echo shar: "will not over-write existing file 'patch.man'"
else
sed 's/^X//' << \SHAR_EOF > 'patch.man'
X.rn '' }`
X''' $Header: patch.man,v 2.0.1.1 88/06/03 15:12:51 lwall Locked $
X''' 
X''' $Log:	patch.man,v $
X''' Revision 2.0.1.1  88/06/03  15:12:51  lwall
X''' patch10: -B switch was contributed.
X''' 
X''' Revision 2.0  86/09/17  15:39:09  lwall
X''' Baseline for netwide release.
X''' 
X''' Revision 1.4  86/08/01  19:23:22  lwall
X''' Documented -v, -p, -F.
X''' Added notes to patch senders.
X''' 
X''' Revision 1.3  85/03/26  15:11:06  lwall
X''' Frozen.
X''' 
X''' Revision 1.2.1.4  85/03/12  16:14:27  lwall
X''' Documented -p.
X''' 
X''' Revision 1.2.1.3  85/03/12  16:09:41  lwall
X''' Documented -D.
X''' 
X''' Revision 1.2.1.2  84/12/05  11:06:55  lwall
X''' Added -l switch, and noted bistability bug.
X''' 
X''' Revision 1.2.1.1  84/12/04  17:23:39  lwall
X''' Branch for sdcrdcf changes.
X''' 
X''' Revision 1.2  84/12/04  17:22:02  lwall
X''' Baseline version.
X''' 
X.de Sh
X.br
X.ne 5
X.PP
X\fB\\$1\fR
X.PP
X..
X.de Sp
X.if t .sp .5v
X.if n .sp
X..
X'''
X'''     Set up \*(-- to give an unbreakable dash;
X'''     string Tr holds user defined translation string.
X'''     Bell System Logo is used as a dummy character.
X'''
X.ie n \{\
X.tr \(bs-\*(Tr
X.ds -- \(bs-
X.if (\n(.H=4u)&(1m=24u) .ds -- \(bs\h'-12u'\(bs\h'-12u'-\" diablo 10 pitch
X.if (\n(.H=4u)&(1m=20u) .ds -- \(bs\h'-12u'\(bs\h'-8u'-\" diablo 12 pitch
X.ds L" ""
X.ds R" ""
X.ds L' '
X.ds R' '
X'br\}
X.el\{\
X.ds -- \(em\|
X.tr \*(Tr
X.ds L" ``
X.ds R" ''
X.ds L' `
X.ds R' '
X'br\}
X.TH PATCH 1 LOCAL
X.SH NAME
Xpatch - a program for applying a diff file to an original
X.SH SYNOPSIS
X.B patch
X[options] orig patchfile [+ [options] orig]
X.sp
Xbut usually just
X.sp
X.B patch
X<patchfile
X.SH DESCRIPTION
X.I Patch
Xwill take a patch file containing any of the three forms of difference
Xlisting produced by the
X.I diff
Xprogram and apply those differences to an original file, producing a patched
Xversion.
XBy default, the patched version is put in place of the original, with
Xthe original file backed up to the same name with the
Xextension \*(L".orig\*(R" or \*(L"~\*(R" , or as specified by the
X.B -b
Xswitch.
XYou may also specify where you want the output to go with a
X.B -o
Xswitch.
XIf
X.I patchfile
Xis omitted, or is a hyphen, the patch will be read from standard input.
X.PP
XUpon startup, patch will attempt to determine the type of the diff listing,
Xunless over-ruled by a
X.BR -c ,
X.BR -e ,
Xor
X.B -n
Xswitch.
XContext diffs and normal diffs are applied by the
X.I patch
Xprogram itself, while ed diffs are simply fed to the
X.I ed
Xeditor via a pipe.
X.PP
X.I Patch
Xwill try to skip any leading garbage, apply the diff,
Xand then skip any trailing garbage.
XThus you could feed an article or message containing a
Xdiff listing to
X.IR patch ,
Xand it should work.
XIf the entire diff is indented by a consistent amount,
Xthis will be taken into account.
X.PP
XWith context diffs, and to a lesser extent with normal diffs,
X.I patch
Xcan detect when the line numbers mentioned in the patch are incorrect,
Xand will attempt to find the correct place to apply each hunk of the patch.
XAs a first guess, it takes the line number mentioned for the hunk, plus or
Xminus any offset used in applying the previous hunk.
XIf that is not the correct place,
X.I patch
Xwill scan both forwards and backwards for a set of lines matching the context
Xgiven in the hunk.
XFirst
X.I patch
Xlooks for a place where all lines of the context match.
XIf no such place is found, and it's a context diff, and the maximum fuzz factor
Xis set to 1 or more, then another scan takes place ignoring the first and last
Xline of context.
XIf that fails, and the maximum fuzz factor is set to 2 or more,
Xthe first two and last two lines of context are ignored,
Xand another scan is made.
X(The default maximum fuzz factor is 2.)
XIf
X.I patch
Xcannot find a place to install that hunk of the patch, it will put the
Xhunk out to a reject file, which normally is the name of the output file
Xplus \*(L".rej\*(R" or \*(L"#\*(R" .
X(Note that the rejected hunk will come out in context diff form whether the
Xinput patch was a context diff or a normal diff.
XIf the input was a normal diff, many of the contexts will simply be null.)
XThe line numbers on the hunks in the reject file may be different than
Xin the patch file: they reflect the approximate location patch thinks the
Xfailed hunks belong in the new file rather than the old one.
X.PP
XAs each hunk is completed, you will be told whether the hunk succeeded or
Xfailed, and which line (in the new file)
X.I patch
Xthought the hunk should go on.
XIf this is different from the line number specified in the diff you will
Xbe told the offset.
XA single large offset MAY be an indication that a hunk was installed in the
Xwrong place.
XYou will also be told if a fuzz factor was used to make the match, in which
Xcase you should also be slightly suspicious.
X.PP
XIf no original file is specified on the command line,
X.I patch
Xwill try to figure out from the leading garbage what the name of the file
Xto edit is.
XIn the header of a context diff, the filename is found from lines beginning
Xwith \*(L"***\*(R" or \*(L"---\*(R", with the shortest name of an existing
Xfile winning.
XOnly context diffs have lines like that, but if there is an \*(L"Index:\*(R"
Xline in the leading garbage,
X.I patch
Xwill try to use the filename from that line.
XThe context diff header takes precedence over an Index line.
XIf no filename can be intuited from the leading garbage, you will be asked
Xfor the name of the file to patch.
X.PP
X(If the original file cannot be found, but a suitable SCCS or RCS file is
Xhandy,
X.I patch
Xwill attempt to get or check out the file.)
X.PP
XAdditionally, if the leading garbage contains a \*(L"Prereq: \*(R" line,
X.I patch
Xwill take the first word from the prerequisites line (normally a version
Xnumber) and check the input file to see if that word can be found.
XIf not,
X.I patch
Xwill ask for confirmation before proceeding.
X.PP
XThe upshot of all this is that you should be able to say, while in a news
Xinterface, the following:
X.Sp
X	| patch -d /usr/src/local/blurfl
X.Sp
Xand patch a file in the blurfl directory directly from the article containing
Xthe patch.
X.PP
XIf the patch file contains more than one patch,
X.I patch
Xwill try to apply each of them as if they came from separate patch files.
XThis means, among other things, that it is assumed that the name of the file
Xto patch must be determined for each diff listing,
Xand that the garbage before each diff listing will
Xbe examined for interesting things such as filenames and revision level, as
Xmentioned previously.
XYou can give switches (and another original file name) for the second and
Xsubsequent patches by separating the corresponding argument lists
Xby a \*(L'+\*(R'.
X(The argument list for a second or subsequent patch may not specify a new
Xpatch file, however.)
X.PP
X.I Patch
Xrecognizes the following switches:
X.TP 5
X.B \-b
Xcauses the next argument to be interpreted as the backup extension, to be
Xused in place of \*(L".orig\*(R" or \*(L"~\*(R".
X.TP 5
X.B \-B
Xcauses the next argument to be interpreted as a prefix to the backup file
Xname. If this argument is specified any argument from -b will be ignored.
XThis argument is an extension to Larry Wall's patch v2.0.1.4, patchlevel 8,
Xmade by M. Greim (greim at sbsvax.uucp).
X.TP 5
X.B \-c
Xforces
X.I patch
Xto interpret the patch file as a context diff.
X.TP 5
X.B \-d
Xcauses
X.I patch
Xto interpret the next argument as a directory, and cd to it before doing
Xanything else.
X.TP 5
X.B \-D
Xcauses
X.I patch
Xto use the "#ifdef...#endif" construct to mark changes.
XThe argument following will be used as the differentiating symbol.
XNote that, unlike the C compiler, there must be a space between the
X.B \-D
Xand the argument.
X.TP 5
X.B \-e
Xforces
X.I patch
Xto interpret the patch file as an ed script.
X.TP 5
X.B \-f
Xforces
X.I patch
Xto assume that the user knows exactly what he or she is doing, and to not
Xask any questions.
XIt does not suppress commentary, however.
XUse
X.B \-s
Xfor that.
X.TP 5
X.B \-F<number>
Xsets the maximum fuzz factor.
XThis switch only applies to context diffs, and causes
X.I patch
Xto ignore up to that many lines in looking for places to install a hunk.
XNote that a larger fuzz factor increases the odds of a faulty patch.
XThe default fuzz factor is 2, and it may not be set to more than
Xthe number of lines of context in the context diff, ordinarily 3.
X.TP 5
X.B \-l
Xcauses the pattern matching to be done loosely, in case the tabs and
Xspaces have been munged in your input file.
XAny sequence of whitespace in the pattern line will match any sequence
Xin the input file.
XNormal characters must still match exactly.
XEach line of the context must still match a line in the input file.
X.TP 5
X.B \-n
Xforces
X.I patch
Xto interpret the patch file as a normal diff.
X.TP 5
X.B \-N
Xcauses
X.I patch
Xto ignore patches that it thinks are reversed or already applied.
XSee also
X.B \-R .
X.TP 5
X.B \-o
Xcauses the next argument to be interpreted as the output file name.
X.TP 5
X.B \-p<number>
Xsets the pathname strip count,
Xwhich controls how pathnames found in the patch file are treated, in case
Xthe you keep your files in a different directory than the person who sent
Xout the patch.
XThe strip count specifies how many slashes are to be stripped from
Xthe front of the pathname.
X(Any intervening directory names also go away.)
XFor example, supposing the filename in the patch file was
X.sp
X	/u/howard/src/blurfl/blurfl.c
X.sp
Xsetting
X.B \-p
Xor
X.B \-p0
Xgives the entire pathname unmodified,
X.B \-p1
Xgives
X.sp
X	u/howard/src/blurfl/blurfl.c
X.sp
Xwithout the leading slash,
X.B \-p4
Xgives
X.sp
X	blurfl/blurfl.c
X.sp
Xand not specifying
X.B \-p
Xat all just gives you "blurfl.c".
XWhatever you end up with is looked for either in the current directory,
Xor the directory specified by the
X.B \-d
Xswitch.
X.TP 5
X.B \-r
Xcauses the next argument to be interpreted as the reject file name.
X.TP 5
X.B \-R
Xtells
X.I patch
Xthat this patch was created with the old and new files swapped.
X(Yes, I'm afraid that does happen occasionally, human nature being what it
Xis.)
X.I Patch
Xwill attempt to swap each hunk around before applying it.
XRejects will come out in the swapped format.
XThe
X.B \-R
Xswitch will not work with ed diff scripts because there is too little
Xinformation to reconstruct the reverse operation.
X.Sp
XIf the first hunk of a patch fails,
X.I patch
Xwill reverse the hunk to see if it can be applied that way.
XIf it can, you will be asked if you want to have the
X.B \-R
Xswitch set.
XIf it can't, the patch will continue to be applied normally.
X(Note: this method cannot detect a reversed patch if it is a normal diff
Xand if the first command is an append (i.e. it should have been a delete)
Xsince appends always succeed, due to the fact that a null context will match
Xanywhere.
XLuckily, most patches add or change lines rather than delete them, so most
Xreversed normal diffs will begin with a delete, which will fail, triggering
Xthe heuristic.)
X.TP 5
X.B \-s
Xmakes
X.I patch
Xdo its work silently, unless an error occurs.
X.TP 5
X.B \-S
Xcauses
X.I patch
Xto ignore this patch from the patch file, but continue on looking
Xfor the next patch in the file.
XThus
X.sp
X	patch -S + -S + <patchfile
X.sp
Xwill ignore the first and second of three patches.
X.TP 5
X.B \-v
Xcauses
X.I patch
Xto print out it's revision header and patch level.
X.TP 5
X.B \-x<number>
Xsets internal debugging flags, and is of interest only to
X.I patch
Xpatchers.
X.SH ENVIRONMENT
XNo environment variables are used by
X.IR patch .
X.SH FILES
X/tmp/patch*
X.SH SEE ALSO
Xdiff(1)
X.SH NOTES FOR PATCH SENDERS
XThere are several things you should bear in mind if you are going to
Xbe sending out patches.
XFirst, you can save people a lot of grief by keeping a patchlevel.h file
Xwhich is patched to increment the patch level as the first diff in the
Xpatch file you send out.
XIf you put a Prereq: line in with the patch, it won't let them apply
Xpatches out of order without some warning.
XSecond, make sure you've specified the filenames right, either in a
Xcontext diff header, or with an Index: line.
XIf you are patching something in a subdirectory, be sure to tell the patch
Xuser to specify a 
X.B \-p
Xswitch as needed.
XThird, you can create a file by sending out a diff that compares a
Xnull file to the file you want to create.
XThis will only work if the file you want to create doesn't exist already in
Xthe target directory.
XFourth, take care not to send out reversed patches, since it makes people wonder
Xwhether they already applied the patch.
XFifth, while you may be able to get away with putting 582 diff listings into
Xone file, it is probably wiser to group related patches into separate files in
Xcase something goes haywire.
X.SH DIAGNOSTICS
XToo many to list here, but generally indicative that
X.I patch
Xcouldn't parse your patch file.
X.PP
XThe message \*(L"Hmm...\*(R" indicates that there is unprocessed text in
Xthe patch file and that
X.I patch
Xis attempting to intuit whether there is a patch in that text and, if so,
Xwhat kind of patch it is.
X.PP
X.I Patch
Xwill exit with a non-zero status if any reject files were created.
XWhen applying a set of patches in a loop it behooves you to check this
Xexit status so you don't apply a later patch to a partially patched file.
X.SH CAVEATS
X.I Patch
Xcannot tell if the line numbers are off in an ed script, and can only detect
Xbad line numbers in a normal diff when it finds a \*(L"change\*(R" or
Xa \*(L"delete\*(R" command.
XA context diff using fuzz factor 3 may have the same problem.
XUntil a suitable interactive interface is added, you should probably do
Xa context diff in these cases to see if the changes made sense.
XOf course, compiling without errors is a pretty good indication that the patch
Xworked, but not always.
X.PP
X.I Patch
Xusually produces the correct results, even when it has to do a lot of
Xguessing.
XHowever, the results are guaranteed to be correct only when the patch is
Xapplied to exactly the same version of the file that the patch was
Xgenerated from.
X.SH BUGS
XCould be smarter about partial matches, excessively \&deviant offsets and
Xswapped code, but that would take an extra pass.
X.PP
XIf code has been duplicated (for instance with #ifdef OLDCODE ... #else ...
X#endif),
X.I patch
Xis incapable of patching both versions, and, if it works at all, will likely
Xpatch the wrong one, and tell you that it succeeded to boot.
X.PP
XIf you apply a patch you've already applied,
X.I patch
Xwill think it is a reversed patch, and offer to un-apply the patch.
XThis could be construed as a feature.
X.rn }` ''
SHAR_EOF
if test 14363 -ne "`wc -c < 'patch.man'`"
then
	echo shar: "error transmitting 'patch.man'" '(should have been 14363 characters)'
fi
fi
echo shar: "extracting 'patchlevel.h'" '(22 characters)'
if test -f 'patchlevel.h'
then
	echo shar: "will not over-write existing file 'patchlevel.h'"
else
sed 's/^X//' << \SHAR_EOF > 'patchlevel.h'
X#define PATCHLEVEL 11
SHAR_EOF
if test 22 -ne "`wc -c < 'patchlevel.h'`"
then
	echo shar: "error transmitting 'patchlevel.h'" '(should have been 22 characters)'
fi
fi
echo shar: "extracting 'pch.c'" '(28639 characters)'
if test -f 'pch.c'
then
	echo shar: "will not over-write existing file 'pch.c'"
else
sed 's/^X//' << \SHAR_EOF > 'pch.c'
X/* $Header: pch.c,v 2.0.1.7 88/06/03 15:13:28 lwall Locked $
X *
X * $Log:	pch.c,v $
X * Revision 2.0.1.7  88/06/03  15:13:28  lwall
X * patch10: Can now find patches in shar scripts.
X * patch10: Hunks that swapped and then swapped back could core dump.
X * 
X * Revision 2.0.1.6  87/06/04  16:18:13  lwall
X * pch_swap didn't swap p_bfake and p_efake.
X * 
X * Revision 2.0.1.5  87/01/30  22:47:42  lwall
X * Improved responses to mangled patches.
X * 
X * Revision 2.0.1.4  87/01/05  16:59:53  lwall
X * New-style context diffs caused double call to free().
X * 
X * Revision 2.0.1.3  86/11/14  10:08:33  lwall
X * Fixed problem where a long pattern wouldn't grow the hunk.
X * Also restored p_input_line when backtracking so error messages are right.
X * 
X * Revision 2.0.1.2  86/11/03  17:49:52  lwall
X * New-style delete triggers spurious assertion error.
X * 
X * Revision 2.0.1.1  86/10/29  15:52:08  lwall
X * Could falsely report new-style context diff.
X * 
X * Revision 2.0  86/09/17  15:39:37  lwall
X * Baseline for netwide release.
X * 
X */
X
X#include "EXTERN.h"
X#include "common.h"
X#include "util.h"
X#include "INTERN.h"
X#include "pch.h"
X
X/* Patch (diff listing) abstract type. */
X
Xstatic long p_filesize;			/* size of the patch file */
Xstatic LINENUM p_first;			/* 1st line number */
Xstatic LINENUM p_newfirst;		/* 1st line number of replacement */
Xstatic LINENUM p_ptrn_lines;		/* # lines in pattern */
Xstatic LINENUM p_repl_lines;		/* # lines in replacement text */
Xstatic LINENUM p_end = -1;		/* last line in hunk */
Xstatic LINENUM p_max;			/* max allowed value of p_end */
Xstatic LINENUM p_context = 3;		/* # of context lines */
Xstatic LINENUM p_input_line = 0;	/* current line # from patch file */
Xstatic char **p_line = Null(char**);	/* the text of the hunk */
Xstatic short *p_len = Null(short*);	/* length of each line */
Xstatic char *p_char = Nullch;		/* +, -, and ! */
Xstatic int hunkmax = INITHUNKMAX;	/* size of above arrays to begin with */
Xstatic int p_indent;			/* indent to patch */
Xstatic LINENUM p_base;			/* where to intuit this time */
Xstatic LINENUM p_bline;			/* line # of p_base */
Xstatic LINENUM p_start;			/* where intuit found a patch */
Xstatic LINENUM p_sline;			/* and the line number for it */
Xstatic LINENUM p_hunk_beg;		/* line number of current hunk */
Xstatic LINENUM p_efake = -1;		/* end of faked up lines--don't free */
Xstatic LINENUM p_bfake = -1;		/* beg of faked up lines */
X
X/* Prepare to look for the next patch in the patch file. */
X
Xvoid
Xre_patch()
X{
X    p_first = Nulline;
X    p_newfirst = Nulline;
X    p_ptrn_lines = Nulline;
X    p_repl_lines = Nulline;
X    p_end = (LINENUM)-1;
X    p_max = Nulline;
X    p_indent = 0;
X}
X
X/* Open the patch file at the beginning of time. */
X
Xvoid
Xopen_patch_file(filename)
Xchar *filename;
X{
X    if (filename == Nullch || !*filename || strEQ(filename, "-")) {
X	pfp = fopen(TMPPATNAME, "w");
X	if (pfp == Nullfp)
X	    fatal2("patch: can't create %s.\n", TMPPATNAME);
X	while (fgets(buf, sizeof buf, stdin) != Nullch)
X	    fputs(buf, pfp);
X	Fclose(pfp);
X	filename = TMPPATNAME;
X    }
X    pfp = fopen(filename, "r");
X    if (pfp == Nullfp)
X	fatal2("patch file %s not found\n", filename);
X    Fstat(fileno(pfp), &filestat);
X    p_filesize = filestat.st_size;
X    next_intuit_at(0L,1L);			/* start at the beginning */
X    set_hunkmax();
X}
X
X/* Make sure our dynamically realloced tables are malloced to begin with. */
X
Xvoid
Xset_hunkmax()
X{
X#ifndef lint
X    if (p_line == Null(char**))
X	p_line = (char**) malloc((MEM)hunkmax * sizeof(char *));
X    if (p_len == Null(short*))
X	p_len  = (short*) malloc((MEM)hunkmax * sizeof(short));
X#endif
X    if (p_char == Nullch)
X	p_char = (char*)  malloc((MEM)hunkmax * sizeof(char));
X}
X
X/* Enlarge the arrays containing the current hunk of patch. */
X
Xvoid
Xgrow_hunkmax()
X{
X    hunkmax *= 2;
X    /* 
X     * Note that on most systems, only the p_line array ever gets fresh memory
X     * since p_len can move into p_line's old space, and p_char can move into
X     * p_len's old space.  Not on PDP-11's however.  But it doesn't matter.
X     */
X    assert(p_line != Null(char**) && p_len != Null(short*) && p_char != Nullch);
X#ifndef lint
X    p_line = (char**) realloc((char*)p_line, (MEM)hunkmax * sizeof(char *));
X    p_len  = (short*) realloc((char*)p_len,  (MEM)hunkmax * sizeof(short));
X    p_char = (char*)  realloc((char*)p_char, (MEM)hunkmax * sizeof(char));
X#endif
X    if (p_line != Null(char**) && p_len != Null(short*) && p_char != Nullch)
X	return;
X    if (!using_plan_a)
X	fatal1("patch: out of memory (grow_hunkmax)\n");
X    out_of_mem = TRUE;		/* whatever is null will be allocated again */
X				/* from within plan_a(), of all places */
X}
X
X/* True if the remainder of the patch file contains a diff of some sort. */
X
Xbool
Xthere_is_another_patch()
X{
X    if (p_base != 0L && p_base >= p_filesize) {
X	if (verbose)
X	    say1("done\n");
X	return FALSE;
X    }
X    if (verbose)
X	say1("Hmm...");
X    diff_type = intuit_diff_type();
X    if (!diff_type) {
X	if (p_base != 0L) {
X	    if (verbose)
X		say1("  Ignoring the trailing garbage.\ndone\n");
X	}
X	else
X	    say1("  I can't seem to find a patch in there anywhere.\n");
X	return FALSE;
X    }
X    if (verbose)
X	say3("  %sooks like %s to me...\n",
X	    (p_base == 0L ? "L" : "The next patch l"),
X	    diff_type == CONTEXT_DIFF ? "a context diff" :
X	    diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
X	    diff_type == NORMAL_DIFF ? "a normal diff" :
X	    "an ed script" );
X    if (p_indent && verbose)
X	say3("(Patch is indented %d space%s.)\n", p_indent, p_indent==1?"":"s");
X    skip_to(p_start,p_sline);
X    while (filearg[0] == Nullch) {
X	if (force) {
X	    say1("No file to patch.  Skipping...\n");
X	    filearg[0] = savestr(bestguess);
X	    return TRUE;
X	}
X	ask1("File to patch: ");
X	if (*buf != '\n') {
X	    if (bestguess)
X		free(bestguess);
X	    bestguess = savestr(buf);
X	    filearg[0] = fetchname(buf, 0, FALSE);
X	}
X	if (filearg[0] == Nullch) {
X	    ask1("No file found--skip this patch? [n] ");
X	    if (*buf != 'y') {
X		continue;
X	    }
X	    if (verbose)
X		say1("Skipping patch...\n");
X	    filearg[0] = fetchname(bestguess, 0, TRUE);
X	    skip_rest_of_patch = TRUE;
X	    return TRUE;
X	}
X    }
X    return TRUE;
X}
X
X/* Determine what kind of diff is in the remaining part of the patch file. */
X
Xint
Xintuit_diff_type()
X{
X    Reg4 long this_line = 0;
X    Reg5 long previous_line;
X    Reg6 long first_command_line = -1;
X    long fcl_line;
X    Reg7 bool last_line_was_command = FALSE;
X    Reg8 bool this_is_a_command = FALSE;
X    Reg9 bool stars_last_line = FALSE;
X    Reg10 bool stars_this_line = FALSE;
X    Reg3 int indent;
X    Reg1 char *s;
X    Reg2 char *t;
X    char *indtmp = Nullch;
X    char *oldtmp = Nullch;
X    char *newtmp = Nullch;
X    char *indname = Nullch;
X    char *oldname = Nullch;
X    char *newname = Nullch;
X    Reg11 int retval;
X    bool no_filearg = (filearg[0] == Nullch);
X
X    ok_to_create_file = FALSE;
X    Fseek(pfp, p_base, 0);
X    p_input_line = p_bline - 1;
X    for (;;) {
X	previous_line = this_line;
X	last_line_was_command = this_is_a_command;
X	stars_last_line = stars_this_line;
X	this_line = ftell(pfp);
X	indent = 0;
X	p_input_line++;
X	if (fgets(buf, sizeof buf, pfp) == Nullch) {
X	    if (first_command_line >= 0L) {
X					/* nothing but deletes!? */
X		p_start = first_command_line;
X		p_sline = fcl_line;
X		retval = ED_DIFF;
X		goto scan_exit;
X	    }
X	    else {
X		p_start = this_line;
X		p_sline = p_input_line;
X		retval = 0;
X		goto scan_exit;
X	    }
X	}
X	for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
X	    if (*s == '\t')
X		indent += 8 - (indent % 8);
X	    else
X		indent++;
X	}
X	for (t=s; isdigit(*t) || *t == ','; t++) ; 
X	this_is_a_command = (isdigit(*s) &&
X	  (*t == 'd' || *t == 'c' || *t == 'a') );
X	if (first_command_line < 0L && this_is_a_command) { 
X	    first_command_line = this_line;
X	    fcl_line = p_input_line;
X	    p_indent = indent;		/* assume this for now */
X	}
X	if (!stars_last_line && strnEQ(s, "*** ", 4))
X	    oldtmp = savestr(s+4);
X	else if (strnEQ(s, "--- ", 4))
X	    newtmp = savestr(s+4);
X	else if (strnEQ(s, "Index:", 6))
X	    indtmp = savestr(s+6);
X	else if (strnEQ(s, "Prereq:", 7)) {
X	    for (t=s+7; isspace(*t); t++) ;
X	    revision = savestr(t);
X	    for (t=revision; *t && !isspace(*t); t++) ;
X	    *t = '\0';
X	    if (!*revision) {
X		free(revision);
X		revision = Nullch;
X	    }
X	}
X	if ((!diff_type || diff_type == ED_DIFF) &&
X	  first_command_line >= 0L &&
X	  strEQ(s, ".\n") ) {
X	    p_indent = indent;
X	    p_start = first_command_line;
X	    p_sline = fcl_line;
X	    retval = ED_DIFF;
X	    goto scan_exit;
X	}
X	stars_this_line = strnEQ(s, "********", 8);
X	if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
X		 strnEQ(s, "*** ", 4)) {
X	    if (!atol(s+4))
X		ok_to_create_file = TRUE;
X	    /* if this is a new context diff the character just before */
X	    /* the newline is a '*'. */
X	    while (*s != '\n')
X		s++;
X	    p_indent = indent;
X	    p_start = previous_line;
X	    p_sline = p_input_line - 1;
X	    retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
X	    goto scan_exit;
X	}
X	if ((!diff_type || diff_type == NORMAL_DIFF) && 
X	  last_line_was_command &&
X	  (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) {
X	    p_start = previous_line;
X	    p_sline = p_input_line - 1;
X	    p_indent = indent;
X	    retval = NORMAL_DIFF;
X	    goto scan_exit;
X	}
X    }
X  scan_exit:
X    if (no_filearg) {
X	if (indtmp != Nullch)
X	    indname = fetchname(indtmp, strippath, ok_to_create_file);
X	if (oldtmp != Nullch)
X	    oldname = fetchname(oldtmp, strippath, ok_to_create_file);
X	if (newtmp != Nullch)
X	    newname = fetchname(newtmp, strippath, ok_to_create_file);
X	if (oldname && newname) {
X	    if (strlen(oldname) < strlen(newname))
X		filearg[0] = savestr(oldname);
X	    else
X		filearg[0] = savestr(newname);
X	}
X	else if (oldname)
X	    filearg[0] = savestr(oldname);
X	else if (newname)
X	    filearg[0] = savestr(newname);
X	else if (indname)
X	    filearg[0] = savestr(indname);
X    }
X    if (bestguess) {
X	free(bestguess);
X	bestguess = Nullch;
X    }
X    if (filearg[0] != Nullch)
X	bestguess = savestr(filearg[0]);
X    else if (indtmp != Nullch)
X	bestguess = fetchname(indtmp, strippath, TRUE);
X    else {
X	if (oldtmp != Nullch)
X	    oldname = fetchname(oldtmp, strippath, TRUE);
X	if (newtmp != Nullch)
X	    newname = fetchname(newtmp, strippath, TRUE);
X	if (oldname && newname) {
X	    if (strlen(oldname) < strlen(newname))
X		bestguess = savestr(oldname);
X	    else
X		bestguess = savestr(newname);
X	}
X	else if (oldname)
X	    bestguess = savestr(oldname);
X	else if (newname)
X	    bestguess = savestr(newname);
X    }
X    if (indtmp != Nullch)
X	free(indtmp);
X    if (oldtmp != Nullch)
X	free(oldtmp);
X    if (newtmp != Nullch)
X	free(newtmp);
X    if (indname != Nullch)
X	free(indname);
X    if (oldname != Nullch)
X	free(oldname);
X    if (newname != Nullch)
X	free(newname);
X    return retval;
X}
X
X/* Remember where this patch ends so we know where to start up again. */
X
Xvoid
Xnext_intuit_at(file_pos,file_line)
Xlong file_pos;
Xlong file_line;
X{
X    p_base = file_pos;
X    p_bline = file_line;
X}
X
X/* Basically a verbose fseek() to the actual diff listing. */
X
Xvoid
Xskip_to(file_pos,file_line)
Xlong file_pos;
Xlong file_line;
X{
X    char *ret;
X
X    assert(p_base <= file_pos);
X    if (verbose && p_base < file_pos) {
X	Fseek(pfp, p_base, 0);
X	say1("The text leading up to this was:\n--------------------------\n");
X	while (ftell(pfp) < file_pos) {
X	    ret = fgets(buf, sizeof buf, pfp);
X	    assert(ret != Nullch);
X	    say2("|%s", buf);
X	}
X	say1("--------------------------\n");
X    }
X    else
X	Fseek(pfp, file_pos, 0);
X    p_input_line = file_line - 1;
X}
X
X/* True if there is more of the current diff listing to process. */
X
Xbool
Xanother_hunk()
X{
X    Reg1 char *s;
X    Reg8 char *ret;
X    Reg2 int context = 0;
X
X    while (p_end >= 0) {
X	if (p_end == p_efake)
X	    p_end = p_bfake;		/* don't free twice */
X	else
X	    free(p_line[p_end]);
X	p_end--;
X    }
X    assert(p_end == -1);
X    p_efake = -1;
X
X    p_max = hunkmax;			/* gets reduced when --- found */
X    if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
X	long line_beginning = ftell(pfp);
X					/* file pos of the current line */
X	LINENUM repl_beginning = 0;	/* index of --- line */
X	Reg4 LINENUM fillcnt = 0;	/* #lines of missing ptrn or repl */
X	Reg5 LINENUM fillsrc;		/* index of first line to copy */
X	Reg6 LINENUM filldst;		/* index of first missing line */
X	bool ptrn_spaces_eaten = FALSE;	/* ptrn was slightly misformed */
X	Reg9 bool repl_could_be_missing = TRUE;
X					/* no + or ! lines in this hunk */
X	bool repl_missing = FALSE;	/* we are now backtracking */
X	long repl_backtrack_position = 0;
X					/* file pos of first repl line */
X	LINENUM repl_patch_line;	/* input line number for same */
X	Reg7 LINENUM ptrn_copiable = 0;
X					/* # of copiable lines in ptrn */
X
X	ret = pgets(buf, sizeof buf, pfp);
X	p_input_line++;
X	if (ret == Nullch || strnNE(buf, "********", 8)) {
X	    next_intuit_at(line_beginning,p_input_line);
X	    return FALSE;
X	}
X	p_context = 100;
X	p_hunk_beg = p_input_line + 1;
X	while (p_end < p_max) {
X	    line_beginning = ftell(pfp);
X	    ret = pgets(buf, sizeof buf, pfp);
X	    p_input_line++;
X	    if (ret == Nullch) {
X		if (p_max - p_end < 4)
X		    Strcpy(buf, "  \n");  /* assume blank lines got chopped */
X		else {
X		    if (repl_beginning && repl_could_be_missing) {
X			repl_missing = TRUE;
X			goto hunk_done;
X		    }
X		    fatal1("Unexpected end of file in patch.\n");
X		}
X	    }
X	    p_end++;
X	    assert(p_end < hunkmax);
X	    p_char[p_end] = *buf;
X#ifdef zilog
X	    p_line[(short)p_end] = Nullch;
X#else
X	    p_line[p_end] = Nullch;
X#endif
X	    switch (*buf) {
X	    case '*':
X		if (strnEQ(buf, "********", 8)) {
X		    if (repl_beginning && repl_could_be_missing) {
X			repl_missing = TRUE;
X			goto hunk_done;
X		    }
X		    else
X			fatal2("Unexpected end of hunk at line %ld.\n",
X			    p_input_line);
X		}
X		if (p_end != 0) {
X		    if (repl_beginning && repl_could_be_missing) {
X			repl_missing = TRUE;
X			goto hunk_done;
X		    }
X		    fatal3("Unexpected *** at line %ld: %s", p_input_line, buf);
X		}
X		context = 0;
X		p_line[p_end] = savestr(buf);
X		if (out_of_mem) {
X		    p_end--;
X		    return FALSE;
X		}
X		for (s=buf; *s && !isdigit(*s); s++) ;
X		if (!*s)
X		    goto malformed;
X		if (strnEQ(s,"0,0",3))
X		    strcpy(s,s+2);
X		p_first = (LINENUM) atol(s);
X		while (isdigit(*s)) s++;
X		if (*s == ',') {
X		    for (; *s && !isdigit(*s); s++) ;
X		    if (!*s)
X			goto malformed;
X		    p_ptrn_lines = ((LINENUM)atol(s)) - p_first + 1;
X		}
X		else if (p_first)
X		    p_ptrn_lines = 1;
X		else {
X		    p_ptrn_lines = 0;
X		    p_first = 1;
X		}
X		p_max = p_ptrn_lines + 6;	/* we need this much at least */
X		while (p_max >= hunkmax)
X		    grow_hunkmax();
X		p_max = hunkmax;
X		break;
X	    case '-':
X		if (buf[1] == '-') {
X		    if (repl_beginning ||
X			(p_end != p_ptrn_lines + 1 + (p_char[p_end-1] == '\n')))
X		    {
X			if (p_end == 1) {
X			    /* `old' lines were omitted - set up to fill */
X			    /* them in from 'new' context lines. */
X			    p_end = p_ptrn_lines + 1;
X			    fillsrc = p_end + 1;
X			    filldst = 1;
X			    fillcnt = p_ptrn_lines;
X			}
X			else {
X			    if (repl_beginning) {
X				if (repl_could_be_missing){
X				    repl_missing = TRUE;
X				    goto hunk_done;
X				}
X				fatal3(
X"Duplicate \"---\" at line %ld--check line numbers at line %ld.\n",
X				    p_input_line, p_hunk_beg + repl_beginning);
X			    }
X			    else {
X				fatal4(
X"%s \"---\" at line %ld--check line numbers at line %ld.\n",
X				    (p_end <= p_ptrn_lines
X					? "Premature"
X					: "Overdue" ),
X				    p_input_line, p_hunk_beg);
X			    }
X			}
X		    }
X		    repl_beginning = p_end;
X		    repl_backtrack_position = ftell(pfp);
X		    repl_patch_line = p_input_line;
X		    p_line[p_end] = savestr(buf);
X		    if (out_of_mem) {
X			p_end--;
X			return FALSE;
X		    }
X		    p_char[p_end] = '=';
X		    for (s=buf; *s && !isdigit(*s); s++) ;
X		    if (!*s)
X			goto malformed;
X		    p_newfirst = (LINENUM) atol(s);
X		    while (isdigit(*s)) s++;
X		    if (*s == ',') {
X			for (; *s && !isdigit(*s); s++) ;
X			if (!*s)
X			    goto malformed;
X			p_repl_lines = ((LINENUM)atol(s)) - p_newfirst + 1;
X		    }
X		    else if (p_newfirst)
X			p_repl_lines = 1;
X		    else {
X			p_repl_lines = 0;
X			p_newfirst = 1;
X		    }
X		    p_max = p_repl_lines + p_end;
X		    if (p_max > MAXHUNKSIZE)
X			fatal4("Hunk too large (%ld lines) at line %ld: %s",
X			      p_max, p_input_line, buf);
X		    while (p_max >= hunkmax)
X			grow_hunkmax();
X		    if (p_repl_lines != ptrn_copiable)
X			repl_could_be_missing = FALSE;
X		    break;
X		}
X		goto change_line;
X	    case '+':  case '!':
X		repl_could_be_missing = FALSE;
X	      change_line:
X		if (buf[1] == '\n' && canonicalize)
X		    strcpy(buf+1," \n");
X		if (!isspace(buf[1]) && buf[1] != '>' && buf[1] != '<' &&
X		  repl_beginning && repl_could_be_missing) {
X		    repl_missing = TRUE;
X		    goto hunk_done;
X		}
X		if (context > 0) {
X		    if (context < p_context)
X			p_context = context;
X		    context = -1000;
X		}
X		p_line[p_end] = savestr(buf+2);
X		if (out_of_mem) {
X		    p_end--;
X		    return FALSE;
X		}
X		break;
X	    case '\t': case '\n':	/* assume the 2 spaces got eaten */
X		if (repl_beginning && repl_could_be_missing &&
X		  (!ptrn_spaces_eaten || diff_type == NEW_CONTEXT_DIFF) ) {
X		    repl_missing = TRUE;
X		    goto hunk_done;
X		}
X		p_line[p_end] = savestr(buf);
X		if (out_of_mem) {
X		    p_end--;
X		    return FALSE;
X		}
X		if (p_end != p_ptrn_lines + 1) {
X		    ptrn_spaces_eaten |= (repl_beginning != 0);
X		    context++;
X		    if (!repl_beginning)
X			ptrn_copiable++;
X		    p_char[p_end] = ' ';
X		}
X		break;
X	    case ' ':
X		if (!isspace(buf[1]) &&
X		  repl_beginning && repl_could_be_missing) {
X		    repl_missing = TRUE;
X		    goto hunk_done;
X		}
X		context++;
X		if (!repl_beginning)
X		    ptrn_copiable++;
X		p_line[p_end] = savestr(buf+2);
X		if (out_of_mem) {
X		    p_end--;
X		    return FALSE;
X		}
X		break;
X	    default:
X		if (repl_beginning && repl_could_be_missing) {
X		    repl_missing = TRUE;
X		    goto hunk_done;
X		}
X		goto malformed;
X	    }
X	    /* set up p_len for strncmp() so we don't have to */
X	    /* assume null termination */
X	    if (p_line[p_end])
X		p_len[p_end] = strlen(p_line[p_end]);
X	    else
X		p_len[p_end] = 0;
X	}
X	
X    hunk_done:
X	if (p_end >=0 && !repl_beginning)
X	    fatal2("No --- found in patch at line %ld\n", pch_hunk_beg());
X
X	if (repl_missing) {
X	    
X	    /* reset state back to just after --- */
X	    p_input_line = repl_patch_line;
X	    for (p_end--; p_end > repl_beginning; p_end--)
X		free(p_line[p_end]);
X	    Fseek(pfp, repl_backtrack_position, 0);
X	    
X	    /* redundant 'new' context lines were omitted - set */
X	    /* up to fill them in from the old file context */
X	    fillsrc = 1;
X	    filldst = repl_beginning+1;
X	    fillcnt = p_repl_lines;
X	    p_end = p_max;
X	}
X
X	if (diff_type == CONTEXT_DIFF &&
X	  (fillcnt || (p_first > 1 && ptrn_copiable > 2*p_context)) ) {
X	    if (verbose)
X		say4("%s\n%s\n%s\n",
X"(Fascinating--this is really a new-style context diff but without",
X"the telltale extra asterisks on the *** line that usually indicate",
X"the new style...)");
X	    diff_type = NEW_CONTEXT_DIFF;
X	}
X	
X	/* if there were omitted context lines, fill them in now */
X	if (fillcnt) {
X	    p_bfake = filldst;		/* remember where not to free() */
X	    p_efake = filldst + fillcnt - 1;
X	    while (fillcnt-- > 0) {
X		while (fillsrc <= p_end && p_char[fillsrc] != ' ')
X		    fillsrc++;
X		if (fillsrc > p_end)
X		    fatal2("Replacement text or line numbers mangled in hunk at line %ld\n",
X			p_hunk_beg);
X		p_line[filldst] = p_line[fillsrc];
X		p_char[filldst] = p_char[fillsrc];
X		p_len[filldst] = p_len[fillsrc];
X		fillsrc++; filldst++;
X	    }
X	    while (fillsrc <= p_end && fillsrc != repl_beginning &&
X	      p_char[fillsrc] != ' ')
X		fillsrc++;
X#ifdef DEBUGGING
X	    if (debug & 64)
X		printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
X		    fillsrc,filldst,repl_beginning,p_end+1);
X#endif
X	    assert(fillsrc==p_end+1 || fillsrc==repl_beginning);
X	    assert(filldst==p_end+1 || filldst==repl_beginning);
X	}
X    }
X    else {				/* normal diff--fake it up */
X	char hunk_type;
X	Reg3 int i;
X	LINENUM min, max;
X	long line_beginning = ftell(pfp);
X
X	p_context = 0;
X	ret = pgets(buf, sizeof buf, pfp);
X	p_input_line++;
X	if (ret == Nullch || !isdigit(*buf)) {
X	    next_intuit_at(line_beginning,p_input_line);
X	    return FALSE;
X	}
X	p_first = (LINENUM)atol(buf);
X	for (s=buf; isdigit(*s); s++) ;
X	if (*s == ',') {
X	    p_ptrn_lines = (LINENUM)atol(++s) - p_first + 1;
X	    while (isdigit(*s)) s++;
X	}
X	else
X	    p_ptrn_lines = (*s != 'a');
X	hunk_type = *s;
X	if (hunk_type == 'a')
X	    p_first++;			/* do append rather than insert */
X	min = (LINENUM)atol(++s);
X	for (; isdigit(*s); s++) ;
X	if (*s == ',')
X	    max = (LINENUM)atol(++s);
X	else
X	    max = min;
X	if (hunk_type == 'd')
X	    min++;
X	p_end = p_ptrn_lines + 1 + max - min + 1;
X	if (p_end > MAXHUNKSIZE)
X	    fatal4("Hunk too large (%ld lines) at line %ld: %s",
X		  p_end, p_input_line, buf);
X	while (p_end >= hunkmax)
X	    grow_hunkmax();
X	p_newfirst = min;
X	p_repl_lines = max - min + 1;
X	Sprintf(buf, "*** %ld,%ld\n", p_first, p_first + p_ptrn_lines - 1);
X	p_line[0] = savestr(buf);
X	if (out_of_mem) {
X	    p_end = -1;
X	    return FALSE;
X	}
X	p_char[0] = '*';
X	for (i=1; i<=p_ptrn_lines; i++) {
X	    ret = pgets(buf, sizeof buf, pfp);
X	    p_input_line++;
X	    if (ret == Nullch)
X		fatal2("Unexpected end of file in patch at line %ld.\n",
X		  p_input_line);
X	    if (*buf != '<')
X		fatal2("< expected at line %ld of patch.\n", p_input_line);
X	    p_line[i] = savestr(buf+2);
X	    if (out_of_mem) {
X		p_end = i-1;
X		return FALSE;
X	    }
X	    p_len[i] = strlen(p_line[i]);
X	    p_char[i] = '-';
X	}
X	if (hunk_type == 'c') {
X	    ret = pgets(buf, sizeof buf, pfp);
X	    p_input_line++;
X	    if (ret == Nullch)
X		fatal2("Unexpected end of file in patch at line %ld.\n",
X		    p_input_line);
X	    if (*buf != '-')
X		fatal2("--- expected at line %ld of patch.\n", p_input_line);
X	}
X	Sprintf(buf, "--- %ld,%ld\n", min, max);
X	p_line[i] = savestr(buf);
X	if (out_of_mem) {
X	    p_end = i-1;
X	    return FALSE;
X	}
X	p_char[i] = '=';
X	for (i++; i<=p_end; i++) {
X	    ret = pgets(buf, sizeof buf, pfp);
X	    p_input_line++;
X	    if (ret == Nullch)
X		fatal2("Unexpected end of file in patch at line %ld.\n",
X		    p_input_line);
X	    if (*buf != '>')
X		fatal2("> expected at line %ld of patch.\n", p_input_line);
X	    p_line[i] = savestr(buf+2);
X	    if (out_of_mem) {
X		p_end = i-1;
X		return FALSE;
X	    }
X	    p_len[i] = strlen(p_line[i]);
X	    p_char[i] = '+';
X	}
X    }
X    if (reverse)			/* backwards patch? */
X	if (!pch_swap())
X	    say1("Not enough memory to swap next hunk!\n");
X#ifdef DEBUGGING
X    if (debug & 2) {
X	int i;
X	char special;
X
X	for (i=0; i <= p_end; i++) {
X	    if (i == p_ptrn_lines)
X		special = '^';
X	    else
X		special = ' ';
X	    fprintf(stderr, "%3d %c %c %s", i, p_char[i], special, p_line[i]);
X	    Fflush(stderr);
X	}
X    }
X#endif
X    if (p_end+1 < hunkmax)	/* paranoia reigns supreme... */
X	p_char[p_end+1] = '^';  /* add a stopper for apply_hunk */
X    return TRUE;
X
Xmalformed:
X    fatal3("Malformed patch at line %ld: %s", p_input_line, buf);
X		/* about as informative as "Syntax error" in C */
X    return FALSE;	/* for lint */
X}
X
X/* Input a line from the patch file, worrying about indentation. */
X
Xchar *
Xpgets(bf,sz,fp)
Xchar *bf;
Xint sz;
XFILE *fp;
X{
X    char *ret = fgets(bf, sz, fp);
X    Reg1 char *s;
X    Reg2 int indent = 0;
X
X    if (p_indent && ret != Nullch) {
X	for (s=buf;
X	  indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X'); s++) {
X	    if (*s == '\t')
X		indent += 8 - (indent % 7);
X	    else
X		indent++;
X	}
X	if (buf != s)
X	    Strcpy(buf, s);
X    }
X    return ret;
X}
X
X/* Reverse the old and new portions of the current hunk. */
X
Xbool
Xpch_swap()
X{
X    char **tp_line;		/* the text of the hunk */
X    short *tp_len;		/* length of each line */
X    char *tp_char;		/* +, -, and ! */
X    Reg1 LINENUM i;
X    Reg2 LINENUM n;
X    bool blankline = FALSE;
X    Reg3 char *s;
X
X    i = p_first;
X    p_first = p_newfirst;
X    p_newfirst = i;
X    
X    /* make a scratch copy */
X
X    tp_line = p_line;
X    tp_len = p_len;
X    tp_char = p_char;
X    p_line = Null(char**);	/* force set_hunkmax to allocate again */
X    p_len = Null(short*);
X    p_char = Nullch;
X    set_hunkmax();
X    if (p_line == Null(char**) || p_len == Null(short*) || p_char == Nullch) {
X#ifndef lint
X	if (p_line == Null(char**))
X	    free((char*)p_line);
X	p_line = tp_line;
X	if (p_len == Null(short*))
X	    free((char*)p_len);
X	p_len = tp_len;
X#endif
X	if (p_char == Nullch)
X	    free((char*)p_char);
X	p_char = tp_char;
X	return FALSE;		/* not enough memory to swap hunk! */
X    }
X
X    /* now turn the new into the old */
X
X    i = p_ptrn_lines + 1;
X    if (tp_char[i] == '\n') {		/* account for possible blank line */
X	blankline = TRUE;
X	i++;
X    }
X    if (p_efake >= 0) {			/* fix non-freeable ptr range */
X	if (p_efake <= i)
X	    n = p_end - i + 1;
X	else
X	    n = -i;
X	p_efake += n;
X	p_bfake += n;
X    }
X    for (n=0; i <= p_end; i++,n++) {
X	p_line[n] = tp_line[i];
X	p_char[n] = tp_char[i];
X	if (p_char[n] == '+')
X	    p_char[n] = '-';
X	p_len[n] = tp_len[i];
X    }
X    if (blankline) {
X	i = p_ptrn_lines + 1;
X	p_line[n] = tp_line[i];
X	p_char[n] = tp_char[i];
X	p_len[n] = tp_len[i];
X	n++;
X    }
X    assert(p_char[0] == '=');
X    p_char[0] = '*';
X    for (s=p_line[0]; *s; s++)
X	if (*s == '-')
X	    *s = '*';
X
X    /* now turn the old into the new */
X
X    assert(tp_char[0] == '*');
X    tp_char[0] = '=';
X    for (s=tp_line[0]; *s; s++)
X	if (*s == '*')
X	    *s = '-';
X    for (i=0; n <= p_end; i++,n++) {
X	p_line[n] = tp_line[i];
X	p_char[n] = tp_char[i];
X	if (p_char[n] == '-')
X	    p_char[n] = '+';
X	p_len[n] = tp_len[i];
X    }
X    assert(i == p_ptrn_lines + 1);
X    i = p_ptrn_lines;
X    p_ptrn_lines = p_repl_lines;
X    p_repl_lines = i;
X#ifndef lint
X    if (tp_line == Null(char**))
X	free((char*)tp_line);
X    if (tp_len == Null(short*))
X	free((char*)tp_len);
X#endif
X    if (tp_char == Nullch)
X	free((char*)tp_char);
X    return TRUE;
X}
X
X/* Return the specified line position in the old file of the old context. */
X
XLINENUM
Xpch_first()
X{
X    return p_first;
X}
X
X/* Return the number of lines of old context. */
X
XLINENUM
Xpch_ptrn_lines()
X{
X    return p_ptrn_lines;
X}
X
X/* Return the probable line position in the new file of the first line. */
X
XLINENUM
Xpch_newfirst()
X{
X    return p_newfirst;
X}
X
X/* Return the number of lines in the replacement text including context. */
X
XLINENUM
Xpch_repl_lines()
X{
X    return p_repl_lines;
X}
X
X/* Return the number of lines in the whole hunk. */
X
XLINENUM
Xpch_end()
X{
X    return p_end;
X}
X
X/* Return the number of context lines before the first changed line. */
X
XLINENUM
Xpch_context()
X{
X    return p_context;
X}
X
X/* Return the length of a particular patch line. */
X
Xshort
Xpch_line_len(line)
XLINENUM line;
X{
X    return p_len[line];
X}
X
X/* Return the control character (+, -, *, !, etc) for a patch line. */
X
Xchar
Xpch_char(line)
XLINENUM line;
X{
X    return p_char[line];
X}
X
X/* Return a pointer to a particular patch line. */
X
Xchar *
Xpfetch(line)
XLINENUM line;
X{
X    return p_line[line];
X}
X
X/* Return where in the patch file this hunk began, for error messages. */
X
XLINENUM
Xpch_hunk_beg()
X{
X    return p_hunk_beg;
X}
X
X/* Apply an ed script by feeding ed itself. */
X
Xvoid
Xdo_ed_script()
X{
X    Reg1 char *t;
X    Reg2 long beginning_of_this_line;
X    Reg3 bool this_line_is_command = FALSE;
X    Reg4 FILE *pipefp;
X    FILE *popen();
X
X    if (!skip_rest_of_patch) {
X	Unlink(TMPOUTNAME);
X	copy_file(filearg[0], TMPOUTNAME);
X	if (verbose)
X	    Sprintf(buf, "/bin/ed %s", TMPOUTNAME);
X	else
X	    Sprintf(buf, "/bin/ed - %s", TMPOUTNAME);
X	pipefp = popen(buf, "w");
X    }
X    for (;;) {
X	beginning_of_this_line = ftell(pfp);
X	if (pgets(buf, sizeof buf, pfp) == Nullch) {
X	    next_intuit_at(beginning_of_this_line,p_input_line);
X	    break;
X	}
X	p_input_line++;
X	for (t=buf; isdigit(*t) || *t == ','; t++) ;
X	this_line_is_command = (isdigit(*buf) &&
X	  (*t == 'd' || *t == 'c' || *t == 'a') );
X	if (this_line_is_command) {
X	    if (!skip_rest_of_patch)
X		fputs(buf, pipefp);
X	    if (*t != 'd') {
X		while (pgets(buf, sizeof buf, pfp) != Nullch) {
X		    p_input_line++;
X		    if (!skip_rest_of_patch)
X			fputs(buf, pipefp);
X		    if (strEQ(buf, ".\n"))
X			break;
X		}
X	    }
X	}
X	else {
X	    next_intuit_at(beginning_of_this_line,p_input_line);
X	    break;
X	}
X    }
X    if (skip_rest_of_patch)
X	return;
X    fprintf(pipefp, "w\n");
X    fprintf(pipefp, "q\n");
X    Fflush(pipefp);
X    Pclose(pipefp);
X    ignore_signals();
X    if (move_file(TMPOUTNAME, outname) < 0) {
X	toutkeep = TRUE;
X	chmod(TMPOUTNAME, filemode);
X    }
X    else
X	chmod(outname, filemode);
X    set_signals(1);
X}
SHAR_EOF
if test 28639 -ne "`wc -c < 'pch.c'`"
then
	echo shar: "error transmitting 'pch.c'" '(should have been 28639 characters)'
fi
fi
echo shar: "extracting 'pch.h'" '(780 characters)'
if test -f 'pch.h'
then
	echo shar: "will not over-write existing file 'pch.h'"
else
sed 's/^X//' << \SHAR_EOF > 'pch.h'
X/* $Header: pch.h,v 2.0.1.1 87/01/30 22:47:16 lwall Exp $
X *
X * $Log:	pch.h,v $
X * Revision 2.0.1.1  87/01/30  22:47:16  lwall
X * Added do_ed_script().
X * 
X * Revision 2.0  86/09/17  15:39:57  lwall
X * Baseline for netwide release.
X * 
X */
X
XEXT FILE *pfp INIT(Nullfp);		/* patch file pointer */
X
Xvoid re_patch();
Xvoid open_patch_file();
Xvoid set_hunkmax();
Xvoid grow_hunkmax();
Xbool there_is_another_patch();
Xint intuit_diff_type();
Xvoid next_intuit_at();
Xvoid skip_to();
Xbool another_hunk();
Xbool pch_swap();
Xchar *pfetch();
Xshort pch_line_len();
XLINENUM pch_first();
XLINENUM pch_ptrn_lines();
XLINENUM pch_newfirst();
XLINENUM pch_repl_lines();
XLINENUM pch_end();
XLINENUM pch_context();
XLINENUM pch_hunk_beg();
Xchar pch_char();
Xchar *pfetch();
Xchar *pgets();
Xvoid do_ed_script();
SHAR_EOF
if test 780 -ne "`wc -c < 'pch.h'`"
then
	echo shar: "error transmitting 'pch.h'" '(should have been 780 characters)'
fi
fi
echo shar: "extracting 'util.c'" '(7226 characters)'
if test -f 'util.c'
then
	echo shar: "will not over-write existing file 'util.c'"
else
sed 's/^X//' << \SHAR_EOF > 'util.c'
X#include "EXTERN.h"
X#include "common.h"
X#include "INTERN.h"
X#include "util.h"
X
X/* Rename a file, copying it if necessary. */
X
Xint
Xmove_file(from,to)
Xchar *from, *to;
X{
X    char bakname[512];
X    Reg1 char *s;
X    Reg2 int i;
X    Reg3 int fromfd;
X
X    /* to stdout? */
X
X    if (strEQ(to, "-")) {
X#ifdef DEBUGGING
X	if (debug & 4)
X	    say2("Moving %s to stdout.\n", from);
X#endif
X	fromfd = open(from, 0);
X	if (fromfd < 0)
X	    fatal2("patch: internal error, can't reopen %s\n", from);
X	while ((i=read(fromfd, buf, sizeof buf)) > 0)
X	    if (write(1, buf, i) != 1)
X		fatal1("patch: write failed\n");
X	Close(fromfd);
X	return 0;
X    }
X
X	if (origprae) {
X		Strcpy (bakname, origprae);
X    	Strcat(bakname, to);
X	} else {
X   		Strcpy(bakname, to);
X    	Strcat(bakname, origext?origext:ORIGEXT);
X	}
X    if (stat(to, &filestat) >= 0) {	/* output file exists */
X	dev_t to_device = filestat.st_dev;
X	ino_t to_inode  = filestat.st_ino;
X	char *simplename = bakname;
X	
X	for (s=bakname; *s; s++) {
X	    if (*s == '/')
X		simplename = s+1;
X	}
X	/* find a backup name that is not the same file */
X	while (stat(bakname, &filestat) >= 0 &&
X		to_device == filestat.st_dev && to_inode == filestat.st_ino) {
X	    for (s=simplename; *s && !islower(*s); s++) ;
X	    if (*s)
X		*s = toupper(*s);
X	    else
X		Strcpy(simplename, simplename+1);
X	}
X	while (unlink(bakname) >= 0) ;	/* while() is for benefit of Eunice */
X#ifdef DEBUGGING
X	if (debug & 4)
X	    say3("Moving %s to %s.\n", to, bakname);
X#endif
X	if (link(to, bakname) < 0) {
X	    say3("patch: can't backup %s, output is in %s\n",
X		to, from);
X	    return -1;
X	}
X	while (unlink(to) >= 0) ;
X    }
X#ifdef DEBUGGING
X    if (debug & 4)
X	say3("Moving %s to %s.\n", from, to);
X#endif
X    if (link(from, to) < 0) {		/* different file system? */
X	Reg4 int tofd;
X	
X	tofd = creat(to, 0666);
X	if (tofd < 0) {
X	    say3("patch: can't create %s, output is in %s.\n",
X	      to, from);
X	    return -1;
X	}
X	fromfd = open(from, 0);
X	if (fromfd < 0)
X	    fatal2("patch: internal error, can't reopen %s\n", from);
X	while ((i=read(fromfd, buf, sizeof buf)) > 0)
X	    if (write(tofd, buf, i) != i)
X		fatal1("patch: write failed\n");
X	Close(fromfd);
X	Close(tofd);
X    }
X    Unlink(from);
X    return 0;
X}
X
X/* Copy a file. */
X
Xvoid
Xcopy_file(from,to)
Xchar *from, *to;
X{
X    Reg3 int tofd;
X    Reg2 int fromfd;
X    Reg1 int i;
X    
X    tofd = creat(to, 0666);
X    if (tofd < 0)
X	fatal2("patch: can't create %s.\n", to);
X    fromfd = open(from, 0);
X    if (fromfd < 0)
X	fatal2("patch: internal error, can't reopen %s\n", from);
X    while ((i=read(fromfd, buf, sizeof buf)) > 0)
X	if (write(tofd, buf, i) != i)
X	    fatal2("patch: write (%s) failed\n", to);
X    Close(fromfd);
X    Close(tofd);
X}
X
X/* Allocate a unique area for a string. */
X
Xchar *
Xsavestr(s)
XReg1 char *s;
X{
X    Reg3 char *rv;
X    Reg2 char *t;
X
X    if (!s)
X	s = "Oops";
X    t = s;
X    while (*t++);
X    rv = malloc((MEM) (t - s));
X    if (rv == Nullch) {
X	if (using_plan_a)
X	    out_of_mem = TRUE;
X	else
X	    fatal1("patch: out of memory (savestr)\n");
X    }
X    else {
X	t = rv;
X	while (*t++ = *s++);
X    }
X    return rv;
X}
X
X#if defined(lint) && defined(CANVARARG)
X
X/*VARARGS ARGSUSED*/
Xsay(pat) char *pat; { ; }
X/*VARARGS ARGSUSED*/
Xfatal(pat) char *pat; { ; }
X/*VARARGS ARGSUSED*/
Xask(pat) char *pat; { ; }
X
X#else
X
X/* Vanilla terminal output (buffered). */
X
Xvoid
Xsay(pat,arg1,arg2,arg3)
Xchar *pat;
Xlong arg1,arg2,arg3;
X{
X    fprintf(stderr, pat, arg1, arg2, arg3);
X    Fflush(stderr);
X}
X
X/* Terminal output, pun intended. */
X
Xvoid				/* very void */
Xfatal(pat,arg1,arg2,arg3)
Xchar *pat;
Xlong arg1,arg2,arg3;
X{
X    void my_exit();
X
X    say(pat, arg1, arg2, arg3);
X    my_exit(1);
X}
X
X/* Get a response from the user, somehow or other. */
X
Xvoid
Xask(pat,arg1,arg2,arg3)
Xchar *pat;
Xlong arg1,arg2,arg3;
X{
X    int ttyfd;
X    int r;
X    bool tty2 = isatty(2);
X
X    Sprintf(buf, pat, arg1, arg2, arg3);
X    Fflush(stderr);
X    write(2, buf, strlen(buf));
X    if (tty2) {				/* might be redirected to a file */
X	r = read(2, buf, sizeof buf);
X    }
X    else if (isatty(1)) {		/* this may be new file output */
X	Fflush(stdout);
X	write(1, buf, strlen(buf));
X	r = read(1, buf, sizeof buf);
X    }
X    else if ((ttyfd = open("/dev/tty", 2)) >= 0 && isatty(ttyfd)) {
X					/* might be deleted or unwriteable */
X	write(ttyfd, buf, strlen(buf));
X	r = read(ttyfd, buf, sizeof buf);
X	Close(ttyfd);
X    }
X    else if (isatty(0)) {		/* this is probably patch input */
X	Fflush(stdin);
X	write(0, buf, strlen(buf));
X	r = read(0, buf, sizeof buf);
X    }
X    else {				/* no terminal at all--default it */
X	buf[0] = '\n';
X	r = 1;
X    }
X    if (r <= 0)
X	buf[0] = 0;
X    else
X	buf[r] = '\0';
X    if (!tty2)
X	say1(buf);
X}
X#endif /* lint */
X
X/* How to handle certain events when not in a critical region. */
X
Xvoid
Xset_signals(reset)
Xint reset;
X{
X    void my_exit();
X#ifndef lint
X#ifdef VOIDSIG
X    static void (*hupval)(),(*intval)();
X#else
X    static int (*hupval)(),(*intval)();
X#endif
X
X    if (!reset) {
X	hupval = signal(SIGHUP, SIG_IGN);
X	if (hupval != SIG_IGN)
X	    hupval = my_exit;
X	intval = signal(SIGINT, SIG_IGN);
X	if (intval != SIG_IGN)
X	    intval = my_exit;
X    }
X    Signal(SIGHUP, hupval);
X    Signal(SIGINT, intval);
X#endif
X}
X
X/* How to handle certain events when in a critical region. */
X
Xvoid
Xignore_signals()
X{
X#ifndef lint
X    Signal(SIGHUP, SIG_IGN);
X    Signal(SIGINT, SIG_IGN);
X#endif
X}
X
X/* Make sure we'll have the directories to create a file. */
X
Xvoid
Xmakedirs(filename,striplast)
XReg1 char *filename;
Xbool striplast;
X{
X    char tmpbuf[256];
X    Reg2 char *s = tmpbuf;
X    char *dirv[20];
X    Reg3 int i;
X    Reg4 int dirvp = 0;
X
X    while (*filename) {
X	if (*filename == '/') {
X	    filename++;
X	    dirv[dirvp++] = s;
X	    *s++ = '\0';
X	}
X	else {
X	    *s++ = *filename++;
X	}
X    }
X    *s = '\0';
X    dirv[dirvp] = s;
X    if (striplast)
X	dirvp--;
X    if (dirvp < 0)
X	return;
X    strcpy(buf, "mkdir");
X    s = buf;
X    for (i=0; i<=dirvp; i++) {
X	while (*s) s++;
X	*s++ = ' ';
X	strcpy(s, tmpbuf);
X	*dirv[i] = '/';
X    }
X    system(buf);
X}
X
X/* Make filenames more reasonable. */
X
Xchar *
Xfetchname(at,strip_leading,assume_exists)
Xchar *at;
Xint strip_leading;
Xint assume_exists;
X{
X    char *s;
X    char *name;
X    Reg1 char *t;
X    char tmpbuf[200];
X
X    if (!at)
X	return Nullch;
X    s = savestr(at);
X    for (t=s; isspace(*t); t++) ;
X    name = t;
X#ifdef DEBUGGING
X    if (debug & 128)
X	say4("fetchname %s %d %d\n",name,strip_leading,assume_exists);
X#endif
X    if (strnEQ(name, "/dev/null", 9))	/* so files can be created by diffing */
X	return Nullch;			/*   against /dev/null. */
X    for (; *t && !isspace(*t); t++)
X	if (*t == '/')
X	    if (--strip_leading >= 0)
X		name = t+1;
X    *t = '\0';
X    if (name != s && *s != '/') {
X	name[-1] = '\0';
X	if (stat(s, &filestat) && filestat.st_mode & S_IFDIR) {
X	    name[-1] = '/';
X	    name=s;
X	}
X    }
X    name = savestr(name);
X    Sprintf(tmpbuf, "RCS/%s", name);
X    free(s);
X    if (stat(name, &filestat) < 0 && !assume_exists) {
X	Strcat(tmpbuf, RCSSUFFIX);
X	if (stat(tmpbuf, &filestat) < 0 && stat(tmpbuf+4, &filestat) < 0) {
X	    Sprintf(tmpbuf, "SCCS/%s%s", SCCSPREFIX, name);
X	    if (stat(tmpbuf, &filestat) < 0 && stat(tmpbuf+5, &filestat) < 0) {
X		free(name);
X		name = Nullch;
X	    }
X	}
X    }
X    return name;
X}
SHAR_EOF
if test 7226 -ne "`wc -c < 'util.c'`"
then
	echo shar: "error transmitting 'util.c'" '(should have been 7226 characters)'
fi
fi
exit 0
#	End of shell archive



More information about the Unix-pc.sources mailing list