xref: /freebsd/usr.bin/diff/diff.c (revision 1d30387920db245bcefde34fc1d3ae0ee49906ca)
1 /*	$OpenBSD: diff.c,v 1.65 2015/12/29 19:04:46 gsoares 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/cdefs.h>
24 __FBSDID("$FreeBSD$");
25 
26 #include <sys/stat.h>
27 
28 #include <ctype.h>
29 #include <err.h>
30 #include <errno.h>
31 #include <getopt.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <stdarg.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <limits.h>
38 
39 #include "diff.h"
40 #include "xmalloc.h"
41 
42 int	 lflag, Nflag, Pflag, rflag, sflag, Tflag, cflag;
43 int	 diff_format, diff_context, status, ignore_file_case;
44 int	 tabsize = 8;
45 char	*start, *ifdefname, *diffargs, *label[2], *ignore_pats;
46 struct stat stb1, stb2;
47 struct excludes *excludes_list;
48 regex_t	 ignore_re;
49 
50 #define	OPTIONS	"0123456789aBbC:cdD:efhI:iL:lnNPpqrS:sTtU:uwX:x:"
51 enum {
52 	OPT_TSIZE = CHAR_MAX + 1,
53 	OPT_STRIPCR,
54 	OPT_IGN_FN_CASE,
55 	OPT_NO_IGN_FN_CASE,
56 	OPT_NORMAL,
57 	OPT_HORIZON_LINES,
58 };
59 
60 static struct option longopts[] = {
61 	{ "text",			no_argument,		0,	'a' },
62 	{ "ignore-space-change",	no_argument,		0,	'b' },
63 	{ "context",			optional_argument,	0,	'C' },
64 	{ "ifdef",			required_argument,	0,	'D' },
65 	{ "minimal",			no_argument,		0,	'd' },
66 	{ "ed",				no_argument,		0,	'e' },
67 	{ "forward-ed",			no_argument,		0,	'f' },
68 	{ "ignore-matching-lines",	required_argument,	0,	'I' },
69 	{ "ignore-case",		no_argument,		0,	'i' },
70 	{ "paginate",			no_argument,		NULL,	'l' },
71 	{ "label",			required_argument,	0,	'L' },
72 	{ "new-file",			no_argument,		0,	'N' },
73 	{ "rcs",			no_argument,		0,	'n' },
74 	{ "unidirectional-new-file",	no_argument,		0,	'P' },
75 	{ "show-c-function",		no_argument,		0,	'p' },
76 	{ "brief",			no_argument,		0,	'q' },
77 	{ "recursive",			no_argument,		0,	'r' },
78 	{ "report-identical-files",	no_argument,		0,	's' },
79 	{ "starting-file",		required_argument,	0,	'S' },
80 	{ "expand-tabs",		no_argument,		0,	't' },
81 	{ "initial-tab",		no_argument,		0,	'T' },
82 	{ "unified",			optional_argument,	0,	'U' },
83 	{ "ignore-all-space",		no_argument,		0,	'w' },
84 	{ "exclude",			required_argument,	0,	'x' },
85 	{ "exclude-from",		required_argument,	0,	'X' },
86 	{ "ignore-file-name-case",	no_argument,		NULL,	OPT_IGN_FN_CASE },
87 	{ "horizon-lines",		required_argument,	NULL,	OPT_HORIZON_LINES },
88 	{ "no-ignore-file-name-case",	no_argument,		NULL,	OPT_NO_IGN_FN_CASE },
89 	{ "normal",			no_argument,		NULL,	OPT_NORMAL },
90 	{ "strip-trailing-cr",		no_argument,		NULL,	OPT_STRIPCR },
91 	{ "tabsize",			optional_argument,	NULL,	OPT_TSIZE },
92 	{ NULL,				0,			0,	'\0'}
93 };
94 
95 void usage(void) __dead2;
96 void push_excludes(char *);
97 void push_ignore_pats(char *);
98 void read_excludes_file(char *file);
99 void set_argstr(char **, char **);
100 
101 int
102 main(int argc, char **argv)
103 {
104 	const char *errstr = NULL;
105 	char *ep, **oargv;
106 	long  l;
107 	int   ch, dflags, lastch, gotstdin, prevoptind, newarg;
108 
109 	oargv = argv;
110 	gotstdin = 0;
111 	dflags = 0;
112 	lastch = '\0';
113 	prevoptind = 1;
114 	newarg = 1;
115 	diff_context = 3;
116 	diff_format = 0;
117 	while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
118 		switch (ch) {
119 		case '0': case '1': case '2': case '3': case '4':
120 		case '5': case '6': case '7': case '8': case '9':
121 			if (newarg)
122 				usage();	/* disallow -[0-9]+ */
123 			else if (lastch == 'c' || lastch == 'u')
124 				diff_context = 0;
125 			else if (!isdigit(lastch) || diff_context > INT_MAX / 10)
126 				usage();
127 			diff_context = (diff_context * 10) + (ch - '0');
128 			break;
129 		case 'a':
130 			dflags |= D_FORCEASCII;
131 			break;
132 		case 'b':
133 			dflags |= D_FOLDBLANKS;
134 			break;
135 		case 'C':
136 		case 'c':
137 			cflag = 1;
138 			diff_format = D_CONTEXT;
139 			if (optarg != NULL) {
140 				l = strtol(optarg, &ep, 10);
141 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
142 					usage();
143 				diff_context = (int)l;
144 			}
145 			break;
146 		case 'd':
147 			dflags |= D_MINIMAL;
148 			break;
149 		case 'D':
150 			diff_format = D_IFDEF;
151 			ifdefname = optarg;
152 			break;
153 		case 'e':
154 			diff_format = D_EDIT;
155 			break;
156 		case 'f':
157 			diff_format = D_REVERSE;
158 			break;
159 		case 'h':
160 			/* silently ignore for backwards compatibility */
161 			break;
162 		case 'I':
163 			push_ignore_pats(optarg);
164 			break;
165 		case 'i':
166 			dflags |= D_IGNORECASE;
167 			break;
168 		case 'L':
169 			if (label[0] == NULL)
170 				label[0] = optarg;
171 			else if (label[1] == NULL)
172 				label[1] = optarg;
173 			else
174 				usage();
175 			break;
176 		case 'l':
177 			lflag = 1;
178 			break;
179 		case 'N':
180 			Nflag = 1;
181 			break;
182 		case 'n':
183 			diff_format = D_NREVERSE;
184 			break;
185 		case 'p':
186 			if (diff_format == 0)
187 				diff_format = D_CONTEXT;
188 			dflags |= D_PROTOTYPE;
189 			break;
190 		case 'P':
191 			Pflag = 1;
192 			break;
193 		case 'r':
194 			rflag = 1;
195 			break;
196 		case 'q':
197 			diff_format = D_BRIEF;
198 			break;
199 		case 'S':
200 			start = optarg;
201 			break;
202 		case 's':
203 			sflag = 1;
204 			break;
205 		case 'T':
206 			Tflag = 1;
207 			break;
208 		case 't':
209 			dflags |= D_EXPANDTABS;
210 			break;
211 		case 'U':
212 		case 'u':
213 			diff_format = D_UNIFIED;
214 			if (optarg != NULL) {
215 				l = strtol(optarg, &ep, 10);
216 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
217 					usage();
218 				diff_context = (int)l;
219 			}
220 			break;
221 		case 'w':
222 			dflags |= D_IGNOREBLANKS;
223 			break;
224 		case 'X':
225 			read_excludes_file(optarg);
226 			break;
227 		case 'x':
228 			push_excludes(optarg);
229 			break;
230 		case OPT_HORIZON_LINES:
231 			break; /* XXX TODO for compatibility with GNU diff3 */
232 		case OPT_IGN_FN_CASE:
233 			ignore_file_case = 1;
234 			break;
235 		case OPT_NO_IGN_FN_CASE:
236 			ignore_file_case = 0;
237 			break;
238 		case OPT_NORMAL:
239 			diff_format = D_NORMAL;
240 			break;
241 		case OPT_TSIZE:
242 			tabsize = (int) strtonum(optarg, 1, INT_MAX, &errstr);
243 			if (errstr) {
244 				warnx("Invalid argument for tabsize");
245 				usage();
246 			}
247 			break;
248 		case OPT_STRIPCR:
249 			dflags |= D_STRIPCR;
250 			break;
251 		default:
252 			usage();
253 			break;
254 		}
255 		lastch = ch;
256 		newarg = optind != prevoptind;
257 		prevoptind = optind;
258 	}
259 	argc -= optind;
260 	argv += optind;
261 
262 #ifdef __OpenBSD__
263 	if (pledge("stdio rpath tmppath", NULL) == -1)
264 		err(2, "pledge");
265 #endif
266 
267 	/*
268 	 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
269 	 * driver routine.  Both drivers use the contents of stb1 and stb2.
270 	 */
271 	if (argc != 2)
272 		usage();
273 	if (ignore_pats != NULL) {
274 		char buf[BUFSIZ];
275 		int error;
276 
277 		if ((error = regcomp(&ignore_re, ignore_pats,
278 				     REG_NEWLINE | REG_EXTENDED)) != 0) {
279 			regerror(error, &ignore_re, buf, sizeof(buf));
280 			if (*ignore_pats != '\0')
281 				errx(2, "%s: %s", ignore_pats, buf);
282 			else
283 				errx(2, "%s", buf);
284 		}
285 	}
286 	if (strcmp(argv[0], "-") == 0) {
287 		fstat(STDIN_FILENO, &stb1);
288 		gotstdin = 1;
289 	} else if (stat(argv[0], &stb1) != 0)
290 		err(2, "%s", argv[0]);
291 	if (strcmp(argv[1], "-") == 0) {
292 		fstat(STDIN_FILENO, &stb2);
293 		gotstdin = 1;
294 	} else if (stat(argv[1], &stb2) != 0)
295 		err(2, "%s", argv[1]);
296 	if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
297 		errx(2, "can't compare - to a directory");
298 	set_argstr(oargv, argv);
299 	if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
300 		if (diff_format == D_IFDEF)
301 			errx(2, "-D option not supported with directories");
302 		diffdir(argv[0], argv[1], dflags);
303 	} else {
304 		if (S_ISDIR(stb1.st_mode)) {
305 			argv[0] = splice(argv[0], argv[1]);
306 			if (stat(argv[0], &stb1) < 0)
307 				err(2, "%s", argv[0]);
308 		}
309 		if (S_ISDIR(stb2.st_mode)) {
310 			argv[1] = splice(argv[1], argv[0]);
311 			if (stat(argv[1], &stb2) < 0)
312 				err(2, "%s", argv[1]);
313 		}
314 		print_status(diffreg(argv[0], argv[1], dflags, 1), argv[0],
315 		    argv[1], "");
316 	}
317 	exit(status);
318 }
319 
320 void
321 set_argstr(char **av, char **ave)
322 {
323 	size_t argsize;
324 	char **ap;
325 
326 	argsize = 4 + *ave - *av + 1;
327 	diffargs = xmalloc(argsize);
328 	strlcpy(diffargs, "diff", argsize);
329 	for (ap = av + 1; ap < ave; ap++) {
330 		if (strcmp(*ap, "--") != 0) {
331 			strlcat(diffargs, " ", argsize);
332 			strlcat(diffargs, *ap, argsize);
333 		}
334 	}
335 }
336 
337 /*
338  * Read in an excludes file and push each line.
339  */
340 void
341 read_excludes_file(char *file)
342 {
343 	FILE *fp;
344 	char *buf, *pattern;
345 	size_t len;
346 
347 	if (strcmp(file, "-") == 0)
348 		fp = stdin;
349 	else if ((fp = fopen(file, "r")) == NULL)
350 		err(2, "%s", file);
351 	while ((buf = fgetln(fp, &len)) != NULL) {
352 		if (buf[len - 1] == '\n')
353 			len--;
354 		if ((pattern = strndup(buf, len)) == NULL)
355 			err(2, "xstrndup");
356 		push_excludes(pattern);
357 	}
358 	if (strcmp(file, "-") != 0)
359 		fclose(fp);
360 }
361 
362 /*
363  * Push a pattern onto the excludes list.
364  */
365 void
366 push_excludes(char *pattern)
367 {
368 	struct excludes *entry;
369 
370 	entry = xmalloc(sizeof(*entry));
371 	entry->pattern = pattern;
372 	entry->next = excludes_list;
373 	excludes_list = entry;
374 }
375 
376 void
377 push_ignore_pats(char *pattern)
378 {
379 	size_t len;
380 
381 	if (ignore_pats == NULL)
382 		ignore_pats = xstrdup(pattern);
383 	else {
384 		/* old + "|" + new + NUL */
385 		len = strlen(ignore_pats) + strlen(pattern) + 2;
386 		ignore_pats = xreallocarray(ignore_pats, 1, len);
387 		strlcat(ignore_pats, "|", len);
388 		strlcat(ignore_pats, pattern, len);
389 	}
390 }
391 
392 void
393 print_only(const char *path, size_t dirlen, const char *entry)
394 {
395 	if (dirlen > 1)
396 		dirlen--;
397 	printf("Only in %.*s: %s\n", (int)dirlen, path, entry);
398 }
399 
400 void
401 print_status(int val, char *path1, char *path2, const char *entry)
402 {
403 	switch (val) {
404 	case D_BINARY:
405 		printf("Binary files %s%s and %s%s differ\n",
406 		    path1, entry, path2, entry);
407 		break;
408 	case D_DIFFER:
409 		if (diff_format == D_BRIEF)
410 			printf("Files %s%s and %s%s differ\n",
411 			    path1, entry, path2, entry);
412 		break;
413 	case D_SAME:
414 		if (sflag)
415 			printf("Files %s%s and %s%s are identical\n",
416 			    path1, entry, path2, entry);
417 		break;
418 	case D_MISMATCH1:
419 		printf("File %s%s is a directory while file %s%s is a regular file\n",
420 		    path1, entry, path2, entry);
421 		break;
422 	case D_MISMATCH2:
423 		printf("File %s%s is a regular file while file %s%s is a directory\n",
424 		    path1, entry, path2, entry);
425 		break;
426 	case D_SKIPPED1:
427 		printf("File %s%s is not a regular file or directory and was skipped\n",
428 		    path1, entry);
429 		break;
430 	case D_SKIPPED2:
431 		printf("File %s%s is not a regular file or directory and was skipped\n",
432 		    path2, entry);
433 		break;
434 	}
435 }
436 
437 void
438 usage(void)
439 {
440 	(void)fprintf(stderr,
441 	    "usage: diff [-abdilpTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
442 	    "            [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
443 	    "            [-I pattern] [-L label] file1 file2\n"
444 	    "       diff [-abdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
445 	    "            [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
446 	    "            -C number file1 file2\n"
447 	    "       diff [-abdiltw] [-I pattern] [--ignore-case] [--no-ignore-case]\n"
448 	    "            [--normal] [--strip-trailing-cr] [--tabsize] -D string file1 file2\n"
449 	    "       diff [-abdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
450 	    "            [--no-ignore-case] [--normal] [--tabsize] [--strip-trailing-cr]\n"
451 	    "            -U number file1 file2\n"
452 	    "       diff [-abdilNPprsTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
453 	    "            [--no-ignore-case] [--normal] [--tabsize] [-I pattern] [-L label]\n"
454 	    "            [-S name] [-X file] [-x pattern] dir1 dir2\n");
455 
456 	exit(2);
457 }
458