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