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