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