home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / rcs57pc3.zip / diff / diff.c < prev    next >
C/C++ Source or Header  |  1999-02-21  |  34KB  |  1,194 lines

  1. /* GNU DIFF main routine.
  2.    Copyright (C) 1988, 1989, 1992, 1993, 1994 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU DIFF.
  5.  
  6. GNU DIFF is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10.  
  11. GNU DIFF is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU DIFF; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /* GNU DIFF was written by Mike Haertel, David Hayes,
  21.    Richard Stallman, Len Tower, and Paul Eggert.  */
  22.  
  23. #define GDIFF_MAIN
  24. #include "diff.h"
  25. #include <signal.h>
  26. #include "getopt.h"
  27. #include "fnmatch.h"
  28.  
  29. #ifndef DEFAULT_WIDTH
  30. #define DEFAULT_WIDTH 130
  31. #endif
  32.  
  33. #ifndef GUTTER_WIDTH_MINIMUM
  34. #define GUTTER_WIDTH_MINIMUM 3
  35. #endif
  36.  
  37. struct regexp_list
  38. {
  39.   char *regexps;    /* chars representing disjunction of the regexps */
  40.   size_t len;        /* chars used in `regexps' */
  41.   size_t size;        /* size malloc'ed for `regexps'; 0 if not malloc'ed */
  42.   int multiple_regexps;    /* Does `regexps' represent a disjunction?  */
  43.   struct re_pattern_buffer *buf;
  44. };
  45.  
  46. static char const *filetype PARAMS((struct stat const *));
  47. static char *option_list PARAMS((char **, int));
  48. static int add_exclude_file PARAMS((char const *));
  49. static int ck_atoi PARAMS((char const *, int *));
  50. static int compare_files PARAMS((char const *, char const *, char const *, char const *, int));
  51. static int specify_format PARAMS((char **, char *));
  52. static void add_exclude PARAMS((char const *));
  53. static void add_regexp PARAMS((struct regexp_list *, char const *));
  54. static void summarize_regexp_list PARAMS((struct regexp_list *));
  55. static void specify_style PARAMS((enum output_style));
  56. static void try_help PARAMS((char const *));
  57. static void check_stdout PARAMS((void));
  58. static void usage PARAMS((void));
  59.  
  60. /* Nonzero for -r: if comparing two directories,
  61.    compare their common subdirectories recursively.  */
  62.  
  63. static int recursive;
  64.  
  65. /* For debugging: don't do discard_confusing_lines.  */
  66.  
  67. int no_discards;
  68.  
  69. /* For -F and -I: lists of regular expressions.  */
  70. struct regexp_list function_regexp_list;
  71. struct regexp_list ignore_regexp_list;
  72.  
  73. #if HAVE_SETMODE
  74. /* I/O mode: nonzero only if using binary input/output.  */
  75. static int binary_I_O;
  76. #endif
  77.  
  78. /* Return a string containing the command options with which diff was invoked.
  79.    Spaces appear between what were separate ARGV-elements.
  80.    There is a space at the beginning but none at the end.
  81.    If there were no options, the result is an empty string.
  82.  
  83.    Arguments: OPTIONVEC, a vector containing separate ARGV-elements, and COUNT,
  84.    the length of that vector.  */
  85.  
  86. static char *
  87. option_list (optionvec, count)
  88.      char **optionvec;  /* Was `vector', but that collides on Alliant.  */
  89.      int count;
  90. {
  91.   int i;
  92.   size_t size = 1;
  93.   char *result;
  94.   char *p;
  95.  
  96.   for (i = 0; i < count; i++)
  97.     size += 1 + system_quote_arg ((char *) 0, optionvec[i]);
  98.  
  99.   p = result = xmalloc (size);
  100.  
  101.   for (i = 0; i < count; i++)
  102.     {
  103.       *p++ = ' ';
  104.       p += system_quote_arg (p, optionvec[i]);
  105.     }
  106.  
  107.   *p = 0;
  108.   return result;
  109. }
  110.  
  111. /* Convert STR to a positive integer, storing the result in *OUT.
  112.    If STR is not a valid integer, return -1 (otherwise 0).  */
  113. static int
  114. ck_atoi (str, out)
  115.      char const *str;
  116.      int *out;
  117. {
  118.   char const *p;
  119.   for (p = str; *p; p++)
  120.     if (*p < '0' || *p > '9')
  121.       return -1;
  122.  
  123.   *out = atoi (optarg);
  124.   return 0;
  125. }
  126.  
  127. /* Keep track of excluded file name patterns.  */
  128.  
  129. static char const **exclude;
  130. static int exclude_alloc, exclude_count;
  131.  
  132. int
  133. excluded_filename (f)
  134.      char const *f;
  135. {
  136.   int i;
  137.   for (i = 0;  i < exclude_count;  i++)
  138.     if (fnmatch (exclude[i], f, 0) == 0)
  139.       return 1;
  140.   return 0;
  141. }
  142.  
  143. static void
  144. add_exclude (pattern)
  145.      char const *pattern;
  146. {
  147.   if (exclude_alloc <= exclude_count)
  148.     {
  149.       exclude_alloc = exclude_alloc ? 2 * exclude_alloc : 64;
  150.       exclude = (char const **) xrealloc (exclude,
  151.                       exclude_alloc * sizeof (*exclude));
  152.     }
  153.  
  154.   exclude[exclude_count++] = pattern;
  155. }
  156.  
  157. static int
  158. add_exclude_file (name)
  159.      char const *name;
  160. {
  161.   struct file_data f;
  162.   char *p, *q, *lim;
  163.  
  164.   f.name = optarg;
  165.   f.desc = (strcmp (optarg, "-") == 0
  166.         ? STDIN_FILENO
  167.         : open (optarg, O_RDONLY, 0));
  168.   if (f.desc < 0 || fstat (f.desc, &f.stat) != 0)
  169.     return -1;
  170.  
  171.   sip (&f, 1);
  172.   slurp (&f);
  173.  
  174.   for (p = f.buffer, lim = p + f.buffered_chars;  p < lim;  p = q)
  175.     {
  176.       q = (char *) memchr (p, '\n', lim - p);
  177.       if (!q)
  178.     q = lim;
  179.       *q++ = 0;
  180.       add_exclude (p);
  181.     }
  182.  
  183.   return close (f.desc);
  184. }
  185.  
  186. /* The numbers 129- that appear in the fourth element of some entries
  187.    tell the big switch in `main' how to process those options.  */
  188.  
  189. static struct option const longopts[] =
  190. {
  191.   {"ignore-blank-lines", 0, 0, 'B'},
  192.   {"context", 2, 0, 'C'},
  193.   {"ifdef", 1, 0, 'D'},
  194.   {"show-function-line", 1, 0, 'F'},
  195.   {"speed-large-files", 0, 0, 'H'},
  196.   {"ignore-matching-lines", 1, 0, 'I'},
  197.   {"label", 1, 0, 'L'},
  198.   {"file-label", 1, 0, 'L'},    /* An alias, no longer recommended */
  199.   {"new-file", 0, 0, 'N'},
  200.   {"entire-new-file", 0, 0, 'N'},    /* An alias, no longer recommended */
  201.   {"unidirectional-new-file", 0, 0, 'P'},
  202.   {"starting-file", 1, 0, 'S'},
  203.   {"initial-tab", 0, 0, 'T'},
  204.   {"width", 1, 0, 'W'},
  205.   {"text", 0, 0, 'a'},
  206.   {"ascii", 0, 0, 'a'},        /* An alias, no longer recommended */
  207.   {"ignore-space-change", 0, 0, 'b'},
  208.   {"minimal", 0, 0, 'd'},
  209.   {"ed", 0, 0, 'e'},
  210.   {"forward-ed", 0, 0, 'f'},
  211.   {"ignore-case", 0, 0, 'i'},
  212.   {"paginate", 0, 0, 'l'},
  213.   {"print", 0, 0, 'l'},        /* An alias, no longer recommended */
  214.   {"rcs", 0, 0, 'n'},
  215.   {"show-c-function", 0, 0, 'p'},
  216.   {"brief", 0, 0, 'q'},
  217.   {"recursive", 0, 0, 'r'},
  218.   {"report-identical-files", 0, 0, 's'},
  219.   {"expand-tabs", 0, 0, 't'},
  220.   {"version", 0, 0, 'v'},
  221.   {"ignore-all-space", 0, 0, 'w'},
  222.   {"exclude", 1, 0, 'x'},
  223.   {"exclude-from", 1, 0, 'X'},
  224.   {"side-by-side", 0, 0, 'y'},
  225.   {"unified", 2, 0, 'U'},
  226.   {"left-column", 0, 0, 129},
  227.   {"suppress-common-lines", 0, 0, 130},
  228.   {"sdiff-merge-assist", 0, 0, 131},
  229.   {"old-line-format", 1, 0, 132},
  230.   {"new-line-format", 1, 0, 133},
  231.   {"unchanged-line-format", 1, 0, 134},
  232.   {"line-format", 1, 0, 135},
  233.   {"old-group-format", 1, 0, 136},
  234.   {"new-group-format", 1, 0, 137},
  235.   {"unchanged-group-format", 1, 0, 138},
  236.   {"changed-group-format", 1, 0, 139},
  237.   {"horizon-lines", 1, 0, 140},
  238.   {"help", 0, 0, 141},
  239.   {"binary", 0, 0, 142},
  240.   {0, 0, 0, 0}
  241. };
  242.  
  243. int
  244. main (argc, argv)
  245.      int argc;
  246.      char *argv[];
  247. {
  248.   int val;
  249.   int c;
  250.   int prev = -1;
  251.   int width = DEFAULT_WIDTH;
  252.   int show_c_function = 0;
  253.  
  254.   /* Do our initializations.  */
  255.   initialize_main (&argc, &argv);
  256.   setlocale (LC_ALL, "");
  257.   program_name = argv[0];
  258.   xmalloc_exit_failure = 2;
  259.   output_style = OUTPUT_NORMAL;
  260.   context = -1;
  261.   function_regexp_list.buf = &function_regexp;
  262.   ignore_regexp_list.buf = &ignore_regexp;
  263.  
  264.   /* Decode the options.  */
  265.  
  266.   while ((c = getopt_long (argc, argv,
  267.                "0123456789abBcC:dD:efF:hHiI:lL:nNpPqrsS:tTuU:vwW:x:X:y",
  268.                longopts, 0)) != EOF)
  269.     {
  270.       switch (c)
  271.     {
  272.       /* All digits combine in decimal to specify the context-size.  */
  273.     case '1':
  274.     case '2':
  275.     case '3':
  276.     case '4':
  277.     case '5':
  278.     case '6':
  279.     case '7':
  280.     case '8':
  281.     case '9':
  282.     case '0':
  283.       if (context == -1)
  284.         context = 0;
  285.       /* If a context length has already been specified,
  286.          more digits allowed only if they follow right after the others.
  287.          Reject two separate runs of digits, or digits after -C.  */
  288.       else if (prev < '0' || prev > '9')
  289.         fatal ("context length specified twice");
  290.  
  291.       context = context * 10 + c - '0';
  292.       break;
  293.  
  294.     case 'a':
  295.       /* Treat all files as text files; never treat as binary.  */
  296.       always_text_flag = 1;
  297.       break;
  298.  
  299.     case 'b':
  300.       /* Ignore changes in amount of white space.  */
  301.       ignore_space_change_flag = 1;
  302.       ignore_some_changes = 1;
  303.       break;
  304.  
  305.     case 'B':
  306.       /* Ignore changes affecting only blank lines.  */
  307.       ignore_blank_lines_flag = 1;
  308.       ignore_some_changes = 1;
  309.       break;
  310.  
  311.     case 'C':        /* +context[=lines] */
  312.     case 'U':        /* +unified[=lines] */
  313.       if (optarg)
  314.         {
  315.           if (context >= 0)
  316.         fatal ("context length specified twice");
  317.  
  318.           if (ck_atoi (optarg, &context))
  319.         fatal ("context length must be a nonnegative integer");
  320.         }
  321.       /* Fall through.  */
  322.     case 'c':
  323.       /* Make context-style output.  */
  324.       specify_style (c == 'U' ? OUTPUT_UNIFIED : OUTPUT_CONTEXT);
  325.       break;
  326.  
  327.     case 'd':
  328.       /* Don't discard lines.  This makes things slower (sometimes much
  329.          slower) but will find a guaranteed minimal set of changes.  */
  330.       no_discards = 1;
  331.       break;
  332.  
  333.     case 'D':
  334.       /* Make merged #ifdef output.  */
  335.       specify_style (OUTPUT_IFDEF);
  336.       {
  337.         int i, err = 0;
  338.         static char const C_ifdef_group_formats[] =
  339.           "#ifndef %s\n%%<#endif /* ! %s */\n%c#ifdef %s\n%%>#endif /* %s */\n%c%%=%c#ifndef %s\n%%<#else /* %s */\n%%>#endif /* %s */\n";
  340.         char *b = xmalloc (sizeof (C_ifdef_group_formats)
  341.                    + 7 * strlen (optarg) - 14 /* 7*"%s" */
  342.                    - 8 /* 5*"%%" + 3*"%c" */);
  343.         sprintf (b, C_ifdef_group_formats,
  344.              optarg, optarg, 0,
  345.              optarg, optarg, 0, 0,
  346.              optarg, optarg, optarg);
  347.         for (i = 0; i < 4; i++)
  348.           {
  349.         err |= specify_format (&group_format[i], b);
  350.         b += strlen (b) + 1;
  351.           }
  352.         if (err)
  353.           error (0, 0, gettext ("conflicting #ifdef format"));
  354.       }
  355.       break;
  356.  
  357.     case 'e':
  358.       /* Make output that is a valid `ed' script.  */
  359.       specify_style (OUTPUT_ED);
  360.       break;
  361.  
  362.     case 'f':
  363.       /* Make output that looks vaguely like an `ed' script
  364.          but has changes in the order they appear in the file.  */
  365.       specify_style (OUTPUT_FORWARD_ED);
  366.       break;
  367.  
  368.     case 'F':
  369.       /* Show, for each set of changes, the previous line that
  370.          matches the specified regexp.  Currently affects only
  371.          context-style output.  */
  372.       add_regexp (&function_regexp_list, optarg);
  373.       break;
  374.  
  375.     case 'h':
  376.       /* Split the files into chunks of around 1500 lines
  377.          for faster processing.  Usually does not change the result.
  378.  
  379.          This currently has no effect.  */
  380.       break;
  381.  
  382.     case 'H':
  383.       /* Turn on heuristics that speed processing of large files
  384.          with a small density of changes.  */
  385.       heuristic = 1;
  386.       break;
  387.  
  388.     case 'i':
  389.       /* Ignore changes in case.  */
  390.       ignore_case_flag = 1;
  391.       ignore_some_changes = 1;
  392.       break;
  393.  
  394.     case 'I':
  395.       /* Ignore changes affecting only lines that match the
  396.          specified regexp.  */
  397.       add_regexp (&ignore_regexp_list, optarg);
  398.       ignore_some_changes = 1;
  399.       break;
  400.  
  401.     case 'l':
  402.       /* Pass the output through `pr' to paginate it.  */
  403.       paginate_flag = 1;
  404. #if !defined (SIGCHLD) && defined (SIGCLD)
  405. #define SIGCHLD SIGCLD
  406. #endif
  407. #ifdef SIGCHLD
  408.       /* Pagination requires forking and waiting, and
  409.          System V fork+wait does not work if SIGCHLD is ignored.  */
  410.       signal (SIGCHLD, SIG_DFL);
  411. #endif
  412.       break;
  413.  
  414.     case 'L':
  415.       /* Specify file labels for `-c' output headers.  */
  416.       if (!file_label[0])
  417.         file_label[0] = optarg;
  418.       else if (!file_label[1])
  419.         file_label[1] = optarg;
  420.       else
  421.         fatal ("too many file label options");
  422.       break;
  423.  
  424.     case 'n':
  425.       /* Output RCS-style diffs, like `-f' except that each command
  426.          specifies the number of lines affected.  */
  427.       specify_style (OUTPUT_RCS);
  428.       break;
  429.  
  430.     case 'N':
  431.       /* When comparing directories, if a file appears only in one
  432.          directory, treat it as present but empty in the other.  */
  433.       entire_new_file_flag = 1;
  434.       break;
  435.  
  436.     case 'p':
  437.       /* Make context-style output and show name of last C function.  */
  438.       show_c_function = 1;
  439.       add_regexp (&function_regexp_list, "^[_a-zA-Z$]");
  440.       break;
  441.  
  442.     case 'P':
  443.       /* When comparing directories, if a file appears only in
  444.          the second directory of the two,
  445.          treat it as present but empty in the other.  */
  446.       unidirectional_new_file_flag = 1;
  447.       break;
  448.  
  449.     case 'q':
  450.       no_details_flag = 1;
  451.       break;
  452.  
  453.     case 'r':
  454.       /* When comparing directories,
  455.          recursively compare any subdirectories found.  */
  456.       recursive = 1;
  457.       break;
  458.  
  459.     case 's':
  460.       /* Print a message if the files are the same.  */
  461.       print_file_same_flag = 1;
  462.       break;
  463.  
  464.     case 'S':
  465.       /* When comparing directories, start with the specified
  466.          file name.  This is used for resuming an aborted comparison.  */
  467.       dir_start_file = optarg;
  468.       break;
  469.  
  470.     case 't':
  471.       /* Expand tabs to spaces in the output so that it preserves
  472.          the alignment of the input files.  */
  473.       tab_expand_flag = 1;
  474.       break;
  475.  
  476.     case 'T':
  477.       /* Use a tab in the output, rather than a space, before the
  478.          text of an input line, so as to keep the proper alignment
  479.          in the input line without changing the characters in it.  */
  480.       tab_align_flag = 1;
  481.       break;
  482.  
  483.     case 'u':
  484.       /* Output the context diff in unidiff format.  */
  485.       specify_style (OUTPUT_UNIFIED);
  486.       break;
  487.  
  488.     case 'v':
  489.       printf ("diff - %s\n", version_string);
  490.       exit (0);
  491.  
  492.     case 'w':
  493.       /* Ignore horizontal white space when comparing lines.  */
  494.       ignore_all_space_flag = 1;
  495.       ignore_some_changes = 1;
  496.       break;
  497.  
  498.     case 'x':
  499.       add_exclude (optarg);
  500.       break;
  501.  
  502.     case 'X':
  503.       if (add_exclude_file (optarg) != 0)
  504.         pfatal_with_name (optarg);
  505.       break;
  506.  
  507.     case 'y':
  508.       /* Use side-by-side (sdiff-style) columnar output.  */
  509.       specify_style (OUTPUT_SDIFF);
  510.       break;
  511.  
  512.     case 'W':
  513.       /* Set the line width for OUTPUT_SDIFF.  */
  514.       if (ck_atoi (optarg, &width) || width <= 0)
  515.         fatal ("column width must be a positive integer");
  516.       break;
  517.  
  518.     case 129:
  519.       sdiff_left_only = 1;
  520.       break;
  521.  
  522.     case 130:
  523.       sdiff_skip_common_lines = 1;
  524.       break;
  525.  
  526.     case 131:
  527.       /* sdiff-style columns output.  */
  528.       specify_style (OUTPUT_SDIFF);
  529.       sdiff_help_sdiff = 1;
  530.       break;
  531.  
  532.     case 132:
  533.     case 133:
  534.     case 134:
  535.       specify_style (OUTPUT_IFDEF);
  536.       if (specify_format (&line_format[c - 132], optarg) != 0)
  537.         error (0, 0, gettext ("conflicting line format"));
  538.       break;
  539.  
  540.     case 135:
  541.       specify_style (OUTPUT_IFDEF);
  542.       {
  543.         int i, err = 0;
  544.         for (i = 0; i < sizeof (line_format) / sizeof (*line_format); i++)
  545.           err |= specify_format (&line_format[i], optarg);
  546.         if (err)
  547.           error (0, 0, gettext ("conflicting line format"));
  548.       }
  549.       break;
  550.  
  551.     case 136:
  552.     case 137:
  553.     case 138:
  554.     case 139:
  555.       specify_style (OUTPUT_IFDEF);
  556.       if (specify_format (&group_format[c - 136], optarg) != 0)
  557.         error (0, 0, gettext ("conflicting group format"));
  558.       break;
  559.  
  560.     case 140:
  561.       if (ck_atoi (optarg, &horizon_lines) || horizon_lines < 0)
  562.         fatal ("horizon must be a nonnegative integer");
  563.       break;
  564.  
  565.     case 141:
  566.       usage ();
  567.       check_stdout ();
  568.       exit (0);
  569.  
  570.     case 142:
  571.       /* Use binary I/O when reading and writing data.
  572.          On Posix hosts, this has no effect.  */
  573. #if HAVE_SETMODE
  574.       binary_I_O = 1;
  575. #ifdef __IBMC__
  576.       freopen("", "wb", stdout);
  577. #else
  578.       setmode (STDOUT_FILENO, O_BINARY);
  579. #endif
  580. #endif
  581.       break;
  582.  
  583.     default:
  584.       try_help (0);
  585.     }
  586.       prev = c;
  587.     }
  588.  
  589.   if (argc - optind != 2)
  590.     try_help (argc - optind < 2 ? "missing operand" : "extra operand");
  591.  
  592.  
  593.   {
  594.     /*
  595.      *    We maximize first the half line width, and then the gutter width,
  596.      *    according to the following constraints:
  597.      *    1.  Two half lines plus a gutter must fit in a line.
  598.      *    2.  If the half line width is nonzero:
  599.      *        a.  The gutter width is at least GUTTER_WIDTH_MINIMUM.
  600.      *        b.  If tabs are not expanded to spaces,
  601.      *        a half line plus a gutter is an integral number of tabs,
  602.      *        so that tabs in the right column line up.
  603.      */
  604.     int t = tab_expand_flag ? 1 : TAB_WIDTH;
  605.     int off = (width + t + GUTTER_WIDTH_MINIMUM) / (2*t)  *  t;
  606.     sdiff_half_width = max (0, min (off - GUTTER_WIDTH_MINIMUM, width - off)),
  607.     sdiff_column2_offset = sdiff_half_width ? off : width;
  608.   }
  609.  
  610.   if (show_c_function && output_style != OUTPUT_UNIFIED)
  611.     specify_style (OUTPUT_CONTEXT);
  612.  
  613.   if (output_style != OUTPUT_CONTEXT && output_style != OUTPUT_UNIFIED)
  614.     context = 0;
  615.   else if (context == -1)
  616.     /* Default amount of context for -c.  */
  617.     context = 3;
  618.  
  619.   summarize_regexp_list (&function_regexp_list);
  620.   summarize_regexp_list (&ignore_regexp_list);
  621.  
  622.   if (output_style == OUTPUT_IFDEF)
  623.     {
  624.       /* Format arrays are char *, not char const *,
  625.      because integer formats are temporarily modified.
  626.      But it is safe to assign a constant like "%=" to a format array,
  627.      since "%=" does not format any integers.  */
  628.       int i;
  629.       for (i = 0; i < sizeof (line_format) / sizeof (*line_format); i++)
  630.     if (!line_format[i])
  631.       line_format[i] = "%l\n";
  632.       if (!group_format[OLD])
  633.     group_format[OLD]
  634.       = group_format[UNCHANGED] ? group_format[UNCHANGED] : "%<";
  635.       if (!group_format[NEW])
  636.     group_format[NEW]
  637.       = group_format[UNCHANGED] ? group_format[UNCHANGED] : "%>";
  638.       if (!group_format[UNCHANGED])
  639.     group_format[UNCHANGED] = "%=";
  640.       if (!group_format[CHANGED])
  641.     group_format[CHANGED] = concat (group_format[OLD],
  642.                     group_format[NEW], "");
  643.     }
  644.  
  645.   no_diff_means_no_output =
  646.     (output_style == OUTPUT_IFDEF ?
  647.       (!*group_format[UNCHANGED]
  648.        || (strcmp (group_format[UNCHANGED], "%=") == 0
  649.        && !*line_format[UNCHANGED]))
  650.      : output_style == OUTPUT_SDIFF ? sdiff_skip_common_lines : 1);
  651.  
  652.   switch_string = option_list (argv + 1, optind - 1);
  653.  
  654.   val = compare_files (0, argv[optind], 0, argv[optind + 1], 0);
  655.  
  656.   /* Print any messages that were saved up for last.  */
  657.   print_message_queue ();
  658.  
  659.   check_stdout ();
  660.   exit (val);
  661.   return val;
  662. }
  663.  
  664. /* Append to REGLIST the regexp PATTERN.  */
  665.  
  666. static void
  667. add_regexp (reglist, pattern)
  668.      struct regexp_list *reglist;
  669.      char const *pattern;
  670. {
  671.   size_t patlen = strlen (pattern);
  672.   char const *m = re_compile_pattern (pattern, patlen, reglist->buf);
  673.  
  674.   if (m != 0)
  675.     error (0, 0, "%s: %s", pattern, m);
  676.   else
  677.     {
  678.       char *regexps = reglist->regexps;
  679.       size_t len = reglist->len;
  680.       int multiple_regexps = reglist->multiple_regexps = regexps != 0;
  681.       size_t newlen = reglist->len = len + 2 * multiple_regexps + patlen;
  682.       size_t size = reglist->size;
  683.  
  684.       if (size <= newlen)
  685.     {
  686.       if (!size)
  687.         size = 1;
  688.  
  689.       do size *= 2;
  690.       while (size <= newlen);
  691.  
  692.       reglist->size = size;
  693.       reglist->regexps = regexps = xrealloc (regexps, size);
  694.     }
  695.       if (multiple_regexps)
  696.     {
  697.       regexps[len++] = '\\';
  698.       regexps[len++] = '|';
  699.     }
  700.       memcpy (regexps + len, pattern, patlen + 1);
  701.     }
  702. }
  703.  
  704. /* Ensure that REGLIST represents the disjunction of its regexps.
  705.    This is done here, rather than earlier, to avoid O(N^2) behavior.  */
  706.  
  707. static void
  708. summarize_regexp_list (reglist)
  709.      struct regexp_list *reglist;
  710. {
  711.   if (reglist->regexps)
  712.     {
  713.       /* At least one regexp was specified.  Allocate a fastmap for it.  */
  714.       reglist->buf->fastmap = xmalloc (1 << CHAR_BIT);
  715.       if (reglist->multiple_regexps)
  716.     {
  717.       /* Compile the disjunction of the regexps.
  718.          (If just one regexp was specified, it is already compiled.)  */
  719.       char const *m = re_compile_pattern (reglist->regexps, reglist->len,
  720.                           reglist->buf);
  721.       if (m != 0)
  722.         error (2, 0, "%s: %s", reglist->regexps, m);
  723.     }
  724.     }
  725. }
  726.  
  727. static void
  728. try_help (reason_msgid)
  729.      char const *reason_msgid;
  730. {
  731.   if (reason_msgid)
  732.     error (0, 0, "%s", gettext (reason_msgid));
  733.   error (2, 0, gettext ("Try `%s --help' for more information."), program_name);
  734. }
  735.  
  736. static void
  737. check_stdout ()
  738. {
  739.   if (ferror (stdout) || fclose (stdout) != 0)
  740.     fatal ("write failed");
  741. }
  742.  
  743. static char const * const option_help_msgid[] = {
  744.   "",
  745.   "-i  --ignore-case  Consider upper- and lower-case to be the same.",
  746.   "-w  --ignore-all-space  Ignore all white space.",
  747.   "-b  --ignore-space-change  Ignore changes in the amount of white space.",
  748.   "-B  --ignore-blank-lines  Ignore changes whose lines are all blank.",
  749.   "-I RE  --ignore-matching-lines=RE  Ignore changes whose lines all match RE.",
  750. #if HAVE_SETMODE
  751.   "--binary  Read and write data in binary mode.",
  752. #endif
  753.   "-a  --text  Treat all files as text.",
  754.   "",
  755.   "-c  -C NUM  --context[=NUM]  Output NUM (default 2) lines of copied context.",
  756.   "-u  -U NUM  --unified[=NUM]  Output NUM (default 2) lines of unified context.",
  757.   "  -NUM  Use NUM context lines.",
  758.   "  -L LABEL  --label LABEL  Use LABEL instead of file name.",
  759.   "  -p  --show-c-function  Show which C function each change is in.",
  760.   "  -F RE  --show-function-line=RE  Show the most recent line matching RE.",
  761.   "-q  --brief  Output only whether files differ.",
  762.   "-e  --ed  Output an ed script.",
  763.   "-n  --rcs  Output an RCS format diff.",
  764.   "-y  --side-by-side  Output in two columns.",
  765.   "  -w NUM  --width=NUM  Output at most NUM (default 130) characters per line.",
  766.   "  --left-column  Output only the left column of common lines.",
  767.   "  --suppress-common-lines  Do not output common lines.",
  768.   "-DNAME  --ifdef=NAME  Output merged file to show `#ifdef NAME' diffs.",
  769.   "--GTYPE-group-format=GFMT  Similar, but format GTYPE input groups with GFMT.",
  770.   "--line-format=LFMT  Similar, but format all input lines with LFMT.",
  771.   "--LTYPE-line-format=LFMT  Similar, but format LTYPE input lines with LFMT.",
  772.   "  LTYPE is `old', `new', or `unchanged'.  GTYPE is LTYPE or `changed'.",
  773.   "  GFMT may contain:",
  774.   "    %<  lines from FILE1",
  775.   "    %>  lines from FILE2",
  776.   "    %=  lines common to FILE1 and FILE2",
  777.   "    %[-][WIDTH][.[PREC]]{doxX}LETTER  printf-style spec for LETTER",
  778.   "      LETTERs are as follows for new group, lower case for old group:",
  779.   "        F  first line number",
  780.   "        L  last line number",
  781.   "        N  number of lines = L-F+1",
  782.   "        E  F-1",
  783.   "        M  L+1",
  784.   "  LFMT may contain:",
  785.   "    %L  contents of line",
  786.   "    %l  contents of line, excluding any trailing newline",
  787.   "    %[-][WIDTH][.[PREC]]{doxX}n  printf-style spec for input line number",
  788.   "  Either GFMT or LFMT may contain:",
  789.   "    %%  %",
  790.   "    %c'C'  the single character C",
  791.   "    %c'\\OOO'  the character with octal code OOO",
  792.   "",
  793.   "-l  --paginate  Pass the output through `pr' to paginate it.",
  794.   "-t  --expand-tabs  Expand tabs to spaces in output.",
  795.   "-T  --initial-tab  Make tabs line up by prepending a tab.",
  796.   "",
  797.   "-r  --recursive  Recursively compare any subdirectories found.",
  798.   "-N  --new-file  Treat absent files as empty.",
  799.   "-P  --unidirectional-new-file  Treat absent first files as empty.",
  800.   "-s  --report-identical-files  Report when two files are the same.",
  801.   "-x PAT  --exclude=PAT  Exclude files that match PAT.",
  802.   "-X FILE  --exclude-from=FILE  Exclude files that match any pattern in FILE.",
  803.   "-S FILE  --starting-file=FILE  Start with FILE when comparing directories.",
  804.   "",
  805.   "--horizon-lines=NUM  Keep NUM lines of the common prefix and suffix.",
  806.   "-d  --minimal  Try hard to find a smaller set of changes.",
  807.   "-H  --speed-large-files  Assume large files and many scattered small changes.",
  808.   "",
  809.   "-v  --version  Output version info.",
  810.   "--help  Output this help.",
  811.   "",
  812.   0
  813. };
  814.  
  815. static void
  816. usage ()
  817. {
  818.   char const * const *p;
  819.  
  820.   printf (gettext ("Usage: %s [OPTION]... FILE1 FILE2\n"), program_name);
  821.   for (p = option_help_msgid;  *p;  p++)
  822.     if (**p)
  823.       printf ("  %s\n", gettext (*p));
  824.     else
  825.       putchar ('\n');
  826.   printf (gettext ("If a FILE is `-', read standard input.\n"));
  827. }
  828.  
  829. static int
  830. specify_format (var, value)
  831.      char **var;
  832.      char *value;
  833. {
  834.   int err = *var ? strcmp (*var, value) : 0;
  835.   *var = value;
  836.   return err;
  837. }
  838.  
  839. static void
  840. specify_style (style)
  841.      enum output_style style;
  842. {
  843.   if (output_style != OUTPUT_NORMAL
  844.       && output_style != style)
  845.     error (0, 0, gettext ("conflicting specifications of output style"));
  846.   output_style = style;
  847. }
  848.  
  849. static char const *
  850. filetype (st)
  851.      struct stat const *st;
  852. {
  853.   /* See Posix.2 section 4.17.6.1.1 and Table 5-1 for these formats.
  854.      To keep diagnostics grammatical, the returned string must start
  855.      with a consonant.  */
  856.  
  857.   if (S_ISREG (st->st_mode))
  858.     {
  859.       if (st->st_size == 0)
  860.     return gettext ("regular empty file");
  861.       /* Posix.2 section 5.14.2 seems to suggest that we must read the file
  862.      and guess whether it's C, Fortran, etc., but this is somewhat useless
  863.      and doesn't reflect historical practice.  We're allowed to guess
  864.      wrong, so we don't bother to read the file.  */
  865.       return gettext ("regular file");
  866.     }
  867.   if (S_ISDIR (st->st_mode)) return gettext ("directory");
  868.  
  869.   /* other Posix.1 file types */
  870. #ifdef S_ISBLK
  871.   if (S_ISBLK (st->st_mode)) return gettext ("block special file");
  872. #endif
  873. #ifdef S_ISCHR
  874.   if (S_ISCHR (st->st_mode)) return gettext ("character special file");
  875. #endif
  876. #ifdef S_ISFIFO
  877.   if (S_ISFIFO (st->st_mode)) return gettext ("fifo");
  878. #endif
  879.  
  880.   /* other Posix.1b file types */
  881. #ifdef S_TYPEISMQ
  882.   if (S_TYPEISMQ (st)) return gettext ("message queue");
  883. #endif
  884. #ifdef S_TYPEISSEM
  885.   if (S_TYPEISSEM (st)) return gettext ("semaphore");
  886. #endif
  887. #ifdef S_TYPEISSHM
  888.   if (S_TYPEISSHM (st)) return gettext ("shared memory object");
  889. #endif
  890.  
  891.   /* other popular file types */
  892.   /* S_ISLNK is impossible with `fstat' and `stat'.  */
  893. #ifdef S_ISSOCK
  894.   if (S_ISSOCK (st->st_mode)) return gettext ("socket");
  895. #endif
  896.  
  897.   return gettext ("weird file");
  898. }
  899.  
  900. /* Compare two files (or dirs) with specified names
  901.    DIR0/NAME0 and DIR1/NAME1, at level DEPTH in directory recursion.
  902.    (if DIR0 is 0, then the name is just NAME0, etc.)
  903.    This is self-contained; it opens the files and closes them.
  904.  
  905.    Value is 0 if files are the same, 1 if different,
  906.    2 if there is a problem opening them.  */
  907.  
  908. static int
  909. compare_files (dir0, name0, dir1, name1, depth)
  910.      char const *dir0, *dir1;
  911.      char const *name0, *name1;
  912.      int depth;
  913. {
  914.   struct file_data inf[2];
  915.   register int i;
  916.   int val;
  917.   int same_files;
  918.   int failed = 0;
  919.   char *free0 = 0, *free1 = 0;
  920.  
  921.   /* If this is directory comparison, perhaps we have a file
  922.      that exists only in one of the directories.
  923.      If so, just print a message to that effect.  */
  924.  
  925.   if (! ((name0 != 0 && name1 != 0)
  926.      || (unidirectional_new_file_flag && name1 != 0)
  927.      || entire_new_file_flag))
  928.     {
  929.       char const *name = name0 == 0 ? name1 : name0;
  930.       char const *dir = name0 == 0 ? dir1 : dir0;
  931.       message ("Only in %s: %s\n", dir, name);
  932.       /* Return 1 so that diff_dirs will return 1 ("some files differ").  */
  933.       return 1;
  934.     }
  935.  
  936.   bzero (inf, sizeof (inf));
  937.  
  938.   /* Mark any nonexistent file with -1 in the desc field.
  939.      Mark unopened files (e.g. directories) with -2.  */
  940.  
  941.   inf[0].desc = name0 == 0 ? -1 : -2;
  942.   inf[1].desc = name1 == 0 ? -1 : -2;
  943.  
  944.   /* Now record the full name of each file, including nonexistent ones.  */
  945.  
  946.   if (name0 == 0)
  947.     name0 = name1;
  948.   if (name1 == 0)
  949.     name1 = name0;
  950.  
  951.   inf[0].name = dir0 == 0 ? name0 : (free0 = dir_file_pathname (dir0, name0));
  952.   inf[1].name = dir1 == 0 ? name1 : (free1 = dir_file_pathname (dir1, name1));
  953.  
  954.   /* Stat the files.  Record whether they are directories.  */
  955.  
  956.   for (i = 0; i <= 1; i++)
  957.     {
  958.       if (inf[i].desc != -1)
  959.     {
  960.       int stat_result;
  961.  
  962.       if (i && filename_cmp (inf[i].name, inf[0].name) == 0)
  963.         {
  964.           inf[i].stat = inf[0].stat;
  965.           stat_result = 0;
  966.         }
  967.       else if (strcmp (inf[i].name, "-") == 0)
  968.         {
  969.           inf[i].desc = STDIN_FILENO;
  970.           stat_result = fstat (STDIN_FILENO, &inf[i].stat);
  971.           if (stat_result == 0 && S_ISREG (inf[i].stat.st_mode))
  972.         {
  973.           off_t pos = lseek (STDIN_FILENO, (off_t) 0, SEEK_CUR);
  974.           if (pos == -1)
  975.             stat_result = -1;
  976.           else
  977.             {
  978.               if (pos <= inf[i].stat.st_size)
  979.             inf[i].stat.st_size -= pos;
  980.               else
  981.             inf[i].stat.st_size = 0;
  982.               /* Posix.2 4.17.6.1.4 requires current time for stdin.  */
  983.               time (&inf[i].stat.st_mtime);
  984.             }
  985.         }
  986.         }
  987.       else
  988.         stat_result = stat (inf[i].name, &inf[i].stat);
  989.  
  990. #ifdef __EMX__
  991.       /* HACK: Treat 'nul' as a nonexistent file. */
  992.       if (stat_result != 0 && errno == EINVAL && stricmp (inf[i].name, "nul") == 0)
  993.         {
  994.           stat_result = 0;
  995.           inf[i].desc = -1;
  996.         }
  997. #endif /*__EMX__*/
  998.  
  999.       if (stat_result != 0)
  1000.         {
  1001.           perror_with_name (inf[i].name);
  1002.           failed = 1;
  1003.         }
  1004.       else
  1005.         {
  1006.           inf[i].dir_p = S_ISDIR (inf[i].stat.st_mode) && inf[i].desc != 0;
  1007.           if (inf[1 - i].desc == -1)
  1008.         {
  1009.           inf[1 - i].dir_p = inf[i].dir_p;
  1010.           inf[1 - i].stat.st_mode = inf[i].stat.st_mode;
  1011.         }
  1012.         }
  1013.     }
  1014.     }
  1015.  
  1016.   if (! failed && depth == 0 && inf[0].dir_p != inf[1].dir_p)
  1017.     {
  1018.       /* If one is a directory, and it was specified in the command line,
  1019.      use the file in that dir with the other file's basename.  */
  1020.  
  1021.       int fnm_arg = inf[0].dir_p;
  1022.       int dir_arg = 1 - fnm_arg;
  1023.       char const *fnm = inf[fnm_arg].name;
  1024.       char const *dir = inf[dir_arg].name;
  1025.       char const *p = filename_lastdirchar (fnm);
  1026.       char const *filename = inf[dir_arg].name
  1027.     = dir_file_pathname (dir, p ? p + 1 : fnm);
  1028.  
  1029.       if (strcmp (fnm, "-") == 0)
  1030.     fatal ("cannot compare `-' to a directory");
  1031.  
  1032.       if (stat (filename, &inf[dir_arg].stat) != 0)
  1033.     {
  1034.       perror_with_name (filename);
  1035.       failed = 1;
  1036.     }
  1037.       else
  1038.     inf[dir_arg].dir_p = S_ISDIR (inf[dir_arg].stat.st_mode);
  1039.     }
  1040.  
  1041.   if (failed)
  1042.     {
  1043.  
  1044.       /* If either file should exist but does not, return 2.  */
  1045.  
  1046.       val = 2;
  1047.  
  1048.     }
  1049.   else if ((same_files = inf[0].desc != -1 && inf[1].desc != -1
  1050.              && 0 < same_file (&inf[0].stat, &inf[1].stat))
  1051.        && no_diff_means_no_output)
  1052.     {
  1053.       /* The two named files are actually the same physical file.
  1054.      We know they are identical without actually reading them.  */
  1055.  
  1056.       val = 0;
  1057.     }
  1058.   else if (inf[0].dir_p & inf[1].dir_p)
  1059.     {
  1060.       if (output_style == OUTPUT_IFDEF)
  1061.     fatal ("-D option not supported with directories");
  1062.  
  1063.       /* If both are directories, compare the files in them.  */
  1064.  
  1065.       if (depth > 0 && !recursive)
  1066.     {
  1067.       /* But don't compare dir contents one level down
  1068.          unless -r was specified.  */
  1069.       message ("Common subdirectories: %s and %s\n",
  1070.            inf[0].name, inf[1].name);
  1071.       val = 0;
  1072.     }
  1073.       else
  1074.     {
  1075.       val = diff_dirs (inf, compare_files, depth);
  1076.     }
  1077.  
  1078.     }
  1079.   else if ((inf[0].dir_p | inf[1].dir_p)
  1080.        || (depth > 0
  1081.            && (! S_ISREG (inf[0].stat.st_mode)
  1082.            || ! S_ISREG (inf[1].stat.st_mode))))
  1083.     {
  1084.       /* Perhaps we have a subdirectory that exists only in one directory.
  1085.      If so, just print a message to that effect.  */
  1086.  
  1087.       if (inf[0].desc == -1 || inf[1].desc == -1)
  1088.     {
  1089.       if ((inf[0].dir_p | inf[1].dir_p)
  1090.           && recursive
  1091.           && (entire_new_file_flag
  1092.           || (unidirectional_new_file_flag && inf[0].desc == -1)))
  1093.         val = diff_dirs (inf, compare_files, depth);
  1094.       else
  1095.         {
  1096.           char const *dir = (inf[0].desc == -1) ? dir1 : dir0;
  1097.           /* See Posix.2 section 4.17.6.1.1 for this format.  */
  1098.           message ("Only in %s: %s\n", dir, name0);
  1099.           val = 1;
  1100.         }
  1101.     }
  1102.       else
  1103.     {
  1104.       /* We have two files that are not to be compared.  */
  1105.  
  1106.       /* See Posix.2 section 4.17.6.1.1 for this format.  */
  1107.       message5 ("File %s is a %s while file %s is a %s\n",
  1108.             file_label[0] ? file_label[0] : inf[0].name,
  1109.             filetype (&inf[0].stat),
  1110.             file_label[1] ? file_label[1] : inf[1].name,
  1111.             filetype (&inf[1].stat));
  1112.  
  1113.       /* This is a difference.  */
  1114.       val = 1;
  1115.     }
  1116.     }
  1117.   else if ((no_details_flag & ~ignore_some_changes)
  1118.        && inf[0].stat.st_size != inf[1].stat.st_size
  1119.        && (inf[0].desc == -1 || S_ISREG (inf[0].stat.st_mode))
  1120.        && (inf[1].desc == -1 || S_ISREG (inf[1].stat.st_mode)))
  1121.     {
  1122.       message ("Files %s and %s differ\n",
  1123.            file_label[0] ? file_label[0] : inf[0].name,
  1124.            file_label[1] ? file_label[1] : inf[1].name);
  1125.       val = 1;
  1126.     }
  1127.   else
  1128.     {
  1129.       /* Both exist and neither is a directory.  */
  1130.  
  1131.       /* Open the files and record their descriptors.  */
  1132.  
  1133.       if (inf[0].desc == -2)
  1134.     if ((inf[0].desc = open (inf[0].name, O_RDONLY, 0)) < 0)
  1135.       {
  1136.         perror_with_name (inf[0].name);
  1137.         failed = 1;
  1138.       }
  1139.       if (inf[1].desc == -2)
  1140.     if (same_files)
  1141.       inf[1].desc = inf[0].desc;
  1142.     else if ((inf[1].desc = open (inf[1].name, O_RDONLY, 0)) < 0)
  1143.       {
  1144.         perror_with_name (inf[1].name);
  1145.         failed = 1;
  1146.       }
  1147.  
  1148. #if HAVE_SETMODE
  1149.       if (binary_I_O)
  1150.     for (i = 0; i <= 1; i++)
  1151.       if (0 <= inf[i].desc)
  1152.         setmode (inf[i].desc, O_BINARY);
  1153. #endif
  1154.  
  1155.       /* Compare the files, if no error was found.  */
  1156.  
  1157.       val = failed ? 2 : diff_2_files (inf, depth);
  1158.  
  1159.       /* Close the file descriptors.  */
  1160.  
  1161.       if (inf[0].desc >= 0 && close (inf[0].desc) != 0)
  1162.     {
  1163.       perror_with_name (inf[0].name);
  1164.       val = 2;
  1165.     }
  1166.       if (inf[1].desc >= 0 && inf[0].desc != inf[1].desc
  1167.       && close (inf[1].desc) != 0)
  1168.     {
  1169.       perror_with_name (inf[1].name);
  1170.       val = 2;
  1171.     }
  1172.     }
  1173.  
  1174.   /* Now the comparison has been done, if no error prevented it,
  1175.      and VAL is the value this function will return.  */
  1176.  
  1177.   if (val == 0 && !inf[0].dir_p)
  1178.     {
  1179.       if (print_file_same_flag)
  1180.     message ("Files %s and %s are identical\n",
  1181.          file_label[0] ? file_label[0] : inf[0].name,
  1182.          file_label[1] ? file_label[1] : inf[1].name);
  1183.     }
  1184.   else
  1185.     fflush (stdout);
  1186.  
  1187.   if (free0)
  1188.     free (free0);
  1189.   if (free1)
  1190.     free (free1);
  1191.  
  1192.   return val;
  1193. }
  1194.