pch.c revision 281800
1246091Sdelphij
2246074Sgabor/*-
3246074Sgabor * Copyright 1986, Larry Wall
4246074Sgabor *
5246074Sgabor * Redistribution and use in source and binary forms, with or without
6246074Sgabor * modification, are permitted provided that the following condition is met:
7246074Sgabor * 1. Redistributions of source code must retain the above copyright notice,
8246074Sgabor * this condition and the following disclaimer.
9246074Sgabor *
10246074Sgabor * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
11246074Sgabor * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
12246074Sgabor * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
13246074Sgabor * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
14246074Sgabor * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
15246074Sgabor * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
16246074Sgabor * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
17246074Sgabor * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18246074Sgabor * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
19246074Sgabor * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
20246074Sgabor * SUCH DAMAGE.
21246074Sgabor *
22246074Sgabor * patch - a program to apply diffs to original files
23246074Sgabor *
24246074Sgabor * -C option added in 1998, original code by Marc Espie, based on FreeBSD
25246074Sgabor * behaviour
26246074Sgabor *
27275582Spfg * $OpenBSD: pch.c,v 1.43 2014/11/18 17:03:35 tobias Exp $
28246091Sdelphij * $FreeBSD: head/usr.bin/patch/pch.c 281800 2015-04-20 22:15:18Z pfg $
29246074Sgabor */
30246074Sgabor
31246074Sgabor#include <sys/types.h>
32246074Sgabor#include <sys/stat.h>
33246074Sgabor
34246074Sgabor#include <ctype.h>
35246074Sgabor#include <libgen.h>
36246074Sgabor#include <limits.h>
37281800Spfg#include <stdint.h>
38246074Sgabor#include <stdio.h>
39246074Sgabor#include <stdlib.h>
40246074Sgabor#include <string.h>
41246074Sgabor#include <unistd.h>
42246074Sgabor
43246074Sgabor#include "common.h"
44246074Sgabor#include "util.h"
45246074Sgabor#include "pch.h"
46246074Sgabor#include "pathnames.h"
47246074Sgabor
48246074Sgabor/* Patch (diff listing) abstract type. */
49246074Sgabor
50275553Spfgstatic off_t	p_filesize;	/* size of the patch file */
51246074Sgaborstatic LINENUM	p_first;	/* 1st line number */
52246074Sgaborstatic LINENUM	p_newfirst;	/* 1st line number of replacement */
53246074Sgaborstatic LINENUM	p_ptrn_lines;	/* # lines in pattern */
54246074Sgaborstatic LINENUM	p_repl_lines;	/* # lines in replacement text */
55246074Sgaborstatic LINENUM	p_end = -1;	/* last line in hunk */
56246074Sgaborstatic LINENUM	p_max;		/* max allowed value of p_end */
57246074Sgaborstatic LINENUM	p_context = 3;	/* # of context lines */
58246074Sgaborstatic LINENUM	p_input_line = 0;	/* current line # from patch file */
59246074Sgaborstatic char	**p_line = NULL;/* the text of the hunk */
60267490Spfgstatic unsigned short	*p_len = NULL; /* length of each line */
61246074Sgaborstatic char	*p_char = NULL;	/* +, -, and ! */
62246074Sgaborstatic int	hunkmax = INITHUNKMAX;	/* size of above arrays to begin with */
63246074Sgaborstatic int	p_indent;	/* indent to patch */
64275553Spfgstatic off_t	p_base;		/* where to intuit this time */
65246074Sgaborstatic LINENUM	p_bline;	/* line # of p_base */
66275553Spfgstatic off_t	p_start;	/* where intuit found a patch */
67246074Sgaborstatic LINENUM	p_sline;	/* and the line number for it */
68246074Sgaborstatic LINENUM	p_hunk_beg;	/* line number of current hunk */
69246074Sgaborstatic LINENUM	p_efake = -1;	/* end of faked up lines--don't free */
70246074Sgaborstatic LINENUM	p_bfake = -1;	/* beg of faked up lines */
71246074Sgaborstatic FILE	*pfp = NULL;	/* patch file pointer */
72246074Sgaborstatic char	*bestguess = NULL;	/* guess at correct filename */
73246074Sgabor
74246074Sgaborstatic void	grow_hunkmax(void);
75246074Sgaborstatic int	intuit_diff_type(void);
76275553Spfgstatic void	next_intuit_at(off_t, LINENUM);
77275553Spfgstatic void	skip_to(off_t, LINENUM);
78246074Sgaborstatic size_t	pgets(bool _do_indent);
79246074Sgaborstatic char	*best_name(const struct file_name *, bool);
80246074Sgaborstatic char	*posix_name(const struct file_name *, bool);
81246074Sgaborstatic size_t	num_components(const char *);
82275612Spfgstatic LINENUM	strtolinenum(char *, char **);
83246074Sgabor
84246074Sgabor/*
85246074Sgabor * Prepare to look for the next patch in the patch file.
86246074Sgabor */
87246074Sgaborvoid
88246074Sgaborre_patch(void)
89246074Sgabor{
90246074Sgabor	p_first = 0;
91246074Sgabor	p_newfirst = 0;
92246074Sgabor	p_ptrn_lines = 0;
93246074Sgabor	p_repl_lines = 0;
94246074Sgabor	p_end = (LINENUM) - 1;
95246074Sgabor	p_max = 0;
96246074Sgabor	p_indent = 0;
97246074Sgabor}
98246074Sgabor
99246074Sgabor/*
100246074Sgabor * Open the patch file at the beginning of time.
101246074Sgabor */
102246074Sgaborvoid
103246074Sgaboropen_patch_file(const char *filename)
104246074Sgabor{
105246074Sgabor	struct stat filestat;
106252636Sobrien	int nr, nw;
107246074Sgabor
108246074Sgabor	if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
109246074Sgabor		pfp = fopen(TMPPATNAME, "w");
110246074Sgabor		if (pfp == NULL)
111246074Sgabor			pfatal("can't create %s", TMPPATNAME);
112252636Sobrien		while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
113252636Sobrien			nw = fwrite(buf, 1, nr, pfp);
114252636Sobrien			if (nr != nw)
115252636Sobrien				pfatal("write error to %s", TMPPATNAME);
116252636Sobrien		}
117246074Sgabor		if (ferror(pfp) || fclose(pfp))
118246074Sgabor			pfatal("can't write %s", TMPPATNAME);
119246074Sgabor		filename = TMPPATNAME;
120246074Sgabor	}
121246074Sgabor	pfp = fopen(filename, "r");
122246074Sgabor	if (pfp == NULL)
123246074Sgabor		pfatal("patch file %s not found", filename);
124275553Spfg	if (fstat(fileno(pfp), &filestat))
125275553Spfg		pfatal("can't stat %s", filename);
126246074Sgabor	p_filesize = filestat.st_size;
127275553Spfg	next_intuit_at(0, 1L);	/* start at the beginning */
128246074Sgabor	set_hunkmax();
129246074Sgabor}
130246074Sgabor
131246074Sgabor/*
132246074Sgabor * Make sure our dynamically realloced tables are malloced to begin with.
133246074Sgabor */
134246074Sgaborvoid
135246074Sgaborset_hunkmax(void)
136246074Sgabor{
137246074Sgabor	if (p_line == NULL)
138267464Spfg		p_line = malloc(hunkmax * sizeof(char *));
139246074Sgabor	if (p_len == NULL)
140267490Spfg		p_len = malloc(hunkmax * sizeof(unsigned short));
141246074Sgabor	if (p_char == NULL)
142267464Spfg		p_char = malloc(hunkmax * sizeof(char));
143246074Sgabor}
144246074Sgabor
145246074Sgabor/*
146246074Sgabor * Enlarge the arrays containing the current hunk of patch.
147246074Sgabor */
148246074Sgaborstatic void
149246074Sgaborgrow_hunkmax(void)
150246074Sgabor{
151267464Spfg	int new_hunkmax = hunkmax * 2;
152246074Sgabor
153246074Sgabor	if (p_line == NULL || p_len == NULL || p_char == NULL)
154246074Sgabor		fatal("Internal memory allocation error\n");
155246074Sgabor
156267464Spfg	p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
157267490Spfg	p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
158267464Spfg	p_char = reallocf(p_char, new_hunkmax * sizeof(char));
159246074Sgabor
160246074Sgabor	if (p_line != NULL && p_len != NULL && p_char != NULL) {
161246074Sgabor		hunkmax = new_hunkmax;
162246074Sgabor		return;
163246074Sgabor	}
164246074Sgabor
165246074Sgabor	if (!using_plan_a)
166246074Sgabor		fatal("out of memory\n");
167246074Sgabor	out_of_mem = true;	/* whatever is null will be allocated again */
168246074Sgabor				/* from within plan_a(), of all places */
169246074Sgabor}
170246074Sgabor
171246074Sgabor/* True if the remainder of the patch file contains a diff of some sort. */
172246074Sgabor
173246074Sgaborbool
174246074Sgaborthere_is_another_patch(void)
175246074Sgabor{
176246074Sgabor	bool exists = false;
177246074Sgabor
178275553Spfg	if (p_base != 0 && p_base >= p_filesize) {
179246074Sgabor		if (verbose)
180246074Sgabor			say("done\n");
181246074Sgabor		return false;
182246074Sgabor	}
183246074Sgabor	if (verbose)
184246074Sgabor		say("Hmm...");
185246074Sgabor	diff_type = intuit_diff_type();
186246074Sgabor	if (!diff_type) {
187275553Spfg		if (p_base != 0) {
188246074Sgabor			if (verbose)
189246074Sgabor				say("  Ignoring the trailing garbage.\ndone\n");
190246074Sgabor		} else
191246074Sgabor			say("  I can't seem to find a patch in there anywhere.\n");
192246074Sgabor		return false;
193246074Sgabor	}
194246074Sgabor	if (verbose)
195246074Sgabor		say("  %sooks like %s to me...\n",
196275553Spfg		    (p_base == 0 ? "L" : "The next patch l"),
197246074Sgabor		    diff_type == UNI_DIFF ? "a unified diff" :
198246074Sgabor		    diff_type == CONTEXT_DIFF ? "a context diff" :
199246074Sgabor		diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
200246074Sgabor		    diff_type == NORMAL_DIFF ? "a normal diff" :
201246074Sgabor		    "an ed script");
202246074Sgabor	if (p_indent && verbose)
203246074Sgabor		say("(Patch is indented %d space%s.)\n", p_indent,
204246074Sgabor		    p_indent == 1 ? "" : "s");
205246074Sgabor	skip_to(p_start, p_sline);
206246074Sgabor	while (filearg[0] == NULL) {
207246074Sgabor		if (force || batch) {
208246074Sgabor			say("No file to patch.  Skipping...\n");
209276218Spfg			filearg[0] = xstrdup(bestguess);
210246074Sgabor			skip_rest_of_patch = true;
211246074Sgabor			return true;
212246074Sgabor		}
213246074Sgabor		ask("File to patch: ");
214246074Sgabor		if (*buf != '\n') {
215246074Sgabor			free(bestguess);
216276218Spfg			bestguess = xstrdup(buf);
217246074Sgabor			filearg[0] = fetchname(buf, &exists, 0);
218246074Sgabor		}
219246074Sgabor		if (!exists) {
220246074Sgabor			ask("No file found--skip this patch? [n] ");
221246074Sgabor			if (*buf != 'y')
222246074Sgabor				continue;
223246074Sgabor			if (verbose)
224246074Sgabor				say("Skipping patch...\n");
225246074Sgabor			free(filearg[0]);
226246074Sgabor			filearg[0] = fetchname(bestguess, &exists, 0);
227246074Sgabor			skip_rest_of_patch = true;
228246074Sgabor			return true;
229246074Sgabor		}
230246074Sgabor	}
231246074Sgabor	return true;
232246074Sgabor}
233246074Sgabor
234246074Sgaborstatic void
235246074Sgaborp4_fetchname(struct file_name *name, char *str)
236246074Sgabor{
237246074Sgabor	char *t, *h;
238246074Sgabor
239246074Sgabor	/* Skip leading whitespace. */
240246074Sgabor	while (isspace((unsigned char)*str))
241246074Sgabor		str++;
242246074Sgabor
243246074Sgabor	/* Remove the file revision number. */
244246074Sgabor	for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
245246074Sgabor		if (*t == '#')
246246074Sgabor			h = t;
247246074Sgabor	if (h != NULL)
248246074Sgabor		*h = '\0';
249246074Sgabor
250246074Sgabor	name->path = fetchname(str, &name->exists, strippath);
251246074Sgabor}
252246074Sgabor
253246074Sgabor/* Determine what kind of diff is in the remaining part of the patch file. */
254246074Sgabor
255246074Sgaborstatic int
256246074Sgaborintuit_diff_type(void)
257246074Sgabor{
258275553Spfg	off_t	this_line = 0, previous_line;
259275553Spfg	off_t	first_command_line = -1;
260246074Sgabor	LINENUM	fcl_line = -1;
261246074Sgabor	bool	last_line_was_command = false, this_is_a_command = false;
262246074Sgabor	bool	stars_last_line = false, stars_this_line = false;
263246074Sgabor	char	*s, *t;
264246074Sgabor	int	indent, retval;
265246074Sgabor	struct file_name names[MAX_FILE];
266246074Sgabor
267246074Sgabor	memset(names, 0, sizeof(names));
268246074Sgabor	ok_to_create_file = false;
269275553Spfg	fseeko(pfp, p_base, SEEK_SET);
270246074Sgabor	p_input_line = p_bline - 1;
271246074Sgabor	for (;;) {
272246074Sgabor		previous_line = this_line;
273246074Sgabor		last_line_was_command = this_is_a_command;
274246074Sgabor		stars_last_line = stars_this_line;
275275553Spfg		this_line = ftello(pfp);
276246074Sgabor		indent = 0;
277246074Sgabor		p_input_line++;
278246074Sgabor		if (pgets(false) == 0) {
279275553Spfg			if (first_command_line >= 0) {
280246074Sgabor				/* nothing but deletes!? */
281246074Sgabor				p_start = first_command_line;
282246074Sgabor				p_sline = fcl_line;
283246074Sgabor				retval = ED_DIFF;
284246074Sgabor				goto scan_exit;
285246074Sgabor			} else {
286246074Sgabor				p_start = this_line;
287246074Sgabor				p_sline = p_input_line;
288246074Sgabor				retval = 0;
289246074Sgabor				goto scan_exit;
290246074Sgabor			}
291246074Sgabor		}
292246074Sgabor		for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
293246074Sgabor			if (*s == '\t')
294246074Sgabor				indent += 8 - (indent % 8);
295246074Sgabor			else
296246074Sgabor				indent++;
297246074Sgabor		}
298246074Sgabor		for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
299246074Sgabor			;
300246074Sgabor		this_is_a_command = (isdigit((unsigned char)*s) &&
301246074Sgabor		    (*t == 'd' || *t == 'c' || *t == 'a'));
302275553Spfg		if (first_command_line < 0 && this_is_a_command) {
303246074Sgabor			first_command_line = this_line;
304246074Sgabor			fcl_line = p_input_line;
305246074Sgabor			p_indent = indent;	/* assume this for now */
306246074Sgabor		}
307246074Sgabor		if (!stars_last_line && strnEQ(s, "*** ", 4))
308246074Sgabor			names[OLD_FILE].path = fetchname(s + 4,
309246074Sgabor			    &names[OLD_FILE].exists, strippath);
310246074Sgabor		else if (strnEQ(s, "--- ", 4))
311246074Sgabor			names[NEW_FILE].path = fetchname(s + 4,
312246074Sgabor			    &names[NEW_FILE].exists, strippath);
313246074Sgabor		else if (strnEQ(s, "+++ ", 4))
314246074Sgabor			/* pretend it is the old name */
315246074Sgabor			names[OLD_FILE].path = fetchname(s + 4,
316246074Sgabor			    &names[OLD_FILE].exists, strippath);
317246074Sgabor		else if (strnEQ(s, "Index:", 6))
318246074Sgabor			names[INDEX_FILE].path = fetchname(s + 6,
319246074Sgabor			    &names[INDEX_FILE].exists, strippath);
320246074Sgabor		else if (strnEQ(s, "Prereq:", 7)) {
321246074Sgabor			for (t = s + 7; isspace((unsigned char)*t); t++)
322246074Sgabor				;
323276218Spfg			revision = xstrdup(t);
324275582Spfg			for (t = revision;
325275582Spfg			     *t && !isspace((unsigned char)*t); t++)
326246074Sgabor				;
327246074Sgabor			*t = '\0';
328246074Sgabor			if (*revision == '\0') {
329246074Sgabor				free(revision);
330246074Sgabor				revision = NULL;
331246074Sgabor			}
332246074Sgabor		} else if (strnEQ(s, "==== ", 5)) {
333246074Sgabor			/* Perforce-style diffs. */
334246074Sgabor			if ((t = strstr(s + 5, " - ")) != NULL)
335246074Sgabor				p4_fetchname(&names[NEW_FILE], t + 3);
336246074Sgabor			p4_fetchname(&names[OLD_FILE], s + 5);
337246074Sgabor		}
338246074Sgabor		if ((!diff_type || diff_type == ED_DIFF) &&
339275553Spfg		    first_command_line >= 0 &&
340246074Sgabor		    strEQ(s, ".\n")) {
341246074Sgabor			p_indent = indent;
342246074Sgabor			p_start = first_command_line;
343246074Sgabor			p_sline = fcl_line;
344246074Sgabor			retval = ED_DIFF;
345246074Sgabor			goto scan_exit;
346246074Sgabor		}
347246074Sgabor		if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
348246074Sgabor			if (strnEQ(s + 4, "0,0", 3))
349246074Sgabor				ok_to_create_file = true;
350246074Sgabor			p_indent = indent;
351246074Sgabor			p_start = this_line;
352246074Sgabor			p_sline = p_input_line;
353246074Sgabor			retval = UNI_DIFF;
354246074Sgabor			goto scan_exit;
355246074Sgabor		}
356246074Sgabor		stars_this_line = strnEQ(s, "********", 8);
357246074Sgabor		if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
358246074Sgabor		    strnEQ(s, "*** ", 4)) {
359275612Spfg			if (strtolinenum(s + 4, &s) == 0)
360246074Sgabor				ok_to_create_file = true;
361246074Sgabor			/*
362246074Sgabor			 * If this is a new context diff the character just
363275553Spfg			 * at the end of the line is a '*'.
364246074Sgabor			 */
365275553Spfg			while (*s && *s != '\n')
366246074Sgabor				s++;
367246074Sgabor			p_indent = indent;
368246074Sgabor			p_start = previous_line;
369246074Sgabor			p_sline = p_input_line - 1;
370246074Sgabor			retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
371246074Sgabor			goto scan_exit;
372246074Sgabor		}
373246074Sgabor		if ((!diff_type || diff_type == NORMAL_DIFF) &&
374246074Sgabor		    last_line_was_command &&
375246074Sgabor		    (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
376246074Sgabor			p_start = previous_line;
377246074Sgabor			p_sline = p_input_line - 1;
378246074Sgabor			p_indent = indent;
379246074Sgabor			retval = NORMAL_DIFF;
380246074Sgabor			goto scan_exit;
381246074Sgabor		}
382246074Sgabor	}
383246074Sgaborscan_exit:
384246074Sgabor	if (retval == UNI_DIFF) {
385246074Sgabor		/* unswap old and new */
386246074Sgabor		struct file_name tmp = names[OLD_FILE];
387246074Sgabor		names[OLD_FILE] = names[NEW_FILE];
388246074Sgabor		names[NEW_FILE] = tmp;
389246074Sgabor	}
390246074Sgabor	if (filearg[0] == NULL) {
391246074Sgabor		if (posix)
392246074Sgabor			filearg[0] = posix_name(names, ok_to_create_file);
393246074Sgabor		else {
394246074Sgabor			/* Ignore the Index: name for context diffs, like GNU */
395246074Sgabor			if (names[OLD_FILE].path != NULL ||
396246074Sgabor			    names[NEW_FILE].path != NULL) {
397246074Sgabor				free(names[INDEX_FILE].path);
398246074Sgabor				names[INDEX_FILE].path = NULL;
399246074Sgabor			}
400246074Sgabor			filearg[0] = best_name(names, ok_to_create_file);
401246074Sgabor		}
402246074Sgabor	}
403246074Sgabor
404246074Sgabor	free(bestguess);
405246074Sgabor	bestguess = NULL;
406246074Sgabor	if (filearg[0] != NULL)
407276218Spfg		bestguess = xstrdup(filearg[0]);
408246074Sgabor	else if (!ok_to_create_file) {
409246074Sgabor		/*
410246074Sgabor		 * We don't want to create a new file but we need a
411246074Sgabor		 * filename to set bestguess.  Avoid setting filearg[0]
412246074Sgabor		 * so the file is not created automatically.
413246074Sgabor		 */
414246074Sgabor		if (posix)
415246074Sgabor			bestguess = posix_name(names, true);
416246074Sgabor		else
417246074Sgabor			bestguess = best_name(names, true);
418246074Sgabor	}
419246074Sgabor	free(names[OLD_FILE].path);
420246074Sgabor	free(names[NEW_FILE].path);
421246074Sgabor	free(names[INDEX_FILE].path);
422246074Sgabor	return retval;
423246074Sgabor}
424246074Sgabor
425246074Sgabor/*
426246074Sgabor * Remember where this patch ends so we know where to start up again.
427246074Sgabor */
428246074Sgaborstatic void
429275553Spfgnext_intuit_at(off_t file_pos, LINENUM file_line)
430246074Sgabor{
431246074Sgabor	p_base = file_pos;
432246074Sgabor	p_bline = file_line;
433246074Sgabor}
434246074Sgabor
435246074Sgabor/*
436275553Spfg * Basically a verbose fseeko() to the actual diff listing.
437246074Sgabor */
438246074Sgaborstatic void
439275553Spfgskip_to(off_t file_pos, LINENUM file_line)
440246074Sgabor{
441246074Sgabor	size_t	len;
442246074Sgabor
443246074Sgabor	if (p_base > file_pos)
444275553Spfg		fatal("Internal error: seek %lld>%lld\n",
445275553Spfg		   (long long)p_base, (long long)file_pos);
446246074Sgabor	if (verbose && p_base < file_pos) {
447275553Spfg		fseeko(pfp, p_base, SEEK_SET);
448246074Sgabor		say("The text leading up to this was:\n--------------------------\n");
449275553Spfg		while (ftello(pfp) < file_pos) {
450246074Sgabor			len = pgets(false);
451246074Sgabor			if (len == 0)
452246074Sgabor				fatal("Unexpected end of file\n");
453246074Sgabor			say("|%s", buf);
454246074Sgabor		}
455246074Sgabor		say("--------------------------\n");
456246074Sgabor	} else
457275553Spfg		fseeko(pfp, file_pos, SEEK_SET);
458246074Sgabor	p_input_line = file_line - 1;
459246074Sgabor}
460246074Sgabor
461246074Sgabor/* Make this a function for better debugging.  */
462246074Sgaborstatic void
463246074Sgabormalformed(void)
464246074Sgabor{
465246074Sgabor	fatal("malformed patch at line %ld: %s", p_input_line, buf);
466246074Sgabor	/* about as informative as "Syntax error" in C */
467246074Sgabor}
468246074Sgabor
469246074Sgabor/*
470246074Sgabor * True if the line has been discarded (i.e. it is a line saying
471246074Sgabor *  "\ No newline at end of file".)
472246074Sgabor */
473246074Sgaborstatic bool
474246074Sgaborremove_special_line(void)
475246074Sgabor{
476246074Sgabor	int	c;
477246074Sgabor
478246074Sgabor	c = fgetc(pfp);
479246074Sgabor	if (c == '\\') {
480246074Sgabor		do {
481246074Sgabor			c = fgetc(pfp);
482246074Sgabor		} while (c != EOF && c != '\n');
483246074Sgabor
484246074Sgabor		return true;
485246074Sgabor	}
486246074Sgabor	if (c != EOF)
487275553Spfg		fseeko(pfp, -1, SEEK_CUR);
488246074Sgabor
489246074Sgabor	return false;
490246074Sgabor}
491246074Sgabor
492246074Sgabor/*
493246074Sgabor * True if there is more of the current diff listing to process.
494246074Sgabor */
495246074Sgaborbool
496246074Sgaboranother_hunk(void)
497246074Sgabor{
498275553Spfg	off_t	line_beginning;			/* file pos of the current line */
499246074Sgabor	LINENUM	repl_beginning;			/* index of --- line */
500246074Sgabor	LINENUM	fillcnt;			/* #lines of missing ptrn or repl */
501246074Sgabor	LINENUM	fillsrc;			/* index of first line to copy */
502246074Sgabor	LINENUM	filldst;			/* index of first missing line */
503246074Sgabor	bool	ptrn_spaces_eaten;		/* ptrn was slightly misformed */
504246074Sgabor	bool	repl_could_be_missing;		/* no + or ! lines in this hunk */
505246074Sgabor	bool	repl_missing;			/* we are now backtracking */
506275553Spfg	off_t	repl_backtrack_position;	/* file pos of first repl line */
507246074Sgabor	LINENUM	repl_patch_line;		/* input line number for same */
508246074Sgabor	LINENUM	ptrn_copiable;			/* # of copiable lines in ptrn */
509246074Sgabor	char	*s;
510246074Sgabor	size_t	len;
511246074Sgabor	int	context = 0;
512246074Sgabor
513246074Sgabor	while (p_end >= 0) {
514246074Sgabor		if (p_end == p_efake)
515246074Sgabor			p_end = p_bfake;	/* don't free twice */
516246074Sgabor		else
517246074Sgabor			free(p_line[p_end]);
518246074Sgabor		p_end--;
519246074Sgabor	}
520246074Sgabor	p_efake = -1;
521246074Sgabor
522246074Sgabor	p_max = hunkmax;	/* gets reduced when --- found */
523246074Sgabor	if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
524275553Spfg		line_beginning = ftello(pfp);
525246074Sgabor		repl_beginning = 0;
526246074Sgabor		fillcnt = 0;
527246074Sgabor		fillsrc = 0;
528246074Sgabor		filldst = 0;
529246074Sgabor		ptrn_spaces_eaten = false;
530246074Sgabor		repl_could_be_missing = true;
531246074Sgabor		repl_missing = false;
532246074Sgabor		repl_backtrack_position = 0;
533246074Sgabor		repl_patch_line = 0;
534246074Sgabor		ptrn_copiable = 0;
535246074Sgabor
536246074Sgabor		len = pgets(true);
537246074Sgabor		p_input_line++;
538246074Sgabor		if (len == 0 || strnNE(buf, "********", 8)) {
539246074Sgabor			next_intuit_at(line_beginning, p_input_line);
540246074Sgabor			return false;
541246074Sgabor		}
542246074Sgabor		p_context = 100;
543246074Sgabor		p_hunk_beg = p_input_line + 1;
544246074Sgabor		while (p_end < p_max) {
545275553Spfg			line_beginning = ftello(pfp);
546246074Sgabor			len = pgets(true);
547246074Sgabor			p_input_line++;
548246074Sgabor			if (len == 0) {
549246074Sgabor				if (p_max - p_end < 4) {
550246074Sgabor					/* assume blank lines got chopped */
551246074Sgabor					strlcpy(buf, "  \n", buf_size);
552246074Sgabor				} else {
553246074Sgabor					if (repl_beginning && repl_could_be_missing) {
554246074Sgabor						repl_missing = true;
555246074Sgabor						goto hunk_done;
556246074Sgabor					}
557246074Sgabor					fatal("unexpected end of file in patch\n");
558246074Sgabor				}
559246074Sgabor			}
560246074Sgabor			p_end++;
561246074Sgabor			if (p_end >= hunkmax)
562246074Sgabor				fatal("Internal error: hunk larger than hunk "
563246074Sgabor				    "buffer size");
564246074Sgabor			p_char[p_end] = *buf;
565246074Sgabor			p_line[p_end] = NULL;
566246074Sgabor			switch (*buf) {
567246074Sgabor			case '*':
568246074Sgabor				if (strnEQ(buf, "********", 8)) {
569246074Sgabor					if (repl_beginning && repl_could_be_missing) {
570246074Sgabor						repl_missing = true;
571246074Sgabor						goto hunk_done;
572246074Sgabor					} else
573246074Sgabor						fatal("unexpected end of hunk "
574246074Sgabor						    "at line %ld\n",
575246074Sgabor						    p_input_line);
576246074Sgabor				}
577246074Sgabor				if (p_end != 0) {
578246074Sgabor					if (repl_beginning && repl_could_be_missing) {
579246074Sgabor						repl_missing = true;
580246074Sgabor						goto hunk_done;
581246074Sgabor					}
582246074Sgabor					fatal("unexpected *** at line %ld: %s",
583246074Sgabor					    p_input_line, buf);
584246074Sgabor				}
585246074Sgabor				context = 0;
586246074Sgabor				p_line[p_end] = savestr(buf);
587246074Sgabor				if (out_of_mem) {
588246074Sgabor					p_end--;
589246074Sgabor					return false;
590246074Sgabor				}
591275582Spfg				for (s = buf;
592275582Spfg				     *s && !isdigit((unsigned char)*s); s++)
593246074Sgabor					;
594246074Sgabor				if (!*s)
595246074Sgabor					malformed();
596246074Sgabor				if (strnEQ(s, "0,0", 3))
597246074Sgabor					memmove(s, s + 2, strlen(s + 2) + 1);
598275612Spfg				p_first = strtolinenum(s, &s);
599246074Sgabor				if (*s == ',') {
600275582Spfg					for (;
601275582Spfg					     *s && !isdigit((unsigned char)*s); s++)
602246074Sgabor						;
603246074Sgabor					if (!*s)
604246074Sgabor						malformed();
605275612Spfg					p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
606275612Spfg					if (p_ptrn_lines < 0)
607275612Spfg						malformed();
608246074Sgabor				} else if (p_first)
609246074Sgabor					p_ptrn_lines = 1;
610246074Sgabor				else {
611246074Sgabor					p_ptrn_lines = 0;
612246074Sgabor					p_first = 1;
613246074Sgabor				}
614275612Spfg				if (p_first >= LINENUM_MAX - p_ptrn_lines ||
615275612Spfg				    p_ptrn_lines >= LINENUM_MAX - 6)
616275612Spfg					malformed();
617246074Sgabor
618246074Sgabor				/* we need this much at least */
619246074Sgabor				p_max = p_ptrn_lines + 6;
620246074Sgabor				while (p_max >= hunkmax)
621246074Sgabor					grow_hunkmax();
622246074Sgabor				p_max = hunkmax;
623246074Sgabor				break;
624246074Sgabor			case '-':
625246074Sgabor				if (buf[1] == '-') {
626246074Sgabor					if (repl_beginning ||
627246074Sgabor					    (p_end != p_ptrn_lines + 1 +
628246074Sgabor					    (p_char[p_end - 1] == '\n'))) {
629246074Sgabor						if (p_end == 1) {
630246074Sgabor							/*
631246074Sgabor							 * `old' lines were omitted;
632246074Sgabor							 * set up to fill them in
633246074Sgabor							 * from 'new' context lines.
634246074Sgabor							 */
635246074Sgabor							p_end = p_ptrn_lines + 1;
636246074Sgabor							fillsrc = p_end + 1;
637246074Sgabor							filldst = 1;
638246074Sgabor							fillcnt = p_ptrn_lines;
639246074Sgabor						} else {
640246074Sgabor							if (repl_beginning) {
641246074Sgabor								if (repl_could_be_missing) {
642246074Sgabor									repl_missing = true;
643246074Sgabor									goto hunk_done;
644246074Sgabor								}
645246074Sgabor								fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
646246074Sgabor								    p_input_line, p_hunk_beg + repl_beginning);
647246074Sgabor							} else {
648246074Sgabor								fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
649246074Sgabor								    (p_end <= p_ptrn_lines
650246074Sgabor								    ? "Premature"
651246074Sgabor								    : "Overdue"),
652246074Sgabor								    p_input_line, p_hunk_beg);
653246074Sgabor							}
654246074Sgabor						}
655246074Sgabor					}
656246074Sgabor					repl_beginning = p_end;
657275553Spfg					repl_backtrack_position = ftello(pfp);
658246074Sgabor					repl_patch_line = p_input_line;
659246074Sgabor					p_line[p_end] = savestr(buf);
660246074Sgabor					if (out_of_mem) {
661246074Sgabor						p_end--;
662246074Sgabor						return false;
663246074Sgabor					}
664246074Sgabor					p_char[p_end] = '=';
665246074Sgabor					for (s = buf; *s && !isdigit((unsigned char)*s); s++)
666246074Sgabor						;
667246074Sgabor					if (!*s)
668246074Sgabor						malformed();
669275612Spfg					p_newfirst = strtolinenum(s, &s);
670246074Sgabor					if (*s == ',') {
671246074Sgabor						for (; *s && !isdigit((unsigned char)*s); s++)
672246074Sgabor							;
673246074Sgabor						if (!*s)
674246074Sgabor							malformed();
675275612Spfg						p_repl_lines = strtolinenum(s, &s) -
676246074Sgabor						    p_newfirst + 1;
677275612Spfg						if (p_repl_lines < 0)
678275612Spfg							malformed();
679246074Sgabor					} else if (p_newfirst)
680246074Sgabor						p_repl_lines = 1;
681246074Sgabor					else {
682246074Sgabor						p_repl_lines = 0;
683246074Sgabor						p_newfirst = 1;
684246074Sgabor					}
685275612Spfg					if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
686275612Spfg					    p_repl_lines >= LINENUM_MAX - p_end)
687275612Spfg						malformed();
688246074Sgabor					p_max = p_repl_lines + p_end;
689246074Sgabor					if (p_max > MAXHUNKSIZE)
690246074Sgabor						fatal("hunk too large (%ld lines) at line %ld: %s",
691246074Sgabor						    p_max, p_input_line, buf);
692246074Sgabor					while (p_max >= hunkmax)
693246074Sgabor						grow_hunkmax();
694246074Sgabor					if (p_repl_lines != ptrn_copiable &&
695246074Sgabor					    (p_context != 0 || p_repl_lines != 1))
696246074Sgabor						repl_could_be_missing = false;
697246074Sgabor					break;
698246074Sgabor				}
699246074Sgabor				goto change_line;
700246074Sgabor			case '+':
701246074Sgabor			case '!':
702246074Sgabor				repl_could_be_missing = false;
703246074Sgabor		change_line:
704246074Sgabor				if (buf[1] == '\n' && canonicalize)
705246074Sgabor					strlcpy(buf + 1, " \n", buf_size - 1);
706275582Spfg				if (!isspace((unsigned char)buf[1]) &&
707275582Spfg				    buf[1] != '>' && buf[1] != '<' &&
708246074Sgabor				    repl_beginning && repl_could_be_missing) {
709246074Sgabor					repl_missing = true;
710246074Sgabor					goto hunk_done;
711246074Sgabor				}
712246074Sgabor				if (context >= 0) {
713246074Sgabor					if (context < p_context)
714246074Sgabor						p_context = context;
715246074Sgabor					context = -1000;
716246074Sgabor				}
717246074Sgabor				p_line[p_end] = savestr(buf + 2);
718246074Sgabor				if (out_of_mem) {
719246074Sgabor					p_end--;
720246074Sgabor					return false;
721246074Sgabor				}
722246074Sgabor				if (p_end == p_ptrn_lines) {
723246074Sgabor					if (remove_special_line()) {
724246074Sgabor						int	l;
725246074Sgabor
726246074Sgabor						l = strlen(p_line[p_end]) - 1;
727246074Sgabor						(p_line[p_end])[l] = 0;
728246074Sgabor					}
729246074Sgabor				}
730246074Sgabor				break;
731246074Sgabor			case '\t':
732246074Sgabor			case '\n':	/* assume the 2 spaces got eaten */
733246074Sgabor				if (repl_beginning && repl_could_be_missing &&
734246074Sgabor				    (!ptrn_spaces_eaten ||
735246074Sgabor				    diff_type == NEW_CONTEXT_DIFF)) {
736246074Sgabor					repl_missing = true;
737246074Sgabor					goto hunk_done;
738246074Sgabor				}
739246074Sgabor				p_line[p_end] = savestr(buf);
740246074Sgabor				if (out_of_mem) {
741246074Sgabor					p_end--;
742246074Sgabor					return false;
743246074Sgabor				}
744246074Sgabor				if (p_end != p_ptrn_lines + 1) {
745246074Sgabor					ptrn_spaces_eaten |= (repl_beginning != 0);
746246074Sgabor					context++;
747246074Sgabor					if (!repl_beginning)
748246074Sgabor						ptrn_copiable++;
749246074Sgabor					p_char[p_end] = ' ';
750246074Sgabor				}
751246074Sgabor				break;
752246074Sgabor			case ' ':
753246074Sgabor				if (!isspace((unsigned char)buf[1]) &&
754246074Sgabor				    repl_beginning && repl_could_be_missing) {
755246074Sgabor					repl_missing = true;
756246074Sgabor					goto hunk_done;
757246074Sgabor				}
758246074Sgabor				context++;
759246074Sgabor				if (!repl_beginning)
760246074Sgabor					ptrn_copiable++;
761246074Sgabor				p_line[p_end] = savestr(buf + 2);
762246074Sgabor				if (out_of_mem) {
763246074Sgabor					p_end--;
764246074Sgabor					return false;
765246074Sgabor				}
766246074Sgabor				break;
767246074Sgabor			default:
768246074Sgabor				if (repl_beginning && repl_could_be_missing) {
769246074Sgabor					repl_missing = true;
770246074Sgabor					goto hunk_done;
771246074Sgabor				}
772246074Sgabor				malformed();
773246074Sgabor			}
774246074Sgabor			/* set up p_len for strncmp() so we don't have to */
775246074Sgabor			/* assume null termination */
776246074Sgabor			if (p_line[p_end])
777246074Sgabor				p_len[p_end] = strlen(p_line[p_end]);
778246074Sgabor			else
779246074Sgabor				p_len[p_end] = 0;
780246074Sgabor		}
781246074Sgabor
782246074Sgaborhunk_done:
783246074Sgabor		if (p_end >= 0 && !repl_beginning)
784246074Sgabor			fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
785246074Sgabor
786246074Sgabor		if (repl_missing) {
787246074Sgabor
788246074Sgabor			/* reset state back to just after --- */
789246074Sgabor			p_input_line = repl_patch_line;
790246074Sgabor			for (p_end--; p_end > repl_beginning; p_end--)
791246074Sgabor				free(p_line[p_end]);
792275553Spfg			fseeko(pfp, repl_backtrack_position, SEEK_SET);
793246074Sgabor
794246074Sgabor			/* redundant 'new' context lines were omitted - set */
795246074Sgabor			/* up to fill them in from the old file context */
796246074Sgabor			if (!p_context && p_repl_lines == 1) {
797246074Sgabor				p_repl_lines = 0;
798246074Sgabor				p_max--;
799246074Sgabor			}
800246074Sgabor			fillsrc = 1;
801246074Sgabor			filldst = repl_beginning + 1;
802246074Sgabor			fillcnt = p_repl_lines;
803246074Sgabor			p_end = p_max;
804246074Sgabor		} else if (!p_context && fillcnt == 1) {
805246074Sgabor			/* the first hunk was a null hunk with no context */
806246074Sgabor			/* and we were expecting one line -- fix it up. */
807246074Sgabor			while (filldst < p_end) {
808246074Sgabor				p_line[filldst] = p_line[filldst + 1];
809246074Sgabor				p_char[filldst] = p_char[filldst + 1];
810246074Sgabor				p_len[filldst] = p_len[filldst + 1];
811246074Sgabor				filldst++;
812246074Sgabor			}
813246074Sgabor#if 0
814246074Sgabor			repl_beginning--;	/* this doesn't need to be fixed */
815246074Sgabor#endif
816246074Sgabor			p_end--;
817246074Sgabor			p_first++;	/* do append rather than insert */
818246074Sgabor			fillcnt = 0;
819246074Sgabor			p_ptrn_lines = 0;
820246074Sgabor		}
821246074Sgabor		if (diff_type == CONTEXT_DIFF &&
822246074Sgabor		    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
823246074Sgabor			if (verbose)
824246074Sgabor				say("%s\n%s\n%s\n",
825246074Sgabor				    "(Fascinating--this is really a new-style context diff but without",
826246074Sgabor				    "the telltale extra asterisks on the *** line that usually indicate",
827246074Sgabor				    "the new style...)");
828246074Sgabor			diff_type = NEW_CONTEXT_DIFF;
829246074Sgabor		}
830246074Sgabor		/* if there were omitted context lines, fill them in now */
831246074Sgabor		if (fillcnt) {
832246074Sgabor			p_bfake = filldst;	/* remember where not to free() */
833246074Sgabor			p_efake = filldst + fillcnt - 1;
834246074Sgabor			while (fillcnt-- > 0) {
835246074Sgabor				while (fillsrc <= p_end && p_char[fillsrc] != ' ')
836246074Sgabor					fillsrc++;
837246074Sgabor				if (fillsrc > p_end)
838246074Sgabor					fatal("replacement text or line numbers mangled in hunk at line %ld\n",
839246074Sgabor					    p_hunk_beg);
840246074Sgabor				p_line[filldst] = p_line[fillsrc];
841246074Sgabor				p_char[filldst] = p_char[fillsrc];
842246074Sgabor				p_len[filldst] = p_len[fillsrc];
843246074Sgabor				fillsrc++;
844246074Sgabor				filldst++;
845246074Sgabor			}
846246074Sgabor			while (fillsrc <= p_end && fillsrc != repl_beginning &&
847246074Sgabor			    p_char[fillsrc] != ' ')
848246074Sgabor				fillsrc++;
849246074Sgabor#ifdef DEBUGGING
850246074Sgabor			if (debug & 64)
851246074Sgabor				printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
852246074Sgabor				fillsrc, filldst, repl_beginning, p_end + 1);
853246074Sgabor#endif
854246074Sgabor			if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
855246074Sgabor				malformed();
856246074Sgabor			if (filldst != p_end + 1 && filldst != repl_beginning)
857246074Sgabor				malformed();
858246074Sgabor		}
859246074Sgabor		if (p_line[p_end] != NULL) {
860246074Sgabor			if (remove_special_line()) {
861246074Sgabor				p_len[p_end] -= 1;
862246074Sgabor				(p_line[p_end])[p_len[p_end]] = 0;
863246074Sgabor			}
864246074Sgabor		}
865246074Sgabor	} else if (diff_type == UNI_DIFF) {
866246074Sgabor		LINENUM	fillold;	/* index of old lines */
867246074Sgabor		LINENUM	fillnew;	/* index of new lines */
868246074Sgabor		char	ch;
869246074Sgabor
870275553Spfg		line_beginning = ftello(pfp); /* file pos of the current line */
871246074Sgabor		len = pgets(true);
872246074Sgabor		p_input_line++;
873246074Sgabor		if (len == 0 || strnNE(buf, "@@ -", 4)) {
874246074Sgabor			next_intuit_at(line_beginning, p_input_line);
875246074Sgabor			return false;
876246074Sgabor		}
877246074Sgabor		s = buf + 4;
878246074Sgabor		if (!*s)
879246074Sgabor			malformed();
880275612Spfg		p_first = strtolinenum(s, &s);
881246074Sgabor		if (*s == ',') {
882275612Spfg			p_ptrn_lines = strtolinenum(s + 1, &s);
883246074Sgabor		} else
884246074Sgabor			p_ptrn_lines = 1;
885246074Sgabor		if (*s == ' ')
886246074Sgabor			s++;
887246074Sgabor		if (*s != '+' || !*++s)
888246074Sgabor			malformed();
889275612Spfg		p_newfirst = strtolinenum(s, &s);
890246074Sgabor		if (*s == ',') {
891275612Spfg			p_repl_lines = strtolinenum(s + 1, &s);
892246074Sgabor		} else
893246074Sgabor			p_repl_lines = 1;
894246074Sgabor		if (*s == ' ')
895246074Sgabor			s++;
896246074Sgabor		if (*s != '@')
897246074Sgabor			malformed();
898275612Spfg		if (p_first >= LINENUM_MAX - p_ptrn_lines ||
899275612Spfg		    p_newfirst > LINENUM_MAX - p_repl_lines ||
900275612Spfg		    p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
901275612Spfg			malformed();
902246074Sgabor		if (!p_ptrn_lines)
903246074Sgabor			p_first++;	/* do append rather than insert */
904246074Sgabor		p_max = p_ptrn_lines + p_repl_lines + 1;
905246074Sgabor		while (p_max >= hunkmax)
906246074Sgabor			grow_hunkmax();
907246074Sgabor		fillold = 1;
908246074Sgabor		fillnew = fillold + p_ptrn_lines;
909246074Sgabor		p_end = fillnew + p_repl_lines;
910246074Sgabor		snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
911246074Sgabor		    p_first + p_ptrn_lines - 1);
912246074Sgabor		p_line[0] = savestr(buf);
913246074Sgabor		if (out_of_mem) {
914246074Sgabor			p_end = -1;
915246074Sgabor			return false;
916246074Sgabor		}
917246074Sgabor		p_char[0] = '*';
918246074Sgabor		snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
919246074Sgabor		    p_newfirst + p_repl_lines - 1);
920246074Sgabor		p_line[fillnew] = savestr(buf);
921246074Sgabor		if (out_of_mem) {
922246074Sgabor			p_end = 0;
923246074Sgabor			return false;
924246074Sgabor		}
925246074Sgabor		p_char[fillnew++] = '=';
926246074Sgabor		p_context = 100;
927246074Sgabor		context = 0;
928246074Sgabor		p_hunk_beg = p_input_line + 1;
929246074Sgabor		while (fillold <= p_ptrn_lines || fillnew <= p_end) {
930275553Spfg			line_beginning = ftello(pfp);
931246074Sgabor			len = pgets(true);
932246074Sgabor			p_input_line++;
933246074Sgabor			if (len == 0) {
934246074Sgabor				if (p_max - fillnew < 3) {
935246074Sgabor					/* assume blank lines got chopped */
936246074Sgabor					strlcpy(buf, " \n", buf_size);
937246074Sgabor				} else {
938246074Sgabor					fatal("unexpected end of file in patch\n");
939246074Sgabor				}
940246074Sgabor			}
941246074Sgabor			if (*buf == '\t' || *buf == '\n') {
942246074Sgabor				ch = ' ';	/* assume the space got eaten */
943246074Sgabor				s = savestr(buf);
944246074Sgabor			} else {
945246074Sgabor				ch = *buf;
946246074Sgabor				s = savestr(buf + 1);
947246074Sgabor			}
948246074Sgabor			if (out_of_mem) {
949246074Sgabor				while (--fillnew > p_ptrn_lines)
950246074Sgabor					free(p_line[fillnew]);
951246074Sgabor				p_end = fillold - 1;
952246074Sgabor				return false;
953246074Sgabor			}
954246074Sgabor			switch (ch) {
955246074Sgabor			case '-':
956246074Sgabor				if (fillold > p_ptrn_lines) {
957246074Sgabor					free(s);
958246074Sgabor					p_end = fillnew - 1;
959246074Sgabor					malformed();
960246074Sgabor				}
961246074Sgabor				p_char[fillold] = ch;
962246074Sgabor				p_line[fillold] = s;
963246074Sgabor				p_len[fillold++] = strlen(s);
964246074Sgabor				if (fillold > p_ptrn_lines) {
965246074Sgabor					if (remove_special_line()) {
966246074Sgabor						p_len[fillold - 1] -= 1;
967246074Sgabor						s[p_len[fillold - 1]] = 0;
968246074Sgabor					}
969246074Sgabor				}
970246074Sgabor				break;
971246074Sgabor			case '=':
972246074Sgabor				ch = ' ';
973246074Sgabor				/* FALL THROUGH */
974246074Sgabor			case ' ':
975246074Sgabor				if (fillold > p_ptrn_lines) {
976246074Sgabor					free(s);
977246074Sgabor					while (--fillnew > p_ptrn_lines)
978246074Sgabor						free(p_line[fillnew]);
979246074Sgabor					p_end = fillold - 1;
980246074Sgabor					malformed();
981246074Sgabor				}
982246074Sgabor				context++;
983246074Sgabor				p_char[fillold] = ch;
984246074Sgabor				p_line[fillold] = s;
985246074Sgabor				p_len[fillold++] = strlen(s);
986246074Sgabor				s = savestr(s);
987246074Sgabor				if (out_of_mem) {
988246074Sgabor					while (--fillnew > p_ptrn_lines)
989246074Sgabor						free(p_line[fillnew]);
990246074Sgabor					p_end = fillold - 1;
991246074Sgabor					return false;
992246074Sgabor				}
993246074Sgabor				if (fillold > p_ptrn_lines) {
994246074Sgabor					if (remove_special_line()) {
995246074Sgabor						p_len[fillold - 1] -= 1;
996246074Sgabor						s[p_len[fillold - 1]] = 0;
997246074Sgabor					}
998246074Sgabor				}
999246074Sgabor				/* FALL THROUGH */
1000246074Sgabor			case '+':
1001246074Sgabor				if (fillnew > p_end) {
1002246074Sgabor					free(s);
1003246074Sgabor					while (--fillnew > p_ptrn_lines)
1004246074Sgabor						free(p_line[fillnew]);
1005246074Sgabor					p_end = fillold - 1;
1006246074Sgabor					malformed();
1007246074Sgabor				}
1008246074Sgabor				p_char[fillnew] = ch;
1009246074Sgabor				p_line[fillnew] = s;
1010246074Sgabor				p_len[fillnew++] = strlen(s);
1011246074Sgabor				if (fillold > p_ptrn_lines) {
1012246074Sgabor					if (remove_special_line()) {
1013246074Sgabor						p_len[fillnew - 1] -= 1;
1014246074Sgabor						s[p_len[fillnew - 1]] = 0;
1015246074Sgabor					}
1016246074Sgabor				}
1017246074Sgabor				break;
1018246074Sgabor			default:
1019246074Sgabor				p_end = fillnew;
1020246074Sgabor				malformed();
1021246074Sgabor			}
1022246074Sgabor			if (ch != ' ' && context > 0) {
1023246074Sgabor				if (context < p_context)
1024246074Sgabor					p_context = context;
1025246074Sgabor				context = -1000;
1026246074Sgabor			}
1027246074Sgabor		}		/* while */
1028246074Sgabor	} else {		/* normal diff--fake it up */
1029246074Sgabor		char	hunk_type;
1030246074Sgabor		int	i;
1031246074Sgabor		LINENUM	min, max;
1032246074Sgabor
1033275553Spfg		line_beginning = ftello(pfp);
1034246074Sgabor		p_context = 0;
1035246074Sgabor		len = pgets(true);
1036246074Sgabor		p_input_line++;
1037246074Sgabor		if (len == 0 || !isdigit((unsigned char)*buf)) {
1038246074Sgabor			next_intuit_at(line_beginning, p_input_line);
1039246074Sgabor			return false;
1040246074Sgabor		}
1041275612Spfg		p_first = strtolinenum(buf, &s);
1042246074Sgabor		if (*s == ',') {
1043275612Spfg			p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1044275612Spfg			if (p_ptrn_lines < 0)
1045275612Spfg				malformed();
1046246074Sgabor		} else
1047246074Sgabor			p_ptrn_lines = (*s != 'a');
1048246074Sgabor		hunk_type = *s;
1049246074Sgabor		if (hunk_type == 'a')
1050246074Sgabor			p_first++;	/* do append rather than insert */
1051275612Spfg		min = strtolinenum(s + 1, &s);
1052246074Sgabor		if (*s == ',')
1053275612Spfg			max = strtolinenum(s + 1, &s);
1054246074Sgabor		else
1055246074Sgabor			max = min;
1056275612Spfg		if (min < 0 || min > max || max - min == LINENUM_MAX)
1057275612Spfg			malformed();
1058246074Sgabor		if (hunk_type == 'd')
1059246074Sgabor			min++;
1060275612Spfg		p_newfirst = min;
1061275612Spfg		p_repl_lines = max - min + 1;
1062275612Spfg		if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1063275612Spfg		    p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1064275612Spfg			malformed();
1065275612Spfg		p_end = p_ptrn_lines + p_repl_lines + 1;
1066246074Sgabor		if (p_end > MAXHUNKSIZE)
1067246074Sgabor			fatal("hunk too large (%ld lines) at line %ld: %s",
1068246074Sgabor			    p_end, p_input_line, buf);
1069246074Sgabor		while (p_end >= hunkmax)
1070246074Sgabor			grow_hunkmax();
1071246074Sgabor		snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1072246074Sgabor		    p_first + p_ptrn_lines - 1);
1073246074Sgabor		p_line[0] = savestr(buf);
1074246074Sgabor		if (out_of_mem) {
1075246074Sgabor			p_end = -1;
1076246074Sgabor			return false;
1077246074Sgabor		}
1078246074Sgabor		p_char[0] = '*';
1079246074Sgabor		for (i = 1; i <= p_ptrn_lines; i++) {
1080246074Sgabor			len = pgets(true);
1081246074Sgabor			p_input_line++;
1082246074Sgabor			if (len == 0)
1083246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1084246074Sgabor				    p_input_line);
1085246074Sgabor			if (*buf != '<')
1086246074Sgabor				fatal("< expected at line %ld of patch\n",
1087246074Sgabor				    p_input_line);
1088246074Sgabor			p_line[i] = savestr(buf + 2);
1089246074Sgabor			if (out_of_mem) {
1090246074Sgabor				p_end = i - 1;
1091246074Sgabor				return false;
1092246074Sgabor			}
1093246074Sgabor			p_len[i] = strlen(p_line[i]);
1094246074Sgabor			p_char[i] = '-';
1095246074Sgabor		}
1096246074Sgabor
1097246074Sgabor		if (remove_special_line()) {
1098246074Sgabor			p_len[i - 1] -= 1;
1099246074Sgabor			(p_line[i - 1])[p_len[i - 1]] = 0;
1100246074Sgabor		}
1101246074Sgabor		if (hunk_type == 'c') {
1102246074Sgabor			len = pgets(true);
1103246074Sgabor			p_input_line++;
1104246074Sgabor			if (len == 0)
1105246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1106246074Sgabor				    p_input_line);
1107246074Sgabor			if (*buf != '-')
1108246074Sgabor				fatal("--- expected at line %ld of patch\n",
1109246074Sgabor				    p_input_line);
1110246074Sgabor		}
1111246074Sgabor		snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1112246074Sgabor		p_line[i] = savestr(buf);
1113246074Sgabor		if (out_of_mem) {
1114246074Sgabor			p_end = i - 1;
1115246074Sgabor			return false;
1116246074Sgabor		}
1117246074Sgabor		p_char[i] = '=';
1118246074Sgabor		for (i++; i <= p_end; i++) {
1119246074Sgabor			len = pgets(true);
1120246074Sgabor			p_input_line++;
1121246074Sgabor			if (len == 0)
1122246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1123246074Sgabor				    p_input_line);
1124246074Sgabor			if (*buf != '>')
1125246074Sgabor				fatal("> expected at line %ld of patch\n",
1126246074Sgabor				    p_input_line);
1127246074Sgabor			p_line[i] = savestr(buf + 2);
1128246074Sgabor			if (out_of_mem) {
1129246074Sgabor				p_end = i - 1;
1130246074Sgabor				return false;
1131246074Sgabor			}
1132246074Sgabor			p_len[i] = strlen(p_line[i]);
1133246074Sgabor			p_char[i] = '+';
1134246074Sgabor		}
1135246074Sgabor
1136246074Sgabor		if (remove_special_line()) {
1137246074Sgabor			p_len[i - 1] -= 1;
1138246074Sgabor			(p_line[i - 1])[p_len[i - 1]] = 0;
1139246074Sgabor		}
1140246074Sgabor	}
1141246074Sgabor	if (reverse)		/* backwards patch? */
1142246074Sgabor		if (!pch_swap())
1143246074Sgabor			say("Not enough memory to swap next hunk!\n");
1144246074Sgabor#ifdef DEBUGGING
1145246074Sgabor	if (debug & 2) {
1146246074Sgabor		int	i;
1147246074Sgabor		char	special;
1148246074Sgabor
1149246074Sgabor		for (i = 0; i <= p_end; i++) {
1150246074Sgabor			if (i == p_ptrn_lines)
1151246074Sgabor				special = '^';
1152246074Sgabor			else
1153246074Sgabor				special = ' ';
1154246074Sgabor			fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1155246074Sgabor			    special, p_line[i]);
1156246074Sgabor			fflush(stderr);
1157246074Sgabor		}
1158246074Sgabor	}
1159246074Sgabor#endif
1160246074Sgabor	if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1161246074Sgabor		p_char[p_end + 1] = '^';	/* add a stopper for apply_hunk */
1162246074Sgabor	return true;
1163246074Sgabor}
1164246074Sgabor
1165246074Sgabor/*
1166246074Sgabor * Input a line from the patch file.
1167246074Sgabor * Worry about indentation if do_indent is true.
1168246074Sgabor * The line is read directly into the buf global variable which
1169246074Sgabor * is resized if necessary in order to hold the complete line.
1170246074Sgabor * Returns the number of characters read including the terminating
1171246074Sgabor * '\n', if any.
1172246074Sgabor */
1173246074Sgaborsize_t
1174246074Sgaborpgets(bool do_indent)
1175246074Sgabor{
1176246074Sgabor	char *line;
1177246074Sgabor	size_t len;
1178246074Sgabor	int indent = 0, skipped = 0;
1179246074Sgabor
1180246074Sgabor	line = fgetln(pfp, &len);
1181246074Sgabor	if (line != NULL) {
1182246074Sgabor		if (len + 1 > buf_size) {
1183246074Sgabor			while (len + 1 > buf_size)
1184246074Sgabor				buf_size *= 2;
1185246074Sgabor			free(buf);
1186246074Sgabor			buf = malloc(buf_size);
1187246074Sgabor			if (buf == NULL)
1188246074Sgabor				fatal("out of memory\n");
1189246074Sgabor		}
1190246074Sgabor		if (do_indent == 1 && p_indent) {
1191246074Sgabor			for (;
1192246074Sgabor			    indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1193246074Sgabor			    line++, skipped++) {
1194246074Sgabor				if (*line == '\t')
1195246074Sgabor					indent += 8 - (indent %7);
1196246074Sgabor				else
1197246074Sgabor					indent++;
1198246074Sgabor			}
1199246074Sgabor		}
1200252637Sobrien		memcpy(buf, line, len - skipped);
1201246074Sgabor		buf[len - skipped] = '\0';
1202246074Sgabor	}
1203246074Sgabor	return len;
1204246074Sgabor}
1205246074Sgabor
1206246074Sgabor
1207246074Sgabor/*
1208246074Sgabor * Reverse the old and new portions of the current hunk.
1209246074Sgabor */
1210246074Sgaborbool
1211246074Sgaborpch_swap(void)
1212246074Sgabor{
1213246074Sgabor	char	**tp_line;	/* the text of the hunk */
1214267490Spfg	unsigned short	*tp_len;/* length of each line */
1215246074Sgabor	char	*tp_char;	/* +, -, and ! */
1216246074Sgabor	LINENUM	i;
1217246074Sgabor	LINENUM	n;
1218246074Sgabor	bool	blankline = false;
1219246074Sgabor	char	*s;
1220246074Sgabor
1221246074Sgabor	i = p_first;
1222246074Sgabor	p_first = p_newfirst;
1223246074Sgabor	p_newfirst = i;
1224246074Sgabor
1225246074Sgabor	/* make a scratch copy */
1226246074Sgabor
1227246074Sgabor	tp_line = p_line;
1228246074Sgabor	tp_len = p_len;
1229246074Sgabor	tp_char = p_char;
1230246074Sgabor	p_line = NULL;	/* force set_hunkmax to allocate again */
1231246074Sgabor	p_len = NULL;
1232246074Sgabor	p_char = NULL;
1233246074Sgabor	set_hunkmax();
1234246074Sgabor	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1235246074Sgabor
1236246074Sgabor		free(p_line);
1237246074Sgabor		p_line = tp_line;
1238246074Sgabor		free(p_len);
1239246074Sgabor		p_len = tp_len;
1240246074Sgabor		free(p_char);
1241246074Sgabor		p_char = tp_char;
1242246074Sgabor		return false;	/* not enough memory to swap hunk! */
1243246074Sgabor	}
1244246074Sgabor	/* now turn the new into the old */
1245246074Sgabor
1246246074Sgabor	i = p_ptrn_lines + 1;
1247246074Sgabor	if (tp_char[i] == '\n') {	/* account for possible blank line */
1248246074Sgabor		blankline = true;
1249246074Sgabor		i++;
1250246074Sgabor	}
1251246074Sgabor	if (p_efake >= 0) {	/* fix non-freeable ptr range */
1252246074Sgabor		if (p_efake <= i)
1253246074Sgabor			n = p_end - i + 1;
1254246074Sgabor		else
1255246074Sgabor			n = -i;
1256246074Sgabor		p_efake += n;
1257246074Sgabor		p_bfake += n;
1258246074Sgabor	}
1259246074Sgabor	for (n = 0; i <= p_end; i++, n++) {
1260246074Sgabor		p_line[n] = tp_line[i];
1261246074Sgabor		p_char[n] = tp_char[i];
1262246074Sgabor		if (p_char[n] == '+')
1263246074Sgabor			p_char[n] = '-';
1264246074Sgabor		p_len[n] = tp_len[i];
1265246074Sgabor	}
1266246074Sgabor	if (blankline) {
1267246074Sgabor		i = p_ptrn_lines + 1;
1268246074Sgabor		p_line[n] = tp_line[i];
1269246074Sgabor		p_char[n] = tp_char[i];
1270246074Sgabor		p_len[n] = tp_len[i];
1271246074Sgabor		n++;
1272246074Sgabor	}
1273246074Sgabor	if (p_char[0] != '=')
1274246074Sgabor		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1275246074Sgabor		    p_input_line, p_char[0]);
1276246074Sgabor	p_char[0] = '*';
1277246074Sgabor	for (s = p_line[0]; *s; s++)
1278246074Sgabor		if (*s == '-')
1279246074Sgabor			*s = '*';
1280246074Sgabor
1281246074Sgabor	/* now turn the old into the new */
1282246074Sgabor
1283246074Sgabor	if (p_char[0] != '*')
1284246074Sgabor		fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1285246074Sgabor		    p_input_line, p_char[0]);
1286246074Sgabor	tp_char[0] = '=';
1287246074Sgabor	for (s = tp_line[0]; *s; s++)
1288246074Sgabor		if (*s == '*')
1289246074Sgabor			*s = '-';
1290246074Sgabor	for (i = 0; n <= p_end; i++, n++) {
1291246074Sgabor		p_line[n] = tp_line[i];
1292246074Sgabor		p_char[n] = tp_char[i];
1293246074Sgabor		if (p_char[n] == '-')
1294246074Sgabor			p_char[n] = '+';
1295246074Sgabor		p_len[n] = tp_len[i];
1296246074Sgabor	}
1297246074Sgabor
1298246074Sgabor	if (i != p_ptrn_lines + 1)
1299246074Sgabor		fatal("Malformed patch at line %ld: expected %ld lines, "
1300246074Sgabor		    "got %ld\n",
1301246074Sgabor		    p_input_line, p_ptrn_lines + 1, i);
1302246074Sgabor
1303246074Sgabor	i = p_ptrn_lines;
1304246074Sgabor	p_ptrn_lines = p_repl_lines;
1305246074Sgabor	p_repl_lines = i;
1306246074Sgabor
1307246074Sgabor	free(tp_line);
1308246074Sgabor	free(tp_len);
1309246074Sgabor	free(tp_char);
1310246074Sgabor
1311246074Sgabor	return true;
1312246074Sgabor}
1313246074Sgabor
1314246074Sgabor/*
1315246074Sgabor * Return the specified line position in the old file of the old context.
1316246074Sgabor */
1317246074SgaborLINENUM
1318246074Sgaborpch_first(void)
1319246074Sgabor{
1320246074Sgabor	return p_first;
1321246074Sgabor}
1322246074Sgabor
1323246074Sgabor/*
1324246074Sgabor * Return the number of lines of old context.
1325246074Sgabor */
1326246074SgaborLINENUM
1327246074Sgaborpch_ptrn_lines(void)
1328246074Sgabor{
1329246074Sgabor	return p_ptrn_lines;
1330246074Sgabor}
1331246074Sgabor
1332246074Sgabor/*
1333246074Sgabor * Return the probable line position in the new file of the first line.
1334246074Sgabor */
1335246074SgaborLINENUM
1336246074Sgaborpch_newfirst(void)
1337246074Sgabor{
1338246074Sgabor	return p_newfirst;
1339246074Sgabor}
1340246074Sgabor
1341246074Sgabor/*
1342246074Sgabor * Return the number of lines in the replacement text including context.
1343246074Sgabor */
1344246074SgaborLINENUM
1345246074Sgaborpch_repl_lines(void)
1346246074Sgabor{
1347246074Sgabor	return p_repl_lines;
1348246074Sgabor}
1349246074Sgabor
1350246074Sgabor/*
1351246074Sgabor * Return the number of lines in the whole hunk.
1352246074Sgabor */
1353246074SgaborLINENUM
1354246074Sgaborpch_end(void)
1355246074Sgabor{
1356246074Sgabor	return p_end;
1357246074Sgabor}
1358246074Sgabor
1359246074Sgabor/*
1360246074Sgabor * Return the number of context lines before the first changed line.
1361246074Sgabor */
1362246074SgaborLINENUM
1363246074Sgaborpch_context(void)
1364246074Sgabor{
1365246074Sgabor	return p_context;
1366246074Sgabor}
1367246074Sgabor
1368246074Sgabor/*
1369246074Sgabor * Return the length of a particular patch line.
1370246074Sgabor */
1371267490Spfgunsigned short
1372246074Sgaborpch_line_len(LINENUM line)
1373246074Sgabor{
1374246074Sgabor	return p_len[line];
1375246074Sgabor}
1376246074Sgabor
1377246074Sgabor/*
1378246074Sgabor * Return the control character (+, -, *, !, etc) for a patch line.
1379246074Sgabor */
1380246074Sgaborchar
1381246074Sgaborpch_char(LINENUM line)
1382246074Sgabor{
1383246074Sgabor	return p_char[line];
1384246074Sgabor}
1385246074Sgabor
1386246074Sgabor/*
1387246074Sgabor * Return a pointer to a particular patch line.
1388246074Sgabor */
1389246074Sgaborchar *
1390246074Sgaborpfetch(LINENUM line)
1391246074Sgabor{
1392246074Sgabor	return p_line[line];
1393246074Sgabor}
1394246074Sgabor
1395246074Sgabor/*
1396246074Sgabor * Return where in the patch file this hunk began, for error messages.
1397246074Sgabor */
1398246074SgaborLINENUM
1399246074Sgaborpch_hunk_beg(void)
1400246074Sgabor{
1401246074Sgabor	return p_hunk_beg;
1402246074Sgabor}
1403246074Sgabor
1404246074Sgabor/*
1405246074Sgabor * Apply an ed script by feeding ed itself.
1406246074Sgabor */
1407246074Sgaborvoid
1408246074Sgabordo_ed_script(void)
1409246074Sgabor{
1410246074Sgabor	char	*t;
1411275553Spfg	off_t	beginning_of_this_line;
1412246074Sgabor	FILE	*pipefp = NULL;
1413246074Sgabor
1414246074Sgabor	if (!skip_rest_of_patch) {
1415246074Sgabor		if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1416246074Sgabor			unlink(TMPOUTNAME);
1417246074Sgabor			fatal("can't create temp file %s", TMPOUTNAME);
1418246074Sgabor		}
1419246074Sgabor		snprintf(buf, buf_size, "%s%s%s", _PATH_ED,
1420246074Sgabor		    verbose ? " " : " -s ", TMPOUTNAME);
1421246074Sgabor		pipefp = popen(buf, "w");
1422246074Sgabor	}
1423246074Sgabor	for (;;) {
1424275553Spfg		beginning_of_this_line = ftello(pfp);
1425246074Sgabor		if (pgets(true) == 0) {
1426246074Sgabor			next_intuit_at(beginning_of_this_line, p_input_line);
1427246074Sgabor			break;
1428246074Sgabor		}
1429246074Sgabor		p_input_line++;
1430246074Sgabor		for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1431246074Sgabor			;
1432246074Sgabor		/* POSIX defines allowed commands as {a,c,d,i,s} */
1433275582Spfg		if (isdigit((unsigned char)*buf) &&
1434275582Spfg		    (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1435246074Sgabor			if (pipefp != NULL)
1436246074Sgabor				fputs(buf, pipefp);
1437246074Sgabor			if (*t != 'd') {
1438246074Sgabor				while (pgets(true)) {
1439246074Sgabor					p_input_line++;
1440246074Sgabor					if (pipefp != NULL)
1441246074Sgabor						fputs(buf, pipefp);
1442246074Sgabor					if (strEQ(buf, ".\n"))
1443246074Sgabor						break;
1444246074Sgabor				}
1445246074Sgabor			}
1446246074Sgabor		} else {
1447246074Sgabor			next_intuit_at(beginning_of_this_line, p_input_line);
1448246074Sgabor			break;
1449246074Sgabor		}
1450246074Sgabor	}
1451246074Sgabor	if (pipefp == NULL)
1452246074Sgabor		return;
1453246074Sgabor	fprintf(pipefp, "w\n");
1454246074Sgabor	fprintf(pipefp, "q\n");
1455246074Sgabor	fflush(pipefp);
1456246074Sgabor	pclose(pipefp);
1457246074Sgabor	ignore_signals();
1458246074Sgabor	if (!check_only) {
1459246074Sgabor		if (move_file(TMPOUTNAME, outname) < 0) {
1460246074Sgabor			toutkeep = true;
1461246074Sgabor			chmod(TMPOUTNAME, filemode);
1462246074Sgabor		} else
1463246074Sgabor			chmod(outname, filemode);
1464246074Sgabor	}
1465246074Sgabor	set_signals(1);
1466246074Sgabor}
1467246074Sgabor
1468246074Sgabor/*
1469246074Sgabor * Choose the name of the file to be patched based on POSIX rules.
1470246074Sgabor * NOTE: the POSIX rules are amazingly stupid and we only follow them
1471246074Sgabor *       if the user specified --posix or set POSIXLY_CORRECT.
1472246074Sgabor */
1473246074Sgaborstatic char *
1474246074Sgaborposix_name(const struct file_name *names, bool assume_exists)
1475246074Sgabor{
1476246074Sgabor	char *path = NULL;
1477246074Sgabor	int i;
1478246074Sgabor
1479246074Sgabor	/*
1480246074Sgabor	 * POSIX states that the filename will be chosen from one
1481246074Sgabor	 * of the old, new and index names (in that order) if
1482246074Sgabor	 * the file exists relative to CWD after -p stripping.
1483246074Sgabor	 */
1484246074Sgabor	for (i = 0; i < MAX_FILE; i++) {
1485246074Sgabor		if (names[i].path != NULL && names[i].exists) {
1486246074Sgabor			path = names[i].path;
1487246074Sgabor			break;
1488246074Sgabor		}
1489246074Sgabor	}
1490246074Sgabor	if (path == NULL && !assume_exists) {
1491246074Sgabor		/*
1492246074Sgabor		 * No files found, look for something we can checkout from
1493246074Sgabor		 * RCS/SCCS dirs.  Same order as above.
1494246074Sgabor		 */
1495246074Sgabor		for (i = 0; i < MAX_FILE; i++) {
1496246074Sgabor			if (names[i].path != NULL &&
1497246074Sgabor			    (path = checked_in(names[i].path)) != NULL)
1498246074Sgabor				break;
1499246074Sgabor		}
1500246074Sgabor		/*
1501246074Sgabor		 * Still no match?  Check to see if the diff could be creating
1502246074Sgabor		 * a new file.
1503246074Sgabor		 */
1504246074Sgabor		if (path == NULL && ok_to_create_file &&
1505246074Sgabor		    names[NEW_FILE].path != NULL)
1506246074Sgabor			path = names[NEW_FILE].path;
1507246074Sgabor	}
1508246074Sgabor
1509276218Spfg	return path ? xstrdup(path) : NULL;
1510246074Sgabor}
1511246074Sgabor
1512246074Sgaborstatic char *
1513255232Ssecompare_names(const struct file_name *names, bool assume_exists, int phase)
1514246074Sgabor{
1515246074Sgabor	size_t min_components, min_baselen, min_len, tmp;
1516246074Sgabor	char *best = NULL;
1517255232Sse	char *path;
1518246074Sgabor	int i;
1519246074Sgabor
1520246074Sgabor	/*
1521246074Sgabor	 * The "best" name is the one with the fewest number of path
1522246074Sgabor	 * components, the shortest basename length, and the shortest
1523246074Sgabor	 * overall length (in that order).  We only use the Index: file
1524246074Sgabor	 * if neither of the old or new files could be intuited from
1525246074Sgabor	 * the diff header.
1526246074Sgabor	 */
1527246074Sgabor	min_components = min_baselen = min_len = SIZE_MAX;
1528246074Sgabor	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1529255232Sse		path = names[i].path;
1530255232Sse		if (path == NULL ||
1531255232Sse		    (phase == 1 && !names[i].exists && !assume_exists) ||
1532255232Sse		    (phase == 2 && checked_in(path) == NULL))
1533246074Sgabor			continue;
1534255232Sse		if ((tmp = num_components(path)) > min_components)
1535246074Sgabor			continue;
1536250943Sse		if (tmp < min_components) {
1537250943Sse			min_components = tmp;
1538255232Sse			best = path;
1539250943Sse		}
1540255232Sse		if ((tmp = strlen(basename(path))) > min_baselen)
1541246074Sgabor			continue;
1542250943Sse		if (tmp < min_baselen) {
1543250943Sse			min_baselen = tmp;
1544255232Sse			best = path;
1545250943Sse		}
1546255232Sse		if ((tmp = strlen(path)) > min_len)
1547246074Sgabor			continue;
1548246074Sgabor		min_len = tmp;
1549255232Sse		best = path;
1550246074Sgabor	}
1551255232Sse	return best;
1552255232Sse}
1553255232Sse
1554255232Sse/*
1555255232Sse * Choose the name of the file to be patched based the "best" one
1556255232Sse * available.
1557255232Sse */
1558255232Ssestatic char *
1559255232Ssebest_name(const struct file_name *names, bool assume_exists)
1560255232Sse{
1561255232Sse	char *best;
1562255232Sse
1563255232Sse	best = compare_names(names, assume_exists, 1);
1564246074Sgabor	if (best == NULL) {
1565255232Sse		best = compare_names(names, assume_exists, 2);
1566246074Sgabor		/*
1567246074Sgabor		 * Still no match?  Check to see if the diff could be creating
1568246074Sgabor		 * a new file.
1569246074Sgabor		 */
1570246074Sgabor		if (best == NULL && ok_to_create_file &&
1571246074Sgabor		    names[NEW_FILE].path != NULL)
1572246074Sgabor			best = names[NEW_FILE].path;
1573246074Sgabor	}
1574246074Sgabor
1575276218Spfg	return best ? xstrdup(best) : NULL;
1576246074Sgabor}
1577246074Sgabor
1578246074Sgaborstatic size_t
1579246074Sgabornum_components(const char *path)
1580246074Sgabor{
1581246074Sgabor	size_t n;
1582246074Sgabor	const char *cp;
1583246074Sgabor
1584246074Sgabor	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1585246074Sgabor		while (*cp == '/')
1586246074Sgabor			cp++;		/* skip consecutive slashes */
1587246074Sgabor	}
1588246074Sgabor	return n;
1589246074Sgabor}
1590275612Spfg
1591275612Spfg/*
1592275612Spfg * Convert number at NPTR into LINENUM and save address of first
1593275612Spfg * character that is not a digit in ENDPTR.  If conversion is not
1594275612Spfg * possible, call fatal.
1595275612Spfg */
1596275612Spfgstatic LINENUM
1597275612Spfgstrtolinenum(char *nptr, char **endptr)
1598275612Spfg{
1599275612Spfg	LINENUM rv;
1600275612Spfg	char c;
1601275612Spfg	char *p;
1602275612Spfg	const char *errstr;
1603275612Spfg
1604275612Spfg	for (p = nptr; isdigit((unsigned char)*p); p++)
1605275612Spfg		;
1606275612Spfg
1607275612Spfg	if (p == nptr)
1608275612Spfg		malformed();
1609275612Spfg
1610275612Spfg	c = *p;
1611275612Spfg	*p = '\0';
1612275612Spfg
1613275612Spfg	rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1614275612Spfg	if (errstr != NULL)
1615275612Spfg		fatal("invalid line number at line %ld: `%s' is %s\n",
1616275612Spfg		    p_input_line, nptr, errstr);
1617276218Spfg
1618275612Spfg	*p = c;
1619275612Spfg	*endptr = p;
1620275612Spfg
1621275612Spfg	return rv;
1622275612Spfg}
1623