1 /* $OpenBSD: diff.c,v 1.67 2019/06/28 13:35:00 deraadt Exp $ */
4 * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
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.
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.
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.
23 #include <sys/cdefs.h>
39 static const char diff_version[] = "FreeBSD diff 20220309";
40 bool lflag, Nflag, Pflag, rflag, sflag, Tflag, cflag;
41 bool ignore_file_case, suppress_common, color, noderef;
42 static bool help = false;
43 int diff_format, diff_context, status;
44 int tabsize = 8, width = 130;
45 static int colorflag = COLORFLAG_NEVER;
46 char *start, *ifdefname, *diffargs, *label[2];
47 char *ignore_pats, *most_recent_pat;
48 char *group_format = NULL;
49 const char *add_code, *del_code;
50 struct stat stb1, stb2;
51 struct excludes *excludes_list;
52 regex_t ignore_re, most_recent_re;
54 #define OPTIONS "0123456789aBbC:cdD:efF:HhI:iL:lnNPpqrS:sTtU:uwW:X:x:y"
56 OPT_TSIZE = CHAR_MAX + 1,
63 OPT_CHANGED_GROUP_FORMAT,
70 static struct option longopts[] = {
71 { "text", no_argument, 0, 'a' },
72 { "ignore-space-change", no_argument, 0, 'b' },
73 { "context", optional_argument, 0, 'C' },
74 { "ifdef", required_argument, 0, 'D' },
75 { "minimal", no_argument, 0, 'd' },
76 { "ed", no_argument, 0, 'e' },
77 { "forward-ed", no_argument, 0, 'f' },
78 { "show-function-line", required_argument, 0, 'F' },
79 { "speed-large-files", no_argument, NULL, 'H' },
80 { "ignore-blank-lines", no_argument, 0, 'B' },
81 { "ignore-matching-lines", required_argument, 0, 'I' },
82 { "ignore-case", no_argument, 0, 'i' },
83 { "paginate", no_argument, NULL, 'l' },
84 { "label", required_argument, 0, 'L' },
85 { "new-file", no_argument, 0, 'N' },
86 { "rcs", no_argument, 0, 'n' },
87 { "unidirectional-new-file", no_argument, 0, 'P' },
88 { "show-c-function", no_argument, 0, 'p' },
89 { "brief", no_argument, 0, 'q' },
90 { "recursive", no_argument, 0, 'r' },
91 { "report-identical-files", no_argument, 0, 's' },
92 { "starting-file", required_argument, 0, 'S' },
93 { "expand-tabs", no_argument, 0, 't' },
94 { "initial-tab", no_argument, 0, 'T' },
95 { "unified", optional_argument, 0, 'U' },
96 { "ignore-all-space", no_argument, 0, 'w' },
97 { "width", required_argument, 0, 'W' },
98 { "exclude", required_argument, 0, 'x' },
99 { "exclude-from", required_argument, 0, 'X' },
100 { "side-by-side", no_argument, NULL, 'y' },
101 { "ignore-file-name-case", no_argument, NULL, OPT_IGN_FN_CASE },
102 { "help", no_argument, NULL, OPT_HELP},
103 { "horizon-lines", required_argument, NULL, OPT_HORIZON_LINES },
104 { "no-dereference", no_argument, NULL, OPT_NO_DEREFERENCE},
105 { "no-ignore-file-name-case", no_argument, NULL, OPT_NO_IGN_FN_CASE },
106 { "normal", no_argument, NULL, OPT_NORMAL },
107 { "strip-trailing-cr", no_argument, NULL, OPT_STRIPCR },
108 { "tabsize", required_argument, NULL, OPT_TSIZE },
109 { "changed-group-format", required_argument, NULL, OPT_CHANGED_GROUP_FORMAT},
110 { "suppress-common-lines", no_argument, NULL, OPT_SUPPRESS_COMMON },
111 { "color", optional_argument, NULL, OPT_COLOR },
112 { "version", no_argument, NULL, OPT_VERSION},
116 static void checked_regcomp(char const *, regex_t *);
117 static void usage(void) __dead2;
118 static void conflicting_format(void) __dead2;
119 static void push_excludes(char *);
120 static void push_ignore_pats(char *);
121 static void read_excludes_file(char *file);
122 static void set_argstr(char **, char **);
123 static char *splice(char *, char *);
124 static bool do_color(void);
127 main(int argc, char **argv)
129 const char *errstr = NULL;
132 int ch, dflags, lastch, gotstdin, prevoptind, newarg;
141 diff_format = D_UNSET;
142 #define FORMAT_MISMATCHED(type) \
143 (diff_format != D_UNSET && diff_format != (type))
144 while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
146 case '0': case '1': case '2': case '3': case '4':
147 case '5': case '6': case '7': case '8': case '9':
149 usage(); /* disallow -[0-9]+ */
150 else if (lastch == 'c' || lastch == 'u')
152 else if (!isdigit(lastch) || diff_context > INT_MAX / 10)
154 diff_context = (diff_context * 10) + (ch - '0');
157 dflags |= D_FORCEASCII;
160 dflags |= D_FOLDBLANKS;
164 if (FORMAT_MISMATCHED(D_CONTEXT))
165 conflicting_format();
167 diff_format = D_CONTEXT;
168 if (optarg != NULL) {
169 l = strtol(optarg, &ep, 10);
170 if (*ep != '\0' || l < 0 || l >= INT_MAX)
172 diff_context = (int)l;
179 if (FORMAT_MISMATCHED(D_IFDEF))
180 conflicting_format();
181 diff_format = D_IFDEF;
185 if (FORMAT_MISMATCHED(D_EDIT))
186 conflicting_format();
187 diff_format = D_EDIT;
190 if (FORMAT_MISMATCHED(D_REVERSE))
191 conflicting_format();
192 diff_format = D_REVERSE;
195 /* ignore but needed for compatibility with GNU diff */
198 /* silently ignore for backwards compatibility */
201 dflags |= D_SKIPBLANKLINES;
204 if (dflags & D_PROTOTYPE)
205 conflicting_format();
206 dflags |= D_MATCHLAST;
207 most_recent_pat = xstrdup(optarg);
210 push_ignore_pats(optarg);
213 dflags |= D_IGNORECASE;
216 if (label[0] == NULL)
218 else if (label[1] == NULL)
230 if (FORMAT_MISMATCHED(D_NREVERSE))
231 conflicting_format();
232 diff_format = D_NREVERSE;
235 if (dflags & D_MATCHLAST)
236 conflicting_format();
237 dflags |= D_PROTOTYPE;
246 if (FORMAT_MISMATCHED(D_BRIEF))
247 conflicting_format();
248 diff_format = D_BRIEF;
260 dflags |= D_EXPANDTABS;
264 if (FORMAT_MISMATCHED(D_UNIFIED))
265 conflicting_format();
266 diff_format = D_UNIFIED;
267 if (optarg != NULL) {
268 l = strtol(optarg, &ep, 10);
269 if (*ep != '\0' || l < 0 || l >= INT_MAX)
271 diff_context = (int)l;
275 dflags |= D_IGNOREBLANKS;
278 width = (int) strtonum(optarg, 1, INT_MAX, &errstr);
280 warnx("Invalid argument for width");
285 read_excludes_file(optarg);
288 push_excludes(optarg);
291 if (FORMAT_MISMATCHED(D_SIDEBYSIDE))
292 conflicting_format();
293 diff_format = D_SIDEBYSIDE;
295 case OPT_CHANGED_GROUP_FORMAT:
296 if (FORMAT_MISMATCHED(D_GFORMAT))
297 conflicting_format();
298 diff_format = D_GFORMAT;
299 group_format = optarg;
305 case OPT_HORIZON_LINES:
306 break; /* XXX TODO for compatibility with GNU diff3 */
307 case OPT_IGN_FN_CASE:
308 ignore_file_case = true;
310 case OPT_NO_IGN_FN_CASE:
311 ignore_file_case = false;
314 if (FORMAT_MISMATCHED(D_NORMAL))
315 conflicting_format();
316 diff_format = D_NORMAL;
319 tabsize = (int) strtonum(optarg, 1, INT_MAX, &errstr);
321 warnx("Invalid argument for tabsize");
328 case OPT_SUPPRESS_COMMON:
332 if (optarg == NULL || strncmp(optarg, "auto", 4) == 0)
333 colorflag = COLORFLAG_AUTO;
334 else if (strncmp(optarg, "always", 6) == 0)
335 colorflag = COLORFLAG_ALWAYS;
336 else if (strncmp(optarg, "never", 5) == 0)
337 colorflag = COLORFLAG_NEVER;
339 errx(2, "unsupported --color value '%s' (must be always, auto, or never)",
342 case OPT_NO_DEREFERENCE:
347 printf("%s\n", diff_version);
354 newarg = optind != prevoptind;
357 if (diff_format == D_UNSET && (dflags & D_PROTOTYPE) != 0)
358 diff_format = D_CONTEXT;
359 if (diff_format == D_UNSET)
360 diff_format = D_NORMAL;
371 env = getenv("DIFFCOLORS");
372 if (env != NULL && *env != '\0' && (p = strdup(env))) {
381 if (pledge("stdio rpath tmppath", NULL) == -1)
386 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
387 * driver routine. Both drivers use the contents of stb1 and stb2.
391 checked_regcomp(ignore_pats, &ignore_re);
392 checked_regcomp(most_recent_pat, &most_recent_re);
393 if (strcmp(argv[0], "-") == 0) {
394 fstat(STDIN_FILENO, &stb1);
396 } else if (stat(argv[0], &stb1) != 0) {
397 if (!Nflag || errno != ENOENT)
398 err(2, "%s", argv[0]);
400 memset(&stb1, 0, sizeof(struct stat));
403 if (strcmp(argv[1], "-") == 0) {
404 fstat(STDIN_FILENO, &stb2);
406 } else if (stat(argv[1], &stb2) != 0) {
407 if (!Nflag || errno != ENOENT)
408 err(2, "%s", argv[1]);
410 memset(&stb2, 0, sizeof(stb2));
411 stb2.st_mode = stb1.st_mode;
414 if (dflags & D_EMPTY1 && dflags & D_EMPTY2){
420 if (stb1.st_mode == 0)
421 stb1.st_mode = stb2.st_mode;
423 if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
424 errx(2, "can't compare - to a directory");
425 set_argstr(oargv, argv);
426 if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
427 if (diff_format == D_IFDEF)
428 errx(2, "-D option not supported with directories");
429 diffdir(argv[0], argv[1], dflags);
431 if (S_ISDIR(stb1.st_mode)) {
432 argv[0] = splice(argv[0], argv[1]);
433 if (stat(argv[0], &stb1) == -1)
434 err(2, "%s", argv[0]);
436 if (S_ISDIR(stb2.st_mode)) {
437 argv[1] = splice(argv[1], argv[0]);
438 if (stat(argv[1], &stb2) == -1)
439 err(2, "%s", argv[1]);
441 print_status(diffreg(argv[0], argv[1], dflags, 1), argv[0],
448 checked_regcomp(char const *pattern, regex_t *comp)
456 error = regcomp(comp, pattern, REG_NEWLINE | REG_EXTENDED);
458 regerror(error, comp, buf, sizeof(buf));
459 if (*pattern != '\0')
460 errx(2, "%s: %s", pattern, buf);
467 set_argstr(char **av, char **ave)
472 argsize = 4 + *ave - *av + 1;
473 diffargs = xmalloc(argsize);
474 strlcpy(diffargs, "diff", argsize);
475 for (ap = av + 1; ap < ave; ap++) {
476 if (strcmp(*ap, "--") != 0) {
477 strlcat(diffargs, " ", argsize);
478 strlcat(diffargs, *ap, argsize);
484 * Read in an excludes file and push each line.
487 read_excludes_file(char *file)
493 if (strcmp(file, "-") == 0)
495 else if ((fp = fopen(file, "r")) == NULL)
497 while ((buf = fgetln(fp, &len)) != NULL) {
498 if (buf[len - 1] == '\n')
500 if ((pattern = strndup(buf, len)) == NULL)
502 push_excludes(pattern);
504 if (strcmp(file, "-") != 0)
509 * Push a pattern onto the excludes list.
512 push_excludes(char *pattern)
514 struct excludes *entry;
516 entry = xmalloc(sizeof(*entry));
517 entry->pattern = pattern;
518 entry->next = excludes_list;
519 excludes_list = entry;
523 push_ignore_pats(char *pattern)
527 if (ignore_pats == NULL)
528 ignore_pats = xstrdup(pattern);
530 /* old + "|" + new + NUL */
531 len = strlen(ignore_pats) + strlen(pattern) + 2;
532 ignore_pats = xreallocarray(ignore_pats, 1, len);
533 strlcat(ignore_pats, "|", len);
534 strlcat(ignore_pats, pattern, len);
539 print_status(int val, char *path1, char *path2, const char *entry)
541 if (label[0] != NULL)
543 if (label[1] != NULL)
548 printf("Binary files %s%s and %s%s differ\n",
549 path1, entry, path2, entry);
552 if (diff_format == D_BRIEF)
553 printf("Files %s%s and %s%s differ\n",
554 path1, entry, path2, entry);
558 printf("Files %s%s and %s%s are identical\n",
559 path1, entry, path2, entry);
562 printf("File %s%s is a directory while file %s%s is a regular file\n",
563 path1, entry, path2, entry);
566 printf("File %s%s is a regular file while file %s%s is a directory\n",
567 path1, entry, path2, entry);
570 printf("File %s%s is not a regular file or directory and was skipped\n",
574 printf("File %s%s is not a regular file or directory and was skipped\n",
585 (void)fprintf(help ? stdout : stderr,
586 "usage: diff [-aBbdilpTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
587 " [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
588 " [-I pattern] [-F pattern] [-L label] file1 file2\n"
589 " diff [-aBbdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
590 " [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
591 " [-F pattern] -C number file1 file2\n"
592 " diff [-aBbdiltw] [-I pattern] [--ignore-case] [--no-ignore-case]\n"
593 " [--normal] [--strip-trailing-cr] [--tabsize] -D string file1 file2\n"
594 " diff [-aBbdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
595 " [--no-ignore-case] [--normal] [--tabsize] [--strip-trailing-cr]\n"
596 " [-F pattern] -U number file1 file2\n"
597 " diff [-aBbdilNPprsTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
598 " [--no-ignore-case] [--normal] [--tabsize] [-I pattern] [-L label]\n"
599 " [-F pattern] [-S name] [-X file] [-x pattern] dir1 dir2\n"
600 " diff [-aBbditwW] [--expand-tabs] [--ignore-all-blanks]\n"
601 " [--ignore-blank-lines] [--ignore-case] [--minimal]\n"
602 " [--no-ignore-file-name-case] [--strip-trailing-cr]\n"
603 " [--suppress-common-lines] [--tabsize] [--text] [--width]\n"
604 " -y | --side-by-side file1 file2\n"
605 " diff [--help] [--version]\n");
614 conflicting_format(void)
617 fprintf(stderr, "error: conflicting output format options.\n");
628 p = getenv("CLICOLOR");
629 p2 = getenv("COLORTERM");
630 if ((p != NULL && *p != '\0') || (p2 != NULL && *p2 != '\0'))
631 return isatty(STDOUT_FILENO);
633 case COLORFLAG_ALWAYS:
635 case COLORFLAG_NEVER:
643 splice(char *dir, char *path)
648 dirlen = strlen(dir);
649 while (dirlen != 0 && dir[dirlen - 1] == '/')
651 if ((tail = strrchr(path, '/')) == NULL)
655 xasprintf(&buf, "%.*s/%s", (int)dirlen, dir, tail);