1 /* sdiff - side-by-side merge of file differences
3 Copyright (C) 1992-1996, 1998, 2001-2002, 2004, 2006-2007, 2009-2013 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>
34 #include <system-quote.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 static int const sigs[] = {
92 NUM_SIGS = sizeof sigs / sizeof *sigs,
93 handler_index_of_SIGINT = NUM_SIGS - 1
97 /* Prefer 'sigaction' if available, since 'signal' can lose signals. */
98 static struct sigaction initial_action[NUM_SIGS];
99 # define initial_handler(i) (initial_action[i].sa_handler)
100 static void signal_handler (int, void (*) (int));
102 static void (*initial_action[NUM_SIGS]) ();
103 # define initial_handler(i) (initial_action[i])
104 # define signal_handler(sig, handler) signal (sig, handler)
107 static bool diraccess (char const *);
108 static int temporary_file (void);
112 /* Name of output file if -o specified. */
113 static char const *output;
115 /* Do not print common lines. */
116 static bool suppress_common_lines;
118 /* Value for the long option that does not have single-letter equivalents. */
121 DIFF_PROGRAM_OPTION = CHAR_MAX + 1,
123 STRIP_TRAILING_CR_OPTION,
127 static struct option const longopts[] =
129 {"diff-program", 1, 0, DIFF_PROGRAM_OPTION},
130 {"expand-tabs", 0, 0, 't'},
131 {"help", 0, 0, HELP_OPTION},
132 {"ignore-all-space", 0, 0, 'W'}, /* swap W and w for historical reasons */
133 {"ignore-blank-lines", 0, 0, 'B'},
134 {"ignore-case", 0, 0, 'i'},
135 {"ignore-matching-lines", 1, 0, 'I'},
136 {"ignore-space-change", 0, 0, 'b'},
137 {"ignore-tab-expansion", 0, 0, 'E'},
138 {"ignore-trailing-space", 0, 0, 'Z'},
139 {"left-column", 0, 0, 'l'},
140 {"minimal", 0, 0, 'd'},
141 {"output", 1, 0, 'o'},
142 {"speed-large-files", 0, 0, 'H'},
143 {"strip-trailing-cr", 0, 0, STRIP_TRAILING_CR_OPTION},
144 {"suppress-common-lines", 0, 0, 's'},
145 {"tabsize", 1, 0, TABSIZE_OPTION},
147 {"version", 0, 0, 'v'},
148 {"width", 1, 0, 'w'},
152 static void try_help (char const *, char const *) __attribute__((noreturn));
154 try_help (char const *reason_msgid, char const *operand)
157 error (0, 0, _(reason_msgid), operand);
158 error (EXIT_TROUBLE, 0, _("Try '%s --help' for more information."),
167 fatal ("write failed");
168 else if (fclose (stdout) != 0)
169 perror_fatal (_("standard output"));
172 static char const * const option_help_msgid[] = {
173 N_("-o, --output=FILE operate interactively, sending output to FILE"),
175 N_("-i, --ignore-case consider upper- and lower-case to be the same"),
176 N_("-E, --ignore-tab-expansion ignore changes due to tab expansion"),
177 N_("-Z, --ignore-trailing-space ignore white space at line end"),
178 N_("-b, --ignore-space-change ignore changes in the amount of white space"),
179 N_("-W, --ignore-all-space ignore all white space"),
180 N_("-B, --ignore-blank-lines ignore changes whose lines are all blank"),
181 N_("-I, --ignore-matching-lines=RE ignore changes all whose lines match RE"),
182 N_(" --strip-trailing-cr strip trailing carriage return on input"),
183 N_("-a, --text treat all files as text"),
185 N_("-w, --width=NUM output at most NUM (default 130) print columns"),
186 N_("-l, --left-column output only the left column of common lines"),
187 N_("-s, --suppress-common-lines do not output common lines"),
189 N_("-t, --expand-tabs expand tabs to spaces in output"),
190 N_(" --tabsize=NUM tab stops at every NUM (default 8) print columns"),
192 N_("-d, --minimal try hard to find a smaller set of changes"),
193 N_("-H, --speed-large-files assume large files, many scattered small changes"),
194 N_(" --diff-program=PROGRAM use PROGRAM to compare files"),
196 N_(" --help display this help and exit"),
197 N_("-v, --version output version information and exit"),
204 char const * const *p;
206 printf (_("Usage: %s [OPTION]... FILE1 FILE2\n"), program_name);
208 _("Side-by-side merge of differences between FILE1 and FILE2."));
211 Mandatory arguments to long options are mandatory for short options too.\n\
213 for (p = option_help_msgid; *p; p++)
215 printf (" %s\n", _(*p));
218 printf ("\n%s\n%s\n",
219 _("If a FILE is '-', read standard input."),
220 _("Exit status is 0 if inputs are the same, 1 if different, 2 if trouble."));
221 emit_bug_reporting_address ();
224 /* Clean up after a signal or other failure. This function is
225 async-signal-safe. */
227 cleanup (int signo __attribute__((unused)))
229 #if HAVE_WORKING_FORK
231 kill (diffpid, SIGPIPE);
237 static void exiterr (void) __attribute__((noreturn));
248 fatal (char const *msgid)
250 error (0, 0, "%s", _(msgid));
255 perror_fatal (char const *msg)
259 error (0, e, "%s", msg);
264 check_child_status (int werrno, int wstatus, int max_ok_status,
265 char const *subsidiary_program)
267 int status = (! werrno && WIFEXITED (wstatus)
268 ? WEXITSTATUS (wstatus)
271 if (max_ok_status < status)
275 ? "subsidiary program '%s' could not be invoked"
277 ? "subsidiary program '%s' not found"
279 ? "subsidiary program '%s' failed"
280 : "subsidiary program '%s' failed (exit status %d)"),
281 subsidiary_program, status);
287 ck_fopen (char const *fname, char const *type)
289 FILE *r = fopen (fname, type);
291 perror_fatal (fname);
299 perror_fatal ("fclose");
303 ck_fread (char *buf, size_t size, FILE *f)
305 size_t r = fread (buf, sizeof (char), size, f);
306 if (r == 0 && ferror (f))
307 perror_fatal (_("read failed"));
312 ck_fwrite (char const *buf, size_t size, FILE *f)
314 if (fwrite (buf, sizeof (char), size, f) != size)
315 perror_fatal (_("write failed"));
322 perror_fatal (_("write failed"));
326 expand_name (char *name, bool is_dir, char const *other_name)
328 if (STREQ (name, "-"))
329 fatal ("cannot interactively merge standard input");
334 /* Yield NAME/BASE, where BASE is OTHER_NAME's basename. */
335 char const *base = last_component (other_name);
336 size_t namelen = strlen (name), baselen = base_len (base);
337 bool insert_slash = *last_component (name) && name[namelen - 1] != '/';
338 char *r = xmalloc (namelen + insert_slash + baselen + 1);
339 memcpy (r, name, namelen);
341 memcpy (r + namelen + insert_slash, base, baselen);
342 r[namelen + insert_slash + baselen] = '\0';
355 lf_init (struct line_filter *lf, FILE *infile)
358 lf->bufpos = lf->buffer = lf->buflim = xmalloc (SDIFF_BUFSIZE + 1);
359 lf->buflim[0] = '\n';
362 /* Fill an exhausted line_filter buffer from its INFILE */
364 lf_refill (struct line_filter *lf)
366 size_t s = ck_fread (lf->buffer, SDIFF_BUFSIZE, lf->infile);
367 lf->bufpos = lf->buffer;
368 lf->buflim = lf->buffer + s;
369 lf->buflim[0] = '\n';
374 /* Advance LINES on LF's infile, copying lines to OUTFILE */
376 lf_copy (struct line_filter *lf, lin lines, FILE *outfile)
378 char *start = lf->bufpos;
382 lf->bufpos = (char *) memchr (lf->bufpos, '\n', lf->buflim - lf->bufpos);
385 ck_fwrite (start, lf->buflim - start, outfile);
386 if (! lf_refill (lf))
397 ck_fwrite (start, lf->bufpos - start, outfile);
400 /* Advance LINES on LF's infile without doing output */
402 lf_skip (struct line_filter *lf, lin lines)
406 lf->bufpos = (char *) memchr (lf->bufpos, '\n', lf->buflim - lf->bufpos);
409 if (! lf_refill (lf))
420 /* Snarf a line into a buffer. Return EOF if EOF, 0 if error, 1 if OK. */
422 lf_snarf (struct line_filter *lf, char *buffer, size_t bufsize)
426 char *start = lf->bufpos;
427 char *next = (char *) memchr (start, '\n', lf->buflim + 1 - start);
428 size_t s = next - start;
431 memcpy (buffer, start, s);
432 if (next < lf->buflim)
435 lf->bufpos = next + 1;
438 if (! lf_refill (lf))
446 main (int argc, char *argv[])
451 exit_failure = EXIT_TROUBLE;
452 initialize_main (&argc, &argv);
453 set_program_name (argv[0]);
454 setlocale (LC_ALL, "");
455 textdomain (PACKAGE);
456 c_stack_action (cleanup);
458 prog = getenv ("EDITOR");
460 editor_program = prog;
462 diffarg (DEFAULT_DIFF_PROGRAM);
464 /* parse command line args */
465 while ((opt = getopt_long (argc, argv, "abBdEHiI:lo:stvw:WZ", longopts, 0))
504 diffarg ("--left-column");
512 suppress_common_lines = true;
520 version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version,
521 AUTHORS, (char *) NULL);
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
612 char *command = system_quote_argv (SCI_SYSTEM, (char **) diffargv);
614 diffout = popen (command, "r");
616 perror_fatal (command);
623 if (pipe (diff_fds) != 0)
624 perror_fatal ("pipe");
628 perror_fatal ("fork");
631 /* Alter the child's SIGINT and SIGPIPE handlers;
632 this may munge the parent.
633 The child ignores SIGINT in case the user interrupts the editor.
634 The child does not ignore SIGPIPE, even if the parent does. */
635 if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
636 signal_handler (SIGINT, SIG_IGN);
637 signal_handler (SIGPIPE, SIG_DFL);
639 if (diff_fds[1] != STDOUT_FILENO)
641 dup2 (diff_fds[1], STDOUT_FILENO);
645 execvp (diffargv[0], (char **) diffargv);
646 _exit (errno == ENOENT ? 127 : 126);
650 diffout = fdopen (diff_fds[0], "r");
652 perror_fatal ("fdopen");
656 lf_init (&diff_filt, diffout);
657 lf_init (&lfilt, left);
658 lf_init (&rfilt, right);
660 interact_ok = interact (&diff_filt, &lfilt, lname, &rfilt, rname, out);
670 #if ! HAVE_WORKING_FORK
671 wstatus = pclose (diffout);
676 while (waitpid (diffpid, &wstatus, 0) < 0)
680 perror_fatal ("waitpid");
693 check_child_status (werrno, wstatus, EXIT_FAILURE, diffargv[0]);
696 exit (WEXITSTATUS (wstatus));
699 return EXIT_SUCCESS; /* Fool '-Wall'. */
703 diffarg (char const *a)
705 static size_t diffargs, diffarglim;
707 if (diffargs == diffarglim)
711 else if (PTRDIFF_MAX / (2 * sizeof *diffargv) <= diffarglim)
715 diffargv = xrealloc (diffargv, diffarglim * sizeof *diffargv);
717 diffargv[diffargs++] = a;
720 /* Signal handling */
722 static bool volatile ignore_SIGINT;
723 static int volatile signal_received;
724 static bool sigs_trapped;
732 if (! (s == SIGINT && ignore_SIGINT))
737 static struct sigaction catchaction;
740 signal_handler (int sig, void (*handler) (int))
742 catchaction.sa_handler = handler;
743 sigaction (sig, &catchaction, 0);
753 catchaction.sa_flags = SA_RESTART;
754 sigemptyset (&catchaction.sa_mask);
755 for (i = 0; i < NUM_SIGS; i++)
756 sigaddset (&catchaction.sa_mask, sigs[i]);
759 for (i = 0; i < NUM_SIGS; i++)
762 sigaction (sigs[i], 0, &initial_action[i]);
764 initial_action[i] = signal (sigs[i], SIG_IGN);
766 if (initial_handler (i) != SIG_IGN)
767 signal_handler (sigs[i], catchsig);
771 /* System V fork+wait does not work if SIGCHLD is ignored. */
772 signal (SIGCHLD, SIG_DFL);
778 /* Untrap signal S, or all trapped signals if S is zero. */
785 for (i = 0; i < NUM_SIGS; i++)
786 if ((! s || sigs[i] == s) && initial_handler (i) != SIG_IGN)
789 sigaction (sigs[i], &initial_action[i], 0);
791 signal (sigs[i], initial_action[i]);
796 /* Exit if a signal has been received. */
800 int s = signal_received;
805 /* Yield an exit status indicating that a signal was received. */
809 /* That didn't work, so exit with error status. */
817 fprintf (stderr, "%s", _("\
818 ed:\tEdit then use both versions, each decorated with a header.\n\
819 eb:\tEdit then use both versions.\n\
820 el or e1:\tEdit then use the left version.\n\
821 er or e2:\tEdit then use the right version.\n\
822 e:\tDiscard both versions then edit a new one.\n\
823 l or 1:\tUse the left version.\n\
824 r or 2:\tUse the right version.\n\
825 s:\tSilently include common lines.\n\
826 v:\tVerbosely include common lines.\n\
838 if (! isspace (c) || c == '\n')
843 perror_fatal (_("read failed"));
851 while ((c = getchar ()) != '\n' && c != EOF)
854 perror_fatal (_("read failed"));
858 /* interpret an edit command */
860 edit (struct line_filter *left, char const *lname, lin lline, lin llen,
861 struct line_filter *right, char const *rname, lin rline, lin rlen,
866 int cmd0 IF_LINT (= 0);
867 int cmd1 IF_LINT (= 0);
872 if (putchar ('%') != '%')
873 perror_fatal (_("write failed"));
876 cmd0 = skip_white ();
879 case '1': case '2': case 'l': case 'r':
880 case 's': case 'v': case 'q':
881 if (skip_white () != '\n')
891 cmd1 = skip_white ();
894 case '1': case '2': case 'b': case 'd': case 'l': case 'r':
895 if (skip_white () != '\n')
933 lf_copy (left, llen, outfile);
934 lf_skip (right, rlen);
937 lf_copy (right, rlen, outfile);
938 lf_skip (left, llen);
941 suppress_common_lines = true;
944 suppress_common_lines = false;
953 tmp = fopen (tmpname, "w");
956 if ((fd = temporary_file ()) < 0)
957 perror_fatal ("mkstemp");
958 tmp = fdopen (fd, "w");
962 perror_fatal (tmpname);
970 fprintf (tmp, "--- %s %ld\n", lname, (long int) lline);
972 fprintf (tmp, "--- %s %ld,%ld\n", lname,
974 (long int) (lline + llen - 1));
977 case '1': case 'b': case 'l':
978 lf_copy (left, llen, tmp);
982 lf_skip (left, llen);
992 fprintf (tmp, "+++ %s %ld\n", rname, (long int) rline);
994 fprintf (tmp, "+++ %s %ld,%ld\n", rname,
996 (long int) (rline + rlen - 1));
999 case '2': case 'b': case 'r':
1000 lf_copy (right, rlen, tmp);
1004 lf_skip (right, rlen);
1013 char const *argv[3];
1015 ignore_SIGINT = true;
1017 argv[0] = editor_program;
1022 #if ! HAVE_WORKING_FORK
1023 char *command = system_quote_argv (SCI_SYSTEM, (char **) argv);
1024 wstatus = system (command);
1034 execvp (editor_program, (char **) argv);
1035 _exit (errno == ENOENT ? 127 : 126);
1039 perror_fatal ("fork");
1041 while (waitpid (pid, &wstatus, 0) < 0)
1045 perror_fatal ("waitpid");
1049 ignore_SIGINT = false;
1050 check_child_status (werrno, wstatus, EXIT_SUCCESS,
1055 char buf[SDIFF_BUFSIZE];
1057 tmp = ck_fopen (tmpname, "r");
1058 while ((size = ck_fread (buf, SDIFF_BUFSIZE, tmp)) != 0)
1061 ck_fwrite (buf, size, outfile);
1074 /* Alternately reveal bursts of diff output and handle user commands. */
1076 interact (struct line_filter *diff,
1077 struct line_filter *left, char const *lname,
1078 struct line_filter *right, char const *rname,
1081 lin lline = 1, rline = 1;
1085 char diff_help[256];
1086 int snarfed = lf_snarf (diff, diff_help, sizeof diff_help);
1089 return snarfed != 0;
1093 if (diff_help[0] == ' ')
1094 puts (diff_help + 1);
1099 lin llen, rlen, lenmax;
1101 llen = val = strtoumax (diff_help + 1, &numend, 10);
1102 if (llen < 0 || llen != val || errno || *numend != ',')
1104 rlen = val = strtoumax (numend + 1, &numend, 10);
1105 if (rlen < 0 || rlen != val || errno || *numend)
1108 lenmax = MAX (llen, rlen);
1110 switch (diff_help[0])
1113 if (suppress_common_lines)
1114 lf_skip (diff, lenmax);
1116 lf_copy (diff, lenmax, stdout);
1118 lf_copy (left, llen, outfile);
1119 lf_skip (right, rlen);
1123 lf_copy (diff, lenmax, stdout);
1124 if (! edit (left, lname, lline, llen,
1125 right, rname, rline, rlen,
1140 /* Return true if DIR is an existing directory. */
1142 diraccess (char const *dir)
1145 return stat (dir, &buf) == 0 && S_ISDIR (buf.st_mode);
1149 # define P_tmpdir "/tmp"
1152 # define TMPDIR_ENV "TMPDIR"
1155 /* Open a temporary file and return its file descriptor. Put into
1156 tmpname the address of a newly allocated buffer that holds the
1157 file's name. Use the prefix "sdiff". */
1159 temporary_file (void)
1161 char const *tmpdir = getenv (TMPDIR_ENV);
1162 char const *dir = tmpdir ? tmpdir : P_tmpdir;
1163 char *buf = xmalloc (strlen (dir) + 1 + 5 + 6 + 1);
1165 sprintf (buf, "%s/sdiffXXXXXX", dir);