1 /* sdiff - side-by-side merge of file differences
3 Copyright (C) 1992-1996, 1998, 2001-2002, 2004, 2006-2007, 2009-2011 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;
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[] = {
90 #define handler_index_of_SIGINT (NUM_SIGS - 1)
94 /* Prefer `sigaction' if available, since `signal' can lose signals. */
95 static struct sigaction initial_action[NUM_SIGS];
96 # define initial_handler(i) (initial_action[i].sa_handler)
97 static void signal_handler (int, void (*) (int));
99 static void (*initial_action[NUM_SIGS]) ();
100 # define initial_handler(i) (initial_action[i])
101 # define signal_handler(sig, handler) signal (sig, handler)
104 static bool diraccess (char const *);
105 static int temporary_file (void);
109 /* Name of output file if -o specified. */
110 static char const *output;
112 /* Do not print common lines. */
113 static bool suppress_common_lines;
115 /* Value for the long option that does not have single-letter equivalents. */
118 DIFF_PROGRAM_OPTION = CHAR_MAX + 1,
120 STRIP_TRAILING_CR_OPTION,
124 static struct option const longopts[] =
126 {"diff-program", 1, 0, DIFF_PROGRAM_OPTION},
127 {"expand-tabs", 0, 0, 't'},
128 {"help", 0, 0, HELP_OPTION},
129 {"ignore-all-space", 0, 0, 'W'}, /* swap W and w for historical reasons */
130 {"ignore-blank-lines", 0, 0, 'B'},
131 {"ignore-case", 0, 0, 'i'},
132 {"ignore-matching-lines", 1, 0, 'I'},
133 {"ignore-space-change", 0, 0, 'b'},
134 {"ignore-tab-expansion", 0, 0, 'E'},
135 {"ignore-trailing-space", 0, 0, 'Z'},
136 {"left-column", 0, 0, 'l'},
137 {"minimal", 0, 0, 'd'},
138 {"output", 1, 0, 'o'},
139 {"speed-large-files", 0, 0, 'H'},
140 {"strip-trailing-cr", 0, 0, STRIP_TRAILING_CR_OPTION},
141 {"suppress-common-lines", 0, 0, 's'},
142 {"tabsize", 1, 0, TABSIZE_OPTION},
144 {"version", 0, 0, 'v'},
145 {"width", 1, 0, 'w'},
149 static void try_help (char const *, char const *) __attribute__((noreturn));
151 try_help (char const *reason_msgid, char const *operand)
154 error (0, 0, _(reason_msgid), operand);
155 error (EXIT_TROUBLE, 0, _("Try `%s --help' for more information."),
164 fatal ("write failed");
165 else if (fclose (stdout) != 0)
166 perror_fatal (_("standard output"));
169 static char const * const option_help_msgid[] = {
170 N_("-o, --output=FILE operate interactively, sending output to FILE"),
172 N_("-i, --ignore-case consider upper- and lower-case to be the same"),
173 N_("-E, --ignore-tab-expansion ignore changes due to tab expansion"),
174 N_("-Z, --ignore-trailing-space ignore white space at line end"),
175 N_("-b, --ignore-space-change ignore changes in the amount of white space"),
176 N_("-W, --ignore-all-space ignore all white space"),
177 N_("-B, --ignore-blank-lines ignore changes whose lines are all blank"),
178 N_("-I, --ignore-matching-lines=RE ignore changes whose lines all match RE"),
179 N_(" --strip-trailing-cr strip trailing carriage return on input"),
180 N_("-a, --text treat all files as text"),
182 N_("-w, --width=NUM output at most NUM (default 130) print columns"),
183 N_("-l, --left-column output only the left column of common lines"),
184 N_("-s, --suppress-common-lines do not output common lines"),
186 N_("-t, --expand-tabs expand tabs to spaces in output"),
187 N_(" --tabsize=NUM tab stops at every NUM (default 8) print columns"),
189 N_("-d, --minimal try hard to find a smaller set of changes"),
190 N_("-H, --speed-large-files assume large files, many scattered small changes"),
191 N_(" --diff-program=PROGRAM use PROGRAM to compare files"),
193 N_(" --help display this help and exit"),
194 N_("-v, --version output version information and exit"),
201 char const * const *p;
203 printf (_("Usage: %s [OPTION]... FILE1 FILE2\n"), program_name);
205 _("Side-by-side merge of differences between FILE1 and FILE2."));
208 Mandatory arguments to long options are mandatory for short options too.\n\
210 for (p = option_help_msgid; *p; p++)
212 printf (" %s\n", _(*p));
215 printf ("\n%s\n%s\n",
216 _("If a FILE is `-', read standard input."),
217 _("Exit status is 0 if inputs are the same, 1 if different, 2 if trouble."));
218 emit_bug_reporting_address ();
221 /* Clean up after a signal or other failure. This function is
222 async-signal-safe. */
224 cleanup (int signo __attribute__((unused)))
226 #if HAVE_WORKING_FORK
228 kill (diffpid, SIGPIPE);
234 static void exiterr (void) __attribute__((noreturn));
245 fatal (char const *msgid)
247 error (0, 0, "%s", _(msgid));
252 perror_fatal (char const *msg)
256 error (0, e, "%s", msg);
261 check_child_status (int werrno, int wstatus, int max_ok_status,
262 char const *subsidiary_program)
264 int status = (! werrno && WIFEXITED (wstatus)
265 ? WEXITSTATUS (wstatus)
268 if (max_ok_status < status)
272 ? "subsidiary program `%s' could not be invoked"
274 ? "subsidiary program `%s' not found"
276 ? "subsidiary program `%s' failed"
277 : "subsidiary program `%s' failed (exit status %d)"),
278 subsidiary_program, status);
284 ck_fopen (char const *fname, char const *type)
286 FILE *r = fopen (fname, type);
288 perror_fatal (fname);
296 perror_fatal ("fclose");
300 ck_fread (char *buf, size_t size, FILE *f)
302 size_t r = fread (buf, sizeof (char), size, f);
303 if (r == 0 && ferror (f))
304 perror_fatal (_("read failed"));
309 ck_fwrite (char const *buf, size_t size, FILE *f)
311 if (fwrite (buf, sizeof (char), size, f) != size)
312 perror_fatal (_("write failed"));
319 perror_fatal (_("write failed"));
323 expand_name (char *name, bool is_dir, char const *other_name)
325 if (STREQ (name, "-"))
326 fatal ("cannot interactively merge standard input");
331 /* Yield NAME/BASE, where BASE is OTHER_NAME's basename. */
332 char const *base = last_component (other_name);
333 size_t namelen = strlen (name), baselen = base_len (base);
334 bool insert_slash = *last_component (name) && name[namelen - 1] != '/';
335 char *r = xmalloc (namelen + insert_slash + baselen + 1);
336 memcpy (r, name, namelen);
338 memcpy (r + namelen + insert_slash, base, baselen);
339 r[namelen + insert_slash + baselen] = '\0';
352 lf_init (struct line_filter *lf, FILE *infile)
355 lf->bufpos = lf->buffer = lf->buflim = xmalloc (SDIFF_BUFSIZE + 1);
356 lf->buflim[0] = '\n';
359 /* Fill an exhausted line_filter buffer from its INFILE */
361 lf_refill (struct line_filter *lf)
363 size_t s = ck_fread (lf->buffer, SDIFF_BUFSIZE, lf->infile);
364 lf->bufpos = lf->buffer;
365 lf->buflim = lf->buffer + s;
366 lf->buflim[0] = '\n';
371 /* Advance LINES on LF's infile, copying lines to OUTFILE */
373 lf_copy (struct line_filter *lf, lin lines, FILE *outfile)
375 char *start = lf->bufpos;
379 lf->bufpos = (char *) memchr (lf->bufpos, '\n', lf->buflim - lf->bufpos);
382 ck_fwrite (start, lf->buflim - start, outfile);
383 if (! lf_refill (lf))
394 ck_fwrite (start, lf->bufpos - start, outfile);
397 /* Advance LINES on LF's infile without doing output */
399 lf_skip (struct line_filter *lf, lin lines)
403 lf->bufpos = (char *) memchr (lf->bufpos, '\n', lf->buflim - lf->bufpos);
406 if (! lf_refill (lf))
417 /* Snarf a line into a buffer. Return EOF if EOF, 0 if error, 1 if OK. */
419 lf_snarf (struct line_filter *lf, char *buffer, size_t bufsize)
423 char *start = lf->bufpos;
424 char *next = (char *) memchr (start, '\n', lf->buflim + 1 - start);
425 size_t s = next - start;
428 memcpy (buffer, start, s);
429 if (next < lf->buflim)
432 lf->bufpos = next + 1;
435 if (! lf_refill (lf))
443 main (int argc, char *argv[])
448 exit_failure = EXIT_TROUBLE;
449 initialize_main (&argc, &argv);
450 set_program_name (argv[0]);
451 setlocale (LC_ALL, "");
452 textdomain (PACKAGE);
453 c_stack_action (cleanup);
455 prog = getenv ("EDITOR");
457 editor_program = prog;
459 diffarg (DEFAULT_DIFF_PROGRAM);
461 /* parse command line args */
462 while ((opt = getopt_long (argc, argv, "abBdEHiI:lo:stvw:WZ", longopts, 0))
501 diffarg ("--left-column");
509 suppress_common_lines = true;
517 version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version,
518 AUTHORS, (char *) NULL);
535 case DIFF_PROGRAM_OPTION:
536 diffargv[0] = optarg;
544 case STRIP_TRAILING_CR_OPTION:
545 diffarg ("--strip-trailing-cr");
549 diffarg ("--tabsize");
558 if (argc - optind != 2)
560 if (argc - optind < 2)
561 try_help ("missing operand after `%s'", argv[argc - 1]);
563 try_help ("extra operand `%s'", argv[optind + 2]);
568 /* easy case: diff does everything for us */
569 if (suppress_common_lines)
570 diffarg ("--suppress-common-lines");
573 diffarg (argv[optind]);
574 diffarg (argv[optind + 1]);
576 execvp (diffargv[0], (char **) diffargv);
577 perror_fatal (diffargv[0]);
581 char const *lname, *rname;
582 FILE *left, *right, *out, *diffout;
584 struct line_filter lfilt;
585 struct line_filter rfilt;
586 struct line_filter diff_filt;
587 bool leftdir = diraccess (argv[optind]);
588 bool rightdir = diraccess (argv[optind + 1]);
590 if (leftdir & rightdir)
591 fatal ("both files to be compared are directories");
593 lname = expand_name (argv[optind], leftdir, argv[optind + 1]);
594 left = ck_fopen (lname, "r");
595 rname = expand_name (argv[optind + 1], rightdir, argv[optind]);
596 right = ck_fopen (rname, "r");
597 out = ck_fopen (output, "w");
599 diffarg ("--sdiff-merge-assist");
601 diffarg (argv[optind]);
602 diffarg (argv[optind + 1]);
607 #if ! HAVE_WORKING_FORK
613 for (i = 0; diffargv[i]; i++)
614 cmdsize += shell_quote_length (diffargv[i]) + 1;
615 command = p = xmalloc (cmdsize);
616 for (i = 0; diffargv[i]; i++)
618 p = shell_quote_copy (p, diffargv[i]);
623 diffout = popen (command, "r");
625 perror_fatal (command);
632 if (pipe (diff_fds) != 0)
633 perror_fatal ("pipe");
637 perror_fatal ("fork");
640 /* Alter the child's SIGINT and SIGPIPE handlers;
641 this may munge the parent.
642 The child ignores SIGINT in case the user interrupts the editor.
643 The child does not ignore SIGPIPE, even if the parent does. */
644 if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
645 signal_handler (SIGINT, SIG_IGN);
646 signal_handler (SIGPIPE, SIG_DFL);
648 if (diff_fds[1] != STDOUT_FILENO)
650 dup2 (diff_fds[1], STDOUT_FILENO);
654 execvp (diffargv[0], (char **) diffargv);
655 _exit (errno == ENOENT ? 127 : 126);
659 diffout = fdopen (diff_fds[0], "r");
661 perror_fatal ("fdopen");
665 lf_init (&diff_filt, diffout);
666 lf_init (&lfilt, left);
667 lf_init (&rfilt, right);
669 interact_ok = interact (&diff_filt, &lfilt, lname, &rfilt, rname, out);
679 #if ! HAVE_WORKING_FORK
680 wstatus = pclose (diffout);
685 while (waitpid (diffpid, &wstatus, 0) < 0)
689 perror_fatal ("waitpid");
702 check_child_status (werrno, wstatus, EXIT_FAILURE, diffargv[0]);
705 exit (WEXITSTATUS (wstatus));
708 return EXIT_SUCCESS; /* Fool `-Wall'. */
712 diffarg (char const *a)
714 static size_t diffargs, diffarglim;
716 if (diffargs == diffarglim)
720 else if (PTRDIFF_MAX / (2 * sizeof *diffargv) <= diffarglim)
724 diffargv = xrealloc (diffargv, diffarglim * sizeof *diffargv);
726 diffargv[diffargs++] = a;
729 /* Signal handling */
731 static bool volatile ignore_SIGINT;
732 static int volatile signal_received;
733 static bool sigs_trapped;
741 if (! (s == SIGINT && ignore_SIGINT))
746 static struct sigaction catchaction;
749 signal_handler (int sig, void (*handler) (int))
751 catchaction.sa_handler = handler;
752 sigaction (sig, &catchaction, 0);
762 catchaction.sa_flags = SA_RESTART;
763 sigemptyset (&catchaction.sa_mask);
764 for (i = 0; i < NUM_SIGS; i++)
765 sigaddset (&catchaction.sa_mask, sigs[i]);
768 for (i = 0; i < NUM_SIGS; i++)
771 sigaction (sigs[i], 0, &initial_action[i]);
773 initial_action[i] = signal (sigs[i], SIG_IGN);
775 if (initial_handler (i) != SIG_IGN)
776 signal_handler (sigs[i], catchsig);
780 /* System V fork+wait does not work if SIGCHLD is ignored. */
781 signal (SIGCHLD, SIG_DFL);
787 /* Untrap signal S, or all trapped signals if S is zero. */
794 for (i = 0; i < NUM_SIGS; i++)
795 if ((! s || sigs[i] == s) && initial_handler (i) != SIG_IGN)
798 sigaction (sigs[i], &initial_action[i], 0);
800 signal (sigs[i], initial_action[i]);
805 /* Exit if a signal has been received. */
809 int s = signal_received;
814 /* Yield an exit status indicating that a signal was received. */
818 /* That didn't work, so exit with error status. */
826 fprintf (stderr, "%s", _("\
827 ed:\tEdit then use both versions, each decorated with a header.\n\
828 eb:\tEdit then use both versions.\n\
829 el or e1:\tEdit then use the left version.\n\
830 er or e2:\tEdit then use the right version.\n\
831 e:\tDiscard both versions then edit a new one.\n\
832 l or 1:\tUse the left version.\n\
833 r or 2:\tUse the right version.\n\
834 s:\tSilently include common lines.\n\
835 v:\tVerbosely include common lines.\n\
847 if (! isspace (c) || c == '\n')
852 perror_fatal (_("read failed"));
860 while ((c = getchar ()) != '\n' && c != EOF)
863 perror_fatal (_("read failed"));
867 /* interpret an edit command */
869 edit (struct line_filter *left, char const *lname, lin lline, lin llen,
870 struct line_filter *right, char const *rname, lin rline, lin rlen,
875 int cmd0 IF_LINT (= 0);
876 int cmd1 IF_LINT (= 0);
881 if (putchar ('%') != '%')
882 perror_fatal (_("write failed"));
885 cmd0 = skip_white ();
888 case '1': case '2': case 'l': case 'r':
889 case 's': case 'v': case 'q':
890 if (skip_white () != '\n')
900 cmd1 = skip_white ();
903 case '1': case '2': case 'b': case 'd': case 'l': case 'r':
904 if (skip_white () != '\n')
942 lf_copy (left, llen, outfile);
943 lf_skip (right, rlen);
946 lf_copy (right, rlen, outfile);
947 lf_skip (left, llen);
950 suppress_common_lines = true;
953 suppress_common_lines = false;
962 tmp = fopen (tmpname, "w");
965 if ((fd = temporary_file ()) < 0)
966 perror_fatal ("mkstemp");
967 tmp = fdopen (fd, "w");
971 perror_fatal (tmpname);
979 fprintf (tmp, "--- %s %ld\n", lname, (long int) lline);
981 fprintf (tmp, "--- %s %ld,%ld\n", lname,
983 (long int) (lline + llen - 1));
986 case '1': case 'b': case 'l':
987 lf_copy (left, llen, tmp);
991 lf_skip (left, llen);
1001 fprintf (tmp, "+++ %s %ld\n", rname, (long int) rline);
1003 fprintf (tmp, "+++ %s %ld,%ld\n", rname,
1005 (long int) (rline + rlen - 1));
1008 case '2': case 'b': case 'r':
1009 lf_copy (right, rlen, tmp);
1013 lf_skip (right, rlen);
1022 ignore_SIGINT = true;
1026 #if ! HAVE_WORKING_FORK
1028 xmalloc (shell_quote_length (editor_program)
1029 + 1 + strlen (tmpname) + 1);
1030 sprintf (shell_quote_copy (command, editor_program),
1032 wstatus = system (command);
1042 char const *argv[3];
1045 argv[i++] = editor_program;
1046 argv[i++] = tmpname;
1049 execvp (editor_program, (char **) argv);
1050 _exit (errno == ENOENT ? 127 : 126);
1054 perror_fatal ("fork");
1056 while (waitpid (pid, &wstatus, 0) < 0)
1060 perror_fatal ("waitpid");
1064 ignore_SIGINT = false;
1065 check_child_status (werrno, wstatus, EXIT_SUCCESS,
1070 char buf[SDIFF_BUFSIZE];
1072 tmp = ck_fopen (tmpname, "r");
1073 while ((size = ck_fread (buf, SDIFF_BUFSIZE, tmp)) != 0)
1076 ck_fwrite (buf, size, outfile);
1089 /* Alternately reveal bursts of diff output and handle user commands. */
1091 interact (struct line_filter *diff,
1092 struct line_filter *left, char const *lname,
1093 struct line_filter *right, char const *rname,
1096 lin lline = 1, rline = 1;
1100 char diff_help[256];
1101 int snarfed = lf_snarf (diff, diff_help, sizeof diff_help);
1104 return snarfed != 0;
1108 if (diff_help[0] == ' ')
1109 puts (diff_help + 1);
1114 lin llen, rlen, lenmax;
1116 llen = val = strtoumax (diff_help + 1, &numend, 10);
1117 if (llen < 0 || llen != val || errno || *numend != ',')
1119 rlen = val = strtoumax (numend + 1, &numend, 10);
1120 if (rlen < 0 || rlen != val || errno || *numend)
1123 lenmax = MAX (llen, rlen);
1125 switch (diff_help[0])
1128 if (suppress_common_lines)
1129 lf_skip (diff, lenmax);
1131 lf_copy (diff, lenmax, stdout);
1133 lf_copy (left, llen, outfile);
1134 lf_skip (right, rlen);
1138 lf_copy (diff, lenmax, stdout);
1139 if (! edit (left, lname, lline, llen,
1140 right, rname, rline, rlen,
1155 /* Return true if DIR is an existing directory. */
1157 diraccess (char const *dir)
1160 return stat (dir, &buf) == 0 && S_ISDIR (buf.st_mode);
1164 # define P_tmpdir "/tmp"
1167 # define TMPDIR_ENV "TMPDIR"
1170 /* Open a temporary file and return its file descriptor. Put into
1171 tmpname the address of a newly allocated buffer that holds the
1172 file's name. Use the prefix "sdiff". */
1174 temporary_file (void)
1176 char const *tmpdir = getenv (TMPDIR_ENV);
1177 char const *dir = tmpdir ? tmpdir : P_tmpdir;
1178 char *buf = xmalloc (strlen (dir) + 1 + 5 + 6 + 1);
1183 sprintf (buf, "%s/sdiffXXXXXX", dir);
1184 sigemptyset (&blocked);
1185 sigaddset (&blocked, SIGINT);
1186 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1191 sigprocmask (SIG_SETMASK, &procmask, 0);