1 /* vi: set sw=4 ts=4: */
3 * Mini diff implementation for busybox, adapted from OpenBSD diff.
5 * Copyright (C) 2010 by Matheus Izvekov <mizvekov@gmail.com>
6 * Copyright (C) 2006 by Robert Sullivan <cogito.ergo.cogito@hotmail.com>
7 * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
9 * Sponsored in part by the Defense Advanced Research Projects
10 * Agency (DARPA) and Air Force Research Laboratory, Air Force
11 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
13 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
17 * The following code uses an algorithm due to Harold Stone,
18 * which finds a pair of longest identical subsequences in
21 * The major goal is to generate the match vector J.
22 * J[i] is the index of the line in file1 corresponding
23 * to line i in file0. J[i] = 0 if there is no
26 * Lines are hashed so as to work in core. All potential
27 * matches are located by sorting the lines of each file
28 * on the hash (called "value"). In particular, this
29 * collects the equivalence classes in file1 together.
30 * Subroutine equiv replaces the value of each line in
31 * file0 by the index of the first element of its
32 * matching equivalence in (the reordered) file1.
33 * To save space equiv squeezes file1 into a single
34 * array member in which the equivalence classes
35 * are simply concatenated, except that their first
36 * members are flagged by changing sign.
38 * Next the indices that point into member are unsorted into
39 * array class according to the original order of file0.
41 * The cleverness lies in routine stone. This marches
42 * through the lines of file0, developing a vector klist
43 * of "k-candidates". At step i a k-candidate is a matched
44 * pair of lines x,y (x in file0, y in file1) such that
45 * there is a common subsequence of length k
46 * between the first i lines of file0 and the first y
47 * lines of file1, but there is no such subsequence for
48 * any smaller y. x is the earliest possible mate to y
49 * that occurs in such a subsequence.
51 * Whenever any of the members of the equivalence class of
52 * lines in file1 matable to a line in file0 has serial number
53 * less than the y of some k-candidate, that k-candidate
54 * with the smallest such y is replaced. The new
55 * k-candidate is chained (via pred) to the current
56 * k-1 candidate so that the actual subsequence can
57 * be recovered. When a member has serial number greater
58 * that the y of all k-candidates, the klist is extended.
59 * At the end, the longest subsequence is pulled out
60 * and placed in the array J by unravel
62 * With J in hand, the matches there recorded are
63 * checked against reality to assure that no spurious
64 * matches have crept in due to hashing. If they have,
65 * they are broken, and "jackpot" is recorded--a harmless
66 * matter except that a true match for a spuriously
67 * mated line may now be unnecessarily reported as a change.
69 * Much of the complexity of the program comes simply
70 * from trying to minimize core utilization and
71 * maximize the range of doable problems by dynamically
72 * allocating what is needed and reusing what is not.
73 * The core requirements for problems larger than somewhat
74 * are (in words) 2*length(file0) + length(file1) +
75 * 3*(number of k-candidates installed), typically about
76 * 6n words for files of length n.
82 //#define dbg_error_msg(...) bb_error_msg(__VA_ARGS__)
84 #define dbg_error_msg(...) ((void)0)
87 enum { /* print_status() and diffreg() return values */
88 STATUS_SAME, /* files are the same */
89 STATUS_DIFFER, /* files differ */
90 STATUS_BINARY, /* binary files differ */
93 enum { /* Commandline flags */
98 FLAG_L, /* never used, handled by getopt32 */
103 FLAG_S, /* never used, handled by getopt32 */
106 FLAG_U, /* never used, handled by getopt32 */
108 FLAG_u, /* ignored, this is the default */
109 FLAG_p, /* not implemented */
111 FLAG_E, /* not implemented */
113 #define FLAG(x) (1 << FLAG_##x)
115 /* We cache file position to avoid excessive seeking */
116 typedef struct FILE_and_pos_t {
122 smallint exit_status;
127 #define G (*ptr_to_globals)
128 #define exit_status (G.exit_status )
129 #define opt_U_context (G.opt_U_context )
130 #define label (G.label )
132 #define INIT_G() do { \
133 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
141 TOK_EMPTY = 1 << 9, /* Line fully processed, you can proceed to the next */
142 TOK_EOF = 1 << 10, /* File ended */
143 /* Private (Only to be used by read_token() */
144 TOK_EOL = 1 << 11, /* we saw EOL (sticky) */
145 TOK_SPACE = 1 << 12, /* used -b code, means we are skipping spaces */
146 SHIFT_EOF = (sizeof(token_t)*8 - 8) - 1,
147 CHAR_MASK = 0x1ff, /* 8th bit is used to distinguish EOF from 0xff */
150 /* Restores full EOF from one 8th bit: */
151 //#define TOK2CHAR(t) (((t) << SHIFT_EOF) >> SHIFT_EOF)
152 /* We don't really need the above, we only need to have EOF != any_real_char: */
153 #define TOK2CHAR(t) ((t) & CHAR_MASK)
155 static void seek_ft(FILE_and_pos_t *ft, off_t pos)
157 if (ft->ft_pos != pos) {
159 fseeko(ft->ft_fp, pos, SEEK_SET);
163 /* Reads tokens from given fp, handling -b and -w flags
164 * The user must reset tok every line start
166 static int read_token(FILE_and_pos_t *ft, token_t tok)
169 while (!(tok & TOK_EOL)) {
173 t = fgetc(ft->ft_fp);
176 is_space = (t == EOF || isspace(t));
178 /* If t == EOF (-1), set both TOK_EOF and TOK_EOL */
179 tok |= (t & (TOK_EOF + TOK_EOL));
184 if (option_mask32 & FLAG(i)) /* Handcoded tolower() */
185 t = (t >= 'A' && t <= 'Z') ? t - ('A' - 'a') : t;
187 if ((option_mask32 & FLAG(w)) && is_space)
190 /* Trim char value to low 9 bits */
193 if (option_mask32 & FLAG(b)) {
194 /* Was prev char whitespace? */
195 if (tok & TOK_SPACE) { /* yes */
196 if (is_space) /* this one too, ignore it */
199 } else if (is_space) {
200 /* 1st whitespace char.
201 * Set TOK_SPACE and replace char by ' ' */
206 tok &= ~(TOK_EMPTY + CHAR_MASK);
207 /* Assign char value (low 9 bits) and maybe set TOK_SPACE */
212 bb_error_msg("fp:%p tok:%x '%c'%s%s%s%s", fp, tok, tok & 0xff
213 , tok & TOK_EOF ? " EOF" : ""
214 , tok & TOK_EOL ? " EOL" : ""
215 , tok & TOK_EMPTY ? " EMPTY" : ""
216 , tok & TOK_SPACE ? " SPACE" : ""
228 static int search(const int *c, int k, int y, const struct cand *list)
232 if (list[c[k]].y < y) /* quick look for typical case */
235 for (i = 0, j = k + 1;;) {
236 const int l = (i + j) >> 1;
238 const int t = list[c[l]].y;
250 static unsigned isqrt(unsigned n)
254 const unsigned y = x;
255 x = ((n / x) + x) >> 1;
256 if (x <= (y + 1) && x >= (y - 1))
261 static void stone(const int *a, int n, const int *b, int *J, int pref)
263 const unsigned isq = isqrt(n);
264 const unsigned bound =
265 (option_mask32 & FLAG(d)) ? UINT_MAX : MAX(256, isq);
269 struct cand *clist = xzalloc(clistlen * sizeof(clist[0]));
272 int *klist = xzalloc((n + 2) * sizeof(klist[0]));
273 /*clist[0] = (struct cand){0}; - xzalloc did it */
276 for (cand.x = 1; cand.x <= n; cand.x++) {
277 int j = a[cand.x], oldl = 0;
278 unsigned numtries = 0;
282 cand.pred = klist[0];
285 if (cand.y <= clist[cand.pred].y)
287 l = search(klist, k, cand.y, clist);
289 cand.pred = klist[l - 1];
290 if (l <= k && clist[klist[l]].y <= cand.y)
292 if (clen == clistlen) {
293 clistlen = clistlen * 11 / 10;
294 clist = xrealloc(clist, clistlen * sizeof(clist[0]));
307 } while ((cand.y = b[++j]) > 0 && numtries < bound);
310 for (q = clist + klist[k]; q->y; q = clist + q->pred)
311 J[q->x + pref] = q->y + pref;
317 /* 'serial' is not used in the begining, so we reuse it
318 * to store line offsets, thus reducing memory pressure
327 static void equiv(struct line *a, int n, struct line *b, int m, int *c)
331 while (i <= n && j <= m) {
332 if (a[i].value < b[j].value)
334 else if (a[i].value == b[j].value)
345 while (b[j + 1].value == b[j].value) {
353 static void unsort(const struct line *f, int l, int *b)
356 int *a = xmalloc((l + 1) * sizeof(a[0]));
357 for (i = 1; i <= l; i++)
358 a[f[i].serial] = f[i].value;
359 for (i = 1; i <= l; i++)
364 static int line_compar(const void *a, const void *b)
366 #define l0 ((const struct line*)a)
367 #define l1 ((const struct line*)b)
368 int r = l0->value - l1->value;
371 return l0->serial - l1->serial;
376 static void fetch(FILE_and_pos_t *ft, const off_t *ix, int a, int b, int ch)
379 for (i = a; i <= b; i++) {
380 seek_ft(ft, ix[i - 1]);
382 if (option_mask32 & FLAG(T))
384 for (j = 0, col = 0; j < ix[i] - ix[i - 1]; j++) {
385 int c = fgetc(ft->ft_fp);
387 printf("\n\\ No newline at end of file\n");
391 if (c == '\t' && (option_mask32 & FLAG(t)))
392 do putchar(' '); while (++col & 7);
401 /* Creates the match vector J, where J[i] is the index
402 * of the line in the new file corresponding to the line i
403 * in the old file. Lines start at 1 instead of 0, that value
404 * being used instead to denote no corresponding line.
405 * This vector is dynamically allocated and must be freed by the caller.
407 * * fp is an input parameter, where fp[0] and fp[1] are the open
408 * old file and new file respectively.
409 * * nlen is an output variable, where nlen[0] and nlen[1]
410 * gets the number of lines in the old and new file respectively.
411 * * ix is an output variable, where ix[0] and ix[1] gets
412 * assigned dynamically allocated vectors of the offsets of the lines
413 * of the old and new file respectively. These must be freed by the caller.
415 static NOINLINE int *create_J(FILE_and_pos_t ft[2], int nlen[2], off_t *ix[2])
417 int *J, slen[2], *class, *member;
418 struct line *nfile[2], *sfile[2];
419 int pref = 0, suff = 0, i, j, delta;
421 /* Lines of both files are hashed, and in the process
422 * their offsets are stored in the array ix[fileno]
423 * where fileno == 0 points to the old file, and
424 * fileno == 1 points to the new one.
426 for (i = 0; i < 2; i++) {
430 nfile[i] = xmalloc((sz + 3) * sizeof(nfile[i][0]));
431 /* ft gets here without the correct position, cant use seek_ft */
433 fseeko(ft[i].ft_fp, 0, SEEK_SET);
436 /* We could zalloc nfile, but then zalloc starts showing in gprof at ~1% */
437 nfile[i][0].offset = 0;
438 goto start; /* saves code */
440 tok = read_token(&ft[i], tok);
441 if (!(tok & TOK_EMPTY)) {
442 /* Hash algorithm taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578. */
443 /*hash = hash * 128 - hash + TOK2CHAR(tok);
444 * gcc insists on optimizing above to "hash * 127 + ...", thus... */
445 unsigned o = hash - TOK2CHAR(tok);
446 hash = hash * 128 - o; /* we want SPEED here */
449 if (nlen[i]++ == sz) {
451 nfile[i] = xrealloc(nfile[i], (sz + 3) * sizeof(nfile[i][0]));
453 /* line_compar needs hashes fit into positive int */
454 nfile[i][nlen[i]].value = hash & INT_MAX;
455 /* like ftello(ft[i].ft_fp) but faster (avoids lseek syscall) */
456 nfile[i][nlen[i]].offset = ft[i].ft_pos;
458 /* EOF counts as a token, so we have to adjust it here */
459 nfile[i][nlen[i]].offset++;
465 /* Exclude lone EOF line from the end of the file, to make fetch()'s job easier */
466 if (nfile[i][nlen[i]].offset - nfile[i][nlen[i] - 1].offset == 1)
468 /* Now we copy the line offsets into ix */
469 ix[i] = xmalloc((nlen[i] + 2) * sizeof(ix[i][0]));
470 for (j = 0; j < nlen[i] + 1; j++)
471 ix[i][j] = nfile[i][j].offset;
474 /* lenght of prefix and suffix is calculated */
475 for (; pref < nlen[0] && pref < nlen[1] &&
476 nfile[0][pref + 1].value == nfile[1][pref + 1].value;
478 for (; suff < nlen[0] - pref && suff < nlen[1] - pref &&
479 nfile[0][nlen[0] - suff].value == nfile[1][nlen[1] - suff].value;
481 /* Arrays are pruned by the suffix and prefix lenght,
482 * the result being sorted and stored in sfile[fileno],
483 * and their sizes are stored in slen[fileno]
485 for (j = 0; j < 2; j++) {
486 sfile[j] = nfile[j] + pref;
487 slen[j] = nlen[j] - pref - suff;
488 for (i = 0; i <= slen[j]; i++)
489 sfile[j][i].serial = i;
490 qsort(sfile[j] + 1, slen[j], sizeof(*sfile[j]), line_compar);
492 /* nfile arrays are reused to reduce memory pressure
493 * The #if zeroed out section performs the same task as the
494 * one in the #else section.
495 * Peak memory usage is higher, but one array copy is avoided
496 * by not using unsort()
499 member = xmalloc((slen[1] + 2) * sizeof(member[0]));
500 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
503 class = xmalloc((slen[0] + 1) * sizeof(class[0]));
504 for (int i = 1; i <= slen[0]; i++) /* Unsorting */
505 class[sfile[0][i].serial] = sfile[0][i].value;
508 member = (int *)nfile[1];
509 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
510 member = xrealloc(member, (slen[1] + 2) * sizeof(member[0]));
512 class = (int *)nfile[0];
513 unsort(sfile[0], slen[0], (int *)nfile[0]);
514 class = xrealloc(class, (slen[0] + 2) * sizeof(class[0]));
516 J = xmalloc((nlen[0] + 2) * sizeof(J[0]));
517 /* The elements of J which fall inside the prefix and suffix regions
518 * are marked as unchanged, while the ones which fall outside
519 * are initialized with 0 (no matches), so that function stone can
520 * then assign them their right values
522 for (i = 0, delta = nlen[1] - nlen[0]; i <= nlen[0]; i++)
523 J[i] = i <= pref ? i :
524 i > (nlen[0] - suff) ? (i + delta) : 0;
525 /* Here the magic is performed */
526 stone(class, slen[0], member, J, pref);
527 J[nlen[0] + 1] = nlen[1] + 1;
532 /* Both files are rescanned, in an effort to find any lines
533 * which, due to limitations intrinsic to any hashing algorithm,
534 * are different but ended up confounded as the same
536 for (i = 1; i <= nlen[0]; i++) {
540 seek_ft(&ft[0], ix[0][i - 1]);
541 seek_ft(&ft[1], ix[1][J[i] - 1]);
543 for (j = J[i]; i <= nlen[0] && J[i] == j; i++, j++) {
544 token_t tok0 = 0, tok1 = 0;
546 tok0 = read_token(&ft[0], tok0);
547 tok1 = read_token(&ft[1], tok1);
549 if (((tok0 ^ tok1) & TOK_EMPTY) != 0 /* one is empty (not both) */
550 || (!(tok0 & TOK_EMPTY) && TOK2CHAR(tok0) != TOK2CHAR(tok1))
552 J[i] = 0; /* Break the correspondence */
554 } while (!(tok0 & tok1 & TOK_EMPTY));
561 static bool diff(FILE* fp[2], char *file[2])
565 FILE_and_pos_t ft[2];
566 typedef struct { int a, b; } vec_t[2];
569 bool anychange = false;
574 /* note that ft[i].ft_pos is unintitalized, create_J()
575 * must not assume otherwise */
576 J = create_J(ft, nlen, ix);
579 bool nonempty = false;
584 for (v[0].a = i; v[0].a <= nlen[0] && J[v[0].a] == J[v[0].a - 1] + 1; v[0].a++)
586 v[1].a = J[v[0].a - 1] + 1;
588 for (v[0].b = v[0].a - 1; v[0].b < nlen[0] && !J[v[0].b + 1]; v[0].b++)
590 v[1].b = J[v[0].b + 1] - 1;
592 * Indicate that there is a difference between lines a and b of the 'from' file
593 * to get to lines c to d of the 'to' file. If a is greater than b then there
594 * are no lines in the 'from' file involved and this means that there were
595 * lines appended (beginning at b). If c is greater than d then there are
596 * lines missing from the 'to' file.
598 if (v[0].a <= v[0].b || v[1].a <= v[1].b) {
600 * If this change is more than 'context' lines from the
601 * previous change, dump the record and reset it.
603 int ct = (2 * opt_U_context) + 1;
605 && v[0].a > vec[idx][0].b + ct
606 && v[1].a > vec[idx][1].b + ct
611 for (int j = 0; j < 2; j++)
612 for (int k = v[j].a; k < v[j].b; k++)
613 nonempty |= (ix[j][k+1] - ix[j][k] != 1);
615 vec = xrealloc_vector(vec, 6, ++idx);
616 memcpy(vec[idx], v, sizeof(v));
624 if (idx < 0 || ((option_mask32 & FLAG(B)) && !nonempty))
626 if (!(option_mask32 & FLAG(q))) {
627 vec_t span, *cvp = vec;
630 /* Print the context/unidiff header first time through */
631 printf("--- %s\n", label[0] ? label[0] : file[0]);
632 printf("+++ %s\n", label[1] ? label[1] : file[1]);
636 for (int j = 0; j < 2; j++) {
637 int a = span[j].a = MAX(1, (*cvp)[j].a - opt_U_context);
638 int b = span[j].b = MIN(nlen[j], vec[idx][j].b + opt_U_context);
640 printf(" %c%d", j ? '+' : '-', MIN(a, b));
643 printf(",%d", (a < b) ? b - a + 1 : 0);
647 * Output changes in "unified" diff format--the old and new lines
648 * are printed together.
650 for (int lowa = span[0].a; ; lowa = (*cvp++)[0].b + 1) {
651 bool end = cvp > &vec[idx];
652 fetch(&ft[0], ix[0], lowa, end ? span[0].b : (*cvp)[0].a - 1, ' ');
655 for (int j = 0; j < 2; j++)
656 fetch(&ft[j], ix[j], (*cvp)[j].a, (*cvp)[j].b, j ? '+' : '-');
662 } while (i <= nlen[0]);
671 static int diffreg(char *file[2])
673 FILE *fp[2] = { stdin, stdin };
674 bool binary = false, differ = false;
675 int status = STATUS_SAME, i;
677 for (i = 0; i < 2; i++) {
678 int fd = open_or_warn_stdin(file[i]);
681 /* Our diff implementation is using seek.
682 * When we meet non-seekable file, we must make a temp copy.
684 if (lseek(fd, 0, SEEK_SET) == -1 && errno == ESPIPE) {
685 char name[] = "/tmp/difXXXXXX";
686 int fd_tmp = mkstemp(name);
688 bb_perror_msg_and_die("mkstemp");
690 if (bb_copyfd_eof(fd, fd_tmp) < 0)
692 if (fd) /* Prevents closing of stdin */
696 fp[i] = fdopen(fd, "r");
700 const size_t sz = COMMON_BUFSIZE / 2;
701 char *const buf0 = bb_common_bufsiz1;
702 char *const buf1 = buf0 + sz;
704 i = fread(buf0, 1, sz, fp[0]);
705 j = fread(buf1, 1, sz, fp[1]);
712 for (k = 0; k < i; k++) {
713 if (!buf0[k] || !buf1[k])
715 if (buf0[k] != buf1[k])
720 if (binary && !(option_mask32 & FLAG(a)))
721 status = STATUS_BINARY;
722 else if (diff(fp, file))
723 status = STATUS_DIFFER;
725 if (status != STATUS_SAME)
728 fclose_if_not_stdin(fp[0]);
729 fclose_if_not_stdin(fp[1]);
734 static void print_status(int status, char *path[2])
739 if ((option_mask32 & FLAG(q)) || status == STATUS_BINARY)
740 printf("Files %s and %s differ\n", path[0], path[1]);
743 if (option_mask32 & FLAG(s))
744 printf("Files %s and %s are identical\n", path[0], path[1]);
749 #if ENABLE_FEATURE_DIFF_DIR
756 /* This function adds a filename to dl, the directory listing. */
757 static int FAST_FUNC add_to_dirlist(const char *filename,
758 struct stat *sb UNUSED_PARAM,
759 void *userdata, int depth UNUSED_PARAM)
761 struct dlist *const l = userdata;
762 l->dl = xrealloc_vector(l->dl, 6, l->e);
763 /* + 1 skips "/" after dirname */
764 l->dl[l->e] = xstrdup(filename + l->len + 1);
769 /* If recursion is not set, this function adds the directory
770 * to the list and prevents recursive_action from recursing into it.
772 static int FAST_FUNC skip_dir(const char *filename,
773 struct stat *sb, void *userdata,
776 if (!(option_mask32 & FLAG(r)) && depth) {
777 add_to_dirlist(filename, sb, userdata, depth);
783 static void diffdir(char *p[2], const char *s_start)
785 struct dlist list[2];
788 memset(&list, 0, sizeof(list));
789 for (i = 0; i < 2; i++) {
790 /*list[i].s = list[i].e = 0; - memset did it */
791 /*list[i].dl = NULL; */
793 /* We need to trim root directory prefix.
794 * Using list.len to specify its length,
795 * add_to_dirlist will remove it. */
796 list[i].len = strlen(p[i]);
797 recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
798 add_to_dirlist, skip_dir, &list[i], 0);
799 /* Sort dl alphabetically.
800 * GNU diff does this ignoring any number of trailing dots.
801 * We don't, so for us dotted files almost always are
804 qsort_string_vector(list[i].dl, list[i].e);
805 /* If -S was set, find the starting point. */
808 while (list[i].s < list[i].e && strcmp(list[i].dl[list[i].s], s_start) < 0)
811 /* Now that both dirlist1 and dirlist2 contain sorted directory
812 * listings, we can start to go through dirlist1. If both listings
813 * contain the same file, then do a normal diff. Otherwise, behaviour
814 * is determined by whether the -N flag is set. */
820 dp[0] = list[0].s < list[0].e ? list[0].dl[list[0].s] : NULL;
821 dp[1] = list[1].s < list[1].e ? list[1].dl[list[1].s] : NULL;
822 if (!dp[0] && !dp[1])
824 pos = !dp[0] ? 1 : (!dp[1] ? -1 : strcmp(dp[0], dp[1]));
826 if (pos && !(option_mask32 & FLAG(N)))
827 printf("Only in %s: %s\n", p[k], dp[k]);
829 char *fullpath[2], *path[2]; /* if -N */
831 for (i = 0; i < 2; i++) {
832 if (pos == 0 || i == k) {
833 path[i] = fullpath[i] = concat_path_file(p[i], dp[i]);
834 stat(fullpath[i], &stb[i]);
836 fullpath[i] = concat_path_file(p[i], dp[1 - i]);
837 path[i] = (char *)bb_dev_null;
841 stat(fullpath[k], &stb[1 - k]);
843 if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode))
844 printf("Common subdirectories: %s and %s\n", fullpath[0], fullpath[1]);
845 else if (!S_ISREG(stb[0].st_mode) && !S_ISDIR(stb[0].st_mode))
846 printf("File %s is not a regular file or directory and was skipped\n", fullpath[0]);
847 else if (!S_ISREG(stb[1].st_mode) && !S_ISDIR(stb[1].st_mode))
848 printf("File %s is not a regular file or directory and was skipped\n", fullpath[1]);
849 else if (S_ISDIR(stb[0].st_mode) != S_ISDIR(stb[1].st_mode)) {
850 if (S_ISDIR(stb[0].st_mode))
851 printf("File %s is a %s while file %s is a %s\n", fullpath[0], "directory", fullpath[1], "regular file");
853 printf("File %s is a %s while file %s is a %s\n", fullpath[0], "regular file", fullpath[1], "directory");
855 print_status(diffreg(path), fullpath);
867 if (ENABLE_FEATURE_CLEAN_UP) {
874 #if ENABLE_FEATURE_DIFF_LONG_OPTIONS
875 static const char diff_longopts[] ALIGN1 =
876 "ignore-case\0" No_argument "i"
877 "ignore-tab-expansion\0" No_argument "E"
878 "ignore-space-change\0" No_argument "b"
879 "ignore-all-space\0" No_argument "w"
880 "ignore-blank-lines\0" No_argument "B"
881 "text\0" No_argument "a"
882 "unified\0" Required_argument "U"
883 "label\0" Required_argument "L"
884 "show-c-function\0" No_argument "p"
885 "brief\0" No_argument "q"
886 "expand-tabs\0" No_argument "t"
887 "initial-tab\0" No_argument "T"
888 "recursive\0" No_argument "r"
889 "new-file\0" No_argument "N"
890 "report-identical-files\0" No_argument "s"
891 "starting-file\0" Required_argument "S"
892 "minimal\0" No_argument "d"
896 int diff_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
897 int diff_main(int argc UNUSED_PARAM, char **argv)
900 char *file[2], *s_start = NULL;
901 llist_t *L_arg = NULL;
905 /* exactly 2 params; collect multiple -L <label>; -U N */
906 opt_complementary = "=2:L::U+";
907 #if ENABLE_FEATURE_DIFF_LONG_OPTIONS
908 applet_long_options = diff_longopts;
910 getopt32(argv, "abdiL:NqrsS:tTU:wupBE",
911 &L_arg, &s_start, &opt_U_context);
914 label[!!label[0]] = llist_pop(&L_arg);
915 xfunc_error_retval = 2;
916 for (i = 0; i < 2; i++) {
918 /* Compat: "diff file name_which_doesnt_exist" exits with 2 */
919 if (LONE_DASH(file[i])) {
920 fstat(STDIN_FILENO, &stb[i]);
923 xstat(file[i], &stb[i]);
925 xfunc_error_retval = 1;
926 if (gotstdin && (S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode)))
927 bb_error_msg_and_die("can't compare stdin to a directory");
929 if (S_ISDIR(stb[0].st_mode) && S_ISDIR(stb[1].st_mode)) {
930 #if ENABLE_FEATURE_DIFF_DIR
931 diffdir(file, s_start);
933 bb_error_msg_and_die("no support for directory comparison");
936 bool dirfile = S_ISDIR(stb[0].st_mode) || S_ISDIR(stb[1].st_mode);
937 bool dir = S_ISDIR(stb[1].st_mode);
939 const char *slash = strrchr(file[!dir], '/');
940 file[dir] = concat_path_file(file[dir], slash ? slash + 1 : file[!dir]);
941 xstat(file[dir], &stb[dir]);
943 /* diffreg can get non-regular files here */
944 print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);