/contrib/cvs/diff/diff.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 1266 lines · 937 code · 154 blank · 175 comment · 233 complexity · 287c8ea734c89721622e462ecbe70210 MD5 · raw file

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