1 /* sdiff - side-by-side merge of file differences
3 Copyright (C) 1992-1996, 1998, 2001-2002, 2004, 2006-2007, 2009-2010 Free
4 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>
31 #include <file-type.h>
35 #include <version-etc.h>
38 /* The official name of this program (e.g., no `g' prefix). */
39 #define PROGRAM_NAME "sdiff"
42 proper_name ("Thomas Lord")
44 /* Size of chunks read from files which must be parsed into lines. */
45 #define SDIFF_BUFSIZE ((size_t) 65536)
47 static char const *editor_program = DEFAULT_EDITOR_PROGRAM;
48 static char const **diffargv;
50 static char * volatile tmpname;
53 #if HAVE_WORKING_FORK || HAVE_WORKING_VFORK
54 static pid_t volatile diffpid;
59 static void catchsig (int);
60 static bool edit (struct line_filter *, char const *, lin, lin, struct line_filter *, char const *, lin, lin, FILE *);
61 static bool interact (struct line_filter *, struct line_filter *, char const *, struct line_filter *, char const *, FILE *);
62 static void checksigs (void);
63 static void diffarg (char const *);
64 static void fatal (char const *) __attribute__((noreturn));
65 static void perror_fatal (char const *) __attribute__((noreturn));
66 static void trapsigs (void);
67 static void untrapsig (int);
69 #define NUM_SIGS (sizeof sigs / sizeof *sigs)
70 static int const sigs[] = {
88 # define handler_index_of_SIGPIPE (NUM_SIGS - 2)
91 #define handler_index_of_SIGINT (NUM_SIGS - 1)
95 /* Prefer `sigaction' if available, since `signal' can lose signals. */
96 static struct sigaction initial_action[NUM_SIGS];
97 # define initial_handler(i) (initial_action[i].sa_handler)
98 static void signal_handler (int, void (*) (int));
100 static void (*initial_action[NUM_SIGS]) ();
101 # define initial_handler(i) (initial_action[i])
102 # define signal_handler(sig, handler) signal (sig, handler)
105 #if ! HAVE_SIGPROCMASK
106 # define sigset_t int
107 # define sigemptyset(s) (*(s) = 0)
109 # define sigmask(sig) (1 << ((sig) - 1))
111 # define sigaddset(s, sig) (*(s) |= sigmask (sig))
116 # define SIG_SETMASK (! SIG_BLOCK)
119 # define sigblock(mask) (mask)
120 # define sigsetmask(mask) (mask)
122 # define sigprocmask(how, n, o) \
123 ((how) == SIG_BLOCK \
124 ? ((o) ? (*(sigset_t *) (o) = sigblock (*(n))) : sigblock (*(n))) \
128 static bool diraccess (char const *);
129 static int temporary_file (void);
133 /* Name of output file if -o specified. */
134 static char const *output;
136 /* Do not print common lines. */
137 static bool suppress_common_lines;
139 /* Value for the long option that does not have single-letter equivalents. */
142 DIFF_PROGRAM_OPTION = CHAR_MAX + 1,
144 STRIP_TRAILING_CR_OPTION,
148 static struct option const longopts[] =
150 {"diff-program", 1, 0, DIFF_PROGRAM_OPTION},
151 {"expand-tabs", 0, 0, 't'},
152 {"help", 0, 0, HELP_OPTION},
153 {"ignore-all-space", 0, 0, 'W'}, /* swap W and w for historical reasons */
154 {"ignore-blank-lines", 0, 0, 'B'},
155 {"ignore-case", 0, 0, 'i'},
156 {"ignore-matching-lines", 1, 0, 'I'},
157 {"ignore-space-change", 0, 0, 'b'},
158 {"ignore-tab-expansion", 0, 0, 'E'},
159 {"left-column", 0, 0, 'l'},
160 {"minimal", 0, 0, 'd'},
161 {"output", 1, 0, 'o'},
162 {"speed-large-files", 0, 0, 'H'},
163 {"strip-trailing-cr", 0, 0, STRIP_TRAILING_CR_OPTION},
164 {"suppress-common-lines", 0, 0, 's'},
165 {"tabsize", 1, 0, TABSIZE_OPTION},
167 {"version", 0, 0, 'v'},
168 {"width", 1, 0, 'w'},
172 static void try_help (char const *, char const *) __attribute__((noreturn));
174 try_help (char const *reason_msgid, char const *operand)
177 error (0, 0, _(reason_msgid), operand);
178 error (EXIT_TROUBLE, 0, _("Try `%s --help' for more information."),
187 fatal ("write failed");
188 else if (fclose (stdout) != 0)
189 perror_fatal (_("standard output"));
192 static char const * const option_help_msgid[] = {
193 N_("-o FILE --output=FILE Operate interactively, sending output to FILE."),
195 N_("-i --ignore-case Consider upper- and lower-case to be the same."),
196 N_("-E --ignore-tab-expansion Ignore changes due to tab expansion."),
197 N_("-b --ignore-space-change Ignore changes in the amount of white space."),
198 N_("-W --ignore-all-space Ignore all white space."),
199 N_("-B --ignore-blank-lines Ignore changes whose lines are all blank."),
200 N_("-I RE --ignore-matching-lines=RE Ignore changes whose lines all match RE."),
201 N_("--strip-trailing-cr Strip trailing carriage return on input."),
202 N_("-a --text Treat all files as text."),
204 N_("-w NUM --width=NUM Output at most NUM (default 130) print columns."),
205 N_("-l --left-column Output only the left column of common lines."),
206 N_("-s --suppress-common-lines Do not output common lines."),
208 N_("-t --expand-tabs Expand tabs to spaces in output."),
209 N_("--tabsize=NUM Tab stops are every NUM (default 8) print columns."),
211 N_("-d --minimal Try hard to find a smaller set of changes."),
212 N_("-H --speed-large-files Assume large files and many scattered small changes."),
213 N_("--diff-program=PROGRAM Use PROGRAM to compare files."),
215 N_("-v --version Output version info."),
216 N_("--help Output this help."),
223 char const * const *p;
225 printf (_("Usage: %s [OPTION]... FILE1 FILE2\n"), program_name);
226 printf ("%s\n\n", _("Side-by-side merge of file differences."));
227 for (p = option_help_msgid; *p; p++)
229 printf (" %s\n", _(*p));
232 printf ("\n%s\n%s\n",
233 _("If a FILE is `-', read standard input."),
234 _("Exit status is 0 if inputs are the same, 1 if different, 2 if trouble."));
235 emit_bug_reporting_address ();
238 /* Clean up after a signal or other failure. This function is
239 async-signal-safe. */
241 cleanup (int signo __attribute__((unused)))
243 #if HAVE_WORKING_FORK || HAVE_WORKING_VFORK
245 kill (diffpid, SIGPIPE);
251 static void exiterr (void) __attribute__((noreturn));
262 fatal (char const *msgid)
264 error (0, 0, "%s", _(msgid));
269 perror_fatal (char const *msg)
273 error (0, e, "%s", msg);
278 check_child_status (int werrno, int wstatus, int max_ok_status,
279 char const *subsidiary_program)
281 int status = (! werrno && WIFEXITED (wstatus)
282 ? WEXITSTATUS (wstatus)
285 if (max_ok_status < status)
289 ? "subsidiary program `%s' could not be invoked"
291 ? "subsidiary program `%s' not found"
293 ? "subsidiary program `%s' failed"
294 : "subsidiary program `%s' failed (exit status %d)"),
295 subsidiary_program, status);
301 ck_fopen (char const *fname, char const *type)
303 FILE *r = fopen (fname, type);
305 perror_fatal (fname);
313 perror_fatal ("fclose");
317 ck_fread (char *buf, size_t size, FILE *f)
319 size_t r = fread (buf, sizeof (char), size, f);
320 if (r == 0 && ferror (f))
321 perror_fatal (_("read failed"));
326 ck_fwrite (char const *buf, size_t size, FILE *f)
328 if (fwrite (buf, sizeof (char), size, f) != size)
329 perror_fatal (_("write failed"));
336 perror_fatal (_("write failed"));
340 expand_name (char *name, bool is_dir, char const *other_name)
342 if (STREQ (name, "-"))
343 fatal ("cannot interactively merge standard input");
348 /* Yield NAME/BASE, where BASE is OTHER_NAME's basename. */
349 char const *base = last_component (other_name);
350 size_t namelen = strlen (name), baselen = base_len (base);
351 bool insert_slash = *last_component (name) && name[namelen - 1] != '/';
352 char *r = xmalloc (namelen + insert_slash + baselen + 1);
353 memcpy (r, name, namelen);
355 memcpy (r + namelen + insert_slash, base, baselen);
356 r[namelen + insert_slash + baselen] = '\0';
369 lf_init (struct line_filter *lf, FILE *infile)
372 lf->bufpos = lf->buffer = lf->buflim = xmalloc (SDIFF_BUFSIZE + 1);
373 lf->buflim[0] = '\n';
376 /* Fill an exhausted line_filter buffer from its INFILE */
378 lf_refill (struct line_filter *lf)
380 size_t s = ck_fread (lf->buffer, SDIFF_BUFSIZE, lf->infile);
381 lf->bufpos = lf->buffer;
382 lf->buflim = lf->buffer + s;
383 lf->buflim[0] = '\n';
388 /* Advance LINES on LF's infile, copying lines to OUTFILE */
390 lf_copy (struct line_filter *lf, lin lines, FILE *outfile)
392 char *start = lf->bufpos;
396 lf->bufpos = (char *) memchr (lf->bufpos, '\n', lf->buflim - lf->bufpos);
399 ck_fwrite (start, lf->buflim - start, outfile);
400 if (! lf_refill (lf))
411 ck_fwrite (start, lf->bufpos - start, outfile);
414 /* Advance LINES on LF's infile without doing output */
416 lf_skip (struct line_filter *lf, lin lines)
420 lf->bufpos = (char *) memchr (lf->bufpos, '\n', lf->buflim - lf->bufpos);
423 if (! lf_refill (lf))
434 /* Snarf a line into a buffer. Return EOF if EOF, 0 if error, 1 if OK. */
436 lf_snarf (struct line_filter *lf, char *buffer, size_t bufsize)
440 char *start = lf->bufpos;
441 char *next = (char *) memchr (start, '\n', lf->buflim + 1 - start);
442 size_t s = next - start;
445 memcpy (buffer, start, s);
446 if (next < lf->buflim)
449 lf->bufpos = next + 1;
452 if (! lf_refill (lf))
460 main (int argc, char *argv[])
465 exit_failure = EXIT_TROUBLE;
466 initialize_main (&argc, &argv);
467 set_program_name (argv[0]);
468 setlocale (LC_ALL, "");
469 textdomain (PACKAGE);
470 c_stack_action (cleanup);
472 prog = getenv ("EDITOR");
474 editor_program = prog;
476 diffarg (DEFAULT_DIFF_PROGRAM);
478 /* parse command line args */
479 while ((opt = getopt_long (argc, argv, "abBdEHiI:lo:stvw:W", longopts, 0))
518 diffarg ("--left-column");
526 suppress_common_lines = true;
534 version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, PACKAGE_VERSION,
535 AUTHORS, (char *) NULL);
548 case DIFF_PROGRAM_OPTION:
549 diffargv[0] = optarg;
557 case STRIP_TRAILING_CR_OPTION:
558 diffarg ("--strip-trailing-cr");
562 diffarg ("--tabsize");
571 if (argc - optind != 2)
573 if (argc - optind < 2)
574 try_help ("missing operand after `%s'", argv[argc - 1]);
576 try_help ("extra operand `%s'", argv[optind + 2]);
581 /* easy case: diff does everything for us */
582 if (suppress_common_lines)
583 diffarg ("--suppress-common-lines");
586 diffarg (argv[optind]);
587 diffarg (argv[optind + 1]);
589 execvp (diffargv[0], (char **) diffargv);
590 perror_fatal (diffargv[0]);
594 char const *lname, *rname;
595 FILE *left, *right, *out, *diffout;
597 struct line_filter lfilt;
598 struct line_filter rfilt;
599 struct line_filter diff_filt;
600 bool leftdir = diraccess (argv[optind]);
601 bool rightdir = diraccess (argv[optind + 1]);
603 if (leftdir & rightdir)
604 fatal ("both files to be compared are directories");
606 lname = expand_name (argv[optind], leftdir, argv[optind + 1]);
607 left = ck_fopen (lname, "r");
608 rname = expand_name (argv[optind + 1], rightdir, argv[optind]);
609 right = ck_fopen (rname, "r");
610 out = ck_fopen (output, "w");
612 diffarg ("--sdiff-merge-assist");
614 diffarg (argv[optind]);
615 diffarg (argv[optind + 1]);
620 #if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
626 for (i = 0; diffargv[i]; i++)
627 cmdsize += shell_quote_length (diffargv[i]) + 1;
628 command = p = xmalloc (cmdsize);
629 for (i = 0; diffargv[i]; i++)
631 p = shell_quote_copy (p, diffargv[i]);
636 diffout = popen (command, "r");
638 perror_fatal (command);
644 # if HAVE_WORKING_VFORK
649 if (pipe (diff_fds) != 0)
650 perror_fatal ("pipe");
652 # if HAVE_WORKING_VFORK
653 /* Block SIGINT and SIGPIPE. */
654 sigemptyset (&blocked);
655 sigaddset (&blocked, SIGINT);
656 sigaddset (&blocked, SIGPIPE);
657 sigprocmask (SIG_BLOCK, &blocked, &procmask);
661 perror_fatal ("fork");
664 /* Alter the child's SIGINT and SIGPIPE handlers;
665 this may munge the parent.
666 The child ignores SIGINT in case the user interrupts the editor.
667 The child does not ignore SIGPIPE, even if the parent does. */
668 if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
669 signal_handler (SIGINT, SIG_IGN);
670 signal_handler (SIGPIPE, SIG_DFL);
671 # if HAVE_WORKING_VFORK
672 /* Stop blocking SIGINT and SIGPIPE in the child. */
673 sigprocmask (SIG_SETMASK, &procmask, 0);
676 if (diff_fds[1] != STDOUT_FILENO)
678 dup2 (diff_fds[1], STDOUT_FILENO);
682 execvp (diffargv[0], (char **) diffargv);
683 _exit (errno == ENOENT ? 127 : 126);
686 # if HAVE_WORKING_VFORK
687 /* Restore the parent's SIGINT and SIGPIPE behavior. */
688 if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
689 signal_handler (SIGINT, catchsig);
690 if (initial_handler (handler_index_of_SIGPIPE) != SIG_IGN)
691 signal_handler (SIGPIPE, catchsig);
693 signal_handler (SIGPIPE, SIG_IGN);
695 /* Stop blocking SIGINT and SIGPIPE in the parent. */
696 sigprocmask (SIG_SETMASK, &procmask, 0);
700 diffout = fdopen (diff_fds[0], "r");
702 perror_fatal ("fdopen");
706 lf_init (&diff_filt, diffout);
707 lf_init (&lfilt, left);
708 lf_init (&rfilt, right);
710 interact_ok = interact (&diff_filt, &lfilt, lname, &rfilt, rname, out);
720 #if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
721 wstatus = pclose (diffout);
726 while (waitpid (diffpid, &wstatus, 0) < 0)
730 perror_fatal ("waitpid");
743 check_child_status (werrno, wstatus, EXIT_FAILURE, diffargv[0]);
746 exit (WEXITSTATUS (wstatus));
749 return EXIT_SUCCESS; /* Fool `-Wall'. */
753 diffarg (char const *a)
755 static size_t diffargs, diffarglim;
757 if (diffargs == diffarglim)
761 else if (PTRDIFF_MAX / (2 * sizeof *diffargv) <= diffarglim)
765 diffargv = xrealloc (diffargv, diffarglim * sizeof *diffargv);
767 diffargv[diffargs++] = a;
770 /* Signal handling */
772 static bool volatile ignore_SIGINT;
773 static int volatile signal_received;
774 static bool sigs_trapped;
782 if (! (s == SIGINT && ignore_SIGINT))
787 static struct sigaction catchaction;
790 signal_handler (int sig, void (*handler) (int))
792 catchaction.sa_handler = handler;
793 sigaction (sig, &catchaction, 0);
803 catchaction.sa_flags = SA_RESTART;
804 sigemptyset (&catchaction.sa_mask);
805 for (i = 0; i < NUM_SIGS; i++)
806 sigaddset (&catchaction.sa_mask, sigs[i]);
809 for (i = 0; i < NUM_SIGS; i++)
812 sigaction (sigs[i], 0, &initial_action[i]);
814 initial_action[i] = signal (sigs[i], SIG_IGN);
816 if (initial_handler (i) != SIG_IGN)
817 signal_handler (sigs[i], catchsig);
821 /* System V fork+wait does not work if SIGCHLD is ignored. */
822 signal (SIGCHLD, SIG_DFL);
828 /* Untrap signal S, or all trapped signals if S is zero. */
835 for (i = 0; i < NUM_SIGS; i++)
836 if ((! s || sigs[i] == s) && initial_handler (i) != SIG_IGN)
839 sigaction (sigs[i], &initial_action[i], 0);
841 signal (sigs[i], initial_action[i]);
846 /* Exit if a signal has been received. */
850 int s = signal_received;
855 /* Yield an exit status indicating that a signal was received. */
859 /* That didn't work, so exit with error status. */
867 fprintf (stderr, "%s", _("\
868 ed:\tEdit then use both versions, each decorated with a header.\n\
869 eb:\tEdit then use both versions.\n\
870 el or e1:\tEdit then use the left version.\n\
871 er or e2:\tEdit then use the right version.\n\
872 e:\tDiscard both versions then edit a new one.\n\
873 l or 1:\tUse the left version.\n\
874 r or 2:\tUse the right version.\n\
875 s:\tSilently include common lines.\n\
876 v:\tVerbosely include common lines.\n\
888 if (! isspace (c) || c == '\n')
893 perror_fatal (_("read failed"));
901 while ((c = getchar ()) != '\n' && c != EOF)
904 perror_fatal (_("read failed"));
908 /* interpret an edit command */
910 edit (struct line_filter *left, char const *lname, lin lline, lin llen,
911 struct line_filter *right, char const *rname, lin rline, lin rlen,
916 int cmd0 IF_LINT (= 0);
917 int cmd1 IF_LINT (= 0);
922 if (putchar ('%') != '%')
923 perror_fatal (_("write failed"));
926 cmd0 = skip_white ();
929 case '1': case '2': case 'l': case 'r':
930 case 's': case 'v': case 'q':
931 if (skip_white () != '\n')
941 cmd1 = skip_white ();
944 case '1': case '2': case 'b': case 'd': case 'l': case 'r':
945 if (skip_white () != '\n')
983 lf_copy (left, llen, outfile);
984 lf_skip (right, rlen);
987 lf_copy (right, rlen, outfile);
988 lf_skip (left, llen);
991 suppress_common_lines = true;
994 suppress_common_lines = false;
1003 tmp = fopen (tmpname, "w");
1006 if ((fd = temporary_file ()) < 0)
1007 perror_fatal ("mkstemp");
1008 tmp = fdopen (fd, "w");
1012 perror_fatal (tmpname);
1020 fprintf (tmp, "--- %s %ld\n", lname, (long int) lline);
1022 fprintf (tmp, "--- %s %ld,%ld\n", lname,
1024 (long int) (lline + llen - 1));
1027 case '1': case 'b': case 'l':
1028 lf_copy (left, llen, tmp);
1032 lf_skip (left, llen);
1042 fprintf (tmp, "+++ %s %ld\n", rname, (long int) rline);
1044 fprintf (tmp, "+++ %s %ld,%ld\n", rname,
1046 (long int) (rline + rlen - 1));
1049 case '2': case 'b': case 'r':
1050 lf_copy (right, rlen, tmp);
1054 lf_skip (right, rlen);
1063 ignore_SIGINT = true;
1067 #if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
1069 xmalloc (shell_quote_length (editor_program)
1070 + 1 + strlen (tmpname) + 1);
1071 sprintf (shell_quote_copy (command, editor_program),
1073 wstatus = system (command);
1083 char const *argv[3];
1086 argv[i++] = editor_program;
1087 argv[i++] = tmpname;
1090 execvp (editor_program, (char **) argv);
1091 _exit (errno == ENOENT ? 127 : 126);
1095 perror_fatal ("fork");
1097 while (waitpid (pid, &wstatus, 0) < 0)
1101 perror_fatal ("waitpid");
1105 ignore_SIGINT = false;
1106 check_child_status (werrno, wstatus, EXIT_SUCCESS,
1111 char buf[SDIFF_BUFSIZE];
1113 tmp = ck_fopen (tmpname, "r");
1114 while ((size = ck_fread (buf, SDIFF_BUFSIZE, tmp)) != 0)
1117 ck_fwrite (buf, size, outfile);
1130 /* Alternately reveal bursts of diff output and handle user commands. */
1132 interact (struct line_filter *diff,
1133 struct line_filter *left, char const *lname,
1134 struct line_filter *right, char const *rname,
1137 lin lline = 1, rline = 1;
1141 char diff_help[256];
1142 int snarfed = lf_snarf (diff, diff_help, sizeof diff_help);
1145 return snarfed != 0;
1149 if (diff_help[0] == ' ')
1150 puts (diff_help + 1);
1155 lin llen, rlen, lenmax;
1157 llen = val = strtoumax (diff_help + 1, &numend, 10);
1158 if (llen < 0 || llen != val || errno || *numend != ',')
1160 rlen = val = strtoumax (numend + 1, &numend, 10);
1161 if (rlen < 0 || rlen != val || errno || *numend)
1164 lenmax = MAX (llen, rlen);
1166 switch (diff_help[0])
1169 if (suppress_common_lines)
1170 lf_skip (diff, lenmax);
1172 lf_copy (diff, lenmax, stdout);
1174 lf_copy (left, llen, outfile);
1175 lf_skip (right, rlen);
1179 lf_copy (diff, lenmax, stdout);
1180 if (! edit (left, lname, lline, llen,
1181 right, rname, rline, rlen,
1196 /* Return true if DIR is an existing directory. */
1198 diraccess (char const *dir)
1201 return stat (dir, &buf) == 0 && S_ISDIR (buf.st_mode);
1205 # define P_tmpdir "/tmp"
1208 # define TMPDIR_ENV "TMPDIR"
1211 /* Open a temporary file and return its file descriptor. Put into
1212 tmpname the address of a newly allocated buffer that holds the
1213 file's name. Use the prefix "sdiff". */
1215 temporary_file (void)
1217 char const *tmpdir = getenv (TMPDIR_ENV);
1218 char const *dir = tmpdir ? tmpdir : P_tmpdir;
1219 char *buf = xmalloc (strlen (dir) + 1 + 5 + 6 + 1);
1224 sprintf (buf, "%s/sdiffXXXXXX", dir);
1225 sigemptyset (&blocked);
1226 sigaddset (&blocked, SIGINT);
1227 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1232 sigprocmask (SIG_SETMASK, &procmask, 0);