doc: rewrite the "Unusual File Names" section
[diffutils.git] / src / sdiff.c
blob07b4510c17876d07fef7f017b5dd3e2ae4106061
1 /* GNU sdiff - side-by-side merge of file differences
3 Copyright (C) 1992-1996, 1998, 2001-2002, 2004, 2006-2007, 2009-2013,
4 2015-2025 Free 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/>. */
21 #include "system.h"
22 #include "paths.h"
24 #include <stdio.h>
25 #include <unlocked-io.h>
27 #include <c-ctype.h>
28 #include <c-stack.h>
29 #include <dirname.h>
30 #include <diagnose.h>
31 #include <error.h>
32 #include <exitfail.h>
33 #include <file-type.h>
34 #include <getopt.h>
35 #include <progname.h>
36 #include <quote.h>
37 #include <system-quote.h>
38 #include <version-etc.h>
39 #include <xalloc.h>
40 #include <xstdopen.h>
42 /* The official name of this program (e.g., no 'g' prefix). */
43 static char const PROGRAM_NAME[] = "sdiff";
45 #define AUTHORS \
46 _("Thomas Lord")
48 /* Size of chunks read from files which must be parsed into lines. */
49 enum { SDIFF_BUFSIZE = 65536 };
51 static char const *editor_program = DEFAULT_EDITOR_PROGRAM;
52 static char const **diffargv;
54 static char *volatile tmpname;
55 static FILE *tmp;
57 #if HAVE_WORKING_FORK
58 static pid_t volatile diffpid;
59 #endif
61 struct line_filter;
63 static void catchsig (int);
64 static bool edit (struct line_filter *, char const *, lin, lin, struct line_filter *, char const *, lin, lin, FILE *);
65 static bool interact (struct line_filter *, struct line_filter *, char const *, struct line_filter *, char const *, FILE *);
66 static void checksigs (void);
67 static void diffarg (char const *);
68 static _Noreturn void fatal (char const *);
69 static _Noreturn void perror_fatal (char const *);
70 static void trapsigs (void);
71 static void untrapsig (int);
73 static int const sigs[] = {
74 #ifdef SIGHUP
75 SIGHUP,
76 #endif
77 #ifdef SIGQUIT
78 SIGQUIT,
79 #endif
80 #ifdef SIGTERM
81 SIGTERM,
82 #endif
83 #ifdef SIGXCPU
84 SIGXCPU,
85 #endif
86 #ifdef SIGXFSZ
87 SIGXFSZ,
88 #endif
89 #ifdef SIGPIPE
90 SIGPIPE,
91 #endif
92 SIGINT
94 enum
96 NUM_SIGS = sizeof sigs / sizeof *sigs,
97 handler_index_of_SIGINT = NUM_SIGS - 1
100 typedef void (*sighandler) (int);
101 static void signal_handler (int, sighandler);
103 #if HAVE_SIGACTION
104 /* Prefer 'sigaction' if available, since 'signal' can lose signals. */
105 static struct sigaction initial_action[NUM_SIGS];
106 static sighandler
107 initial_handler (int i)
109 return initial_action[i].sa_handler;
111 #else
112 static sighandler initial_action[NUM_SIGS];
113 static sighandler
114 initial_handler (int i)
116 return initial_action[i];
118 #endif
120 static bool diraccess (char const *);
121 static int temporary_file (void);
123 /* Options: */
125 /* Name of output file if -o specified. */
126 static char const *output;
128 /* Do not print common lines. */
129 static bool suppress_common_lines;
131 /* Value for the long option that does not have single-letter equivalents. */
132 enum
134 DIFF_PROGRAM_OPTION = CHAR_MAX + 1,
135 HELP_OPTION,
136 STRIP_TRAILING_CR_OPTION,
137 TABSIZE_OPTION
140 static char const shortopts[] = "abBdEHiI:lo:stvw:WZ";
141 static struct option const longopts[] =
143 {"diff-program", 1, 0, DIFF_PROGRAM_OPTION},
144 {"expand-tabs", 0, 0, 't'},
145 {"help", 0, 0, HELP_OPTION},
146 {"ignore-all-space", 0, 0, 'W'}, /* swap W and w for historical reasons */
147 {"ignore-blank-lines", 0, 0, 'B'},
148 {"ignore-case", 0, 0, 'i'},
149 {"ignore-matching-lines", 1, 0, 'I'},
150 {"ignore-space-change", 0, 0, 'b'},
151 {"ignore-tab-expansion", 0, 0, 'E'},
152 {"ignore-trailing-space", 0, 0, 'Z'},
153 {"left-column", 0, 0, 'l'},
154 {"minimal", 0, 0, 'd'},
155 {"output", 1, 0, 'o'},
156 {"speed-large-files", 0, 0, 'H'},
157 {"strip-trailing-cr", 0, 0, STRIP_TRAILING_CR_OPTION},
158 {"suppress-common-lines", 0, 0, 's'},
159 {"tabsize", 1, 0, TABSIZE_OPTION},
160 {"text", 0, 0, 'a'},
161 {"version", 0, 0, 'v'},
162 {"width", 1, 0, 'w'},
163 {0, 0, 0, 0}
166 static void
167 check_stdout (void)
169 if (ferror (stdout))
170 fatal ("write failed");
171 else if (fclose (stdout) != 0)
172 perror_fatal (_("standard output"));
175 static char const *const option_help_msgid[] = {
176 N_("-o, --output=FILE operate interactively, sending output to FILE"),
178 N_("-i, --ignore-case consider upper- and lower-case to be the same"),
179 N_("-E, --ignore-tab-expansion ignore changes due to tab expansion"),
180 N_("-Z, --ignore-trailing-space ignore white space at line end"),
181 N_("-b, --ignore-space-change ignore changes in the amount of white space"),
182 N_("-W, --ignore-all-space ignore all white space"),
183 N_("-B, --ignore-blank-lines ignore changes whose lines are all blank"),
184 N_("-I, --ignore-matching-lines=RE ignore changes all whose lines match RE"),
185 N_(" --strip-trailing-cr strip trailing carriage return on input"),
186 N_("-a, --text treat all files as text"),
188 N_("-w, --width=NUM output at most NUM (default 130) print columns"),
189 N_("-l, --left-column output only the left column of common lines"),
190 N_("-s, --suppress-common-lines do not output common lines"),
192 N_("-t, --expand-tabs expand tabs to spaces in output"),
193 N_(" --tabsize=NUM tab stops at every NUM (default 8) print columns"),
195 N_("-d, --minimal try hard to find a smaller set of changes"),
196 N_("-H, --speed-large-files assume large files, many scattered small changes"),
197 N_(" --diff-program=PROGRAM use PROGRAM to compare files"),
199 N_(" --help display this help and exit"),
200 N_("-v, --version output version information and exit"),
201 nullptr
204 static void
205 usage (void)
207 printf (_("Usage: %s [OPTION]... FILE1 FILE2\n"), squote (0, program_name));
208 printf ("%s\n\n",
209 _("Side-by-side merge of differences between FILE1 and FILE2."));
211 fputs (_("\
212 Mandatory arguments to long options are mandatory for short options too.\n\
213 "), stdout);
214 for (char const *const *p = option_help_msgid; *p; p++)
215 if (**p)
216 printf (" %s\n", _(*p));
217 else
218 putchar ('\n');
219 printf ("\n%s\n%s\n",
220 _("If a FILE is '-', read standard input."),
221 _("Exit status is 0 if inputs are the same, 1 if different, 2 if trouble."));
222 emit_bug_reporting_address ();
225 /* Clean up after a signal or other failure. This function is
226 async-signal-safe. */
227 static void
228 cleanup (_GL_UNUSED int signo)
230 #if HAVE_WORKING_FORK
231 if (0 < diffpid)
232 kill (diffpid, SIGPIPE);
233 #endif
234 if (tmpname)
235 unlink (tmpname);
238 static _Noreturn void
239 exiterr (void)
241 cleanup (0);
242 untrapsig (0);
243 checksigs ();
244 exit (EXIT_TROUBLE);
247 static void
248 fatal (char const *msgid)
250 error (0, 0, "%s", _(msgid));
251 exiterr ();
254 static void
255 perror_fatal (char const *msg)
257 int e = errno;
258 checksigs ();
259 error (0, e, "%s", msg);
260 exiterr ();
263 static void
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)
269 : INT_MAX);
271 if (max_ok_status < status)
273 error (0, werrno,
274 _(status == 126
275 ? "subsidiary program %s could not be invoked"
276 : status == 127
277 ? "subsidiary program %s not found"
278 : status == INT_MAX
279 ? "subsidiary program %s failed"
280 : "subsidiary program %s failed (exit status %d)"),
281 quote (subsidiary_program), status);
282 exiterr ();
286 static FILE *
287 ck_fopen (char const *fname, char const *type)
289 FILE *r = fopen (fname, type);
290 if (! r)
291 perror_fatal (squote (0, fname));
292 return r;
295 static void
296 ck_fclose (FILE *f)
298 if (fclose (f))
299 perror_fatal ("fclose");
302 static idx_t
303 ck_fread (char *buf, idx_t size, FILE *f)
305 idx_t r = fread (buf, sizeof (char), size, f);
306 if (r == 0 && ferror (f))
307 perror_fatal (_("read failed"));
308 return r;
311 static void
312 ck_fwrite (char const *buf, idx_t size, FILE *f)
314 if (fwrite (buf, sizeof (char), size, f) != size)
315 perror_fatal (_("write failed"));
318 static void
319 ck_fflush (FILE *f)
321 if (fflush (f) != 0)
322 perror_fatal (_("write failed"));
325 static char const *
326 expand_name (char *name, bool is_dir, char const *other_name)
328 if (STREQ (name, "-"))
329 fatal ("cannot interactively merge standard input");
330 if (! is_dir)
331 return name;
332 else
334 /* Yield NAME/BASE, where BASE is OTHER_NAME's basename. */
335 char const *base = last_component (other_name);
336 idx_t namelen = strlen (name), baselen = base_len (base);
337 bool insert_slash = *last_component (name) && name[namelen - 1] != '/';
338 char *r = ximalloc (namelen + insert_slash + baselen + 1);
339 char *p = stpcpy (r, name);
340 *p = '/';
341 p = mempcpy (p + insert_slash, base, baselen);
342 *p = '\0';
343 return r;
347 struct line_filter {
348 FILE *infile;
349 char *bufpos;
350 char *buffer;
351 char *buflim;
354 static void
355 lf_init (struct line_filter *lf, FILE *infile)
357 lf->infile = infile;
358 lf->bufpos = lf->buffer = lf->buflim = ximalloc (SDIFF_BUFSIZE + 1);
359 lf->buflim[0] = '\n';
362 /* Fill an exhausted line_filter buffer from its INFILE */
363 static idx_t
364 lf_refill (struct line_filter *lf)
366 idx_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';
370 checksigs ();
371 return s;
374 /* Advance LINES on LF's infile, copying lines to OUTFILE */
375 static void
376 lf_copy (struct line_filter *lf, lin lines, FILE *outfile)
378 char *start = lf->bufpos;
380 while (lines)
382 lf->bufpos = rawmemchr (lf->bufpos, '\n');
383 if (lf->bufpos == lf->buflim)
385 ck_fwrite (start, lf->buflim - start, outfile);
386 if (! lf_refill (lf))
387 return;
388 start = lf->bufpos;
390 else
392 --lines;
393 ++lf->bufpos;
397 ck_fwrite (start, lf->bufpos - start, outfile);
400 /* Advance LINES on LF's infile without doing output */
401 static void
402 lf_skip (struct line_filter *lf, lin lines)
404 while (lines)
406 lf->bufpos = rawmemchr (lf->bufpos, '\n');
407 if (lf->bufpos == lf->buflim)
409 if (! lf_refill (lf))
410 break;
412 else
414 --lines;
415 ++lf->bufpos;
420 /* Snarf a line into a buffer. Return EOF if EOF, 0 if error, 1 if OK. */
421 static int
422 lf_snarf (struct line_filter *lf, char *buffer, idx_t bufsize)
424 for (;;)
426 char *start = lf->bufpos;
427 char *next = rawmemchr (start, '\n');
428 idx_t s = next - start;
429 if (bufsize <= s)
430 return 0;
431 buffer = mempcpy (buffer, start, s);
432 bufsize -= s;
433 if (next < lf->buflim)
435 *buffer = '\0';
436 lf->bufpos = next + 1;
437 return 1;
439 if (! lf_refill (lf))
440 return s ? 0 : EOF;
445 main (int argc, char *argv[])
447 exit_failure = EXIT_TROUBLE;
448 initialize_main (&argc, &argv);
449 set_program_name (argv[0]);
450 setlocale (LC_ALL, "");
451 bindtextdomain (PACKAGE, LOCALEDIR);
452 textdomain (PACKAGE);
453 c_stack_action (cleanup);
454 xstdopen ();
456 char const *prog = getenv ("EDITOR");
457 if (prog)
458 editor_program = prog;
460 diffarg (DEFAULT_DIFF_PROGRAM);
462 /* Parse command line options. */
464 for (int c;
465 0 <= (c = getopt_long (argc, argv, shortopts, longopts, 0)); )
466 switch (c)
468 case 'a':
469 diffarg ("-a");
470 break;
472 case 'b':
473 diffarg ("-b");
474 break;
476 case 'B':
477 diffarg ("-B");
478 break;
480 case 'd':
481 diffarg ("-d");
482 break;
484 case 'E':
485 diffarg ("-E");
486 break;
488 case 'H':
489 diffarg ("-H");
490 break;
492 case 'i':
493 diffarg ("-i");
494 break;
496 case 'I':
497 diffarg ("-I");
498 diffarg (optarg);
499 break;
501 case 'l':
502 diffarg ("--left-column");
503 break;
505 case 'o':
506 output = optarg;
507 break;
509 case 's':
510 suppress_common_lines = true;
511 break;
513 case 't':
514 diffarg ("-t");
515 break;
517 case 'v':
518 version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version,
519 AUTHORS, nullptr);
520 check_stdout ();
521 return EXIT_SUCCESS;
523 case 'w':
524 diffarg ("-W");
525 diffarg (optarg);
526 break;
528 case 'W':
529 diffarg ("-w");
530 break;
532 case 'Z':
533 diffarg ("-Z");
534 break;
536 case DIFF_PROGRAM_OPTION:
537 diffargv[0] = optarg;
538 break;
540 case HELP_OPTION:
541 usage ();
542 check_stdout ();
543 return EXIT_SUCCESS;
545 case STRIP_TRAILING_CR_OPTION:
546 diffarg ("--strip-trailing-cr");
547 break;
549 case TABSIZE_OPTION:
550 diffarg ("--tabsize");
551 diffarg (optarg);
552 break;
554 default:
555 try_help (nullptr, nullptr);
558 if (argc - optind != 2)
560 if (argc - optind < 2)
561 try_help ("missing operand after %s", quote (argv[argc - 1]));
562 else
563 try_help ("extra operand %s", quote (argv[optind + 2]));
566 if (! output)
568 /* easy case: diff does everything for us */
569 if (suppress_common_lines)
570 diffarg ("--suppress-common-lines");
571 diffarg ("-y");
572 diffarg ("--");
573 diffarg (argv[optind]);
574 diffarg (argv[optind + 1]);
575 diffarg (nullptr);
576 execvp (diffargv[0], (char **) diffargv);
577 perror_fatal (squote (0, diffargv[0]));
579 else
581 bool leftdir = diraccess (argv[optind]);
582 bool rightdir = diraccess (argv[optind + 1]);
584 if (leftdir & rightdir)
585 fatal ("both files to be compared are directories");
587 char const *lname
588 = expand_name (argv[optind], leftdir, argv[optind + 1]);
589 char const *rname
590 = expand_name (argv[optind + 1], rightdir, argv[optind]);
591 FILE *left = ck_fopen (lname, "re");
592 FILE *right = ck_fopen (rname, "re");
593 FILE *out = ck_fopen (output, "we");
595 diffarg ("--sdiff-merge-assist");
596 diffarg ("--");
597 diffarg (argv[optind]);
598 diffarg (argv[optind + 1]);
599 diffarg (nullptr);
601 trapsigs ();
603 FILE *diffout;
604 #if ! HAVE_WORKING_FORK
606 char *command = system_quote_argv (SCI_SYSTEM, (char **) diffargv);
607 errno = 0;
608 diffout = popen (command, "r");
609 if (! diffout)
610 perror_fatal (command);
611 free (command);
613 #else
615 int diff_fds[2];
617 if (pipe (diff_fds) != 0)
618 perror_fatal ("pipe");
620 diffpid = fork ();
621 if (diffpid < 0)
622 perror_fatal ("fork");
623 if (! diffpid)
625 /* Alter the child's SIGINT and SIGPIPE handlers;
626 this may munge the parent.
627 The child ignores SIGINT in case the user interrupts the editor.
628 The child does not ignore SIGPIPE, even if the parent does. */
629 if (initial_handler (handler_index_of_SIGINT) != SIG_IGN)
630 signal_handler (SIGINT, SIG_IGN);
631 signal_handler (SIGPIPE, SIG_DFL);
632 close (diff_fds[0]);
633 if (diff_fds[1] != STDOUT_FILENO)
635 dup2 (diff_fds[1], STDOUT_FILENO);
636 close (diff_fds[1]);
639 execvp (diffargv[0], (char **) diffargv);
640 _exit (errno == ENOENT ? 127 : 126);
643 close (diff_fds[1]);
644 diffout = fdopen (diff_fds[0], "r");
645 if (! diffout)
646 perror_fatal ("fdopen");
648 #endif
650 struct line_filter lfilt, rfilt, diff_filt;
651 lf_init (&diff_filt, diffout);
652 lf_init (&lfilt, left);
653 lf_init (&rfilt, right);
655 bool interact_ok
656 = interact (&diff_filt, &lfilt, lname, &rfilt, rname, out);
658 ck_fclose (left);
659 ck_fclose (right);
660 ck_fclose (out);
663 int wstatus;
664 int werrno = 0;
666 #if ! HAVE_WORKING_FORK
667 wstatus = pclose (diffout);
668 if (wstatus == -1)
669 werrno = errno;
670 #else
671 ck_fclose (diffout);
672 while (waitpid (diffpid, &wstatus, 0) < 0)
673 if (errno == EINTR)
674 checksigs ();
675 else
676 perror_fatal ("waitpid");
677 diffpid = 0;
678 #endif
680 if (tmpname)
682 unlink (tmpname);
683 tmpname = nullptr;
686 if (! interact_ok)
687 exiterr ();
689 check_child_status (werrno, wstatus, EXIT_FAILURE, diffargv[0]);
690 untrapsig (0);
691 checksigs ();
692 exit (WEXITSTATUS (wstatus));
695 return EXIT_SUCCESS; /* Fool '-Wall'. */
698 static void
699 diffarg (char const *a)
701 static idx_t diffargs, diffarglim;
703 if (diffargs == diffarglim)
704 diffargv = xpalloc (diffargv, &diffarglim, 1, -1, sizeof *diffargv);
705 diffargv[diffargs++] = a;
708 /* Signal handling */
710 static bool volatile ignore_SIGINT;
711 static int volatile signal_received;
712 static bool sigs_trapped;
714 static void
715 catchsig (int s)
717 #if ! HAVE_SIGACTION
718 signal (s, SIG_IGN);
719 #endif
720 if (! (s == SIGINT && ignore_SIGINT))
721 signal_received = s;
724 #if HAVE_SIGACTION
725 static struct sigaction catchaction;
726 #endif
728 static void
729 signal_handler (int sig, sighandler handler)
731 #if HAVE_SIGACTION
732 catchaction.sa_handler = handler;
733 sigaction (sig, &catchaction, 0);
734 #else
735 signal (sig, handler);
736 #endif
739 static void
740 trapsigs (void)
742 #if HAVE_SIGACTION
743 catchaction.sa_flags = SA_RESTART;
744 sigemptyset (&catchaction.sa_mask);
745 for (int i = 0; i < NUM_SIGS; i++)
746 sigaddset (&catchaction.sa_mask, sigs[i]);
747 #endif
749 for (int i = 0; i < NUM_SIGS; i++)
751 #if HAVE_SIGACTION
752 sigaction (sigs[i], nullptr, &initial_action[i]);
753 #else
754 initial_action[i] = signal (sigs[i], SIG_IGN);
755 #endif
756 if (initial_handler (i) != SIG_IGN)
757 signal_handler (sigs[i], catchsig);
760 #ifdef SIGCHLD
761 /* System V fork+wait does not work if SIGCHLD is ignored. */
762 signal (SIGCHLD, SIG_DFL);
763 #endif
765 sigs_trapped = true;
768 /* Untrap signal S, or all trapped signals if S is zero. */
769 static void
770 untrapsig (int s)
772 if (sigs_trapped)
773 for (int i = 0; i < NUM_SIGS; i++)
774 if ((! s || sigs[i] == s) && initial_handler (i) != SIG_IGN)
776 #if HAVE_SIGACTION
777 sigaction (sigs[i], &initial_action[i], nullptr);
778 #else
779 signal (sigs[i], initial_action[i]);
780 #endif
784 /* Exit if a signal has been received. */
785 static void
786 checksigs (void)
788 int s = signal_received;
789 if (s)
791 cleanup (0);
793 /* Yield an exit status indicating that a signal was received. */
794 untrapsig (s);
795 raise (s);
797 /* That didn't work, so exit with error status. */
798 exit (EXIT_TROUBLE);
802 static void
803 give_help (void)
805 fprintf (stderr, "%s", _("\
806 ed:\tEdit then use both versions, each decorated with a header.\n\
807 eb:\tEdit then use both versions.\n\
808 el or e1:\tEdit then use the left version.\n\
809 er or e2:\tEdit then use the right version.\n\
810 e:\tDiscard both versions then edit a new one.\n\
811 l or 1:\tUse the left version.\n\
812 r or 2:\tUse the right version.\n\
813 s:\tSilently include common lines.\n\
814 v:\tVerbosely include common lines.\n\
815 q:\tQuit.\n\
816 "));
819 static int
820 skip_white (void)
822 int c;
823 for (;;)
825 c = getchar ();
826 if (! c_isspace (c) || c == '\n')
827 break;
828 checksigs ();
830 if (ferror (stdin))
831 perror_fatal (_("read failed"));
832 return c;
835 static void
836 flush_line (void)
838 for (int c; (c = getchar ()) != '\n' && c != EOF; )
839 continue;
840 if (ferror (stdin))
841 perror_fatal (_("read failed"));
844 /* Suppress gcc's "...may be used before initialized" warnings,
845 generated by GCC versions up to at least GCC 14.0.0 20231227. */
846 #if __GNUC__ + (__GNUC_MINOR__ >= 7) > 4
847 # pragma GCC diagnostic push
848 # pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
849 #endif
851 /* interpret an edit command */
852 static bool
853 edit (struct line_filter *left, char const *lname, lin lline, lin llen,
854 struct line_filter *right, char const *rname, lin rline, lin rlen,
855 FILE *outfile)
857 for (;;)
859 int cmd0;
860 int cmd1;
861 bool gotcmd = false;
863 while (! gotcmd)
865 if (putchar ('%') != '%')
866 perror_fatal (_("write failed"));
867 ck_fflush (stdout);
869 cmd0 = skip_white ();
870 switch (cmd0)
872 case '1': case '2': case 'l': case 'r':
873 case 's': case 'v': case 'q':
874 if (skip_white () != '\n')
876 give_help ();
877 flush_line ();
878 continue;
880 gotcmd = true;
881 break;
883 case 'e':
884 cmd1 = skip_white ();
885 switch (cmd1)
887 case '1': case '2': case 'b': case 'd': case 'l': case 'r':
888 if (skip_white () != '\n')
890 give_help ();
891 flush_line ();
892 continue;
894 gotcmd = true;
895 break;
896 case '\n':
897 gotcmd = true;
898 break;
899 default:
900 give_help ();
901 flush_line ();
902 continue;
904 break;
906 case EOF:
907 if (feof (stdin))
909 gotcmd = true;
910 cmd0 = 'q';
911 break;
913 FALLTHROUGH;
914 default:
915 flush_line ();
916 FALLTHROUGH;
917 case '\n':
918 give_help ();
919 continue;
923 switch (cmd0)
925 case '1': case 'l':
926 lf_copy (left, llen, outfile);
927 lf_skip (right, rlen);
928 return true;
929 case '2': case 'r':
930 lf_copy (right, rlen, outfile);
931 lf_skip (left, llen);
932 return true;
933 case 's':
934 suppress_common_lines = true;
935 break;
936 case 'v':
937 suppress_common_lines = false;
938 break;
939 case 'q':
940 return false;
942 case 'e':
943 if (tmpname)
944 tmp = fopen (tmpname, "we");
945 else
947 int fd = temporary_file ();
948 if (fd < 0)
949 perror_fatal ("mkstemp");
950 tmp = fdopen (fd, "w");
953 if (! tmp)
954 perror_fatal (squote (0, tmpname));
956 switch (cmd1)
958 case 'd':
959 if (llen)
961 if (llen == 1)
962 fprintf (tmp, "--- %s %"pI"d\n", lname, lline);
963 else
964 fprintf (tmp, "--- %s %"pI"d,%"pI"d\n", lname, lline,
965 lline + llen - 1);
967 FALLTHROUGH;
968 case '1': case 'b': case 'l':
969 lf_copy (left, llen, tmp);
970 break;
972 default:
973 lf_skip (left, llen);
974 break;
977 switch (cmd1)
979 case 'd':
980 if (rlen)
982 if (rlen == 1)
983 fprintf (tmp, "+++ %s %"pI"d\n", rname, rline);
984 else
985 fprintf (tmp, "+++ %s %"pI"d,%"pI"d\n", rname, rline,
986 rline + rlen - 1);
988 FALLTHROUGH;
989 case '2': case 'b': case 'r':
990 lf_copy (right, rlen, tmp);
991 break;
993 default:
994 lf_skip (right, rlen);
995 break;
998 ck_fclose (tmp);
1000 ignore_SIGINT = true;
1001 checksigs ();
1002 char *argv[] = { (char *) editor_program, tmpname, nullptr };
1003 int wstatus;
1004 int werrno = 0;
1005 #if ! HAVE_WORKING_FORK
1006 char *command = system_quote_argv (SCI_SYSTEM, argv);
1007 wstatus = system (command);
1008 if (wstatus == -1)
1009 werrno = errno;
1010 free (command);
1011 #else
1012 pid_t pid = fork ();
1013 if (pid == 0)
1015 execvp (editor_program, argv);
1016 _exit (errno == ENOENT ? 127 : 126);
1019 if (pid < 0)
1020 perror_fatal ("fork");
1022 while (waitpid (pid, &wstatus, 0) < 0)
1023 if (errno == EINTR)
1024 checksigs ();
1025 else
1026 perror_fatal ("waitpid");
1027 #endif
1028 ignore_SIGINT = false;
1029 check_child_status (werrno, wstatus, EXIT_SUCCESS,
1030 editor_program);
1032 char buf[SDIFF_BUFSIZE];
1033 tmp = ck_fopen (tmpname, "re");
1034 for (idx_t size;
1035 (size = ck_fread (buf, SDIFF_BUFSIZE, tmp)) != 0; )
1037 checksigs ();
1038 ck_fwrite (buf, size, outfile);
1040 ck_fclose (tmp);
1041 return true;
1043 default:
1044 give_help ();
1045 break;
1050 #if __GNUC__ + (__GNUC_MINOR__ >= 7) > 4
1051 # pragma GCC diagnostic pop
1052 #endif
1054 /* Alternately reveal bursts of diff output and handle user commands. */
1055 static bool
1056 interact (struct line_filter *diff,
1057 struct line_filter *left, char const *lname,
1058 struct line_filter *right, char const *rname,
1059 FILE *outfile)
1061 lin lline = 1, rline = 1;
1063 for (;;)
1065 char diff_help[256];
1066 int snarfed = lf_snarf (diff, diff_help, sizeof diff_help);
1068 if (snarfed <= 0)
1069 return snarfed != 0;
1071 checksigs ();
1073 if (diff_help[0] == ' ')
1074 puts (diff_help + 1);
1075 else
1077 errno = 0;
1078 char *numend;
1079 intmax_t val = strtoimax (diff_help + 1, &numend, 10);
1080 if (! (0 <= val && val <= LIN_MAX) || errno || *numend != ',')
1081 fatal (diff_help);
1082 lin llen = val;
1083 val = strtoimax (numend + 1, &numend, 10);
1084 if (! (0 <= val && val <= LIN_MAX) || errno || *numend)
1085 fatal (diff_help);
1086 lin rlen = val;
1088 lin lenmax = MAX (llen, rlen);
1090 switch (diff_help[0])
1092 case 'i':
1093 if (suppress_common_lines)
1094 lf_skip (diff, lenmax);
1095 else
1096 lf_copy (diff, lenmax, stdout);
1098 lf_copy (left, llen, outfile);
1099 lf_skip (right, rlen);
1100 break;
1102 case 'c':
1103 lf_copy (diff, lenmax, stdout);
1104 if (! edit (left, lname, lline, llen,
1105 right, rname, rline, rlen,
1106 outfile))
1107 return false;
1108 break;
1110 default:
1111 fatal (diff_help);
1114 lline += llen;
1115 rline += rlen;
1120 /* Return true if DIR is an existing directory. */
1121 static bool
1122 diraccess (char const *dir)
1124 struct stat buf;
1125 return stat (dir, &buf) == 0 && S_ISDIR (buf.st_mode);
1128 #ifndef P_tmpdir
1129 # define P_tmpdir "/tmp"
1130 #endif
1131 #ifndef TMPDIR_ENV
1132 # define TMPDIR_ENV "TMPDIR"
1133 #endif
1135 /* Open a temporary file and return its file descriptor. Put into
1136 tmpname the address of a newly allocated buffer that holds the
1137 file's name. Use the prefix "sdiff". */
1138 static int
1139 temporary_file (void)
1141 char const *tmpdir = getenv (TMPDIR_ENV);
1142 char const *dir = tmpdir ? tmpdir : P_tmpdir;
1143 char *buf = xmalloc (strlen (dir) + 1 + 5 + 6 + 1);
1144 strcpy (stpcpy (buf, dir), "/sdiffXXXXXX");
1145 int fd = mkstemp (buf);
1146 if (fd < 0)
1147 free (buf);
1148 else
1149 tmpname = buf;
1150 return fd;