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 bindtextdomain (PACKAGE, LOCALEDIR);
470 textdomain (PACKAGE);
471 c_stack_action (cleanup);
473 prog = getenv ("EDITOR");
475 editor_program = prog;
477 diffarg (DEFAULT_DIFF_PROGRAM);
479 /* parse command line args */
480 while ((opt = getopt_long (argc, argv, "abBdEHiI:lo:stvw:W", longopts, 0))
519 diffarg ("--left-column");
527 suppress_common_lines = true;
535 version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, PACKAGE_VERSION,
536 AUTHORS, (char *) NULL);
549 case DIFF_PROGRAM_OPTION:
550 diffargv[0] = optarg;
558 case STRIP_TRAILING_CR_OPTION:
559 diffarg ("--strip-trailing-cr");
563 diffarg ("--tabsize");
572 if (argc - optind != 2)
574 if (argc - optind < 2)
575 try_help ("missing operand after `%s'", argv[argc - 1]);
577 try_help ("extra operand `%s'", argv[optind + 2]);
582 /* easy case: diff does everything for us */
583 if (suppress_common_lines)
584 diffarg ("--suppress-common-lines");
587 diffarg (argv[optind]);
588 diffarg (argv[optind + 1]);
590 execvp (diffargv[0], (char **) diffargv);
591 perror_fatal (diffargv[0]);
595 char const *lname, *rname;
596 FILE *left, *right, *out, *diffout;
598 struct line_filter lfilt;
599 struct line_filter rfilt;
600 struct line_filter diff_filt;
601 bool leftdir = diraccess (argv[optind]);
602 bool rightdir = diraccess (argv[optind + 1]);
604 if (leftdir & rightdir)
605 fatal ("both files to be compared are directories");
607 lname = expand_name (argv[optind], leftdir, argv[optind + 1]);
608 left = ck_fopen (lname, "r");
609 rname = expand_name (argv[optind + 1], rightdir, argv[optind]);
610 right = ck_fopen (rname, "r");
611 out = ck_fopen (output, "w");
613 diffarg ("--sdiff-merge-assist");
615 diffarg (argv[optind]);
616 diffarg (argv[optind + 1]);
621 #if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
627 for (i = 0; diffargv[i]; i++)
628 cmdsize += shell_quote_length (diffargv[i]) + 1;
629 command = p = xmalloc (cmdsize);
630 for (i = 0; diffargv[i]; i++)
632 p = shell_quote_copy (p, diffargv[i]);
637 diffout = popen (command, "r");
639 perror_fatal (command);
645 # if HAVE_WORKING_VFORK
650 if (pipe (diff_fds) != 0)
651 perror_fatal ("pipe");
653 # if HAVE_WORKING_VFORK
654 /* Block SIGINT and SIGPIPE. */
655 sigemptyset (&blocked);
656 sigaddset (&blocked, SIGINT);
657 sigaddset (&blocked, SIGPIPE);
658 sigprocmask (SIG_BLOCK, &blocked, &procmask);
662 perror_fatal ("fork");
665 /* Alter the child's SIGINT and SIGPIPE handlers;
666 this may munge the parent.
667 The child ignores SIGINT in case the user interrupts the editor.
668 The child does not ignore SIGPIPE, even if the parent does. */
669 if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
670 signal_handler (SIGINT, SIG_IGN);
671 signal_handler (SIGPIPE, SIG_DFL);
672 # if HAVE_WORKING_VFORK
673 /* Stop blocking SIGINT and SIGPIPE in the child. */
674 sigprocmask (SIG_SETMASK, &procmask, 0);
677 if (diff_fds[1] != STDOUT_FILENO)
679 dup2 (diff_fds[1], STDOUT_FILENO);
683 execvp (diffargv[0], (char **) diffargv);
684 _exit (errno == ENOENT ? 127 : 126);
687 # if HAVE_WORKING_VFORK
688 /* Restore the parent's SIGINT and SIGPIPE behavior. */
689 if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
690 signal_handler (SIGINT, catchsig);
691 if (initial_handler (handler_index_of_SIGPIPE) != SIG_IGN)
692 signal_handler (SIGPIPE, catchsig);
694 signal_handler (SIGPIPE, SIG_IGN);
696 /* Stop blocking SIGINT and SIGPIPE in the parent. */
697 sigprocmask (SIG_SETMASK, &procmask, 0);
701 diffout = fdopen (diff_fds[0], "r");
703 perror_fatal ("fdopen");
707 lf_init (&diff_filt, diffout);
708 lf_init (&lfilt, left);
709 lf_init (&rfilt, right);
711 interact_ok = interact (&diff_filt, &lfilt, lname, &rfilt, rname, out);
721 #if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
722 wstatus = pclose (diffout);
727 while (waitpid (diffpid, &wstatus, 0) < 0)
731 perror_fatal ("waitpid");
744 check_child_status (werrno, wstatus, EXIT_FAILURE, diffargv[0]);
747 exit (WEXITSTATUS (wstatus));
750 return EXIT_SUCCESS; /* Fool `-Wall'. */
754 diffarg (char const *a)
756 static size_t diffargs, diffarglim;
758 if (diffargs == diffarglim)
762 else if (PTRDIFF_MAX / (2 * sizeof *diffargv) <= diffarglim)
766 diffargv = xrealloc (diffargv, diffarglim * sizeof *diffargv);
768 diffargv[diffargs++] = a;
771 /* Signal handling */
773 static bool volatile ignore_SIGINT;
774 static int volatile signal_received;
775 static bool sigs_trapped;
783 if (! (s == SIGINT && ignore_SIGINT))
788 static struct sigaction catchaction;
791 signal_handler (int sig, void (*handler) (int))
793 catchaction.sa_handler = handler;
794 sigaction (sig, &catchaction, 0);
804 catchaction.sa_flags = SA_RESTART;
805 sigemptyset (&catchaction.sa_mask);
806 for (i = 0; i < NUM_SIGS; i++)
807 sigaddset (&catchaction.sa_mask, sigs[i]);
810 for (i = 0; i < NUM_SIGS; i++)
813 sigaction (sigs[i], 0, &initial_action[i]);
815 initial_action[i] = signal (sigs[i], SIG_IGN);
817 if (initial_handler (i) != SIG_IGN)
818 signal_handler (sigs[i], catchsig);
822 /* System V fork+wait does not work if SIGCHLD is ignored. */
823 signal (SIGCHLD, SIG_DFL);
829 /* Untrap signal S, or all trapped signals if S is zero. */
836 for (i = 0; i < NUM_SIGS; i++)
837 if ((! s || sigs[i] == s) && initial_handler (i) != SIG_IGN)
840 sigaction (sigs[i], &initial_action[i], 0);
842 signal (sigs[i], initial_action[i]);
847 /* Exit if a signal has been received. */
851 int s = signal_received;
856 /* Yield an exit status indicating that a signal was received. */
860 /* That didn't work, so exit with error status. */
868 fprintf (stderr, "%s", _("\
869 ed:\tEdit then use both versions, each decorated with a header.\n\
870 eb:\tEdit then use both versions.\n\
871 el or e1:\tEdit then use the left version.\n\
872 er or e2:\tEdit then use the right version.\n\
873 e:\tDiscard both versions then edit a new one.\n\
874 l or 1:\tUse the left version.\n\
875 r or 2:\tUse the right version.\n\
876 s:\tSilently include common lines.\n\
877 v:\tVerbosely include common lines.\n\
889 if (! isspace (c) || c == '\n')
894 perror_fatal (_("read failed"));
902 while ((c = getchar ()) != '\n' && c != EOF)
905 perror_fatal (_("read failed"));
909 /* interpret an edit command */
911 edit (struct line_filter *left, char const *lname, lin lline, lin llen,
912 struct line_filter *right, char const *rname, lin rline, lin rlen,
917 int cmd0 IF_LINT (= 0);
918 int cmd1 IF_LINT (= 0);
923 if (putchar ('%') != '%')
924 perror_fatal (_("write failed"));
927 cmd0 = skip_white ();
930 case '1': case '2': case 'l': case 'r':
931 case 's': case 'v': case 'q':
932 if (skip_white () != '\n')
942 cmd1 = skip_white ();
945 case '1': case '2': case 'b': case 'd': case 'l': case 'r':
946 if (skip_white () != '\n')
984 lf_copy (left, llen, outfile);
985 lf_skip (right, rlen);
988 lf_copy (right, rlen, outfile);
989 lf_skip (left, llen);
992 suppress_common_lines = true;
995 suppress_common_lines = false;
1004 tmp = fopen (tmpname, "w");
1007 if ((fd = temporary_file ()) < 0)
1008 perror_fatal ("mkstemp");
1009 tmp = fdopen (fd, "w");
1013 perror_fatal (tmpname);
1021 fprintf (tmp, "--- %s %ld\n", lname, (long int) lline);
1023 fprintf (tmp, "--- %s %ld,%ld\n", lname,
1025 (long int) (lline + llen - 1));
1028 case '1': case 'b': case 'l':
1029 lf_copy (left, llen, tmp);
1033 lf_skip (left, llen);
1043 fprintf (tmp, "+++ %s %ld\n", rname, (long int) rline);
1045 fprintf (tmp, "+++ %s %ld,%ld\n", rname,
1047 (long int) (rline + rlen - 1));
1050 case '2': case 'b': case 'r':
1051 lf_copy (right, rlen, tmp);
1055 lf_skip (right, rlen);
1064 ignore_SIGINT = true;
1068 #if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
1070 xmalloc (shell_quote_length (editor_program)
1071 + 1 + strlen (tmpname) + 1);
1072 sprintf (shell_quote_copy (command, editor_program),
1074 wstatus = system (command);
1084 char const *argv[3];
1087 argv[i++] = editor_program;
1088 argv[i++] = tmpname;
1091 execvp (editor_program, (char **) argv);
1092 _exit (errno == ENOENT ? 127 : 126);
1096 perror_fatal ("fork");
1098 while (waitpid (pid, &wstatus, 0) < 0)
1102 perror_fatal ("waitpid");
1106 ignore_SIGINT = false;
1107 check_child_status (werrno, wstatus, EXIT_SUCCESS,
1112 char buf[SDIFF_BUFSIZE];
1114 tmp = ck_fopen (tmpname, "r");
1115 while ((size = ck_fread (buf, SDIFF_BUFSIZE, tmp)) != 0)
1118 ck_fwrite (buf, size, outfile);
1131 /* Alternately reveal bursts of diff output and handle user commands. */
1133 interact (struct line_filter *diff,
1134 struct line_filter *left, char const *lname,
1135 struct line_filter *right, char const *rname,
1138 lin lline = 1, rline = 1;
1142 char diff_help[256];
1143 int snarfed = lf_snarf (diff, diff_help, sizeof diff_help);
1146 return snarfed != 0;
1150 if (diff_help[0] == ' ')
1151 puts (diff_help + 1);
1156 lin llen, rlen, lenmax;
1158 llen = val = strtoumax (diff_help + 1, &numend, 10);
1159 if (llen < 0 || llen != val || errno || *numend != ',')
1161 rlen = val = strtoumax (numend + 1, &numend, 10);
1162 if (rlen < 0 || rlen != val || errno || *numend)
1165 lenmax = MAX (llen, rlen);
1167 switch (diff_help[0])
1170 if (suppress_common_lines)
1171 lf_skip (diff, lenmax);
1173 lf_copy (diff, lenmax, stdout);
1175 lf_copy (left, llen, outfile);
1176 lf_skip (right, rlen);
1180 lf_copy (diff, lenmax, stdout);
1181 if (! edit (left, lname, lline, llen,
1182 right, rname, rline, rlen,
1197 /* Return true if DIR is an existing directory. */
1199 diraccess (char const *dir)
1202 return stat (dir, &buf) == 0 && S_ISDIR (buf.st_mode);
1206 # define P_tmpdir "/tmp"
1209 # define TMPDIR_ENV "TMPDIR"
1212 /* Open a temporary file and return its file descriptor. Put into
1213 tmpname the address of a newly allocated buffer that holds the
1214 file's name. Use the prefix "sdiff". */
1216 temporary_file (void)
1218 char const *tmpdir = getenv (TMPDIR_ENV);
1219 char const *dir = tmpdir ? tmpdir : P_tmpdir;
1220 char *buf = xmalloc (strlen (dir) + 1 + 5 + 6 + 1);
1225 sprintf (buf, "%s/sdiffXXXXXX", dir);
1226 sigemptyset (&blocked);
1227 sigaddset (&blocked, SIGINT);
1228 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1233 sigprocmask (SIG_SETMASK, &procmask, 0);