home *** CD-ROM | disk | FTP | other *** search
/ ftp.mactech.com 2010 / ftp.mactech.com.tar / ftp.mactech.com / online / source / c / compilers / DiffUtils.sit.hqx / DiffUtils / src / diff.c < prev    next >
Text File  |  1993-11-15  |  28KB  |  1,041 lines

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