xref: /openbsd/usr.bin/diff3/diff3prog.c (revision 91f110e0)
1 /*	$OpenBSD: diff3prog.c,v 1.13 2013/11/15 22:20:04 millert Exp $	*/
2 
3 /*
4  * Copyright (C) Caldera International Inc.  2001-2002.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code and documentation must retain the above
11  *    copyright notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed or owned by Caldera
18  *	International, Inc.
19  * 4. Neither the name of Caldera International, Inc. nor the names of other
20  *    contributors may be used to endorse or promote products derived from
21  *    this software without specific prior written permission.
22  *
23  * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
24  * INTERNATIONAL, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE LIABLE FOR ANY DIRECT,
28  * INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
32  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
33  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  */
36 /*-
37  * Copyright (c) 1991, 1993
38  *	The Regents of the University of California.  All rights reserved.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. Neither the name of the University nor the names of its contributors
49  *    may be used to endorse or promote products derived from this software
50  *    without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62  * SUCH DAMAGE.
63  *
64  *	@(#)diff3.c	8.1 (Berkeley) 6/6/93
65  */
66 
67 #include <ctype.h>
68 #include <err.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
73 
74 /* diff3 - 3-way differential file comparison */
75 
76 /* diff3 [-ex3EX] d13 d23 f1 f2 f3 [m1 m3]
77  *
78  * d13 = diff report on f1 vs f3
79  * d23 = diff report on f2 vs f3
80  * f1, f2, f3 the 3 files
81  * if changes in f1 overlap with changes in f3, m1 and m3 are used
82  * to mark the overlaps; otherwise, the file names f1 and f3 are used
83  * (only for options E and X).
84  */
85 
86 /*
87  * "from" is first in range of changed lines; "to" is last+1
88  * from=to=line after point of insertion for added lines.
89  */
90 struct  range {
91 	int from;
92 	int to;
93 };
94 struct diff {
95 	struct range old;
96 	struct range new;
97 };
98 
99 size_t szchanges;
100 
101 struct diff *d13;
102 struct diff *d23;
103 /*
104  * "de" is used to gather editing scripts.  These are later spewed out in
105  * reverse order.  Its first element must be all zero, the "new" component
106  * of "de" contains line positions or byte positions depending on when you
107  * look (!?).  Array overlap indicates which sections in "de" correspond to
108  * lines that are different in all three files.
109  */
110 struct diff *de;
111 char *overlap;
112 int  overlapcnt;
113 FILE *fp[3];
114 int cline[3];		/* # of the last-read line in each file (0-2) */
115 /*
116  * the latest known correspondence between line numbers of the 3 files
117  * is stored in last[1-3];
118  */
119 int last[4];
120 int eflag;
121 int oflag;		/* indicates whether to mark overlaps (-E or -X)*/
122 int debug  = 0;
123 char f1mark[40], f3mark[40];	/* markers for -E and -X */
124 
125 int duplicate(struct range *, struct range *);
126 int edit(struct diff *, int, int);
127 char *getchange(FILE *);
128 char *get_line(FILE *, size_t *);
129 int number(char **);
130 int readin(char *, struct diff **);
131 int skip(int, int, char *);
132 void change(int, struct range *, int);
133 void keep(int, struct range *);
134 void merge(int, int);
135 void prange(struct range *);
136 void repos(int);
137 void separate(const char *);
138 __dead void edscript(int);
139 __dead void trouble(void);
140 void increase(void);
141 __dead void usage(void);
142 
143 int
144 main(int argc, char **argv)
145 {
146 	int ch, i, m, n;
147 
148 	eflag = 0;
149 	oflag = 0;
150 	while ((ch = getopt(argc, argv, "EeXx3")) != -1) {
151 		switch (ch) {
152 		case 'E':
153 			eflag = 3;
154 			oflag = 1;
155 			break;
156 		case 'e':
157 			eflag = 3;
158 			break;
159 		case 'X':
160 			oflag = eflag = 1;
161 			break;
162 		case 'x':
163 			eflag = 1;
164 			break;
165 		case '3':
166 			eflag = 2;
167 			break;
168 		}
169 	}
170 	argc -= optind;
171 	argv += optind;
172 	/* XXX - argc usage seems wrong here */
173 	if (argc < 5)
174 		usage();
175 
176 	if (oflag) {
177 		(void)snprintf(f1mark, sizeof(f1mark), "<<<<<<< %s",
178 		    argc >= 6 ? argv[5] : argv[2]);
179 		(void)snprintf(f3mark, sizeof(f3mark), ">>>>>>> %s",
180 		    argc >= 7 ? argv[6] : argv[4]);
181 	}
182 
183 	increase();
184 	m = readin(argv[0], &d13);
185 	n = readin(argv[1], &d23);
186 	for (i = 0; i <= 2; i++) {
187 		if ((fp[i] = fopen(argv[i + 2], "r")) == NULL)
188 			err(EXIT_FAILURE, "can't open %s", argv[i + 2]);
189 	}
190 	merge(m, n);
191 	exit(EXIT_SUCCESS);
192 }
193 
194 /*
195  * Pick up the line numbers of all changes from one change file.
196  * (This puts the numbers in a vector, which is not strictly necessary,
197  * since the vector is processed in one sequential pass.
198  * The vector could be optimized out of existence)
199  */
200 int
201 readin(char *name, struct diff **dd)
202 {
203 	int a, b, c, d, i;
204 	char kind, *p;
205 
206 	fp[0] = fopen(name, "r");
207 	if (fp[0] == NULL)
208 		err(EXIT_FAILURE, "can't open %s", name);
209 	for (i=0; (p = getchange(fp[0])); i++) {
210 		if (i >= szchanges - 1)
211 			increase();
212 		a = b = number(&p);
213 		if (*p == ',') {
214 			p++;
215 			b = number(&p);
216 		}
217 		kind = *p++;
218 		c = d = number(&p);
219 		if (*p==',') {
220 			p++;
221 			d = number(&p);
222 		}
223 		if (kind == 'a')
224 			a++;
225 		if (kind == 'd')
226 			c++;
227 		b++;
228 		d++;
229 		(*dd)[i].old.from = a;
230 		(*dd)[i].old.to = b;
231 		(*dd)[i].new.from = c;
232 		(*dd)[i].new.to = d;
233 	}
234 	if (i) {
235 		(*dd)[i].old.from = (*dd)[i-1].old.to;
236 		(*dd)[i].new.from = (*dd)[i-1].new.to;
237 	}
238 	(void)fclose(fp[0]);
239 	return (i);
240 }
241 
242 int
243 number(char **lc)
244 {
245 	int nn;
246 	nn = 0;
247 	while (isdigit((unsigned char)(**lc)))
248 		nn = nn*10 + *(*lc)++ - '0';
249 	return (nn);
250 }
251 
252 char *
253 getchange(FILE *b)
254 {
255 	char *line;
256 
257 	while ((line = get_line(b, NULL))) {
258 		if (isdigit((unsigned char)line[0]))
259 			return (line);
260 	}
261 	return (NULL);
262 }
263 
264 char *
265 get_line(FILE *b, size_t *n)
266 {
267 	char *cp;
268 	size_t len;
269 	static char *buf;
270 	static size_t bufsize;
271 
272 	if ((cp = fgetln(b, &len)) == NULL)
273 		return (NULL);
274 
275 	if (cp[len - 1] != '\n')
276 		len++;
277 	if (len + 1 > bufsize) {
278 		do {
279 			bufsize += 1024;
280 		} while (len + 1 > bufsize);
281 		if ((buf = realloc(buf, bufsize)) == NULL)
282 			err(EXIT_FAILURE, NULL);
283 	}
284 	memcpy(buf, cp, len - 1);
285 	buf[len - 1] = '\n';
286 	buf[len] = '\0';
287 	if (n != NULL)
288 		*n = len;
289 	return (buf);
290 }
291 
292 void
293 merge(int m1, int m2)
294 {
295 	struct diff *d1, *d2, *d3;
296 	int dup, j, t1, t2;
297 
298 	d1 = d13;
299 	d2 = d23;
300 	j = 0;
301 	while ((t1 = d1 < d13 + m1) | (t2 = d2 < d23 + m2)) {
302 		if (debug) {
303 			printf("%d,%d=%d,%d %d,%d=%d,%d\n",
304 			d1->old.from,d1->old.to,
305 			d1->new.from,d1->new.to,
306 			d2->old.from,d2->old.to,
307 			d2->new.from,d2->new.to);
308 		}
309 		/* first file is different from others */
310 		if (!t2 || (t1 && d1->new.to < d2->new.from)) {
311 			/* stuff peculiar to 1st file */
312 			if (eflag==0) {
313 				separate("1");
314 				change(1, &d1->old, 0);
315 				keep(2, &d1->new);
316 				change(3, &d1->new, 0);
317 			}
318 			d1++;
319 			continue;
320 		}
321 		/* second file is different from others */
322 		if (!t1 || (t2 && d2->new.to < d1->new.from)) {
323 			if (eflag==0) {
324 				separate("2");
325 				keep(1, &d2->new);
326 				change(2, &d2->old, 0);
327 				change(3, &d2->new, 0);
328 			}
329 			d2++;
330 			continue;
331 		}
332 		/*
333 		 * Merge overlapping changes in first file
334 		 * this happens after extension (see below).
335 		 */
336 		if (d1 + 1 < d13 + m1 && d1->new.to >= d1[1].new.from) {
337 			d1[1].old.from = d1->old.from;
338 			d1[1].new.from = d1->new.from;
339 			d1++;
340 			continue;
341 		}
342 
343 		/* merge overlapping changes in second */
344 		if (d2 + 1 < d23 + m2 && d2->new.to >= d2[1].new.from) {
345 			d2[1].old.from = d2->old.from;
346 			d2[1].new.from = d2->new.from;
347 			d2++;
348 			continue;
349 		}
350 		/* stuff peculiar to third file or different in all */
351 		if (d1->new.from == d2->new.from && d1->new.to == d2->new.to) {
352 			dup = duplicate(&d1->old,&d2->old);
353 			/*
354 			 * dup = 0 means all files differ
355 			 * dup = 1 means files 1 and 2 identical
356 			 */
357 			if (eflag==0) {
358 				separate(dup ? "3" : "");
359 				change(1, &d1->old, dup);
360 				change(2, &d2->old, 0);
361 				d3 = d1->old.to > d1->old.from ? d1 : d2;
362 				change(3, &d3->new, 0);
363 			} else
364 				j = edit(d1, dup, j);
365 			d1++;
366 			d2++;
367 			continue;
368 		}
369 		/*
370 		 * Overlapping changes from file 1 and 2; extend changes
371 		 * appropriately to make them coincide.
372 		 */
373 		if (d1->new.from < d2->new.from) {
374 			d2->old.from -= d2->new.from-d1->new.from;
375 			d2->new.from = d1->new.from;
376 		} else if (d2->new.from < d1->new.from) {
377 			d1->old.from -= d1->new.from-d2->new.from;
378 			d1->new.from = d2->new.from;
379 		}
380 		if (d1->new.to > d2->new.to) {
381 			d2->old.to += d1->new.to - d2->new.to;
382 			d2->new.to = d1->new.to;
383 		} else if (d2->new.to > d1->new.to) {
384 			d1->old.to += d2->new.to - d1->new.to;
385 			d1->new.to = d2->new.to;
386 		}
387 	}
388 	if (eflag)
389 		edscript(j);
390 }
391 
392 void
393 separate(const char *s)
394 {
395 	printf("====%s\n", s);
396 }
397 
398 /*
399  * The range of lines rold.from thru rold.to in file i is to be changed.
400  * It is to be printed only if it does not duplicate something to be
401  * printed later.
402  */
403 void
404 change(int i, struct range *rold, int dup)
405 {
406 	printf("%d:", i);
407 	last[i] = rold->to;
408 	prange(rold);
409 	if (dup || debug)
410 		return;
411 	i--;
412 	(void)skip(i, rold->from, NULL);
413 	(void)skip(i, rold->to, "  ");
414 }
415 
416 /*
417  * print the range of line numbers, rold.from thru rold.to, as n1,n2 or n1
418  */
419 void
420 prange(struct range *rold)
421 {
422 	if (rold->to <= rold->from)
423 		printf("%da\n", rold->from - 1);
424 	else {
425 		printf("%d", rold->from);
426 		if (rold->to > rold->from+1)
427 			printf(",%d", rold->to - 1);
428 		printf("c\n");
429 	}
430 }
431 
432 /*
433  * No difference was reported by diff between file 1 (or 2) and file 3,
434  * and an artificial dummy difference (trange) must be ginned up to
435  * correspond to the change reported in the other file.
436  */
437 void
438 keep(int i, struct range *rnew)
439 {
440 	int delta;
441 	struct range trange;
442 
443 	delta = last[3] - last[i];
444 	trange.from = rnew->from - delta;
445 	trange.to = rnew->to - delta;
446 	change(i, &trange, 1);
447 }
448 
449 /*
450  * skip to just before line number from in file "i".  If "pr" is non-NULL,
451  * print all skipped stuff with string pr as a prefix.
452  */
453 int
454 skip(int i, int from, char *pr)
455 {
456 	size_t j, n;
457 	char *line;
458 
459 	for (n = 0; cline[i] < from - 1; n += j) {
460 		if ((line = get_line(fp[i], &j)) == NULL)
461 			trouble();
462 		if (pr != NULL)
463 			printf("%s%s", pr, line);
464 		cline[i]++;
465 	}
466 	return ((int) n);
467 }
468 
469 /*
470  * Return 1 or 0 according as the old range (in file 1) contains exactly
471  * the same data as the new range (in file 2).
472  */
473 int
474 duplicate(struct range *r1, struct range *r2)
475 {
476 	int c,d;
477 	int nchar;
478 	int nline;
479 
480 	if (r1->to-r1->from != r2->to-r2->from)
481 		return (0);
482 	(void)skip(0, r1->from, NULL);
483 	(void)skip(1, r2->from, NULL);
484 	nchar = 0;
485 	for (nline=0; nline < r1->to - r1->from; nline++) {
486 		do {
487 			c = getc(fp[0]);
488 			d = getc(fp[1]);
489 			if (c == -1 || d== -1)
490 				trouble();
491 			nchar++;
492 			if (c != d) {
493 				repos(nchar);
494 				return (0);
495 			}
496 		} while (c != '\n');
497 	}
498 	repos(nchar);
499 	return (1);
500 }
501 
502 void
503 repos(int nchar)
504 {
505 	int i;
506 
507 	for (i = 0; i < 2; i++)
508 		(void)fseek(fp[i], (long)-nchar, SEEK_CUR);
509 }
510 
511 __dead void
512 trouble(void)
513 {
514 	errx(EXIT_FAILURE, "logic error");
515 }
516 
517 /*
518  * collect an editing script for later regurgitation
519  */
520 int
521 edit(struct diff *diff, int dup, int j)
522 {
523 	if (((dup + 1) & eflag) == 0)
524 		return (j);
525 	j++;
526 	overlap[j] = !dup;
527 	if (!dup)
528 		overlapcnt++;
529 	de[j].old.from = diff->old.from;
530 	de[j].old.to = diff->old.to;
531 	de[j].new.from = de[j-1].new.to + skip(2, diff->new.from, NULL);
532 	de[j].new.to = de[j].new.from + skip(2, diff->new.to, NULL);
533 	return (j);
534 }
535 
536 /* regurgitate */
537 __dead void
538 edscript(int n)
539 {
540 	int j,k;
541 	char block[BUFSIZ];
542 
543 	for (n = n; n > 0; n--) {
544 		if (!oflag || !overlap[n])
545 			prange(&de[n].old);
546 		else
547 			printf("%da\n=======\n", de[n].old.to -1);
548 		(void)fseek(fp[2], (long)de[n].new.from, SEEK_SET);
549 		for (k = de[n].new.to-de[n].new.from; k > 0; k-= j) {
550 			j = k > BUFSIZ ? BUFSIZ : k;
551 			if (fread(block, 1, j, fp[2]) != j)
552 				trouble();
553 			(void)fwrite(block, 1, j, stdout);
554 		}
555 		if (!oflag || !overlap[n])
556 			printf(".\n");
557 		else {
558 			printf("%s\n.\n", f3mark);
559 			printf("%da\n%s\n.\n", de[n].old.from - 1, f1mark);
560 		}
561 	}
562 	exit(overlapcnt);
563 }
564 
565 void
566 increase(void)
567 {
568 	struct diff *p;
569 	char *q;
570 	size_t newsz, incr;
571 
572 	/* are the memset(3) calls needed? */
573 	newsz = szchanges == 0 ? 64 : 2 * szchanges;
574 	incr = newsz - szchanges;
575 
576 	p = realloc(d13, newsz * sizeof(struct diff));
577 	if (p == NULL)
578 		err(1, NULL);
579 	memset(p + szchanges, 0, incr * sizeof(struct diff));
580 	d13 = p;
581 	p = realloc(d23, newsz * sizeof(struct diff));
582 	if (p == NULL)
583 		err(1, NULL);
584 	memset(p + szchanges, 0, incr * sizeof(struct diff));
585 	d23 = p;
586 	p = realloc(de, newsz * sizeof(struct diff));
587 	if (p == NULL)
588 		err(1, NULL);
589 	memset(p + szchanges, 0, incr * sizeof(struct diff));
590 	de = p;
591 	q = realloc(overlap, newsz * sizeof(char));
592 	if (q == NULL)
593 		err(1, NULL);
594 	memset(q + szchanges, 0, incr * sizeof(char));
595 	overlap = q;
596 	szchanges = newsz;
597 }
598 
599 
600 __dead void
601 usage(void)
602 {
603 	extern char *__progname;
604 
605 	fprintf(stderr, "usage: %s [-exEX3] /tmp/d3a.?????????? "
606 	    "/tmp/d3b.?????????? file1 file2 file3\n", __progname);
607 	exit(EXIT_FAILURE);
608 }
609