1 /* GNU sdiff - side-by-side merge of file differences
3 Copyright (C) 1992-1996, 1998, 2001-2002, 2004, 2006-2007, 2009-2013,
4 2015-2021 Free Software Foundation, Inc.
6 This file is part of GNU DIFF.
8 This program is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
25 #include <unlocked-io.h>
32 #include <file-type.h>
35 #include <system-quote.h>
36 #include <version-etc.h>
40 /* The official name of this program (e.g., no 'g' prefix). */
41 #define PROGRAM_NAME "sdiff"
44 proper_name ("Thomas Lord")
46 /* Size of chunks read from files which must be parsed into lines. */
47 #define SDIFF_BUFSIZE ((size_t) 65536)
49 static char const *editor_program = DEFAULT_EDITOR_PROGRAM;
50 static char const **diffargv;
52 static char * volatile tmpname;
56 static pid_t volatile diffpid;
61 static void catchsig (int);
62 static bool edit (struct line_filter *, char const *, lin, lin, struct line_filter *, char const *, lin, lin, FILE *);
63 static bool interact (struct line_filter *, struct line_filter *, char const *, struct line_filter *, char const *, FILE *);
64 static void checksigs (void);
65 static void diffarg (char const *);
66 static void fatal (char const *) __attribute__((noreturn));
67 static void perror_fatal (char const *) __attribute__((noreturn));
68 static void trapsigs (void);
69 static void untrapsig (int);
71 static int const sigs[] = {
94 NUM_SIGS = sizeof sigs / sizeof *sigs,
95 handler_index_of_SIGINT = NUM_SIGS - 1
99 /* Prefer 'sigaction' if available, since 'signal' can lose signals. */
100 static struct sigaction initial_action[NUM_SIGS];
101 # define initial_handler(i) (initial_action[i].sa_handler)
102 static void signal_handler (int, void (*) (int));
104 static void (*initial_action[NUM_SIGS]) ();
105 # define initial_handler(i) (initial_action[i])
106 # define signal_handler(sig, handler) signal (sig, handler)
109 static bool diraccess (char const *);
110 static int temporary_file (void);
114 /* Name of output file if -o specified. */
115 static char const *output;
117 /* Do not print common lines. */
118 static bool suppress_common_lines;
120 /* Value for the long option that does not have single-letter equivalents. */
123 DIFF_PROGRAM_OPTION = CHAR_MAX + 1,
125 STRIP_TRAILING_CR_OPTION,
129 static struct option const longopts[] =
131 {"diff-program", 1, 0, DIFF_PROGRAM_OPTION},
132 {"expand-tabs", 0, 0, 't'},
133 {"help", 0, 0, HELP_OPTION},
134 {"ignore-all-space", 0, 0, 'W'}, /* swap W and w for historical reasons */
135 {"ignore-blank-lines", 0, 0, 'B'},
136 {"ignore-case", 0, 0, 'i'},
137 {"ignore-matching-lines", 1, 0, 'I'},
138 {"ignore-space-change", 0, 0, 'b'},
139 {"ignore-tab-expansion", 0, 0, 'E'},
140 {"ignore-trailing-space", 0, 0, 'Z'},
141 {"left-column", 0, 0, 'l'},
142 {"minimal", 0, 0, 'd'},
143 {"output", 1, 0, 'o'},
144 {"speed-large-files", 0, 0, 'H'},
145 {"strip-trailing-cr", 0, 0, STRIP_TRAILING_CR_OPTION},
146 {"suppress-common-lines", 0, 0, 's'},
147 {"tabsize", 1, 0, TABSIZE_OPTION},
149 {"version", 0, 0, 'v'},
150 {"width", 1, 0, 'w'},
154 static void try_help (char const *, char const *) __attribute__((noreturn));
156 try_help (char const *reason_msgid, char const *operand)
159 error (0, 0, _(reason_msgid), operand);
160 die (EXIT_TROUBLE, 0, _("Try '%s --help' for more information."),
168 fatal ("write failed");
169 else if (fclose (stdout) != 0)
170 perror_fatal (_("standard output"));
173 static char const * const option_help_msgid[] = {
174 N_("-o, --output=FILE operate interactively, sending output to FILE"),
176 N_("-i, --ignore-case consider upper- and lower-case to be the same"),
177 N_("-E, --ignore-tab-expansion ignore changes due to tab expansion"),
178 N_("-Z, --ignore-trailing-space ignore white space at line end"),
179 N_("-b, --ignore-space-change ignore changes in the amount of white space"),
180 N_("-W, --ignore-all-space ignore all white space"),
181 N_("-B, --ignore-blank-lines ignore changes whose lines are all blank"),
182 N_("-I, --ignore-matching-lines=RE ignore changes all whose lines match RE"),
183 N_(" --strip-trailing-cr strip trailing carriage return on input"),
184 N_("-a, --text treat all files as text"),
186 N_("-w, --width=NUM output at most NUM (default 130) print columns"),
187 N_("-l, --left-column output only the left column of common lines"),
188 N_("-s, --suppress-common-lines do not output common lines"),
190 N_("-t, --expand-tabs expand tabs to spaces in output"),
191 N_(" --tabsize=NUM tab stops at every NUM (default 8) print columns"),
193 N_("-d, --minimal try hard to find a smaller set of changes"),
194 N_("-H, --speed-large-files assume large files, many scattered small changes"),
195 N_(" --diff-program=PROGRAM use PROGRAM to compare files"),
197 N_(" --help display this help and exit"),
198 N_("-v, --version output version information and exit"),
205 char const * const *p;
207 printf (_("Usage: %s [OPTION]... FILE1 FILE2\n"), program_name);
209 _("Side-by-side merge of differences between FILE1 and FILE2."));
212 Mandatory arguments to long options are mandatory for short options too.\n\
214 for (p = option_help_msgid; *p; p++)
216 printf (" %s\n", _(*p));
219 printf ("\n%s\n%s\n",
220 _("If a FILE is '-', read standard input."),
221 _("Exit status is 0 if inputs are the same, 1 if different, 2 if trouble."));
222 emit_bug_reporting_address ();
225 /* Clean up after a signal or other failure. This function is
226 async-signal-safe. */
228 cleanup (int signo __attribute__((unused)))
230 #if HAVE_WORKING_FORK
232 kill (diffpid, SIGPIPE);
238 static void exiterr (void) __attribute__((noreturn));
249 fatal (char const *msgid)
251 error (0, 0, "%s", _(msgid));
256 perror_fatal (char const *msg)
260 error (0, e, "%s", msg);
265 check_child_status (int werrno, int wstatus, int max_ok_status,
266 char const *subsidiary_program)
268 int status = (! werrno && WIFEXITED (wstatus)
269 ? WEXITSTATUS (wstatus)
272 if (max_ok_status < status)
276 ? "subsidiary program '%s' could not be invoked"
278 ? "subsidiary program '%s' not found"
280 ? "subsidiary program '%s' failed"
281 : "subsidiary program '%s' failed (exit status %d)"),
282 subsidiary_program, status);
288 ck_fopen (char const *fname, char const *type)
290 FILE *r = fopen (fname, type);
292 perror_fatal (fname);
300 perror_fatal ("fclose");
304 ck_fread (char *buf, size_t size, FILE *f)
306 size_t r = fread (buf, sizeof (char), size, f);
307 if (r == 0 && ferror (f))
308 perror_fatal (_("read failed"));
313 ck_fwrite (char const *buf, size_t size, FILE *f)
315 if (fwrite (buf, sizeof (char), size, f) != size)
316 perror_fatal (_("write failed"));
323 perror_fatal (_("write failed"));
327 expand_name (char *name, bool is_dir, char const *other_name)
329 if (STREQ (name, "-"))
330 fatal ("cannot interactively merge standard input");
335 /* Yield NAME/BASE, where BASE is OTHER_NAME's basename. */
336 char const *base = last_component (other_name);
337 size_t namelen = strlen (name), baselen = base_len (base);
338 bool insert_slash = *last_component (name) && name[namelen - 1] != '/';
339 char *r = xmalloc (namelen + insert_slash + baselen + 1);
340 memcpy (r, name, namelen);
342 memcpy (r + namelen + insert_slash, base, baselen);
343 r[namelen + insert_slash + baselen] = '\0';
356 lf_init (struct line_filter *lf, FILE *infile)
359 lf->bufpos = lf->buffer = lf->buflim = xmalloc (SDIFF_BUFSIZE + 1);
360 lf->buflim[0] = '\n';
363 /* Fill an exhausted line_filter buffer from its INFILE */
365 lf_refill (struct line_filter *lf)
367 size_t s = ck_fread (lf->buffer, SDIFF_BUFSIZE, lf->infile);
368 lf->bufpos = lf->buffer;
369 lf->buflim = lf->buffer + s;
370 lf->buflim[0] = '\n';
375 /* Advance LINES on LF's infile, copying lines to OUTFILE */
377 lf_copy (struct line_filter *lf, lin lines, FILE *outfile)
379 char *start = lf->bufpos;
383 lf->bufpos = rawmemchr (lf->bufpos, '\n');
384 if (lf->bufpos == lf->buflim)
386 ck_fwrite (start, lf->buflim - start, outfile);
387 if (! lf_refill (lf))
398 ck_fwrite (start, lf->bufpos - start, outfile);
401 /* Advance LINES on LF's infile without doing output */
403 lf_skip (struct line_filter *lf, lin lines)
407 lf->bufpos = rawmemchr (lf->bufpos, '\n');
408 if (lf->bufpos == lf->buflim)
410 if (! lf_refill (lf))
421 /* Snarf a line into a buffer. Return EOF if EOF, 0 if error, 1 if OK. */
423 lf_snarf (struct line_filter *lf, char *buffer, size_t bufsize)
427 char *start = lf->bufpos;
428 char *next = rawmemchr (start, '\n');
429 size_t s = next - start;
432 memcpy (buffer, start, s);
433 if (next < lf->buflim)
436 lf->bufpos = next + 1;
439 if (! lf_refill (lf))
447 main (int argc, char *argv[])
452 exit_failure = EXIT_TROUBLE;
453 initialize_main (&argc, &argv);
454 set_program_name (argv[0]);
455 setlocale (LC_ALL, "");
456 bindtextdomain (PACKAGE, LOCALEDIR);
457 textdomain (PACKAGE);
458 c_stack_action (cleanup);
461 prog = getenv ("EDITOR");
463 editor_program = prog;
465 diffarg (DEFAULT_DIFF_PROGRAM);
467 /* parse command line args */
468 while ((opt = getopt_long (argc, argv, "abBdEHiI:lo:stvw:WZ", longopts, 0))
507 diffarg ("--left-column");
515 suppress_common_lines = true;
523 version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version,
524 AUTHORS, (char *) NULL);
541 case DIFF_PROGRAM_OPTION:
542 diffargv[0] = optarg;
550 case STRIP_TRAILING_CR_OPTION:
551 diffarg ("--strip-trailing-cr");
555 diffarg ("--tabsize");
564 if (argc - optind != 2)
566 if (argc - optind < 2)
567 try_help ("missing operand after '%s'", argv[argc - 1]);
569 try_help ("extra operand '%s'", argv[optind + 2]);
574 /* easy case: diff does everything for us */
575 if (suppress_common_lines)
576 diffarg ("--suppress-common-lines");
579 diffarg (argv[optind]);
580 diffarg (argv[optind + 1]);
582 execvp (diffargv[0], (char **) diffargv);
583 perror_fatal (diffargv[0]);
587 char const *lname, *rname;
588 FILE *left, *right, *out, *diffout;
590 struct line_filter lfilt;
591 struct line_filter rfilt;
592 struct line_filter diff_filt;
593 bool leftdir = diraccess (argv[optind]);
594 bool rightdir = diraccess (argv[optind + 1]);
596 if (leftdir & rightdir)
597 fatal ("both files to be compared are directories");
599 lname = expand_name (argv[optind], leftdir, argv[optind + 1]);
600 left = ck_fopen (lname, "r");
601 rname = expand_name (argv[optind + 1], rightdir, argv[optind]);
602 right = ck_fopen (rname, "r");
603 out = ck_fopen (output, "w");
605 diffarg ("--sdiff-merge-assist");
607 diffarg (argv[optind]);
608 diffarg (argv[optind + 1]);
613 #if ! HAVE_WORKING_FORK
615 char *command = system_quote_argv (SCI_SYSTEM, (char **) diffargv);
617 diffout = popen (command, "r");
619 perror_fatal (command);
626 if (pipe (diff_fds) != 0)
627 perror_fatal ("pipe");
631 perror_fatal ("fork");
634 /* Alter the child's SIGINT and SIGPIPE handlers;
635 this may munge the parent.
636 The child ignores SIGINT in case the user interrupts the editor.
637 The child does not ignore SIGPIPE, even if the parent does. */
638 if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
639 signal_handler (SIGINT, SIG_IGN);
640 signal_handler (SIGPIPE, SIG_DFL);
642 if (diff_fds[1] != STDOUT_FILENO)
644 dup2 (diff_fds[1], STDOUT_FILENO);
648 execvp (diffargv[0], (char **) diffargv);
649 _exit (errno == ENOENT ? 127 : 126);
653 diffout = fdopen (diff_fds[0], "r");
655 perror_fatal ("fdopen");
659 lf_init (&diff_filt, diffout);
660 lf_init (&lfilt, left);
661 lf_init (&rfilt, right);
663 interact_ok = interact (&diff_filt, &lfilt, lname, &rfilt, rname, out);
673 #if ! HAVE_WORKING_FORK
674 wstatus = pclose (diffout);
679 while (waitpid (diffpid, &wstatus, 0) < 0)
683 perror_fatal ("waitpid");
696 check_child_status (werrno, wstatus, EXIT_FAILURE, diffargv[0]);
699 exit (WEXITSTATUS (wstatus));
702 return EXIT_SUCCESS; /* Fool '-Wall'. */
706 diffarg (char const *a)
708 static size_t diffargs, diffarglim;
710 if (diffargs == diffarglim)
714 else if (PTRDIFF_MAX / (2 * sizeof *diffargv) <= diffarglim)
718 diffargv = xrealloc (diffargv, diffarglim * sizeof *diffargv);
720 diffargv[diffargs++] = a;
723 /* Signal handling */
725 static bool volatile ignore_SIGINT;
726 static int volatile signal_received;
727 static bool sigs_trapped;
735 if (! (s == SIGINT && ignore_SIGINT))
740 static struct sigaction catchaction;
743 signal_handler (int sig, void (*handler) (int))
745 catchaction.sa_handler = handler;
746 sigaction (sig, &catchaction, 0);
756 catchaction.sa_flags = SA_RESTART;
757 sigemptyset (&catchaction.sa_mask);
758 for (i = 0; i < NUM_SIGS; i++)
759 sigaddset (&catchaction.sa_mask, sigs[i]);
762 for (i = 0; i < NUM_SIGS; i++)
765 sigaction (sigs[i], 0, &initial_action[i]);
767 initial_action[i] = signal (sigs[i], SIG_IGN);
769 if (initial_handler (i) != SIG_IGN)
770 signal_handler (sigs[i], catchsig);
774 /* System V fork+wait does not work if SIGCHLD is ignored. */
775 signal (SIGCHLD, SIG_DFL);
781 /* Untrap signal S, or all trapped signals if S is zero. */
788 for (i = 0; i < NUM_SIGS; i++)
789 if ((! s || sigs[i] == s) && initial_handler (i) != SIG_IGN)
792 sigaction (sigs[i], &initial_action[i], 0);
794 signal (sigs[i], initial_action[i]);
799 /* Exit if a signal has been received. */
803 int s = signal_received;
808 /* Yield an exit status indicating that a signal was received. */
812 /* That didn't work, so exit with error status. */
820 fprintf (stderr, "%s", _("\
821 ed:\tEdit then use both versions, each decorated with a header.\n\
822 eb:\tEdit then use both versions.\n\
823 el or e1:\tEdit then use the left version.\n\
824 er or e2:\tEdit then use the right version.\n\
825 e:\tDiscard both versions then edit a new one.\n\
826 l or 1:\tUse the left version.\n\
827 r or 2:\tUse the right version.\n\
828 s:\tSilently include common lines.\n\
829 v:\tVerbosely include common lines.\n\
841 if (! isspace (c) || c == '\n')
846 perror_fatal (_("read failed"));
854 while ((c = getchar ()) != '\n' && c != EOF)
857 perror_fatal (_("read failed"));
861 /* interpret an edit command */
863 edit (struct line_filter *left, char const *lname, lin lline, lin llen,
864 struct line_filter *right, char const *rname, lin rline, lin rlen,
869 int cmd0 IF_LINT (= 0);
870 int cmd1 IF_LINT (= 0);
875 if (putchar ('%') != '%')
876 perror_fatal (_("write failed"));
879 cmd0 = skip_white ();
882 case '1': case '2': case 'l': case 'r':
883 case 's': case 'v': case 'q':
884 if (skip_white () != '\n')
894 cmd1 = skip_white ();
897 case '1': case '2': case 'b': case 'd': case 'l': case 'r':
898 if (skip_white () != '\n')
936 lf_copy (left, llen, outfile);
937 lf_skip (right, rlen);
940 lf_copy (right, rlen, outfile);
941 lf_skip (left, llen);
944 suppress_common_lines = true;
947 suppress_common_lines = false;
956 tmp = fopen (tmpname, "w");
959 if ((fd = temporary_file ()) < 0)
960 perror_fatal ("mkstemp");
961 tmp = fdopen (fd, "w");
965 perror_fatal (tmpname);
973 printint l2 = lline + llen - 1;
975 fprintf (tmp, "--- %s %"pI"d\n", lname, l1);
977 fprintf (tmp, "--- %s %"pI"d,%"pI"d\n", lname, l1, l2);
980 case '1': case 'b': case 'l':
981 lf_copy (left, llen, tmp);
985 lf_skip (left, llen);
995 printint l2 = rline + rlen - 1;
997 fprintf (tmp, "+++ %s %"pI"d\n", rname, l1);
999 fprintf (tmp, "+++ %s %"pI"d,%"pI"d\n", rname, l1, l2);
1002 case '2': case 'b': case 'r':
1003 lf_copy (right, rlen, tmp);
1007 lf_skip (right, rlen);
1016 char const *argv[3];
1018 ignore_SIGINT = true;
1020 argv[0] = editor_program;
1025 #if ! HAVE_WORKING_FORK
1026 char *command = system_quote_argv (SCI_SYSTEM, (char **) argv);
1027 wstatus = system (command);
1037 execvp (editor_program, (char **) argv);
1038 _exit (errno == ENOENT ? 127 : 126);
1042 perror_fatal ("fork");
1044 while (waitpid (pid, &wstatus, 0) < 0)
1048 perror_fatal ("waitpid");
1052 ignore_SIGINT = false;
1053 check_child_status (werrno, wstatus, EXIT_SUCCESS,
1058 char buf[SDIFF_BUFSIZE];
1060 tmp = ck_fopen (tmpname, "r");
1061 while ((size = ck_fread (buf, SDIFF_BUFSIZE, tmp)) != 0)
1064 ck_fwrite (buf, size, outfile);
1077 /* Alternately reveal bursts of diff output and handle user commands. */
1079 interact (struct line_filter *diff,
1080 struct line_filter *left, char const *lname,
1081 struct line_filter *right, char const *rname,
1084 lin lline = 1, rline = 1;
1088 char diff_help[256];
1089 int snarfed = lf_snarf (diff, diff_help, sizeof diff_help);
1092 return snarfed != 0;
1096 if (diff_help[0] == ' ')
1097 puts (diff_help + 1);
1102 lin llen, rlen, lenmax;
1104 val = strtoimax (diff_help + 1, &numend, 10);
1105 if (! (0 <= val && val <= LIN_MAX) || errno || *numend != ',')
1108 val = strtoimax (numend + 1, &numend, 10);
1109 if (! (0 <= val && val <= LIN_MAX) || errno || *numend)
1113 lenmax = MAX (llen, rlen);
1115 switch (diff_help[0])
1118 if (suppress_common_lines)
1119 lf_skip (diff, lenmax);
1121 lf_copy (diff, lenmax, stdout);
1123 lf_copy (left, llen, outfile);
1124 lf_skip (right, rlen);
1128 lf_copy (diff, lenmax, stdout);
1129 if (! edit (left, lname, lline, llen,
1130 right, rname, rline, rlen,
1145 /* Return true if DIR is an existing directory. */
1147 diraccess (char const *dir)
1150 return stat (dir, &buf) == 0 && S_ISDIR (buf.st_mode);
1154 # define P_tmpdir "/tmp"
1157 # define TMPDIR_ENV "TMPDIR"
1160 /* Open a temporary file and return its file descriptor. Put into
1161 tmpname the address of a newly allocated buffer that holds the
1162 file's name. Use the prefix "sdiff". */
1164 temporary_file (void)
1166 char const *tmpdir = getenv (TMPDIR_ENV);
1167 char const *dir = tmpdir ? tmpdir : P_tmpdir;
1168 char *buf = xmalloc (strlen (dir) + 1 + 5 + 6 + 1);
1170 sprintf (buf, "%s/sdiffXXXXXX", dir);