xref: /freebsd/usr.bin/diff/diff.c (revision f0cfa1b168014f56c02b83e5f28412cc5f78d117)
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-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 	{ "strip-trailing-cr",		no_argument,		NULL,	OPT_STRIPCR },
92 	{ "tabsize",			optional_argument,	NULL,	OPT_TSIZE },
93 	{ "changed-group-format",	required_argument,	NULL,	OPT_CHANGED_GROUP_FORMAT},
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 			/* ignore but needed for compatibility with GNU diff */
163 			break;
164 		case 'h':
165 			/* silently ignore for backwards compatibility */
166 			break;
167 		case 'I':
168 			push_ignore_pats(optarg);
169 			break;
170 		case 'i':
171 			dflags |= D_IGNORECASE;
172 			break;
173 		case 'L':
174 			if (label[0] == NULL)
175 				label[0] = optarg;
176 			else if (label[1] == NULL)
177 				label[1] = optarg;
178 			else
179 				usage();
180 			break;
181 		case 'l':
182 			lflag = 1;
183 			break;
184 		case 'N':
185 			Nflag = 1;
186 			break;
187 		case 'n':
188 			diff_format = D_NREVERSE;
189 			break;
190 		case 'p':
191 			if (diff_format == 0)
192 				diff_format = D_CONTEXT;
193 			dflags |= D_PROTOTYPE;
194 			break;
195 		case 'P':
196 			Pflag = 1;
197 			break;
198 		case 'r':
199 			rflag = 1;
200 			break;
201 		case 'q':
202 			diff_format = D_BRIEF;
203 			break;
204 		case 'S':
205 			start = optarg;
206 			break;
207 		case 's':
208 			sflag = 1;
209 			break;
210 		case 'T':
211 			Tflag = 1;
212 			break;
213 		case 't':
214 			dflags |= D_EXPANDTABS;
215 			break;
216 		case 'U':
217 		case 'u':
218 			diff_format = D_UNIFIED;
219 			if (optarg != NULL) {
220 				l = strtol(optarg, &ep, 10);
221 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
222 					usage();
223 				diff_context = (int)l;
224 			}
225 			break;
226 		case 'w':
227 			dflags |= D_IGNOREBLANKS;
228 			break;
229 		case 'X':
230 			read_excludes_file(optarg);
231 			break;
232 		case 'x':
233 			push_excludes(optarg);
234 			break;
235 		case OPT_CHANGED_GROUP_FORMAT:
236 			diff_format = D_GFORMAT;
237 			group_format = optarg;
238 			break;
239 		case OPT_HORIZON_LINES:
240 			break; /* XXX TODO for compatibility with GNU diff3 */
241 		case OPT_IGN_FN_CASE:
242 			ignore_file_case = 1;
243 			break;
244 		case OPT_NO_IGN_FN_CASE:
245 			ignore_file_case = 0;
246 			break;
247 		case OPT_NORMAL:
248 			diff_format = D_NORMAL;
249 			break;
250 		case OPT_TSIZE:
251 			tabsize = (int) strtonum(optarg, 1, INT_MAX, &errstr);
252 			if (errstr) {
253 				warnx("Invalid argument for tabsize");
254 				usage();
255 			}
256 			break;
257 		case OPT_STRIPCR:
258 			dflags |= D_STRIPCR;
259 			break;
260 		default:
261 			usage();
262 			break;
263 		}
264 		lastch = ch;
265 		newarg = optind != prevoptind;
266 		prevoptind = optind;
267 	}
268 	argc -= optind;
269 	argv += optind;
270 
271 #ifdef __OpenBSD__
272 	if (pledge("stdio rpath tmppath", NULL) == -1)
273 		err(2, "pledge");
274 #endif
275 
276 	/*
277 	 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
278 	 * driver routine.  Both drivers use the contents of stb1 and stb2.
279 	 */
280 	if (argc != 2)
281 		usage();
282 	if (ignore_pats != NULL) {
283 		char buf[BUFSIZ];
284 		int error;
285 
286 		if ((error = regcomp(&ignore_re, ignore_pats,
287 				     REG_NEWLINE | REG_EXTENDED)) != 0) {
288 			regerror(error, &ignore_re, buf, sizeof(buf));
289 			if (*ignore_pats != '\0')
290 				errx(2, "%s: %s", ignore_pats, buf);
291 			else
292 				errx(2, "%s", buf);
293 		}
294 	}
295 	if (strcmp(argv[0], "-") == 0) {
296 		fstat(STDIN_FILENO, &stb1);
297 		gotstdin = 1;
298 	} else if (stat(argv[0], &stb1) != 0)
299 		err(2, "%s", argv[0]);
300 	if (strcmp(argv[1], "-") == 0) {
301 		fstat(STDIN_FILENO, &stb2);
302 		gotstdin = 1;
303 	} else if (stat(argv[1], &stb2) != 0)
304 		err(2, "%s", argv[1]);
305 	if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
306 		errx(2, "can't compare - to a directory");
307 	set_argstr(oargv, argv);
308 	if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
309 		if (diff_format == D_IFDEF)
310 			errx(2, "-D option not supported with directories");
311 		diffdir(argv[0], argv[1], dflags);
312 	} else {
313 		if (S_ISDIR(stb1.st_mode)) {
314 			argv[0] = splice(argv[0], argv[1]);
315 			if (stat(argv[0], &stb1) < 0)
316 				err(2, "%s", argv[0]);
317 		}
318 		if (S_ISDIR(stb2.st_mode)) {
319 			argv[1] = splice(argv[1], argv[0]);
320 			if (stat(argv[1], &stb2) < 0)
321 				err(2, "%s", argv[1]);
322 		}
323 		print_status(diffreg(argv[0], argv[1], dflags, 1), argv[0],
324 		    argv[1], "");
325 	}
326 	exit(status);
327 }
328 
329 void
330 set_argstr(char **av, char **ave)
331 {
332 	size_t argsize;
333 	char **ap;
334 
335 	argsize = 4 + *ave - *av + 1;
336 	diffargs = xmalloc(argsize);
337 	strlcpy(diffargs, "diff", argsize);
338 	for (ap = av + 1; ap < ave; ap++) {
339 		if (strcmp(*ap, "--") != 0) {
340 			strlcat(diffargs, " ", argsize);
341 			strlcat(diffargs, *ap, argsize);
342 		}
343 	}
344 }
345 
346 /*
347  * Read in an excludes file and push each line.
348  */
349 void
350 read_excludes_file(char *file)
351 {
352 	FILE *fp;
353 	char *buf, *pattern;
354 	size_t len;
355 
356 	if (strcmp(file, "-") == 0)
357 		fp = stdin;
358 	else if ((fp = fopen(file, "r")) == NULL)
359 		err(2, "%s", file);
360 	while ((buf = fgetln(fp, &len)) != NULL) {
361 		if (buf[len - 1] == '\n')
362 			len--;
363 		if ((pattern = strndup(buf, len)) == NULL)
364 			err(2, "xstrndup");
365 		push_excludes(pattern);
366 	}
367 	if (strcmp(file, "-") != 0)
368 		fclose(fp);
369 }
370 
371 /*
372  * Push a pattern onto the excludes list.
373  */
374 void
375 push_excludes(char *pattern)
376 {
377 	struct excludes *entry;
378 
379 	entry = xmalloc(sizeof(*entry));
380 	entry->pattern = pattern;
381 	entry->next = excludes_list;
382 	excludes_list = entry;
383 }
384 
385 void
386 push_ignore_pats(char *pattern)
387 {
388 	size_t len;
389 
390 	if (ignore_pats == NULL)
391 		ignore_pats = xstrdup(pattern);
392 	else {
393 		/* old + "|" + new + NUL */
394 		len = strlen(ignore_pats) + strlen(pattern) + 2;
395 		ignore_pats = xreallocarray(ignore_pats, 1, len);
396 		strlcat(ignore_pats, "|", len);
397 		strlcat(ignore_pats, pattern, len);
398 	}
399 }
400 
401 void
402 print_only(const char *path, size_t dirlen, const char *entry)
403 {
404 	if (dirlen > 1)
405 		dirlen--;
406 	printf("Only in %.*s: %s\n", (int)dirlen, path, entry);
407 }
408 
409 void
410 print_status(int val, char *path1, char *path2, const char *entry)
411 {
412 	switch (val) {
413 	case D_BINARY:
414 		printf("Binary files %s%s and %s%s differ\n",
415 		    path1, entry, path2, entry);
416 		break;
417 	case D_DIFFER:
418 		if (diff_format == D_BRIEF)
419 			printf("Files %s%s and %s%s differ\n",
420 			    path1, entry, path2, entry);
421 		break;
422 	case D_SAME:
423 		if (sflag)
424 			printf("Files %s%s and %s%s are identical\n",
425 			    path1, entry, path2, entry);
426 		break;
427 	case D_MISMATCH1:
428 		printf("File %s%s is a directory while file %s%s is a regular file\n",
429 		    path1, entry, path2, entry);
430 		break;
431 	case D_MISMATCH2:
432 		printf("File %s%s is a regular file while file %s%s is a directory\n",
433 		    path1, entry, path2, entry);
434 		break;
435 	case D_SKIPPED1:
436 		printf("File %s%s is not a regular file or directory and was skipped\n",
437 		    path1, entry);
438 		break;
439 	case D_SKIPPED2:
440 		printf("File %s%s is not a regular file or directory and was skipped\n",
441 		    path2, entry);
442 		break;
443 	}
444 }
445 
446 void
447 usage(void)
448 {
449 	(void)fprintf(stderr,
450 	    "usage: diff [-abdilpTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
451 	    "            [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
452 	    "            [-I pattern] [-L label] file1 file2\n"
453 	    "       diff [-abdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
454 	    "            [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
455 	    "            -C number file1 file2\n"
456 	    "       diff [-abdiltw] [-I pattern] [--ignore-case] [--no-ignore-case]\n"
457 	    "            [--normal] [--strip-trailing-cr] [--tabsize] -D string file1 file2\n"
458 	    "       diff [-abdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
459 	    "            [--no-ignore-case] [--normal] [--tabsize] [--strip-trailing-cr]\n"
460 	    "            -U number file1 file2\n"
461 	    "       diff [-abdilNPprsTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
462 	    "            [--no-ignore-case] [--normal] [--tabsize] [-I pattern] [-L label]\n"
463 	    "            [-S name] [-X file] [-x pattern] dir1 dir2\n");
464 
465 	exit(2);
466 }
467