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