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