xref: /openbsd-src/usr.bin/diff/diff.c (revision c31f148d21f4f20a5abf9da2bf779b4c411c42c1)
1 /*	$OpenBSD: diff.c,v 1.61 2015/10/05 15:42:54 semarie Exp $	*/
2 
3 /*
4  * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  *
18  * Sponsored in part by the Defense Advanced Research Projects
19  * Agency (DARPA) and Air Force Research Laboratory, Air Force
20  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
21  */
22 
23 #include <sys/stat.h>
24 
25 #include <ctype.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <getopt.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <limits.h>
36 
37 #include "diff.h"
38 #include "xmalloc.h"
39 
40 int	 lflag, Nflag, Pflag, rflag, sflag, Tflag;
41 int	 diff_format, diff_context, status;
42 char	*start, *ifdefname, *diffargs, *label[2], *ignore_pats;
43 struct stat stb1, stb2;
44 struct excludes *excludes_list;
45 regex_t	 ignore_re;
46 
47 #define	OPTIONS	"0123456789abC:cdD:efhI:iL:lnNPpqrS:sTtU:uwX:x:"
48 static struct option longopts[] = {
49 	{ "text",			no_argument,		0,	'a' },
50 	{ "ignore-space-change",	no_argument,		0,	'b' },
51 	{ "context",			optional_argument,	0,	'C' },
52 	{ "ifdef",			required_argument,	0,	'D' },
53 	{ "minimal",			no_argument,		0,	'd' },
54 	{ "ed",				no_argument,		0,	'e' },
55 	{ "forward-ed",			no_argument,		0,	'f' },
56 	{ "ignore-matching-lines",	required_argument,	0,	'I' },
57 	{ "ignore-case",		no_argument,		0,	'i' },
58 	{ "paginate",			no_argument,		0,	'l' },
59 	{ "label",			required_argument,	0,	'L' },
60 	{ "new-file",			no_argument,		0,	'N' },
61 	{ "rcs",			no_argument,		0,	'n' },
62 	{ "unidirectional-new-file",	no_argument,		0,	'P' },
63 	{ "show-c-function",		no_argument,		0,	'p' },
64 	{ "brief",			no_argument,		0,	'q' },
65 	{ "recursive",			no_argument,		0,	'r' },
66 	{ "report-identical-files",	no_argument,		0,	's' },
67 	{ "starting-file",		required_argument,	0,	'S' },
68 	{ "expand-tabs",		no_argument,		0,	't' },
69 	{ "initial-tab",		no_argument,		0,	'T' },
70 	{ "unified",			optional_argument,	0,	'U' },
71 	{ "ignore-all-space",		no_argument,		0,	'w' },
72 	{ "exclude",			required_argument,	0,	'x' },
73 	{ "exclude-from",		required_argument,	0,	'X' },
74 	{ NULL,				0,			0,	'\0'}
75 };
76 
77 __dead void usage(void);
78 void push_excludes(char *);
79 void push_ignore_pats(char *);
80 void read_excludes_file(char *file);
81 void set_argstr(char **, char **);
82 
83 int
84 main(int argc, char **argv)
85 {
86 	char *ep, **oargv;
87 	long  l;
88 	int   ch, dflags, lastch, gotstdin, prevoptind, newarg;
89 
90 	oargv = argv;
91 	gotstdin = 0;
92 	dflags = 0;
93 	lastch = '\0';
94 	prevoptind = 1;
95 	newarg = 1;
96 	while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
97 		switch (ch) {
98 		case '0': case '1': case '2': case '3': case '4':
99 		case '5': case '6': case '7': case '8': case '9':
100 			if (newarg)
101 				usage();	/* disallow -[0-9]+ */
102 			else if (lastch == 'c' || lastch == 'u')
103 				diff_context = 0;
104 			else if (!isdigit(lastch) || diff_context > INT_MAX / 10)
105 				usage();
106 			diff_context = (diff_context * 10) + (ch - '0');
107 			break;
108 		case 'a':
109 			dflags |= D_FORCEASCII;
110 			break;
111 		case 'b':
112 			dflags |= D_FOLDBLANKS;
113 			break;
114 		case 'C':
115 		case 'c':
116 			diff_format = D_CONTEXT;
117 			if (optarg != NULL) {
118 				l = strtol(optarg, &ep, 10);
119 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
120 					usage();
121 				diff_context = (int)l;
122 			} else
123 				diff_context = 3;
124 			break;
125 		case 'd':
126 			dflags |= D_MINIMAL;
127 			break;
128 		case 'D':
129 			diff_format = D_IFDEF;
130 			ifdefname = optarg;
131 			break;
132 		case 'e':
133 			diff_format = D_EDIT;
134 			break;
135 		case 'f':
136 			diff_format = D_REVERSE;
137 			break;
138 		case 'h':
139 			/* silently ignore for backwards compatibility */
140 			break;
141 		case 'I':
142 			push_ignore_pats(optarg);
143 			break;
144 		case 'i':
145 			dflags |= D_IGNORECASE;
146 			break;
147 		case 'L':
148 			if (label[0] == NULL)
149 				label[0] = optarg;
150 			else if (label[1] == NULL)
151 				label[1] = optarg;
152 			else
153 				usage();
154 			break;
155 		case 'l':
156 			lflag = 1;
157 			signal(SIGPIPE, SIG_IGN);
158 			break;
159 		case 'N':
160 			Nflag = 1;
161 			break;
162 		case 'n':
163 			diff_format = D_NREVERSE;
164 			break;
165 		case 'p':
166 			dflags |= D_PROTOTYPE;
167 			break;
168 		case 'P':
169 			Pflag = 1;
170 			break;
171 		case 'r':
172 			rflag = 1;
173 			break;
174 		case 'q':
175 			diff_format = D_BRIEF;
176 			break;
177 		case 'S':
178 			start = optarg;
179 			break;
180 		case 's':
181 			sflag = 1;
182 			break;
183 		case 'T':
184 			Tflag = 1;
185 			break;
186 		case 't':
187 			dflags |= D_EXPANDTABS;
188 			break;
189 		case 'U':
190 		case 'u':
191 			diff_format = D_UNIFIED;
192 			if (optarg != NULL) {
193 				l = strtol(optarg, &ep, 10);
194 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
195 					usage();
196 				diff_context = (int)l;
197 			} else
198 				diff_context = 3;
199 			break;
200 		case 'w':
201 			dflags |= D_IGNOREBLANKS;
202 			break;
203 		case 'X':
204 			read_excludes_file(optarg);
205 			break;
206 		case 'x':
207 			push_excludes(optarg);
208 			break;
209 		default:
210 			usage();
211 			break;
212 		}
213 		lastch = ch;
214 		newarg = optind != prevoptind;
215 		prevoptind = optind;
216 	}
217 	argc -= optind;
218 	argv += optind;
219 
220 	if (lflag == 0) {
221 		if (getenv("TMPDIR")) {
222 			if (tame("stdio rpath wpath cpath", NULL) == -1)
223 				err(1, "tame");
224 		} else {
225 			if (tame("stdio rpath tmppath", NULL) == -1)
226 				err(1, "tame");
227 		}
228 	}
229 	/*
230 	 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
231 	 * driver routine.  Both drivers use the contents of stb1 and stb2.
232 	 */
233 	if (argc != 2)
234 		usage();
235 	if (ignore_pats != NULL) {
236 		char buf[BUFSIZ];
237 		int error;
238 
239 		if ((error = regcomp(&ignore_re, ignore_pats,
240 				     REG_NEWLINE | REG_EXTENDED)) != 0) {
241 			regerror(error, &ignore_re, buf, sizeof(buf));
242 			if (*ignore_pats != '\0')
243 				errx(2, "%s: %s", ignore_pats, buf);
244 			else
245 				errx(2, "%s", buf);
246 		}
247 	}
248 	if (strcmp(argv[0], "-") == 0) {
249 		fstat(STDIN_FILENO, &stb1);
250 		gotstdin = 1;
251 	} else if (stat(argv[0], &stb1) != 0)
252 		err(2, "%s", argv[0]);
253 	if (strcmp(argv[1], "-") == 0) {
254 		fstat(STDIN_FILENO, &stb2);
255 		gotstdin = 1;
256 	} else if (stat(argv[1], &stb2) != 0)
257 		err(2, "%s", argv[1]);
258 	if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
259 		errx(2, "can't compare - to a directory");
260 	set_argstr(oargv, argv);
261 	if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
262 		if (diff_format == D_IFDEF)
263 			errx(2, "-D option not supported with directories");
264 		diffdir(argv[0], argv[1], dflags);
265 	} else {
266 		if (S_ISDIR(stb1.st_mode)) {
267 			argv[0] = splice(argv[0], argv[1]);
268 			if (stat(argv[0], &stb1) < 0)
269 				err(2, "%s", argv[0]);
270 		}
271 		if (S_ISDIR(stb2.st_mode)) {
272 			argv[1] = splice(argv[1], argv[0]);
273 			if (stat(argv[1], &stb2) < 0)
274 				err(2, "%s", argv[1]);
275 		}
276 		print_status(diffreg(argv[0], argv[1], dflags), argv[0], argv[1],
277 		    "");
278 	}
279 	exit(status);
280 }
281 
282 void
283 set_argstr(char **av, char **ave)
284 {
285 	size_t argsize;
286 	char **ap;
287 
288 	argsize = 4 + *ave - *av + 1;
289 	diffargs = xmalloc(argsize);
290 	strlcpy(diffargs, "diff", argsize);
291 	for (ap = av + 1; ap < ave; ap++) {
292 		if (strcmp(*ap, "--") != 0) {
293 			strlcat(diffargs, " ", argsize);
294 			strlcat(diffargs, *ap, argsize);
295 		}
296 	}
297 }
298 
299 /*
300  * Read in an excludes file and push each line.
301  */
302 void
303 read_excludes_file(char *file)
304 {
305 	FILE *fp;
306 	char *buf, *pattern;
307 	size_t len;
308 
309 	if (strcmp(file, "-") == 0)
310 		fp = stdin;
311 	else if ((fp = fopen(file, "r")) == NULL)
312 		err(2, "%s", file);
313 	while ((buf = fgetln(fp, &len)) != NULL) {
314 		if (buf[len - 1] == '\n')
315 			len--;
316 		pattern = xmalloc(len + 1);
317 		memcpy(pattern, buf, len);
318 		pattern[len] = '\0';
319 		push_excludes(pattern);
320 	}
321 	if (strcmp(file, "-") != 0)
322 		fclose(fp);
323 }
324 
325 /*
326  * Push a pattern onto the excludes list.
327  */
328 void
329 push_excludes(char *pattern)
330 {
331 	struct excludes *entry;
332 
333 	entry = xmalloc(sizeof(*entry));
334 	entry->pattern = pattern;
335 	entry->next = excludes_list;
336 	excludes_list = entry;
337 }
338 
339 void
340 push_ignore_pats(char *pattern)
341 {
342 	size_t len;
343 
344 	if (ignore_pats == NULL)
345 		ignore_pats = xstrdup(pattern);
346 	else {
347 		/* old + "|" + new + NUL */
348 		len = strlen(ignore_pats) + strlen(pattern) + 2;
349 		ignore_pats = xreallocarray(ignore_pats, 1, len);
350 		strlcat(ignore_pats, "|", len);
351 		strlcat(ignore_pats, pattern, len);
352 	}
353 }
354 
355 void
356 print_only(const char *path, size_t dirlen, const char *entry)
357 {
358 	if (dirlen > 1)
359 		dirlen--;
360 	printf("Only in %.*s: %s\n", (int)dirlen, path, entry);
361 }
362 
363 void
364 print_status(int val, char *path1, char *path2, char *entry)
365 {
366 	switch (val) {
367 	case D_ONLY:
368 		print_only(path1, strlen(path1), entry);
369 		break;
370 	case D_COMMON:
371 		printf("Common subdirectories: %s%s and %s%s\n",
372 		    path1, entry, path2, entry);
373 		break;
374 	case D_BINARY:
375 		printf("Binary files %s%s and %s%s differ\n",
376 		    path1, entry, path2, entry);
377 		break;
378 	case D_DIFFER:
379 		if (diff_format == D_BRIEF)
380 			printf("Files %s%s and %s%s differ\n",
381 			    path1, entry, path2, entry);
382 		break;
383 	case D_SAME:
384 		if (sflag)
385 			printf("Files %s%s and %s%s are identical\n",
386 			    path1, entry, path2, entry);
387 		break;
388 	case D_MISMATCH1:
389 		printf("File %s%s is a directory while file %s%s is a regular file\n",
390 		    path1, entry, path2, entry);
391 		break;
392 	case D_MISMATCH2:
393 		printf("File %s%s is a regular file while file %s%s is a directory\n",
394 		    path1, entry, path2, entry);
395 		break;
396 	case D_SKIPPED1:
397 		printf("File %s%s is not a regular file or directory and was skipped\n",
398 		    path1, entry);
399 		break;
400 	case D_SKIPPED2:
401 		printf("File %s%s is not a regular file or directory and was skipped\n",
402 		    path2, entry);
403 		break;
404 	}
405 }
406 
407 __dead void
408 usage(void)
409 {
410 	(void)fprintf(stderr,
411 	    "usage: diff [-abdilpTtw] [-c | -e | -f | -n | -q | -u] [-I pattern] [-L label]\n"
412 	    "            file1 file2\n"
413 	    "       diff [-abdilpTtw] [-I pattern] [-L label] -C number file1 file2\n"
414 	    "       diff [-abdiltw] [-I pattern] -D string file1 file2\n"
415 	    "       diff [-abdilpTtw] [-I pattern] [-L label] -U number file1 file2\n"
416 	    "       diff [-abdilNPprsTtw] [-c | -e | -f | -n | -q | -u] [-I pattern]\n"
417 	    "            [-L label] [-S name] [-X file] [-x pattern] dir1 dir2\n");
418 
419 	exit(2);
420 }
421