diff.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. /* GNU DIFF main routine.
  2. Copyright (C) 1988, 1989, 1992, 1993, 1994 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. You should have received a copy of the GNU General Public License
  13. along with GNU DIFF; see the file COPYING. If not, write to
  14. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
  15. /* GNU DIFF was written by Mike Haertel, David Hayes,
  16. Richard Stallman, Len Tower, and Paul Eggert. */
  17. /* $FreeBSD: src/contrib/diff/diff.c,v 1.3 1999/11/26 02:51:44 obrien Exp $ */
  18. #define GDIFF_MAIN
  19. #include "diff.h"
  20. #include <signal.h>
  21. #include "getopt.h"
  22. #ifdef __FreeBSD__
  23. #include <locale.h>
  24. #include <fnmatch.h>
  25. #else
  26. #include "fnmatch.h"
  27. #endif
  28. #include "prepend_args.h"
  29. #ifndef DEFAULT_WIDTH
  30. #define DEFAULT_WIDTH 130
  31. #endif
  32. #ifndef GUTTER_WIDTH_MINIMUM
  33. #define GUTTER_WIDTH_MINIMUM 3
  34. #endif
  35. static char const *filetype PARAMS((struct stat const *));
  36. static char *option_list PARAMS((char **, int));
  37. static int add_exclude_file PARAMS((char const *));
  38. static int ck_atoi PARAMS((char const *, int *));
  39. static int compare_files PARAMS((char const *, char const *, char const *, char const *, int));
  40. static int specify_format PARAMS((char **, char *));
  41. static void add_exclude PARAMS((char const *));
  42. static void add_regexp PARAMS((struct regexp_list **, char const *));
  43. static void specify_style PARAMS((enum output_style));
  44. static void try_help PARAMS((char const *));
  45. static void check_stdout PARAMS((void));
  46. static void usage PARAMS((void));
  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 (name, "-") == 0
  127. ? STDIN_FILENO
  128. : open (name, 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 `main' 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. main (argc, argv)
  200. int argc;
  201. char *argv[];
  202. {
  203. int val;
  204. int c;
  205. int prev = -1;
  206. int width = DEFAULT_WIDTH;
  207. int show_c_function = 0;
  208. #ifdef __FreeBSD__
  209. setlocale(LC_ALL, "");
  210. #endif
  211. /* Do our initializations. */
  212. initialize_main (&argc, &argv);
  213. program_name = argv[0];
  214. output_style = OUTPUT_NORMAL;
  215. context = -1;
  216. prepend_default_options (getenv ("DIFF_OPTIONS"), &argc, &argv);
  217. /* Decode the options. */
  218. while ((c = getopt_long (argc, argv,
  219. "0123456789abBcC:dD:efF:hHiI:lL:nNopPqrsS:tTuU:vwW:x:X:y",
  220. longopts, 0)) != EOF)
  221. {
  222. switch (c)
  223. {
  224. /* All digits combine in decimal to specify the context-size. */
  225. case '1':
  226. case '2':
  227. case '3':
  228. case '4':
  229. case '5':
  230. case '6':
  231. case '7':
  232. case '8':
  233. case '9':
  234. case '0':
  235. if (context == -1)
  236. context = 0;
  237. /* If a context length has already been specified,
  238. more digits allowed only if they follow right after the others.
  239. Reject two separate runs of digits, or digits after -C. */
  240. else if (prev < '0' || prev > '9')
  241. fatal ("context length specified twice");
  242. context = context * 10 + c - '0';
  243. break;
  244. case 'a':
  245. /* Treat all files as text files; never treat as binary. */
  246. always_text_flag = 1;
  247. break;
  248. case 'b':
  249. /* Ignore changes in amount of white space. */
  250. ignore_space_change_flag = 1;
  251. ignore_some_changes = 1;
  252. ignore_some_line_changes = 1;
  253. break;
  254. case 'B':
  255. /* Ignore changes affecting only blank lines. */
  256. ignore_blank_lines_flag = 1;
  257. ignore_some_changes = 1;
  258. break;
  259. case 'C': /* +context[=lines] */
  260. case 'U': /* +unified[=lines] */
  261. if (optarg)
  262. {
  263. if (context >= 0)
  264. fatal ("context length specified twice");
  265. if (ck_atoi (optarg, &context))
  266. fatal ("invalid context length argument");
  267. }
  268. /* Falls through. */
  269. case 'c':
  270. /* Make context-style output. */
  271. specify_style (c == 'U' ? OUTPUT_UNIFIED : OUTPUT_CONTEXT);
  272. break;
  273. case 'd':
  274. /* Don't discard lines. This makes things slower (sometimes much
  275. slower) but will find a guaranteed minimal set of changes. */
  276. no_discards = 1;
  277. break;
  278. case 'D':
  279. /* Make merged #ifdef output. */
  280. specify_style (OUTPUT_IFDEF);
  281. {
  282. int i, err = 0;
  283. static char const C_ifdef_group_formats[] =
  284. "#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";
  285. char *b = xmalloc (sizeof (C_ifdef_group_formats)
  286. + 7 * strlen(optarg) - 14 /* 7*"%s" */
  287. - 8 /* 5*"%%" + 3*"%c" */);
  288. sprintf (b, C_ifdef_group_formats,
  289. optarg, optarg, 0,
  290. optarg, optarg, 0, 0,
  291. optarg, optarg, optarg);
  292. for (i = 0; i < 4; i++)
  293. {
  294. err |= specify_format (&group_format[i], b);
  295. b += strlen (b) + 1;
  296. }
  297. if (err)
  298. error ("conflicting #ifdef formats", 0, 0);
  299. }
  300. break;
  301. case 'e':
  302. /* Make output that is a valid `ed' script. */
  303. specify_style (OUTPUT_ED);
  304. break;
  305. case 'f':
  306. /* Make output that looks vaguely like an `ed' script
  307. but has changes in the order they appear in the file. */
  308. specify_style (OUTPUT_FORWARD_ED);
  309. break;
  310. case 'F':
  311. /* Show, for each set of changes, the previous line that
  312. matches the specified regexp. Currently affects only
  313. context-style output. */
  314. add_regexp (&function_regexp_list, optarg);
  315. break;
  316. case 'h':
  317. /* Split the files into chunks of around 1500 lines
  318. for faster processing. Usually does not change the result.
  319. This currently has no effect. */
  320. break;
  321. case 'H':
  322. /* Turn on heuristics that speed processing of large files
  323. with a small density of changes. */
  324. heuristic = 1;
  325. break;
  326. case 'i':
  327. /* Ignore changes in case. */
  328. ignore_case_flag = 1;
  329. ignore_some_changes = 1;
  330. ignore_some_line_changes = 1;
  331. break;
  332. case 'I':
  333. /* Ignore changes affecting only lines that match the
  334. specified regexp. */
  335. add_regexp (&ignore_regexp_list, optarg);
  336. ignore_some_changes = 1;
  337. break;
  338. case 'l':
  339. /* Pass the output through `pr' to paginate it. */
  340. paginate_flag = 1;
  341. #if !defined(SIGCHLD) && defined(SIGCLD)
  342. #define SIGCHLD SIGCLD
  343. #endif
  344. #ifdef SIGCHLD
  345. /* Pagination requires forking and waiting, and
  346. System V fork+wait does not work if SIGCHLD is ignored. */
  347. signal (SIGCHLD, SIG_DFL);
  348. #endif
  349. break;
  350. case 'L':
  351. /* Specify file labels for `-c' output headers. */
  352. if (!file_label[0])
  353. file_label[0] = optarg;
  354. else if (!file_label[1])
  355. file_label[1] = optarg;
  356. else
  357. fatal ("too many file label options");
  358. break;
  359. case 'n':
  360. /* Output RCS-style diffs, like `-f' except that each command
  361. specifies the number of lines affected. */
  362. specify_style (OUTPUT_RCS);
  363. break;
  364. case 'N':
  365. /* When comparing directories, if a file appears only in one
  366. directory, treat it as present but empty in the other. */
  367. entire_new_file_flag = 1;
  368. break;
  369. case 'o':
  370. /* Output in the old tradition style. */
  371. specify_style (OUTPUT_NORMAL);
  372. break;
  373. case 'p':
  374. /* Make context-style output and show name of last C function. */
  375. show_c_function = 1;
  376. add_regexp (&function_regexp_list, "^[_a-zA-Z$]");
  377. break;
  378. case 'P':
  379. /* When comparing directories, if a file appears only in
  380. the second directory of the two,
  381. treat it as present but empty in the other. */
  382. unidirectional_new_file_flag = 1;
  383. break;
  384. case 'q':
  385. no_details_flag = 1;
  386. break;
  387. case 'r':
  388. /* When comparing directories,
  389. recursively compare any subdirectories found. */
  390. recursive = 1;
  391. break;
  392. case 's':
  393. /* Print a message if the files are the same. */
  394. print_file_same_flag = 1;
  395. break;
  396. case 'S':
  397. /* When comparing directories, start with the specified
  398. file name. This is used for resuming an aborted comparison. */
  399. dir_start_file = optarg;
  400. break;
  401. case 't':
  402. /* Expand tabs to spaces in the output so that it preserves
  403. the alignment of the input files. */
  404. tab_expand_flag = 1;
  405. break;
  406. case 'T':
  407. /* Use a tab in the output, rather than a space, before the
  408. text of an input line, so as to keep the proper alignment
  409. in the input line without changing the characters in it. */
  410. tab_align_flag = 1;
  411. break;
  412. case 'u':
  413. /* Output the context diff in unidiff format. */
  414. specify_style (OUTPUT_UNIFIED);
  415. break;
  416. case 'v':
  417. printf ("diff - GNU diffutils version %s\n", version_string);
  418. exit (0);
  419. case 'w':
  420. /* Ignore horizontal white space when comparing lines. */
  421. ignore_all_space_flag = 1;
  422. ignore_some_changes = 1;
  423. ignore_some_line_changes = 1;
  424. break;
  425. case 'x':
  426. add_exclude (optarg);
  427. break;
  428. case 'X':
  429. if (add_exclude_file (optarg) != 0)
  430. pfatal_with_name (optarg);
  431. break;
  432. case 'y':
  433. /* Use side-by-side (sdiff-style) columnar output. */
  434. specify_style (OUTPUT_SDIFF);
  435. break;
  436. case 'W':
  437. /* Set the line width for OUTPUT_SDIFF. */
  438. if (ck_atoi (optarg, &width) || width <= 0)
  439. fatal ("column width must be a positive integer");
  440. break;
  441. case 129:
  442. sdiff_left_only = 1;
  443. break;
  444. case 130:
  445. sdiff_skip_common_lines = 1;
  446. break;
  447. case 131:
  448. /* sdiff-style columns output. */
  449. specify_style (OUTPUT_SDIFF);
  450. sdiff_help_sdiff = 1;
  451. break;
  452. case 132:
  453. case 133:
  454. case 134:
  455. specify_style (OUTPUT_IFDEF);
  456. if (specify_format (&line_format[c - 132], optarg) != 0)
  457. error ("conflicting line format", 0, 0);
  458. break;
  459. case 135:
  460. specify_style (OUTPUT_IFDEF);
  461. {
  462. int i, err = 0;
  463. for (i = 0; i < sizeof (line_format) / sizeof (*line_format); i++)
  464. err |= specify_format (&line_format[i], optarg);
  465. if (err)
  466. error ("conflicting line format", 0, 0);
  467. }
  468. break;
  469. case 136:
  470. case 137:
  471. case 138:
  472. case 139:
  473. specify_style (OUTPUT_IFDEF);
  474. if (specify_format (&group_format[c - 136], optarg) != 0)
  475. error ("conflicting group format", 0, 0);
  476. break;
  477. case 140:
  478. if (ck_atoi (optarg, &horizon_lines) || horizon_lines < 0)
  479. fatal ("horizon must be a nonnegative integer");
  480. break;
  481. case 141:
  482. usage ();
  483. check_stdout ();
  484. exit (0);
  485. case 142:
  486. /* Use binary I/O when reading and writing data.
  487. On Posix hosts, this has no effect. */
  488. #if HAVE_SETMODE
  489. binary_I_O = 1;
  490. setmode (STDOUT_FILENO, O_BINARY);
  491. #endif
  492. break;
  493. default:
  494. try_help (0);
  495. }
  496. prev = c;
  497. }
  498. if (argc - optind != 2)
  499. try_help (argc - optind < 2 ? "missing operand" : "extra operand");
  500. {
  501. /*
  502. * We maximize first the half line width, and then the gutter width,
  503. * according to the following constraints:
  504. * 1. Two half lines plus a gutter must fit in a line.
  505. * 2. If the half line width is nonzero:
  506. * a. The gutter width is at least GUTTER_WIDTH_MINIMUM.
  507. * b. If tabs are not expanded to spaces,
  508. * a half line plus a gutter is an integral number of tabs,
  509. * so that tabs in the right column line up.
  510. */
  511. int t = tab_expand_flag ? 1 : TAB_WIDTH;
  512. int off = (width + t + GUTTER_WIDTH_MINIMUM) / (2*t) * t;
  513. sdiff_half_width = max (0, min (off - GUTTER_WIDTH_MINIMUM, width - off)),
  514. sdiff_column2_offset = sdiff_half_width ? off : width;
  515. }
  516. if (show_c_function && output_style != OUTPUT_UNIFIED)
  517. specify_style (OUTPUT_CONTEXT);
  518. if (output_style != OUTPUT_CONTEXT && output_style != OUTPUT_UNIFIED)
  519. context = 0;
  520. else if (context == -1)
  521. /* Default amount of context for -c. */
  522. context = 3;
  523. if (output_style == OUTPUT_IFDEF)
  524. {
  525. /* Format arrays are char *, not char const *,
  526. because integer formats are temporarily modified.
  527. But it is safe to assign a constant like "%=" to a format array,
  528. since "%=" does not format any integers. */
  529. int i;
  530. for (i = 0; i < sizeof (line_format) / sizeof (*line_format); i++)
  531. if (!line_format[i])
  532. line_format[i] = "%l\n";
  533. if (!group_format[OLD])
  534. group_format[OLD]
  535. = group_format[UNCHANGED] ? group_format[UNCHANGED] : "%<";
  536. if (!group_format[NEW])
  537. group_format[NEW]
  538. = group_format[UNCHANGED] ? group_format[UNCHANGED] : "%>";
  539. if (!group_format[UNCHANGED])
  540. group_format[UNCHANGED] = "%=";
  541. if (!group_format[CHANGED])
  542. group_format[CHANGED] = concat (group_format[OLD],
  543. group_format[NEW], "");
  544. }
  545. no_diff_means_no_output =
  546. (output_style == OUTPUT_IFDEF ?
  547. (!*group_format[UNCHANGED]
  548. || (strcmp (group_format[UNCHANGED], "%=") == 0
  549. && !*line_format[UNCHANGED]))
  550. : output_style == OUTPUT_SDIFF ? sdiff_skip_common_lines : 1);
  551. switch_string = option_list (argv + 1, optind - 1);
  552. val = compare_files (0, argv[optind], 0, argv[optind + 1], 0);
  553. /* Print any messages that were saved up for last. */
  554. print_message_queue ();
  555. check_stdout ();
  556. exit (val);
  557. return val;
  558. }
  559. /* Add the compiled form of regexp PATTERN to REGLIST. */
  560. static void
  561. add_regexp (reglist, pattern)
  562. struct regexp_list **reglist;
  563. char const *pattern;
  564. {
  565. struct regexp_list *r;
  566. char const *m;
  567. r = (struct regexp_list *) xmalloc (sizeof (*r));
  568. bzero (r, sizeof (*r));
  569. r->buf.fastmap = xmalloc (256);
  570. m = re_compile_pattern (pattern, strlen (pattern), &r->buf);
  571. if (m != 0)
  572. error ("%s: %s", pattern, m);
  573. /* Add to the start of the list, since it's easier than the end. */
  574. r->next = *reglist;
  575. *reglist = r;
  576. }
  577. static void
  578. try_help (reason)
  579. char const *reason;
  580. {
  581. if (reason)
  582. error ("%s", reason, 0);
  583. error ("Try `%s --help' for more information.", program_name, 0);
  584. exit (2);
  585. }
  586. static void
  587. check_stdout ()
  588. {
  589. if (ferror (stdout) || fclose (stdout) != 0)
  590. fatal ("write error");
  591. }
  592. static char const * const option_help[] = {
  593. "-i --ignore-case Consider upper- and lower-case to be the same.",
  594. "-w --ignore-all-space Ignore all white space.",
  595. "-b --ignore-space-change Ignore changes in the amount of white space.",
  596. "-B --ignore-blank-lines Ignore changes whose lines are all blank.",
  597. "-I RE --ignore-matching-lines=RE Ignore changes whose lines all match RE.",
  598. #if HAVE_SETMODE
  599. "--binary Read and write data in binary mode.",
  600. #endif
  601. "-a --text Treat all files as text.\n",
  602. "-c -C NUM --context[=NUM] Output NUM (default 2) lines of copied context.",
  603. "-u -U NUM --unified[=NUM] Output NUM (default 2) lines of unified context.",
  604. " -NUM Use NUM context lines.",
  605. " -L LABEL --label LABEL Use LABEL instead of file name.",
  606. " -p --show-c-function Show which C function each change is in.",
  607. " -F RE --show-function-line=RE Show the most recent line matching RE.",
  608. "-q --brief Output only whether files differ.",
  609. "-e --ed Output an ed script.",
  610. "-n --rcs Output an RCS format diff.",
  611. "-y --side-by-side Output in two columns.",
  612. " -w NUM --width=NUM Output at most NUM (default 130) characters per line.",
  613. " --left-column Output only the left column of common lines.",
  614. " --suppress-common-lines Do not output common lines.",
  615. "-DNAME --ifdef=NAME Output merged file to show `#ifdef NAME' diffs.",
  616. "--GTYPE-group-format=GFMT Similar, but format GTYPE input groups with GFMT.",
  617. "--line-format=LFMT Similar, but format all input lines with LFMT.",
  618. "--LTYPE-line-format=LFMT Similar, but format LTYPE input lines with LFMT.",
  619. " LTYPE is `old', `new', or `unchanged'. GTYPE is LTYPE or `changed'.",
  620. " GFMT may contain:",
  621. " %< lines from FILE1",
  622. " %> lines from FILE2",
  623. " %= lines common to FILE1 and FILE2",
  624. " %[-][WIDTH][.[PREC]]{doxX}LETTER printf-style spec for LETTER",
  625. " LETTERs are as follows for new group, lower case for old group:",
  626. " F first line number",
  627. " L last line number",
  628. " N number of lines = L-F+1",
  629. " E F-1",
  630. " M L+1",
  631. " LFMT may contain:",
  632. " %L contents of line",
  633. " %l contents of line, excluding any trailing newline",
  634. " %[-][WIDTH][.[PREC]]{doxX}n printf-style spec for input line number",
  635. " Either GFMT or LFMT may contain:",
  636. " %% %",
  637. " %c'C' the single character C",
  638. " %c'\\OOO' the character with octal code OOO\n",
  639. "-l --paginate Pass the output through `pr' to paginate it.",
  640. "-t --expand-tabs Expand tabs to spaces in output.",
  641. "-T --initial-tab Make tabs line up by prepending a tab.\n",
  642. "-r --recursive Recursively compare any subdirectories found.",
  643. "-N --new-file Treat absent files as empty.",
  644. "-P --unidirectional-new-file Treat absent first files as empty.",
  645. "-s --report-identical-files Report when two files are the same.",
  646. "-x PAT --exclude=PAT Exclude files that match PAT.",
  647. "-X FILE --exclude-from=FILE Exclude files that match any pattern in FILE.",
  648. "-S FILE --starting-file=FILE Start with FILE when comparing directories.\n",
  649. "--horizon-lines=NUM Keep NUM lines of the common prefix and suffix.",
  650. "-d --minimal Try hard to find a smaller set of changes.",
  651. "-H --speed-large-files Assume large files and many scattered small changes.\n",
  652. "-v --version Output version info.",
  653. "--help Output this help.",
  654. 0
  655. };
  656. static void
  657. usage ()
  658. {
  659. char const * const *p;
  660. printf ("Usage: %s [OPTION]... FILE1 FILE2\n\n", program_name);
  661. for (p = option_help; *p; p++)
  662. printf (" %s\n", *p);
  663. printf ("\nIf FILE1 or FILE2 is `-', read standard input.\n");
  664. }
  665. static int
  666. specify_format (var, value)
  667. char **var;
  668. char *value;
  669. {
  670. int err = *var ? strcmp (*var, value) : 0;
  671. *var = value;
  672. return err;
  673. }
  674. static void
  675. specify_style (style)
  676. enum output_style style;
  677. {
  678. if (output_style != OUTPUT_NORMAL
  679. && output_style != style)
  680. error ("conflicting specifications of output style", 0, 0);
  681. output_style = style;
  682. }
  683. static char const *
  684. filetype (st)
  685. struct stat const *st;
  686. {
  687. /* See Posix.2 section 4.17.6.1.1 and Table 5-1 for these formats.
  688. To keep diagnostics grammatical, the returned string must start
  689. with a consonant. */
  690. if (S_ISREG (st->st_mode))
  691. {
  692. if (st->st_size == 0)
  693. return "regular empty file";
  694. /* Posix.2 section 5.14.2 seems to suggest that we must read the file
  695. and guess whether it's C, Fortran, etc., but this is somewhat useless
  696. and doesn't reflect historical practice. We're allowed to guess
  697. wrong, so we don't bother to read the file. */
  698. return "regular file";
  699. }
  700. if (S_ISDIR (st->st_mode)) return "directory";
  701. /* other Posix.1 file types */
  702. #ifdef S_ISBLK
  703. if (S_ISBLK (st->st_mode)) return "block special file";
  704. #endif
  705. #ifdef S_ISCHR
  706. if (S_ISCHR (st->st_mode)) return "character special file";
  707. #endif
  708. #ifdef S_ISFIFO
  709. if (S_ISFIFO (st->st_mode)) return "fifo";
  710. #endif
  711. /* other Posix.1b file types */
  712. #ifdef S_TYPEISMQ
  713. if (S_TYPEISMQ (st)) return "message queue";
  714. #endif
  715. #ifdef S_TYPEISSEM
  716. if (S_TYPEISSEM (st)) return "semaphore";
  717. #endif
  718. #ifdef S_TYPEISSHM
  719. if (S_TYPEISSHM (st)) return "shared memory object";
  720. #endif
  721. /* other popular file types */
  722. /* S_ISLNK is impossible with `fstat' and `stat'. */
  723. #ifdef S_ISSOCK
  724. if (S_ISSOCK (st->st_mode)) return "socket";
  725. #endif
  726. return "weird file";
  727. }
  728. /* Compare two files (or dirs) with specified names
  729. DIR0/NAME0 and DIR1/NAME1, at level DEPTH in directory recursion.
  730. (if DIR0 is 0, then the name is just NAME0, etc.)
  731. This is self-contained; it opens the files and closes them.
  732. Value is 0 if files are the same, 1 if different,
  733. 2 if there is a problem opening them. */
  734. static int
  735. compare_files (dir0, name0, dir1, name1, depth)
  736. char const *dir0, *dir1;
  737. char const *name0, *name1;
  738. int depth;
  739. {
  740. struct file_data inf[2];
  741. register int i;
  742. int val;
  743. int same_files;
  744. int failed = 0;
  745. char *free0 = 0, *free1 = 0;
  746. /* If this is directory comparison, perhaps we have a file
  747. that exists only in one of the directories.
  748. If so, just print a message to that effect. */
  749. if (! ((name0 != 0 && name1 != 0)
  750. || (unidirectional_new_file_flag && name1 != 0)
  751. || entire_new_file_flag))
  752. {
  753. char const *name = name0 == 0 ? name1 : name0;
  754. char const *dir = name0 == 0 ? dir1 : dir0;
  755. message ("Only in %s: %s\n", dir, name);
  756. /* Return 1 so that diff_dirs will return 1 ("some files differ"). */
  757. return 1;
  758. }
  759. bzero (inf, sizeof (inf));
  760. /* Mark any nonexistent file with -1 in the desc field. */
  761. /* Mark unopened files (e.g. directories) with -2. */
  762. inf[0].desc = name0 == 0 ? -1 : -2;
  763. inf[1].desc = name1 == 0 ? -1 : -2;
  764. /* Now record the full name of each file, including nonexistent ones. */
  765. if (name0 == 0)
  766. name0 = name1;
  767. if (name1 == 0)
  768. name1 = name0;
  769. inf[0].name = dir0 == 0 ? name0 : (free0 = dir_file_pathname (dir0, name0));
  770. inf[1].name = dir1 == 0 ? name1 : (free1 = dir_file_pathname (dir1, name1));
  771. /* Stat the files. Record whether they are directories. */
  772. for (i = 0; i <= 1; i++)
  773. {
  774. if (inf[i].desc != -1)
  775. {
  776. int stat_result;
  777. if (i && filename_cmp (inf[i].name, inf[0].name) == 0)
  778. {
  779. inf[i].stat = inf[0].stat;
  780. stat_result = 0;
  781. }
  782. else if (strcmp (inf[i].name, "-") == 0)
  783. {
  784. inf[i].desc = STDIN_FILENO;
  785. stat_result = fstat (STDIN_FILENO, &inf[i].stat);
  786. if (stat_result == 0 && S_ISREG (inf[i].stat.st_mode))
  787. {
  788. off_t pos = lseek (STDIN_FILENO, (off_t) 0, SEEK_CUR);
  789. if (pos == -1)
  790. stat_result = -1;
  791. else
  792. {
  793. if (pos <= inf[i].stat.st_size)
  794. inf[i].stat.st_size -= pos;
  795. else
  796. inf[i].stat.st_size = 0;
  797. /* Posix.2 4.17.6.1.4 requires current time for stdin. */
  798. time (&inf[i].stat.st_mtime);
  799. }
  800. }
  801. }
  802. else
  803. stat_result = stat (inf[i].name, &inf[i].stat);
  804. if (stat_result != 0)
  805. {
  806. perror_with_name (inf[i].name);
  807. failed = 1;
  808. }
  809. else
  810. {
  811. inf[i].dir_p = S_ISDIR (inf[i].stat.st_mode) && inf[i].desc != 0;
  812. if (inf[1 - i].desc == -1)
  813. {
  814. inf[1 - i].dir_p = inf[i].dir_p;
  815. inf[1 - i].stat.st_mode = inf[i].stat.st_mode;
  816. }
  817. }
  818. }
  819. }
  820. if (! failed && depth == 0 && inf[0].dir_p != inf[1].dir_p)
  821. {
  822. /* If one is a directory, and it was specified in the command line,
  823. use the file in that dir with the other file's basename. */
  824. int fnm_arg = inf[0].dir_p;
  825. int dir_arg = 1 - fnm_arg;
  826. char const *fnm = inf[fnm_arg].name;
  827. char const *dir = inf[dir_arg].name;
  828. char const *p = filename_lastdirchar (fnm);
  829. char const *filename = inf[dir_arg].name
  830. = dir_file_pathname (dir, p ? p + 1 : fnm);
  831. if (strcmp (fnm, "-") == 0)
  832. fatal ("can't compare - to a directory");
  833. if (stat (filename, &inf[dir_arg].stat) != 0)
  834. {
  835. perror_with_name (filename);
  836. failed = 1;
  837. }
  838. else
  839. inf[dir_arg].dir_p = S_ISDIR (inf[dir_arg].stat.st_mode);
  840. }
  841. if (failed)
  842. {
  843. /* If either file should exist but does not, return 2. */
  844. val = 2;
  845. }
  846. else if ((same_files = inf[0].desc != -1 && inf[1].desc != -1
  847. && 0 < same_file (&inf[0].stat, &inf[1].stat))
  848. && no_diff_means_no_output)
  849. {
  850. /* The two named files are actually the same physical file.
  851. We know they are identical without actually reading them. */
  852. val = 0;
  853. }
  854. else if (inf[0].dir_p & inf[1].dir_p)
  855. {
  856. if (output_style == OUTPUT_IFDEF)
  857. fatal ("-D option not supported with directories");
  858. /* If both are directories, compare the files in them. */
  859. if (depth > 0 && !recursive)
  860. {
  861. /* But don't compare dir contents one level down
  862. unless -r was specified. */
  863. message ("Common subdirectories: %s and %s\n",
  864. inf[0].name, inf[1].name);
  865. val = 0;
  866. }
  867. else
  868. {
  869. val = diff_dirs (inf, compare_files, depth);
  870. }
  871. }
  872. else if ((inf[0].dir_p | inf[1].dir_p)
  873. || (depth > 0
  874. && (! S_ISREG (inf[0].stat.st_mode)
  875. || ! S_ISREG (inf[1].stat.st_mode))))
  876. {
  877. /* Perhaps we have a subdirectory that exists only in one directory.
  878. If so, just print a message to that effect. */
  879. if (inf[0].desc == -1 || inf[1].desc == -1)
  880. {
  881. if ((inf[0].dir_p | inf[1].dir_p)
  882. && recursive
  883. && (entire_new_file_flag
  884. || (unidirectional_new_file_flag && inf[0].desc == -1)))
  885. val = diff_dirs (inf, compare_files, depth);
  886. else
  887. {
  888. char const *dir = (inf[0].desc == -1) ? dir1 : dir0;
  889. /* See Posix.2 section 4.17.6.1.1 for this format. */
  890. message ("Only in %s: %s\n", dir, name0);
  891. val = 1;
  892. }
  893. }
  894. else
  895. {
  896. /* We have two files that are not to be compared. */
  897. /* See Posix.2 section 4.17.6.1.1 for this format. */
  898. message5 ("File %s is a %s while file %s is a %s\n",
  899. inf[0].name, filetype (&inf[0].stat),
  900. inf[1].name, filetype (&inf[1].stat));
  901. /* This is a difference. */
  902. val = 1;
  903. }
  904. }
  905. else if ((no_details_flag & ~ignore_some_changes)
  906. && inf[0].stat.st_size != inf[1].stat.st_size
  907. && (inf[0].desc == -1 || S_ISREG (inf[0].stat.st_mode))
  908. && (inf[1].desc == -1 || S_ISREG (inf[1].stat.st_mode)))
  909. {
  910. message ("Files %s and %s differ\n", inf[0].name, inf[1].name);
  911. val = 1;
  912. }
  913. else
  914. {
  915. /* Both exist and neither is a directory. */
  916. /* Open the files and record their descriptors. */
  917. if (inf[0].desc == -2)
  918. if ((inf[0].desc = open (inf[0].name, O_RDONLY, 0)) < 0)
  919. {
  920. perror_with_name (inf[0].name);
  921. failed = 1;
  922. }
  923. if (inf[1].desc == -2)
  924. if (same_files)
  925. inf[1].desc = inf[0].desc;
  926. else if ((inf[1].desc = open (inf[1].name, O_RDONLY, 0)) < 0)
  927. {
  928. perror_with_name (inf[1].name);
  929. failed = 1;
  930. }
  931. #if HAVE_SETMODE
  932. if (binary_I_O)
  933. for (i = 0; i <= 1; i++)
  934. if (0 <= inf[i].desc)
  935. setmode (inf[i].desc, O_BINARY);
  936. #endif
  937. /* Compare the files, if no error was found. */
  938. val = failed ? 2 : diff_2_files (inf, depth);
  939. /* Close the file descriptors. */
  940. if (inf[0].desc >= 0 && close (inf[0].desc) != 0)
  941. {
  942. perror_with_name (inf[0].name);
  943. val = 2;
  944. }
  945. if (inf[1].desc >= 0 && inf[0].desc != inf[1].desc
  946. && close (inf[1].desc) != 0)
  947. {
  948. perror_with_name (inf[1].name);
  949. val = 2;
  950. }
  951. }
  952. /* Now the comparison has been done, if no error prevented it,
  953. and VAL is the value this function will return. */
  954. if (val == 0 && !inf[0].dir_p)
  955. {
  956. if (print_file_same_flag)
  957. message ("Files %s and %s are identical\n",
  958. inf[0].name, inf[1].name);
  959. }
  960. else
  961. fflush (stdout);
  962. if (free0)
  963. free (free0);
  964. if (free1)
  965. free (free1);
  966. return val;
  967. }