xref: /openbsd-src/usr.bin/diff/diff.c (revision 4893e147a96c816b4d8cd3a964f938216bfca7ef)
1 /*	$OpenBSD: diff.c,v 1.43 2003/10/07 23:37:27 millert 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 #ifndef lint
24 static const char rcsid[] = "$OpenBSD: diff.c,v 1.43 2003/10/07 23:37:27 millert Exp $";
25 #endif /* not lint */
26 
27 #include <sys/param.h>
28 #include <sys/stat.h>
29 
30 #include <ctype.h>
31 #include <err.h>
32 #include <errno.h>
33 #include <getopt.h>
34 #include <signal.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <stdarg.h>
38 #include <string.h>
39 #include <unistd.h>
40 
41 #include "diff.h"
42 
43 int	 aflag, bflag, dflag, iflag, lflag, Nflag, Pflag, rflag;
44 int	 sflag, tflag, Tflag, wflag;
45 int	 format, context, status;
46 char	*start, *ifdefname, *diffargs, *label;
47 struct stat stb1, stb2;
48 struct excludes *excludes_list;
49 
50 #define	OPTIONS	"0123456789abC:cdD:efhiL:lnNPqrS:sTtU:uwX:x:"
51 static struct option longopts[] = {
52 	{ "text",			no_argument,		0,	'a' },
53 	{ "ignore-space-change",	no_argument,		0,	'b' },
54 	{ "context",			optional_argument,	0,	'C' },
55 	{ "ifdef",			required_argument,	0,	'D' },
56 	{ "minimal",			no_argument,		0,	'd' },
57 	{ "ed",				no_argument,		0,	'e' },
58 	{ "forward-ed",			no_argument,		0,	'f' },
59 	{ "ignore-case",		no_argument,		0,	'i' },
60 	{ "paginate",			no_argument,		0,	'l' },
61 	{ "label",			required_argument,	0,	'L' },
62 	{ "new-file",			no_argument,		0,	'N' },
63 	{ "rcs",			no_argument,		0,	'n' },
64 	{ "unidirectional-new-file",	no_argument,		0,	'P' },
65 	{ "brief",			no_argument,		0,	'q' },
66 	{ "recursive",			no_argument,		0,	'r' },
67 	{ "report-identical-files",	no_argument,		0,	's' },
68 	{ "starting-file",		required_argument,	0,	'S' },
69 	{ "expand-tabs",		no_argument,		0,	't' },
70 	{ "initial-tab",		no_argument,		0,	'T' },
71 	{ "unified",			optional_argument,	0,	'U' },
72 	{ "ignore-all-space",		no_argument,		0,	'w' },
73 	{ "exclude",			required_argument,	0,	'x' },
74 	{ "exclude-from",		required_argument,	0,	'X' },
75 	{ NULL,				0,			0,	'\0'}
76 };
77 
78 __dead void usage(void);
79 void push_excludes(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, lastch, gotstdin, prevoptind, newarg;
89 
90 	oargv = argv;
91 	gotstdin = 0;
92 
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 				context = 0;
104 			else if (!isdigit(lastch) || context > INT_MAX / 10)
105 				usage();
106 			context = (context * 10) + (ch - '0');
107 			break;
108 		case 'a':
109 			aflag = 1;
110 			break;
111 		case 'b':
112 			bflag = 1;
113 			break;
114 		case 'C':
115 		case 'c':
116 			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 				context = (int)l;
122 			} else
123 				context = 3;
124 			break;
125 		case 'd':
126 			dflag = 1;
127 			break;
128 		case 'D':
129 			format = D_IFDEF;
130 			ifdefname = optarg;
131 			break;
132 		case 'e':
133 			format = D_EDIT;
134 			break;
135 		case 'f':
136 			format = D_REVERSE;
137 			break;
138 		case 'h':
139 			/* silently ignore for backwards compatibility */
140 			break;
141 		case 'i':
142 			iflag = 1;
143 			break;
144 		case 'L':
145 			label = optarg;
146 			break;
147 		case 'l':
148 			lflag = 1;
149 			signal(SIGPIPE, SIG_IGN);
150 			break;
151 		case 'N':
152 			Nflag = 1;
153 			break;
154 		case 'n':
155 			format = D_NREVERSE;
156 			break;
157 		case 'P':
158 			Pflag = 1;
159 			break;
160 		case 'r':
161 			rflag = 1;
162 			break;
163 		case 'q':
164 			format = D_BRIEF;
165 			break;
166 		case 'S':
167 			start = optarg;
168 			break;
169 		case 's':
170 			sflag = 1;
171 			break;
172 		case 'T':
173 			Tflag = 1;
174 			break;
175 		case 't':
176 			tflag = 1;
177 			break;
178 		case 'U':
179 		case 'u':
180 			format = D_UNIFIED;
181 			if (optarg != NULL) {
182 				l = strtol(optarg, &ep, 10);
183 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
184 					usage();
185 				context = (int)l;
186 			} else
187 				context = 3;
188 			break;
189 		case 'w':
190 			wflag = 1;
191 			break;
192 		case 'X':
193 			read_excludes_file(optarg);
194 			break;
195 		case 'x':
196 			push_excludes(optarg);
197 			break;
198 		default:
199 			usage();
200 			break;
201 		}
202 		lastch = ch;
203 		newarg = optind != prevoptind;
204 		prevoptind = optind;
205 	}
206 	argc -= optind;
207 	argv += optind;
208 
209 	/*
210 	 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
211 	 * driver routine.  Both drivers use the contents of stb1 and stb2.
212 	 */
213 	if (argc != 2)
214 		usage();
215 	if (strcmp(argv[0], "-") == 0) {
216 		fstat(STDIN_FILENO, &stb1);
217 		gotstdin = 1;
218 	} else if (stat(argv[0], &stb1) != 0)
219 		err(2, "%s", argv[0]);
220 	if (strcmp(argv[1], "-") == 0) {
221 		fstat(STDIN_FILENO, &stb2);
222 		gotstdin = 1;
223 	} else if (stat(argv[1], &stb2) != 0)
224 		err(2, "%s", argv[1]);
225 	if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
226 		errx(2, "can't compare - to a directory");
227 	set_argstr(oargv + 1, argv);
228 	if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
229 		if (format == D_IFDEF)
230 			errx(2, "-D option not supported with directories");
231 		diffdir(argv[0], argv[1]);
232 	} else {
233 		if (S_ISDIR(stb1.st_mode)) {
234 			argv[0] = splice(argv[0], argv[1]);
235 			if (stat(argv[0], &stb1) < 0)
236 				err(2, "%s", argv[0]);
237 		}
238 		if (S_ISDIR(stb2.st_mode)) {
239 			argv[1] = splice(argv[1], argv[0]);
240 			if (stat(argv[1], &stb2) < 0)
241 				err(2, "%s", argv[1]);
242 		}
243 		print_status(diffreg(argv[0], argv[1], 0), argv[0], argv[1],
244 		    NULL);
245 	}
246 	exit(status);
247 }
248 
249 void *
250 emalloc(size_t n)
251 {
252 	void *p;
253 
254 	if ((p = malloc(n)) == NULL)
255 		err(2, NULL);
256 	return (p);
257 }
258 
259 void *
260 erealloc(void *p, size_t n)
261 {
262 	void *q;
263 
264 	if ((q = realloc(p, n)) == NULL)
265 		err(2, NULL);
266 	return (q);
267 }
268 
269 int
270 easprintf(char **ret, const char *fmt, ...)
271 {
272 	int len;
273 	va_list ap;
274 
275 	va_start(ap, fmt);
276 	len = vasprintf(ret, fmt, ap);
277 	va_end(ap);
278 
279 	if (len == -1)
280 		err(2, NULL);
281 	return (len);
282 }
283 
284 void
285 set_argstr(char **av, char **ave)
286 {
287 	size_t argsize;
288 	char **ap;
289 
290 	argsize = 4 + *ave - *av + 1;
291 	diffargs = emalloc(argsize);
292 	strlcpy(diffargs, "diff", argsize);
293 	for (ap = av + 1; ap < ave; ap++) {
294 		if (strcmp(*ap, "--") != 0) {
295 			strlcat(diffargs, " ", argsize);
296 			strlcat(diffargs, *ap, argsize);
297 		}
298 	}
299 }
300 
301 /*
302  * Read in an excludes file and push each line.
303  */
304 void
305 read_excludes_file(char *file)
306 {
307 	FILE *fp;
308 	char *buf, *pattern;
309 	size_t len;
310 
311 	if (strcmp(file, "-") == 0)
312 		fp = stdin;
313 	else if ((fp = fopen(file, "r")) == NULL)
314 		err(2, "%s", file);
315 	while ((buf = fgetln(fp, &len)) != NULL) {
316 		if (buf[len - 1] == '\n')
317 			len--;
318 		pattern = emalloc(len + 1);
319 		memcpy(pattern, buf, len);
320 		pattern[len] = '\0';
321 		push_excludes(pattern);
322 	}
323 	if (strcmp(file, "-") != 0)
324 		fclose(fp);
325 }
326 
327 /*
328  * Push a pattern onto the excludes list.
329  */
330 void
331 push_excludes(char *pattern)
332 {
333 	struct excludes *entry;
334 
335 	entry = emalloc(sizeof(*entry));
336 	entry->pattern = pattern;
337 	entry->next = excludes_list;
338 	excludes_list = entry;
339 }
340 
341 void
342 print_only(const char *path, size_t dirlen, const char *entry)
343 {
344 	if (dirlen > 1)
345 		dirlen--;
346 	printf("Only in %.*s: %s\n", (int)dirlen, path, entry);
347 }
348 
349 void
350 print_status(int val, char *path1, char *path2, char *entry)
351 {
352 	switch (val) {
353 	case D_ONLY:
354 		print_only(path1, strlen(path1), entry);
355 		break;
356 	case D_COMMON:
357 		printf("Common subdirectories: %s%s and %s%s\n",
358 		    path1, entry ? entry : "", path2, entry ? entry : "");
359 		break;
360 	case D_BINARY:
361 		printf("Binary files %s%s and %s%s differ\n",
362 		    path1, entry ? entry : "", path2, entry ? entry : "");
363 		break;
364 	case D_DIFFER:
365 		if (format == D_BRIEF)
366 			printf("Files %s%s and %s%s differ\n",
367 			    path1, entry ? entry : "",
368 			    path2, entry ? entry : "");
369 		break;
370 	case D_SAME:
371 		if (sflag)
372 			printf("Files %s%s and %s%s are identical\n",
373 			    path1, entry ? entry : "",
374 			    path2, entry ? entry : "");
375 		break;
376 	case D_MISMATCH1:
377 		printf("File %s%s is a directory while file %s%s is a regular file\n",
378 		    path1, entry ? entry : "", path2, entry ? entry : "");
379 		break;
380 	case D_MISMATCH2:
381 		printf("File %s%s is a regular file while file %s%s is a directory\n",
382 		    path1, entry ? entry : "", path2, entry ? entry : "");
383 		break;
384 	}
385 }
386 
387 __dead void
388 usage(void)
389 {
390 	(void)fprintf(stderr,
391 	    "usage: diff [-abdilqtTw] [-c | -e | -f | -n | -u] [-L label] file1 file2\n"
392 	    "       diff [-abdilqtTw] [-L label] -C number file1 file2\n"
393 	    "       diff [-abdilqtw] -D string file1 file2\n"
394 	    "       diff [-abdilqtTw] [-L label] -U number file1 file2\n"
395 	    "       diff [-abdilNPqtTw] [-c | -e | -f | -n | -u ] [-L label] [-r] [-s]\n"
396 	    "            [-S name] [-X file] [-x pattern] dir1 dir2\n");
397 
398 	exit(2);
399 }
400