1 /* sdiff - side-by-side merge of file differences
3 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 2001, 2002, 2004
4 Free Software Foundation, Inc.
6 This file is part of GNU DIFF.
8 GNU DIFF 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 2, or (at your option)
13 GNU DIFF 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.
16 See the 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; see the file COPYING.
20 If not, write to the Free Software Foundation,
21 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
27 #include <unlocked-io.h>
34 #include <file-type.h>
37 #include <version-etc.h>
40 /* Size of chunks read from files which must be parsed into lines. */
41 #define SDIFF_BUFSIZE ((size_t) 65536)
45 static char const *editor_program = DEFAULT_EDITOR_PROGRAM;
46 static char const **diffargv;
48 static char * volatile tmpname;
51 #if HAVE_WORKING_FORK || HAVE_WORKING_VFORK
52 static pid_t volatile diffpid;
57 static void catchsig (int);
58 static bool edit (struct line_filter *, char const *, lin, lin, struct line_filter *, char const *, lin, lin, FILE *);
59 static bool interact (struct line_filter *, struct line_filter *, char const *, struct line_filter *, char const *, FILE *);
60 static void checksigs (void);
61 static void diffarg (char const *);
62 static void fatal (char const *) __attribute__((noreturn));
63 static void perror_fatal (char const *) __attribute__((noreturn));
64 static void trapsigs (void);
65 static void untrapsig (int);
67 #define NUM_SIGS (sizeof sigs / sizeof *sigs)
68 static int const sigs[] = {
87 #define handler_index_of_SIGINT (NUM_SIGS - 2)
88 #define handler_index_of_SIGPIPE (NUM_SIGS - 1)
91 /* Prefer `sigaction' if available, since `signal' can lose signals. */
92 static struct sigaction initial_action[NUM_SIGS];
93 # define initial_handler(i) (initial_action[i].sa_handler)
94 static void signal_handler (int, void (*) (int));
96 static void (*initial_action[NUM_SIGS]) ();
97 # define initial_handler(i) (initial_action[i])
98 # define signal_handler(sig, handler) signal (sig, handler)
101 #if ! HAVE_SIGPROCMASK
102 # define sigset_t int
103 # define sigemptyset(s) (*(s) = 0)
105 # define sigmask(sig) (1 << ((sig) - 1))
107 # define sigaddset(s, sig) (*(s) |= sigmask (sig))
112 # define SIG_SETMASK (! SIG_BLOCK)
114 # define sigprocmask(how, n, o) \
115 ((how) == SIG_BLOCK ? *(o) = sigblock (*(n)) : sigsetmask (*(n)))
118 static bool diraccess (char const *);
119 static int temporary_file (void);
123 /* Name of output file if -o specified. */
124 static char const *output;
126 /* Do not print common lines. */
127 static bool suppress_common_lines;
129 /* Value for the long option that does not have single-letter equivalents. */
132 DIFF_PROGRAM_OPTION = CHAR_MAX + 1,
134 STRIP_TRAILING_CR_OPTION,
138 static struct option const longopts[] =
140 {"diff-program", 1, 0, DIFF_PROGRAM_OPTION},
141 {"expand-tabs", 0, 0, 't'},
142 {"help", 0, 0, HELP_OPTION},
143 {"ignore-all-space", 0, 0, 'W'}, /* swap W and w for historical reasons */
144 {"ignore-blank-lines", 0, 0, 'B'},
145 {"ignore-case", 0, 0, 'i'},
146 {"ignore-matching-lines", 1, 0, 'I'},
147 {"ignore-space-change", 0, 0, 'b'},
148 {"ignore-tab-expansion", 0, 0, 'E'},
149 {"left-column", 0, 0, 'l'},
150 {"minimal", 0, 0, 'd'},
151 {"output", 1, 0, 'o'},
152 {"speed-large-files", 0, 0, 'H'},
153 {"strip-trailing-cr", 0, 0, STRIP_TRAILING_CR_OPTION},
154 {"suppress-common-lines", 0, 0, 's'},
155 {"tabsize", 1, 0, TABSIZE_OPTION},
157 {"version", 0, 0, 'v'},
158 {"width", 1, 0, 'w'},
162 static void try_help (char const *, char const *) __attribute__((noreturn));
164 try_help (char const *reason_msgid, char const *operand)
167 error (0, 0, _(reason_msgid), operand);
168 error (EXIT_TROUBLE, 0, _("Try `%s --help' for more information."),
177 fatal ("write failed");
178 else if (fclose (stdout) != 0)
179 perror_fatal (_("standard output"));
182 static char const * const option_help_msgid[] = {
183 N_("-o FILE --output=FILE Operate interactively, sending output to FILE."),
185 N_("-i --ignore-case Consider upper- and lower-case to be the same."),
186 N_("-E --ignore-tab-expansion Ignore changes due to tab expansion."),
187 N_("-b --ignore-space-change Ignore changes in the amount of white space."),
188 N_("-W --ignore-all-space Ignore all white space."),
189 N_("-B --ignore-blank-lines Ignore changes whose lines are all blank."),
190 N_("-I RE --ignore-matching-lines=RE Ignore changes whose lines all match RE."),
191 N_("--strip-trailing-cr Strip trailing carriage return on input."),
192 N_("-a --text Treat all files as text."),
194 N_("-w NUM --width=NUM Output at most NUM (default 130) print columns."),
195 N_("-l --left-column Output only the left column of common lines."),
196 N_("-s --suppress-common-lines Do not output common lines."),
198 N_("-t --expand-tabs Expand tabs to spaces in output."),
199 N_("--tabsize=NUM Tab stops are every NUM (default 8) print columns."),
201 N_("-d --minimal Try hard to find a smaller set of changes."),
202 N_("-H --speed-large-files Assume large files and many scattered small changes."),
203 N_("--diff-program=PROGRAM Use PROGRAM to compare files."),
205 N_("-v --version Output version info."),
206 N_("--help Output this help."),
213 char const * const *p;
215 printf (_("Usage: %s [OPTION]... FILE1 FILE2\n"), program_name);
216 printf ("%s\n\n", _("Side-by-side merge of file differences."));
217 for (p = option_help_msgid; *p; p++)
219 printf (" %s\n", _(*p));
222 printf ("\n%s\n%s\n\n%s\n",
223 _("If a FILE is `-', read standard input."),
224 _("Exit status is 0 if inputs are the same, 1 if different, 2 if trouble."),
225 _("Report bugs to <bug-gnu-utils@gnu.org>."));
228 /* Clean up after a signal or other failure. This function is
229 async-signal-safe. */
231 cleanup (int signo __attribute__((unused)))
233 #if HAVE_WORKING_FORK || HAVE_WORKING_VFORK
235 kill (diffpid, SIGPIPE);
241 static void exiterr (void) __attribute__((noreturn));
252 fatal (char const *msgid)
254 error (0, 0, "%s", _(msgid));
259 perror_fatal (char const *msg)
263 error (0, e, "%s", msg);
268 check_child_status (int werrno, int wstatus, int max_ok_status,
269 char const *subsidiary_program)
271 int status = (! werrno && WIFEXITED (wstatus)
272 ? WEXITSTATUS (wstatus)
275 if (max_ok_status < status)
279 ? "subsidiary program `%s' could not be invoked"
281 ? "subsidiary program `%s' not found"
283 ? "subsidiary program `%s' failed"
284 : "subsidiary program `%s' failed (exit status %d)"),
285 subsidiary_program, status);
291 ck_fopen (char const *fname, char const *type)
293 FILE *r = fopen (fname, type);
295 perror_fatal (fname);
303 perror_fatal ("fclose");
307 ck_fread (char *buf, size_t size, FILE *f)
309 size_t r = fread (buf, sizeof (char), size, f);
310 if (r == 0 && ferror (f))
311 perror_fatal (_("read failed"));
316 ck_fwrite (char const *buf, size_t size, FILE *f)
318 if (fwrite (buf, sizeof (char), size, f) != size)
319 perror_fatal (_("write failed"));
326 perror_fatal (_("write failed"));
330 expand_name (char *name, bool is_dir, char const *other_name)
332 if (strcmp (name, "-") == 0)
333 fatal ("cannot interactively merge standard input");
338 /* Yield NAME/BASE, where BASE is OTHER_NAME's basename. */
339 char const *base = base_name (other_name);
340 size_t namelen = strlen (name), baselen = strlen (base);
341 bool insert_slash = *base_name (name) && name[namelen - 1] != '/';
342 char *r = xmalloc (namelen + insert_slash + baselen + 1);
343 memcpy (r, name, namelen);
345 memcpy (r + namelen + insert_slash, base, baselen + 1);
358 lf_init (struct line_filter *lf, FILE *infile)
361 lf->bufpos = lf->buffer = lf->buflim = xmalloc (SDIFF_BUFSIZE + 1);
362 lf->buflim[0] = '\n';
365 /* Fill an exhausted line_filter buffer from its INFILE */
367 lf_refill (struct line_filter *lf)
369 size_t s = ck_fread (lf->buffer, SDIFF_BUFSIZE, lf->infile);
370 lf->bufpos = lf->buffer;
371 lf->buflim = lf->buffer + s;
372 lf->buflim[0] = '\n';
377 /* Advance LINES on LF's infile, copying lines to OUTFILE */
379 lf_copy (struct line_filter *lf, lin lines, FILE *outfile)
381 char *start = lf->bufpos;
385 lf->bufpos = (char *) memchr (lf->bufpos, '\n', lf->buflim - lf->bufpos);
388 ck_fwrite (start, lf->buflim - start, outfile);
389 if (! lf_refill (lf))
400 ck_fwrite (start, lf->bufpos - start, outfile);
403 /* Advance LINES on LF's infile without doing output */
405 lf_skip (struct line_filter *lf, lin lines)
409 lf->bufpos = (char *) memchr (lf->bufpos, '\n', lf->buflim - lf->bufpos);
412 if (! lf_refill (lf))
423 /* Snarf a line into a buffer. Return EOF if EOF, 0 if error, 1 if OK. */
425 lf_snarf (struct line_filter *lf, char *buffer, size_t bufsize)
429 char *start = lf->bufpos;
430 char *next = (char *) memchr (start, '\n', lf->buflim + 1 - start);
431 size_t s = next - start;
434 memcpy (buffer, start, s);
435 if (next < lf->buflim)
438 lf->bufpos = next + 1;
441 if (! lf_refill (lf))
449 main (int argc, char *argv[])
454 exit_failure = EXIT_TROUBLE;
455 initialize_main (&argc, &argv);
456 program_name = argv[0];
457 setlocale (LC_ALL, "");
458 bindtextdomain (PACKAGE, LOCALEDIR);
459 textdomain (PACKAGE);
460 c_stack_action (cleanup);
462 prog = getenv ("EDITOR");
464 editor_program = prog;
466 diffarg (DEFAULT_DIFF_PROGRAM);
468 /* parse command line args */
469 while ((opt = getopt_long (argc, argv, "abBdEHiI:lo:stvw:W", longopts, 0))
508 diffarg ("--left-column");
516 suppress_common_lines = true;
524 version_etc (stdout, "sdiff", PACKAGE_NAME, PACKAGE_VERSION,
525 "Thomas Lord", (char *) 0);
538 case DIFF_PROGRAM_OPTION:
539 diffargv[0] = optarg;
547 case STRIP_TRAILING_CR_OPTION:
548 diffarg ("--strip-trailing-cr");
552 diffarg ("--tabsize");
561 if (argc - optind != 2)
563 if (argc - optind < 2)
564 try_help ("missing operand after `%s'", argv[argc - 1]);
566 try_help ("extra operand `%s'", argv[optind + 2]);
571 /* easy case: diff does everything for us */
572 if (suppress_common_lines)
573 diffarg ("--suppress-common-lines");
576 diffarg (argv[optind]);
577 diffarg (argv[optind + 1]);
579 execvp (diffargv[0], (char **) diffargv);
580 perror_fatal (diffargv[0]);
584 char const *lname, *rname;
585 FILE *left, *right, *out, *diffout;
587 struct line_filter lfilt;
588 struct line_filter rfilt;
589 struct line_filter diff_filt;
590 bool leftdir = diraccess (argv[optind]);
591 bool rightdir = diraccess (argv[optind + 1]);
593 if (leftdir & rightdir)
594 fatal ("both files to be compared are directories");
596 lname = expand_name (argv[optind], leftdir, argv[optind + 1]);
597 left = ck_fopen (lname, "r");
598 rname = expand_name (argv[optind + 1], rightdir, argv[optind]);
599 right = ck_fopen (rname, "r");
600 out = ck_fopen (output, "w");
602 diffarg ("--sdiff-merge-assist");
604 diffarg (argv[optind]);
605 diffarg (argv[optind + 1]);
610 #if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
616 for (i = 0; diffargv[i]; i++)
617 cmdsize += quote_system_arg (0, diffargv[i]) + 1;
618 command = p = xmalloc (cmdsize);
619 for (i = 0; diffargv[i]; i++)
621 p += quote_system_arg (p, diffargv[i]);
626 diffout = popen (command, "r");
628 perror_fatal (command);
634 # if HAVE_WORKING_VFORK
639 if (pipe (diff_fds) != 0)
640 perror_fatal ("pipe");
642 # if HAVE_WORKING_VFORK
643 /* Block SIGINT and SIGPIPE. */
644 sigemptyset (&blocked);
645 sigaddset (&blocked, SIGINT);
646 sigaddset (&blocked, SIGPIPE);
647 sigprocmask (SIG_BLOCK, &blocked, &procmask);
651 perror_fatal ("fork");
654 /* Alter the child's SIGINT and SIGPIPE handlers;
655 this may munge the parent.
656 The child ignores SIGINT in case the user interrupts the editor.
657 The child does not ignore SIGPIPE, even if the parent does. */
658 if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
659 signal_handler (SIGINT, SIG_IGN);
660 signal_handler (SIGPIPE, SIG_DFL);
661 # if HAVE_WORKING_VFORK
662 /* Stop blocking SIGINT and SIGPIPE in the child. */
663 sigprocmask (SIG_SETMASK, &procmask, 0);
666 if (diff_fds[1] != STDOUT_FILENO)
668 dup2 (diff_fds[1], STDOUT_FILENO);
672 execvp (diffargv[0], (char **) diffargv);
673 _exit (errno == ENOENT ? 127 : 126);
676 # if HAVE_WORKING_VFORK
677 /* Restore the parent's SIGINT and SIGPIPE behavior. */
678 if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
679 signal_handler (SIGINT, catchsig);
680 if (initial_handler (handler_index_of_SIGPIPE) != SIG_IGN)
681 signal_handler (SIGPIPE, catchsig);
683 signal_handler (SIGPIPE, SIG_IGN);
685 /* Stop blocking SIGINT and SIGPIPE in the parent. */
686 sigprocmask (SIG_SETMASK, &procmask, 0);
690 diffout = fdopen (diff_fds[0], "r");
692 perror_fatal ("fdopen");
696 lf_init (&diff_filt, diffout);
697 lf_init (&lfilt, left);
698 lf_init (&rfilt, right);
700 interact_ok = interact (&diff_filt, &lfilt, lname, &rfilt, rname, out);
710 #if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
711 wstatus = pclose (diffout);
716 while (waitpid (diffpid, &wstatus, 0) < 0)
720 perror_fatal ("waitpid");
733 check_child_status (werrno, wstatus, EXIT_FAILURE, diffargv[0]);
736 exit (WEXITSTATUS (wstatus));
739 return EXIT_SUCCESS; /* Fool `-Wall'. */
743 diffarg (char const *a)
745 static size_t diffargs, diffarglim;
747 if (diffargs == diffarglim)
751 else if (PTRDIFF_MAX / (2 * sizeof *diffargv) <= diffarglim)
755 diffargv = xrealloc (diffargv, diffarglim * sizeof *diffargv);
757 diffargv[diffargs++] = a;
760 /* Signal handling */
762 static bool volatile ignore_SIGINT;
763 static int volatile signal_received;
764 static bool sigs_trapped;
772 if (! (s == SIGINT && ignore_SIGINT))
777 static struct sigaction catchaction;
780 signal_handler (int sig, void (*handler) (int))
782 catchaction.sa_handler = handler;
783 sigaction (sig, &catchaction, 0);
793 catchaction.sa_flags = SA_RESTART;
794 sigemptyset (&catchaction.sa_mask);
795 for (i = 0; i < NUM_SIGS; i++)
796 sigaddset (&catchaction.sa_mask, sigs[i]);
799 for (i = 0; i < NUM_SIGS; i++)
802 sigaction (sigs[i], 0, &initial_action[i]);
804 initial_action[i] = signal (sigs[i], SIG_IGN);
806 if (initial_handler (i) != SIG_IGN)
807 signal_handler (sigs[i], catchsig);
811 /* System V fork+wait does not work if SIGCHLD is ignored. */
812 signal (SIGCHLD, SIG_DFL);
818 /* Untrap signal S, or all trapped signals if S is zero. */
825 for (i = 0; i < NUM_SIGS; i++)
826 if ((! s || sigs[i] == s) && initial_handler (i) != SIG_IGN)
829 sigaction (sigs[i], &initial_action[i], 0);
831 signal (sigs[i], initial_action[i]);
836 /* Exit if a signal has been received. */
840 int s = signal_received;
845 /* Yield an exit status indicating that a signal was received. */
849 /* That didn't work, so exit with error status. */
857 fprintf (stderr, "%s", _("\
858 ed:\tEdit then use both versions, each decorated with a header.\n\
859 eb:\tEdit then use both versions.\n\
860 el:\tEdit then use the left version.\n\
861 er:\tEdit then use the right version.\n\
862 e:\tEdit a new version.\n\
863 l:\tUse the left version.\n\
864 r:\tUse the right version.\n\
865 s:\tSilently include common lines.\n\
866 v:\tVerbosely include common lines.\n\
878 if (! isspace (c) || c == '\n')
883 perror_fatal (_("read failed"));
891 while ((c = getchar ()) != '\n' && c != EOF)
894 perror_fatal (_("read failed"));
898 /* interpret an edit command */
900 edit (struct line_filter *left, char const *lname, lin lline, lin llen,
901 struct line_filter *right, char const *rname, lin rline, lin rlen,
909 cmd1 = 0; /* Pacify `gcc -W'. */
913 if (putchar ('%') != '%')
914 perror_fatal (_("write failed"));
917 cmd0 = skip_white ();
920 case 'l': case 'r': case 's': case 'v': case 'q':
921 if (skip_white () != '\n')
931 cmd1 = skip_white ();
934 case 'b': case 'd': case 'l': case 'r':
935 if (skip_white () != '\n')
973 lf_copy (left, llen, outfile);
974 lf_skip (right, rlen);
977 lf_copy (right, rlen, outfile);
978 lf_skip (left, llen);
981 suppress_common_lines = true;
984 suppress_common_lines = false;
993 tmp = fopen (tmpname, "w");
996 if ((fd = temporary_file ()) < 0)
997 perror_fatal ("mkstemp");
998 tmp = fdopen (fd, "w");
1002 perror_fatal (tmpname);
1010 fprintf (tmp, "--- %s %ld\n", lname, (long int) lline);
1012 fprintf (tmp, "--- %s %ld,%ld\n", lname,
1014 (long int) (lline + llen - 1));
1018 lf_copy (left, llen, tmp);
1022 lf_skip (left, llen);
1032 fprintf (tmp, "+++ %s %ld\n", rname, (long int) rline);
1034 fprintf (tmp, "+++ %s %ld,%ld\n", rname,
1036 (long int) (rline + rlen - 1));
1040 lf_copy (right, rlen, tmp);
1044 lf_skip (right, rlen);
1053 ignore_SIGINT = true;
1057 #if ! (HAVE_WORKING_FORK || HAVE_WORKING_VFORK)
1059 xmalloc (quote_system_arg (0, editor_program)
1060 + 1 + strlen (tmpname) + 1);
1061 sprintf (command + quote_system_arg (command, editor_program),
1063 wstatus = system (command);
1073 char const *argv[3];
1076 argv[i++] = editor_program;
1077 argv[i++] = tmpname;
1080 execvp (editor_program, (char **) argv);
1081 _exit (errno == ENOENT ? 127 : 126);
1085 perror_fatal ("fork");
1087 while (waitpid (pid, &wstatus, 0) < 0)
1091 perror_fatal ("waitpid");
1095 ignore_SIGINT = false;
1096 check_child_status (werrno, wstatus, EXIT_SUCCESS,
1101 char buf[SDIFF_BUFSIZE];
1103 tmp = ck_fopen (tmpname, "r");
1104 while ((size = ck_fread (buf, SDIFF_BUFSIZE, tmp)) != 0)
1107 ck_fwrite (buf, size, outfile);
1120 /* Alternately reveal bursts of diff output and handle user commands. */
1122 interact (struct line_filter *diff,
1123 struct line_filter *left, char const *lname,
1124 struct line_filter *right, char const *rname,
1127 lin lline = 1, rline = 1;
1131 char diff_help[256];
1132 int snarfed = lf_snarf (diff, diff_help, sizeof diff_help);
1135 return snarfed != 0;
1139 if (diff_help[0] == ' ')
1140 puts (diff_help + 1);
1145 lin llen, rlen, lenmax;
1147 llen = val = strtoumax (diff_help + 1, &numend, 10);
1148 if (llen < 0 || llen != val || errno || *numend != ',')
1150 rlen = val = strtoumax (numend + 1, &numend, 10);
1151 if (rlen < 0 || rlen != val || errno || *numend)
1154 lenmax = MAX (llen, rlen);
1156 switch (diff_help[0])
1159 if (suppress_common_lines)
1160 lf_skip (diff, lenmax);
1162 lf_copy (diff, lenmax, stdout);
1164 lf_copy (left, llen, outfile);
1165 lf_skip (right, rlen);
1169 lf_copy (diff, lenmax, stdout);
1170 if (! edit (left, lname, lline, llen,
1171 right, rname, rline, rlen,
1186 /* Return true if DIR is an existing directory. */
1188 diraccess (char const *dir)
1191 return stat (dir, &buf) == 0 && S_ISDIR (buf.st_mode);
1195 # define P_tmpdir "/tmp"
1198 # define TMPDIR_ENV "TMPDIR"
1201 /* Open a temporary file and return its file descriptor. Put into
1202 tmpname the address of a newly allocated buffer that holds the
1203 file's name. Use the prefix "sdiff". */
1205 temporary_file (void)
1207 char const *tmpdir = getenv (TMPDIR_ENV);
1208 char const *dir = tmpdir ? tmpdir : P_tmpdir;
1209 char *buf = xmalloc (strlen (dir) + 1 + 5 + 6 + 1);
1214 sprintf (buf, "%s/sdiffXXXXXX", dir);
1215 sigemptyset (&blocked);
1216 sigaddset (&blocked, SIGINT);
1217 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1222 sigprocmask (SIG_SETMASK, &procmask, 0);