1 /* diff - compare files line by line
3 Copyright (C) 1988, 1989, 1992, 1993, 1994, 1996, 1998, 2001, 2002
4 Free Software Foundation, Inc.
6 This file is part of GNU DIFF.
8 GNU DIFF is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
13 GNU DIFF is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 See the GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU DIFF; see the file COPYING.
20 If not, write to the Free Software Foundation,
21 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
33 #include <hard-locale.h>
40 static char const authorship_msgid[] =
41 N_("Written by Paul Eggert, Mike Haertel, David Hayes,\n\
42 Richard Stallman, and Len Tower.");
44 static char const copyright_string[] =
45 "Copyright (C) 2002 Free Software Foundation, Inc.";
47 #ifndef GUTTER_WIDTH_MINIMUM
48 # define GUTTER_WIDTH_MINIMUM 3
53 char *regexps; /* chars representing disjunction of the regexps */
54 size_t len; /* chars used in `regexps' */
55 size_t size; /* size malloc'ed for `regexps'; 0 if not malloc'ed */
56 bool multiple_regexps;/* Does `regexps' represent a disjunction? */
57 struct re_pattern_buffer *buf;
60 static int compare_files (struct comparison const *, char const *, char const *);
61 static void add_regexp (struct regexp_list *, char const *);
62 static void summarize_regexp_list (struct regexp_list *);
63 static void specify_style (enum output_style);
64 static void specify_value (char const **, char const *, char const *);
65 static void try_help (char const *, char const *) __attribute__((noreturn));
66 static void check_stdout (void);
67 static void usage (void);
69 /* If comparing directories, compare their common subdirectories
71 static bool recursive;
73 /* In context diffs, show previous lines that match these regexps. */
74 static struct regexp_list function_regexp_list;
76 /* Ignore changes affecting only lines that match these regexps. */
77 static struct regexp_list ignore_regexp_list;
80 /* Use binary I/O when reading and writing data (--binary).
81 On POSIX hosts, this has no effect. */
85 /* When comparing directories, if a file appears only in one
86 directory, treat it as present but empty in the other (-N).
87 Then `patch' would create the file with appropriate contents. */
90 /* When comparing directories, if a file appears only in the second
91 directory of the two, treat it as present but empty in the other
92 (--unidirectional-new-file).
93 Then `patch' would create the file with appropriate contents. */
94 static bool unidirectional_new_file;
96 /* Report files compared that are the same (-s).
97 Normally nothing is output when that happens. */
98 static bool report_identical_files;
101 /* Return a string containing the command options with which diff was invoked.
102 Spaces appear between what were separate ARGV-elements.
103 There is a space at the beginning but none at the end.
104 If there were no options, the result is an empty string.
106 Arguments: OPTIONVEC, a vector containing separate ARGV-elements, and COUNT,
107 the length of that vector. */
110 option_list (char **optionvec, int count)
117 for (i = 0; i < count; i++)
118 size += 1 + quote_system_arg ((char *) 0, optionvec[i]);
120 p = result = xmalloc (size);
122 for (i = 0; i < count; i++)
125 p += quote_system_arg (p, optionvec[i]);
133 /* Return an option value suitable for add_exclude. */
136 exclude_options (void)
138 return EXCLUDE_WILDCARDS | (ignore_file_name_case ? FNM_CASEFOLD : 0);
141 static char const shortopts[] =
142 "0123456789abBcC:dD:eEfF:hHiI:lL:nNpPqrsS:tTuU:vwW:x:X:y";
144 /* Values for long options that do not have single-letter equivalents. */
147 BINARY_OPTION = CHAR_MAX + 1,
150 HORIZON_LINES_OPTION,
151 IGNORE_FILE_NAME_CASE_OPTION,
152 INHIBIT_HUNK_MERGE_OPTION,
155 NO_IGNORE_FILE_NAME_CASE_OPTION,
157 SDIFF_MERGE_ASSIST_OPTION,
158 STRIP_TRAILING_CR_OPTION,
159 SUPPRESS_COMMON_LINES_OPTION,
162 /* These options must be in sequence. */
163 UNCHANGED_LINE_FORMAT_OPTION,
164 OLD_LINE_FORMAT_OPTION,
165 NEW_LINE_FORMAT_OPTION,
167 /* These options must be in sequence. */
168 UNCHANGED_GROUP_FORMAT_OPTION,
169 OLD_GROUP_FORMAT_OPTION,
170 NEW_GROUP_FORMAT_OPTION,
171 CHANGED_GROUP_FORMAT_OPTION
174 static char const group_format_option[][sizeof "--unchanged-group-format"] =
176 "--unchanged-group-format",
177 "--old-group-format",
178 "--new-group-format",
179 "--changed-group-format"
182 static char const line_format_option[][sizeof "--unchanged-line-format"] =
184 "--unchanged-line-format",
189 static struct option const longopts[] =
191 {"binary", 0, 0, BINARY_OPTION},
192 {"brief", 0, 0, 'q'},
193 {"changed-group-format", 1, 0, CHANGED_GROUP_FORMAT_OPTION},
194 {"context", 2, 0, 'C'},
196 {"exclude", 1, 0, 'x'},
197 {"exclude-from", 1, 0, 'X'},
198 {"expand-tabs", 0, 0, 't'},
199 {"forward-ed", 0, 0, 'f'},
200 {"from-file", 1, 0, FROM_FILE_OPTION},
201 {"help", 0, 0, HELP_OPTION},
202 {"horizon-lines", 1, 0, HORIZON_LINES_OPTION},
203 {"ifdef", 1, 0, 'D'},
204 {"ignore-all-space", 0, 0, 'w'},
205 {"ignore-blank-lines", 0, 0, 'B'},
206 {"ignore-case", 0, 0, 'i'},
207 {"ignore-file-name-case", 0, 0, IGNORE_FILE_NAME_CASE_OPTION},
208 {"ignore-matching-lines", 1, 0, 'I'},
209 {"ignore-space-change", 0, 0, 'b'},
210 {"ignore-tab-expansion", 0, 0, 'E'},
211 {"inhibit-hunk-merge", 0, 0, INHIBIT_HUNK_MERGE_OPTION},
212 {"initial-tab", 0, 0, 'T'},
213 {"label", 1, 0, 'L'},
214 {"left-column", 0, 0, LEFT_COLUMN_OPTION},
215 {"line-format", 1, 0, LINE_FORMAT_OPTION},
216 {"minimal", 0, 0, 'd'},
217 {"new-file", 0, 0, 'N'},
218 {"new-group-format", 1, 0, NEW_GROUP_FORMAT_OPTION},
219 {"new-line-format", 1, 0, NEW_LINE_FORMAT_OPTION},
220 {"no-ignore-file-name-case", 0, 0, NO_IGNORE_FILE_NAME_CASE_OPTION},
221 {"normal", 0, 0, NORMAL_OPTION},
222 {"old-group-format", 1, 0, OLD_GROUP_FORMAT_OPTION},
223 {"old-line-format", 1, 0, OLD_LINE_FORMAT_OPTION},
224 {"paginate", 0, 0, 'l'},
226 {"recursive", 0, 0, 'r'},
227 {"report-identical-files", 0, 0, 's'},
228 {"sdiff-merge-assist", 0, 0, SDIFF_MERGE_ASSIST_OPTION},
229 {"show-c-function", 0, 0, 'p'},
230 {"show-function-line", 1, 0, 'F'},
231 {"side-by-side", 0, 0, 'y'},
232 {"speed-large-files", 0, 0, 'H'},
233 {"starting-file", 1, 0, 'S'},
234 {"strip-trailing-cr", 0, 0, STRIP_TRAILING_CR_OPTION},
235 {"suppress-common-lines", 0, 0, SUPPRESS_COMMON_LINES_OPTION},
237 {"to-file", 1, 0, TO_FILE_OPTION},
238 {"unchanged-group-format", 1, 0, UNCHANGED_GROUP_FORMAT_OPTION},
239 {"unchanged-line-format", 1, 0, UNCHANGED_LINE_FORMAT_OPTION},
240 {"unidirectional-new-file", 0, 0, 'P'},
241 {"unified", 2, 0, 'U'},
242 {"version", 0, 0, 'v'},
243 {"width", 1, 0, 'W'},
248 main (int argc, char **argv)
250 int exit_status = EXIT_SUCCESS;
255 bool explicit_context = 0;
257 bool show_c_function = 0;
258 char const *from_file = 0;
259 char const *to_file = 0;
263 /* Do our initializations. */
265 initialize_main (&argc, &argv);
266 program_name = argv[0];
267 setlocale (LC_ALL, "");
268 bindtextdomain (PACKAGE, LOCALEDIR);
269 textdomain (PACKAGE);
270 c_stack_action (c_stack_die);
271 function_regexp_list.buf = &function_regexp;
272 ignore_regexp_list.buf = &ignore_regexp;
273 re_set_syntax (RE_SYNTAX_GREP | RE_NO_POSIX_BACKTRACKING);
274 excluded = new_exclude ();
276 /* Decode the options. */
278 while ((c = getopt_long (argc, argv, shortopts, longopts, 0)) != -1)
295 if (! ISDIGIT (prev))
297 else if (LIN_MAX / 10 < ocontext
298 || ((ocontext = 10 * ocontext + c - '0') < 0))
307 if (ignore_white_space < IGNORE_SPACE_CHANGE)
308 ignore_white_space = IGNORE_SPACE_CHANGE;
312 ignore_blank_lines = 1;
315 case 'C': /* +context[=lines] */
316 case 'U': /* +unified[=lines] */
320 numval = strtoumax (optarg, &numend, 10);
322 try_help ("invalid context length `%s'", optarg);
323 if (LIN_MAX < numval)
329 specify_style (c == 'U' ? OUTPUT_UNIFIED : OUTPUT_CONTEXT);
330 if (context < numval)
332 explicit_context = 1;
337 specify_style (OUTPUT_CONTEXT);
347 specify_style (OUTPUT_IFDEF);
349 static char const C_ifdef_group_formats[] =
350 "%%=%c#ifndef %s\n%%<#endif /* ! %s */\n%c#ifdef %s\n%%>#endif /* %s */\n%c#ifndef %s\n%%<#else /* %s */\n%%>#endif /* %s */\n";
351 char *b = xmalloc (sizeof C_ifdef_group_formats
352 + 7 * strlen (optarg) - 14 /* 7*"%s" */
353 - 8 /* 5*"%%" + 3*"%c" */);
354 sprintf (b, C_ifdef_group_formats,
358 optarg, optarg, optarg);
359 for (i = 0; i < sizeof group_format / sizeof *group_format; i++)
361 specify_value (&group_format[i], b, "-D");
368 specify_style (OUTPUT_ED);
372 if (ignore_white_space < IGNORE_TAB_EXPANSION)
373 ignore_white_space = IGNORE_TAB_EXPANSION;
377 specify_style (OUTPUT_FORWARD_ED);
381 add_regexp (&function_regexp_list, optarg);
385 /* Split the files into chunks for faster processing.
386 Usually does not change the result.
388 This currently has no effect. */
392 speed_large_files = 1;
400 add_regexp (&ignore_regexp_list, optarg);
405 try_help ("pagination not supported on this host", 0);
408 /* Pagination requires forking and waiting, and
409 System V fork+wait does not work if SIGCHLD is ignored. */
410 signal (SIGCHLD, SIG_DFL);
416 file_label[0] = optarg;
417 else if (!file_label[1])
418 file_label[1] = optarg;
420 fatal ("too many file label options");
424 specify_style (OUTPUT_RCS);
433 add_regexp (&function_regexp_list, "^[[:alpha:]$_]");
437 unidirectional_new_file = 1;
449 report_identical_files = 1;
453 specify_value (&starting_file, optarg, "-S");
465 specify_style (OUTPUT_UNIFIED);
471 printf ("diff %s\n%s\n\n%s\n\n%s\n",
472 version_string, copyright_string,
473 _(free_software_msgid), _(authorship_msgid));
478 ignore_white_space = IGNORE_ALL_SPACE;
482 add_exclude (excluded, optarg, exclude_options ());
486 if (add_exclude_file (add_exclude, excluded, optarg,
487 exclude_options (), '\n'))
488 pfatal_with_name (optarg);
492 specify_style (OUTPUT_SDIFF);
496 numval = strtoumax (optarg, &numend, 10);
497 if (! (0 < numval && numval <= INT_MAX) || *numend)
498 try_help ("invalid width `%s'", optarg);
502 fatal ("conflicting width options");
510 set_binary_mode (STDOUT_FILENO, 1);
514 case FROM_FILE_OPTION:
515 specify_value (&from_file, optarg, "--from-file");
523 case HORIZON_LINES_OPTION:
524 numval = strtoumax (optarg, &numend, 10);
526 try_help ("invalid horizon length `%s'", optarg);
527 horizon_lines = MAX (horizon_lines, MIN (numval, LIN_MAX));
530 case IGNORE_FILE_NAME_CASE_OPTION:
531 ignore_file_name_case = 1;
534 case INHIBIT_HUNK_MERGE_OPTION:
535 /* This option is obsolete, but accept it for backward
539 case LEFT_COLUMN_OPTION:
543 case LINE_FORMAT_OPTION:
544 specify_style (OUTPUT_IFDEF);
545 for (i = 0; i < sizeof line_format / sizeof *line_format; i++)
546 specify_value (&line_format[i], optarg, "--line-format");
549 case NO_IGNORE_FILE_NAME_CASE_OPTION:
550 ignore_file_name_case = 0;
554 specify_style (OUTPUT_NORMAL);
557 case SDIFF_MERGE_ASSIST_OPTION:
558 specify_style (OUTPUT_SDIFF);
559 sdiff_merge_assist = 1;
562 case STRIP_TRAILING_CR_OPTION:
563 strip_trailing_cr = 1;
566 case SUPPRESS_COMMON_LINES_OPTION:
567 suppress_common_lines = 1;
571 specify_value (&to_file, optarg, "--to-file");
574 case UNCHANGED_LINE_FORMAT_OPTION:
575 case OLD_LINE_FORMAT_OPTION:
576 case NEW_LINE_FORMAT_OPTION:
577 specify_style (OUTPUT_IFDEF);
578 c -= UNCHANGED_LINE_FORMAT_OPTION;
579 specify_value (&line_format[c], optarg, line_format_option[c]);
582 case UNCHANGED_GROUP_FORMAT_OPTION:
583 case OLD_GROUP_FORMAT_OPTION:
584 case NEW_GROUP_FORMAT_OPTION:
585 case CHANGED_GROUP_FORMAT_OPTION:
586 specify_style (OUTPUT_IFDEF);
587 c -= UNCHANGED_GROUP_FORMAT_OPTION;
588 specify_value (&group_format[c], optarg, group_format_option[c]);
597 if (output_style == OUTPUT_UNSPECIFIED)
601 specify_style (OUTPUT_CONTEXT);
606 specify_style (OUTPUT_NORMAL);
609 if (output_style != OUTPUT_CONTEXT || hard_locale (LC_TIME))
610 time_format = "%Y-%m-%d %H:%M:%S.%N %z";
613 /* See POSIX 1003.1-2001 for this format. */
614 time_format = "%a %b %e %T %Y";
619 bool modern_usage = 200112 <= posix2_version ();
621 if ((output_style == OUTPUT_CONTEXT
622 || output_style == OUTPUT_UNIFIED)
623 && (context < ocontext
624 || (ocontext < context && ! explicit_context)))
629 _("`-%ld' option is obsolete; use `-%c %ld'"),
631 output_style == OUTPUT_CONTEXT ? 'C' : 'U',
641 error (0, 0, _("`-%ld' option is obsolete; omit it"),
650 * We maximize first the half line width, and then the gutter width,
651 * according to the following constraints:
652 * 1. Two half lines plus a gutter must fit in a line.
653 * 2. If the half line width is nonzero:
654 * a. The gutter width is at least GUTTER_WIDTH_MINIMUM.
655 * b. If tabs are not expanded to spaces,
656 * a half line plus a gutter is an integral number of tabs,
657 * so that tabs in the right column line up.
659 unsigned int t = expand_tabs ? 1 : TAB_WIDTH;
660 int w = width ? width : 130;
661 int off = (w + t + GUTTER_WIDTH_MINIMUM) / (2 * t) * t;
662 sdiff_half_width = MAX (0, MIN (off - GUTTER_WIDTH_MINIMUM, w - off)),
663 sdiff_column2_offset = sdiff_half_width ? off : w;
666 /* Make the horizon at least as large as the context, so that
667 shift_boundaries has more freedom to shift the first and last hunks. */
668 if (horizon_lines < context)
669 horizon_lines = context;
671 summarize_regexp_list (&function_regexp_list);
672 summarize_regexp_list (&ignore_regexp_list);
674 if (output_style == OUTPUT_IFDEF)
676 for (i = 0; i < sizeof line_format / sizeof *line_format; i++)
678 line_format[i] = "%l\n";
679 if (!group_format[OLD])
681 = group_format[CHANGED] ? group_format[CHANGED] : "%<";
682 if (!group_format[NEW])
684 = group_format[CHANGED] ? group_format[CHANGED] : "%>";
685 if (!group_format[UNCHANGED])
686 group_format[UNCHANGED] = "%=";
687 if (!group_format[CHANGED])
688 group_format[CHANGED] = concat (group_format[OLD],
689 group_format[NEW], "");
692 no_diff_means_no_output =
693 (output_style == OUTPUT_IFDEF ?
694 (!*group_format[UNCHANGED]
695 || (strcmp (group_format[UNCHANGED], "%=") == 0
696 && !*line_format[UNCHANGED]))
697 : (output_style != OUTPUT_SDIFF) | suppress_common_lines);
699 files_can_be_treated_as_binary =
701 & ~ (ignore_blank_lines | ignore_case | strip_trailing_cr
702 | (ignore_regexp_list.regexps || ignore_white_space)));
704 switch_string = option_list (argv + 1, optind - 1);
709 fatal ("--from-file and --to-file both specified");
711 for (; optind < argc; optind++)
713 int status = compare_files ((struct comparison *) 0,
714 from_file, argv[optind]);
715 if (exit_status < status)
716 exit_status = status;
722 for (; optind < argc; optind++)
724 int status = compare_files ((struct comparison *) 0,
725 argv[optind], to_file);
726 if (exit_status < status)
727 exit_status = status;
731 if (argc - optind != 2)
733 if (argc - optind < 2)
734 try_help ("missing operand after `%s'", argv[argc - 1]);
736 try_help ("extra operand `%s'", argv[optind + 2]);
739 exit_status = compare_files ((struct comparison *) 0,
740 argv[optind], argv[optind + 1]);
744 /* Print any messages that were saved up for last. */
745 print_message_queue ();
752 /* Append to REGLIST the regexp PATTERN. */
755 add_regexp (struct regexp_list *reglist, char const *pattern)
757 size_t patlen = strlen (pattern);
758 char const *m = re_compile_pattern (pattern, patlen, reglist->buf);
761 error (0, 0, "%s: %s", pattern, m);
764 char *regexps = reglist->regexps;
765 size_t len = reglist->len;
766 bool multiple_regexps = reglist->multiple_regexps = regexps != 0;
767 size_t newlen = reglist->len = len + 2 * multiple_regexps + patlen;
768 size_t size = reglist->size;
776 while (size <= newlen);
778 reglist->size = size;
779 reglist->regexps = regexps = xrealloc (regexps, size);
781 if (multiple_regexps)
783 regexps[len++] = '\\';
784 regexps[len++] = '|';
786 memcpy (regexps + len, pattern, patlen + 1);
790 /* Ensure that REGLIST represents the disjunction of its regexps.
791 This is done here, rather than earlier, to avoid O(N^2) behavior. */
794 summarize_regexp_list (struct regexp_list *reglist)
796 if (reglist->regexps)
798 /* At least one regexp was specified. Allocate a fastmap for it. */
799 reglist->buf->fastmap = xmalloc (1 << CHAR_BIT);
800 if (reglist->multiple_regexps)
802 /* Compile the disjunction of the regexps.
803 (If just one regexp was specified, it is already compiled.) */
804 char const *m = re_compile_pattern (reglist->regexps, reglist->len,
807 error (EXIT_TROUBLE, 0, "%s: %s", reglist->regexps, m);
813 try_help (char const *reason_msgid, char const *operand)
816 error (0, 0, _(reason_msgid), operand);
817 error (EXIT_TROUBLE, 0, _("Try `%s --help' for more information."),
826 fatal ("write failed");
827 else if (fclose (stdout) != 0)
828 pfatal_with_name (_("standard output"));
831 static char const * const option_help_msgid[] = {
832 N_("Compare files line by line."),
834 N_("-i --ignore-case Ignore case differences in file contents."),
835 N_("--ignore-file-name-case Ignore case when comparing file names."),
836 N_("--no-ignore-file-name-case Consider case when comparing file names."),
837 N_("-E --ignore-tab-expansion Ignore changes due to tab expansion."),
838 N_("-b --ignore-space-change Ignore changes in the amount of white space."),
839 N_("-w --ignore-all-space Ignore all white space."),
840 N_("-B --ignore-blank-lines Ignore changes whose lines are all blank."),
841 N_("-I RE --ignore-matching-lines=RE Ignore changes whose lines all match RE."),
842 N_("--strip-trailing-cr Strip trailing carriage return on input."),
844 N_("--binary Read and write data in binary mode."),
846 N_("-a --text Treat all files as text."),
848 N_("-c -C NUM --context[=NUM] Output NUM (default 3) lines of copied context.\n\
849 -u -U NUM --unified[=NUM] Output NUM (default 3) lines of unified context.\n\
850 --label LABEL Use LABEL instead of file name.\n\
851 -p --show-c-function Show which C function each change is in.\n\
852 -F RE --show-function-line=RE Show the most recent line matching RE."),
853 N_("-q --brief Output only whether files differ."),
854 N_("-e --ed Output an ed script."),
855 N_("--normal Output a normal diff."),
856 N_("-n --rcs Output an RCS format diff."),
857 N_("-y --side-by-side Output in two columns.\n\
858 -W NUM --width=NUM Output at most NUM (default 130) print columns.\n\
859 --left-column Output only the left column of common lines.\n\
860 --suppress-common-lines Do not output common lines."),
861 N_("-D NAME --ifdef=NAME Output merged file to show `#ifdef NAME' diffs."),
862 N_("--GTYPE-group-format=GFMT Similar, but format GTYPE input groups with GFMT."),
863 N_("--line-format=LFMT Similar, but format all input lines with LFMT."),
864 N_("--LTYPE-line-format=LFMT Similar, but format LTYPE input lines with LFMT."),
865 N_(" LTYPE is `old', `new', or `unchanged'. GTYPE is LTYPE or `changed'."),
866 N_(" GFMT may contain:\n\
867 %< lines from FILE1\n\
868 %> lines from FILE2\n\
869 %= lines common to FILE1 and FILE2\n\
870 %[-][WIDTH][.[PREC]]{doxX}LETTER printf-style spec for LETTER\n\
871 LETTERs are as follows for new group, lower case for old group:\n\
872 F first line number\n\
873 L last line number\n\
874 N number of lines = L-F+1\n\
877 N_(" LFMT may contain:\n\
878 %L contents of line\n\
879 %l contents of line, excluding any trailing newline\n\
880 %[-][WIDTH][.[PREC]]{doxX}n printf-style spec for input line number"),
881 N_(" Either GFMT or LFMT may contain:\n\
883 %c'C' the single character C\n\
884 %c'\\OOO' the character with octal code OOO"),
886 N_("-l --paginate Pass the output through `pr' to paginate it."),
887 N_("-t --expand-tabs Expand tabs to spaces in output."),
888 N_("-T --initial-tab Make tabs line up by prepending a tab."),
890 N_("-r --recursive Recursively compare any subdirectories found."),
891 N_("-N --new-file Treat absent files as empty."),
892 N_("--unidirectional-new-file Treat absent first files as empty."),
893 N_("-s --report-identical-files Report when two files are the same."),
894 N_("-x PAT --exclude=PAT Exclude files that match PAT."),
895 N_("-X FILE --exclude-from=FILE Exclude files that match any pattern in FILE."),
896 N_("-S FILE --starting-file=FILE Start with FILE when comparing directories."),
897 N_("--from-file=FILE1 Compare FILE1 to all operands. FILE1 can be a directory."),
898 N_("--to-file=FILE2 Compare all operands to FILE2. FILE2 can be a directory."),
900 N_("--horizon-lines=NUM Keep NUM lines of the common prefix and suffix."),
901 N_("-d --minimal Try hard to find a smaller set of changes."),
902 N_("--speed-large-files Assume large files and many scattered small changes."),
904 N_("-v --version Output version info."),
905 N_("--help Output this help."),
907 N_("FILES are `FILE1 FILE2' or `DIR1 DIR2' or `DIR FILE...' or `FILE... DIR'."),
908 N_("If --from-file or --to-file is given, there are no restrictions on FILES."),
909 N_("If a FILE is `-', read standard input."),
911 N_("Report bugs to <bug-gnu-utils@gnu.org>."),
918 char const * const *p;
920 printf (_("Usage: %s [OPTION]... FILES\n"), program_name);
922 for (p = option_help_msgid; *p; p++)
928 char const *msg = _(*p);
930 while ((nl = strchr (msg, '\n')))
932 int msglen = nl + 1 - msg;
933 printf (" %.*s", msglen, msg);
937 printf (" %s\n" + 2 * (*msg != ' ' && *msg != '-'), msg);
942 /* Set VAR to VALUE, reporting an OPTION error if this is a
945 specify_value (char const **var, char const *value, char const *option)
947 if (*var && strcmp (*var, value) != 0)
949 error (0, 0, _("conflicting %s option value `%s'"), option, value);
955 /* Set the output style to STYLE, diagnosing conflicts. */
957 specify_style (enum output_style style)
959 if (output_style != style)
961 if (output_style != OUTPUT_UNSPECIFIED)
962 try_help ("conflicting output style options", 0);
963 output_style = style;
968 filetype (struct stat const *st)
970 /* See POSIX 1003.1-2001 for these formats.
972 To keep diagnostics grammatical in English, the returned string
973 must start with a consonant. */
975 if (S_ISREG (st->st_mode))
976 return st->st_size == 0 ? _("regular empty file") : _("regular file");
978 if (S_ISDIR (st->st_mode)) return _("directory");
981 if (S_ISBLK (st->st_mode)) return _("block special file");
984 if (S_ISCHR (st->st_mode)) return _("character special file");
987 if (S_ISFIFO (st->st_mode)) return _("fifo");
989 /* S_ISLNK is impossible with `fstat' and `stat'. */
991 if (S_ISSOCK (st->st_mode)) return _("socket");
994 if (S_TYPEISMQ (st)) return _("message queue");
997 if (S_TYPEISSEM (st)) return _("semaphore");
1000 if (S_TYPEISSHM (st)) return _("shared memory object");
1003 if (S_TYPEISTMO (st)) return _("typed memory object");
1006 return _("weird file");
1009 /* Set the last-modified time of *ST to be the current time. */
1012 set_mtime_to_now (struct stat *st)
1016 # if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
1017 if (clock_gettime (CLOCK_REALTIME, &st->st_mtim) == 0)
1021 # if HAVE_GETTIMEOFDAY
1023 struct timeval timeval;
1024 if (gettimeofday (&timeval, NULL) == 0)
1026 st->st_mtime = timeval.tv_sec;
1027 st->st_mtim.ST_MTIM_NSEC = timeval.tv_usec * 1000;
1033 #endif /* ST_MTIM_NSEC */
1035 time (&st->st_mtime);
1038 /* Compare two files (or dirs) with parent comparison PARENT
1039 and names NAME0 and NAME1.
1040 (If PARENT is 0, then the first name is just NAME0, etc.)
1041 This is self-contained; it opens the files and closes them.
1043 Value is EXIT_SUCCESS if files are the same, EXIT_FAILURE if
1044 different, EXIT_TROUBLE if there is a problem opening them. */
1047 compare_files (struct comparison const *parent,
1051 struct comparison cmp;
1052 #define DIR_P(f) (S_ISDIR (cmp.file[f].stat.st_mode) != 0)
1054 int status = EXIT_SUCCESS;
1056 char *free0, *free1;
1058 /* If this is directory comparison, perhaps we have a file
1059 that exists only in one of the directories.
1060 If so, just print a message to that effect. */
1062 if (! ((name0 && name1)
1063 || (unidirectional_new_file && name1)
1066 char const *name = name0 == 0 ? name1 : name0;
1067 char const *dir = parent->file[name0 == 0].name;
1069 /* See POSIX 1003.1-2001 for this format. */
1070 message ("Only in %s: %s\n", dir, name);
1072 /* Return EXIT_FAILURE so that diff_dirs will return
1073 EXIT_FAILURE ("some files differ"). */
1074 return EXIT_FAILURE;
1077 memset (cmp.file, 0, sizeof cmp.file);
1078 cmp.parent = parent;
1080 /* cmp.file[f].desc markers */
1081 #define NONEXISTENT (-1) /* nonexistent file */
1082 #define UNOPENED (-2) /* unopened file (e.g. directory) */
1083 #define ERRNO_ENCODE(errno) (-3 - (errno)) /* encoded errno value */
1085 #define ERRNO_DECODE(desc) (-3 - (desc)) /* inverse of ERRNO_ENCODE */
1087 cmp.file[0].desc = name0 == 0 ? NONEXISTENT : UNOPENED;
1088 cmp.file[1].desc = name1 == 0 ? NONEXISTENT : UNOPENED;
1090 /* Now record the full name of each file, including nonexistent ones. */
1101 cmp.file[0].name = name0;
1102 cmp.file[1].name = name1;
1106 cmp.file[0].name = free0
1107 = dir_file_pathname (parent->file[0].name, name0);
1108 cmp.file[1].name = free1
1109 = dir_file_pathname (parent->file[1].name, name1);
1112 /* Stat the files. */
1114 for (f = 0; f < 2; f++)
1116 if (cmp.file[f].desc != NONEXISTENT)
1118 if (f && file_name_cmp (cmp.file[f].name, cmp.file[0].name) == 0)
1120 cmp.file[f].desc = cmp.file[0].desc;
1121 cmp.file[f].stat = cmp.file[0].stat;
1123 else if (strcmp (cmp.file[f].name, "-") == 0)
1125 cmp.file[f].desc = STDIN_FILENO;
1126 if (fstat (STDIN_FILENO, &cmp.file[f].stat) != 0)
1127 cmp.file[f].desc = ERRNO_ENCODE (errno);
1130 if (S_ISREG (cmp.file[f].stat.st_mode))
1132 off_t pos = lseek (STDIN_FILENO, (off_t) 0, SEEK_CUR);
1134 cmp.file[f].desc = ERRNO_ENCODE (errno);
1136 cmp.file[f].stat.st_size =
1137 MAX (0, cmp.file[f].stat.st_size - pos);
1140 /* POSIX 1003.1-2001 requires current time for
1142 set_mtime_to_now (&cmp.file[f].stat);
1145 else if (stat (cmp.file[f].name, &cmp.file[f].stat) != 0)
1146 cmp.file[f].desc = ERRNO_ENCODE (errno);
1150 /* Mark files as nonexistent at the top level as needed for -N and
1151 --unidirectional-new-file. */
1154 if ((new_file | unidirectional_new_file)
1155 && cmp.file[0].desc == ERRNO_ENCODE (ENOENT)
1156 && cmp.file[1].desc == UNOPENED)
1157 cmp.file[0].desc = NONEXISTENT;
1160 && cmp.file[0].desc == UNOPENED
1161 && cmp.file[1].desc == ERRNO_ENCODE (ENOENT))
1162 cmp.file[1].desc = NONEXISTENT;
1165 for (f = 0; f < 2; f++)
1166 if (cmp.file[f].desc == NONEXISTENT)
1167 cmp.file[f].stat.st_mode = cmp.file[1 - f].stat.st_mode;
1169 for (f = 0; f < 2; f++)
1171 int e = ERRNO_DECODE (cmp.file[f].desc);
1175 perror_with_name (cmp.file[f].name);
1176 status = EXIT_TROUBLE;
1180 if (status == EXIT_SUCCESS && ! parent && DIR_P (0) != DIR_P (1))
1182 /* If one is a directory, and it was specified in the command line,
1183 use the file in that dir with the other file's basename. */
1185 int fnm_arg = DIR_P (0);
1186 int dir_arg = 1 - fnm_arg;
1187 char const *fnm = cmp.file[fnm_arg].name;
1188 char const *dir = cmp.file[dir_arg].name;
1189 char const *filename = cmp.file[dir_arg].name = free0
1190 = dir_file_pathname (dir, base_name (fnm));
1192 if (strcmp (fnm, "-") == 0)
1193 fatal ("cannot compare `-' to a directory");
1195 if (stat (filename, &cmp.file[dir_arg].stat) != 0)
1197 perror_with_name (filename);
1198 status = EXIT_TROUBLE;
1202 if (status != EXIT_SUCCESS)
1204 /* One of the files should exist but does not. */
1206 else if ((same_files
1207 = (cmp.file[0].desc != NONEXISTENT
1208 && cmp.file[1].desc != NONEXISTENT
1209 && 0 < same_file (&cmp.file[0].stat, &cmp.file[1].stat)
1210 && same_file_attributes (&cmp.file[0].stat,
1211 &cmp.file[1].stat)))
1212 && no_diff_means_no_output)
1214 /* The two named files are actually the same physical file.
1215 We know they are identical without actually reading them. */
1217 else if (DIR_P (0) & DIR_P (1))
1219 if (output_style == OUTPUT_IFDEF)
1220 fatal ("-D option not supported with directories");
1222 /* If both are directories, compare the files in them. */
1224 if (parent && !recursive)
1226 /* But don't compare dir contents one level down
1227 unless -r was specified.
1228 See POSIX 1003.1-2001 for this format. */
1229 message ("Common subdirectories: %s and %s\n",
1230 cmp.file[0].name, cmp.file[1].name);
1233 status = diff_dirs (&cmp, compare_files);
1235 else if ((DIR_P (0) | DIR_P (1))
1237 && (! S_ISREG (cmp.file[0].stat.st_mode)
1238 || ! S_ISREG (cmp.file[1].stat.st_mode))))
1240 if (cmp.file[0].desc == NONEXISTENT || cmp.file[1].desc == NONEXISTENT)
1242 /* We have a subdirectory that exists only in one directory. */
1244 if ((DIR_P (0) | DIR_P (1))
1247 || (unidirectional_new_file
1248 && cmp.file[0].desc == NONEXISTENT)))
1249 status = diff_dirs (&cmp, compare_files);
1253 = parent->file[cmp.file[0].desc == NONEXISTENT].name;
1255 /* See POSIX 1003.1-2001 for this format. */
1256 message ("Only in %s: %s\n", dir, name0);
1258 status = EXIT_FAILURE;
1263 /* We have two files that are not to be compared. */
1265 /* See POSIX 1003.1-2001 for this format. */
1266 message5 ("File %s is a %s while file %s is a %s\n",
1267 file_label[0] ? file_label[0] : cmp.file[0].name,
1268 filetype (&cmp.file[0].stat),
1269 file_label[1] ? file_label[1] : cmp.file[1].name,
1270 filetype (&cmp.file[1].stat));
1272 /* This is a difference. */
1273 status = EXIT_FAILURE;
1276 else if (files_can_be_treated_as_binary
1277 && cmp.file[0].stat.st_size != cmp.file[1].stat.st_size
1278 && (cmp.file[0].desc == NONEXISTENT
1279 || S_ISREG (cmp.file[0].stat.st_mode))
1280 && (cmp.file[1].desc == NONEXISTENT
1281 || S_ISREG (cmp.file[1].stat.st_mode)))
1283 message ("Files %s and %s differ\n",
1284 file_label[0] ? file_label[0] : cmp.file[0].name,
1285 file_label[1] ? file_label[1] : cmp.file[1].name);
1286 status = EXIT_FAILURE;
1290 /* Both exist and neither is a directory. */
1292 /* Open the files and record their descriptors. */
1294 if (cmp.file[0].desc == UNOPENED)
1295 if ((cmp.file[0].desc = open (cmp.file[0].name, O_RDONLY, 0)) < 0)
1297 perror_with_name (cmp.file[0].name);
1298 status = EXIT_TROUBLE;
1300 if (cmp.file[1].desc == UNOPENED)
1303 cmp.file[1].desc = cmp.file[0].desc;
1304 else if ((cmp.file[1].desc = open (cmp.file[1].name, O_RDONLY, 0))
1307 perror_with_name (cmp.file[1].name);
1308 status = EXIT_TROUBLE;
1312 #if HAVE_SETMODE_DOS
1314 for (f = 0; f < 2; f++)
1315 if (0 <= cmp.file[f].desc)
1316 set_binary_mode (cmp.file[f].desc, 1);
1319 /* Compare the files, if no error was found. */
1321 if (status == EXIT_SUCCESS)
1322 status = diff_2_files (&cmp);
1324 /* Close the file descriptors. */
1326 if (0 <= cmp.file[0].desc && close (cmp.file[0].desc) != 0)
1328 perror_with_name (cmp.file[0].name);
1329 status = EXIT_TROUBLE;
1331 if (0 <= cmp.file[1].desc && cmp.file[0].desc != cmp.file[1].desc
1332 && close (cmp.file[1].desc) != 0)
1334 perror_with_name (cmp.file[1].name);
1335 status = EXIT_TROUBLE;
1339 /* Now the comparison has been done, if no error prevented it,
1340 and STATUS is the value this function will return. */
1342 if (status == EXIT_SUCCESS)
1344 if (report_identical_files && !DIR_P (0))
1345 message ("Files %s and %s are identical\n",
1346 file_label[0] ? file_label[0] : cmp.file[0].name,
1347 file_label[1] ? file_label[1] : cmp.file[1].name);
1351 /* Flush stdout so that the user sees differences immediately.
1352 This can hurt performance, unfortunately. */
1353 if (fflush (stdout) != 0)
1354 pfatal_with_name (_("standard output"));