home *** CD-ROM | disk | FTP | other *** search
/ rtsi.com / 2014.01.www.rtsi.com.tar / www.rtsi.com / OS9 / OSK / APPS / diff.lzh / diff / diff.c < prev    next >
Encoding:
C/C++ Source or Header  |  1986-04-24  |  27.2 KB  |  1,050 lines

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