]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/sdiff/sdiff.c
Merge branch 'releng/11.3' into releng-CDN/11.3
[FreeBSD/FreeBSD.git] / usr.bin / sdiff / sdiff.c
1 /*      $OpenBSD: sdiff.c,v 1.36 2015/12/29 19:04:46 gsoares Exp $ */
2
3 /*
4  * Written by Raymond Lai <ray@cyth.net>.
5  * Public domain.
6  */
7
8 #include <sys/cdefs.h>
9 __FBSDID("$FreeBSD$");
10
11 #include <sys/param.h>
12 #include <sys/queue.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include <sys/wait.h>
16
17 #include <ctype.h>
18 #include <err.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <getopt.h>
22 #include <limits.h>
23 #include <paths.h>
24 #include <stdint.h>
25 #define _WITH_GETLINE
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30
31 #include "extern.h"
32
33 #define DIFF_PATH       "/usr/bin/diff"
34
35 #define WIDTH 126
36 /*
37  * Each column must be at least one character wide, plus three
38  * characters between the columns (space, [<|>], space).
39  */
40 #define WIDTH_MIN 5
41
42 /* 3 kilobytes of chars */
43 #define MAX_CHECK 768
44
45 /* A single diff line. */
46 struct diffline {
47         STAILQ_ENTRY(diffline) diffentries;
48         char    *left;
49         char     div;
50         char    *right;
51 };
52
53 static void astrcat(char **, const char *);
54 static void enqueue(char *, char, char *);
55 static char *mktmpcpy(const char *);
56 static int istextfile(FILE *);
57 static void binexec(char *, char *, char *) __dead2;
58 static void freediff(struct diffline *);
59 static void int_usage(void);
60 static int parsecmd(FILE *, FILE *, FILE *);
61 static void printa(FILE *, size_t);
62 static void printc(FILE *, size_t, FILE *, size_t);
63 static void printcol(const char *, size_t *, const size_t);
64 static void printd(FILE *, size_t);
65 static void println(const char *, const char, const char *);
66 static void processq(void);
67 static void prompt(const char *, const char *);
68 static void usage(void) __dead2;
69 static char *xfgets(FILE *);
70
71 static STAILQ_HEAD(, diffline) diffhead = STAILQ_HEAD_INITIALIZER(diffhead);
72 static size_t line_width;       /* width of a line (two columns and divider) */
73 static size_t width;            /* width of each column */
74 static size_t file1ln, file2ln; /* line number of file1 and file2 */
75 static int Iflag = 0;   /* ignore sets matching regexp */
76 static int      lflag;          /* print only left column for identical lines */
77 static int      sflag;          /* skip identical lines */
78 FILE *outfp;            /* file to save changes to */
79 const char *tmpdir;     /* TMPDIR or /tmp */
80
81 enum {
82         HELP_OPT = CHAR_MAX + 1,
83         NORMAL_OPT,
84         FCASE_SENSITIVE_OPT,
85         FCASE_IGNORE_OPT,
86         STRIPCR_OPT,
87         TSIZE_OPT,
88         DIFFPROG_OPT,
89 };
90
91 static struct option longopts[] = {
92         /* options only processed in sdiff */
93         { "suppress-common-lines",      no_argument,            NULL,   's' },
94         { "width",                      required_argument,      NULL,   'w' },
95
96         { "output",                     required_argument,      NULL,   'o' },
97         { "diff-program",               required_argument,      NULL,   DIFFPROG_OPT },
98
99         /* Options processed by diff. */
100         { "ignore-file-name-case",      no_argument,            NULL,   FCASE_IGNORE_OPT },
101         { "no-ignore-file-name-case",   no_argument,            NULL,   FCASE_SENSITIVE_OPT },
102         { "strip-trailing-cr",          no_argument,            NULL,   STRIPCR_OPT },
103         { "tabsize",                    required_argument,      NULL,   TSIZE_OPT },
104         { "help",                       no_argument,            NULL,   HELP_OPT },
105         { "text",                       no_argument,            NULL,   'a' },
106         { "ignore-blank-lines",         no_argument,            NULL,   'B' },
107         { "ignore-space-change",        no_argument,            NULL,   'b' },
108         { "minimal",                    no_argument,            NULL,   'd' },
109         { "ignore-tab-expansion",       no_argument,            NULL,   'E' },
110         { "ignore-matching-lines",      required_argument,      NULL,   'I' },
111         { "ignore-case",                no_argument,            NULL,   'i' },
112         { "left-column",                no_argument,            NULL,   'l' },
113         { "expand-tabs",                no_argument,            NULL,   't' },
114         { "speed-large-files",          no_argument,            NULL,   'H' },
115         { "ignore-all-space",           no_argument,            NULL,   'W' },
116
117         { NULL,                         0,                      NULL,   '\0'}
118 };
119
120 static const char *help_msg[] = {
121         "usage: sdiff [-abdilstW] [-I regexp] [-o outfile] [-w width] file1 file2\n",
122         "-l, --left-column: only print the left column for identical lines.",
123         "-o OUTFILE, --output=OUTFILE: interactively merge file1 and file2 into outfile.",
124         "-s, --suppress-common-lines: skip identical lines.",
125         "-w WIDTH, --width=WIDTH: print a maximum of WIDTH characters on each line.",
126         "",
127         "Options passed to diff(1) are:",
128         "\t-a, --text: treat file1 and file2 as text files.",
129         "\t-b, --ignore-trailing-cr: ignore trailing blank spaces.",
130         "\t-d, --minimal: minimize diff size.",
131         "\t-I RE, --ignore-matching-lines=RE: ignore changes whose line matches RE.",
132         "\t-i, --ignore-case: do a case-insensitive comparison.",
133         "\t-t, --expand-tabs: sxpand tabs to spaces.",
134         "\t-W, --ignore-all-spaces: ignore all spaces.",
135         "\t--speed-large-files: assume large file with scattered changes.",
136         "\t--strip-trailing-cr: strip trailing carriage return.",
137         "\t--ignore-file-name-case: ignore case of file names.",
138         "\t--no-ignore-file-name-case: do not ignore file name case",
139         "\t--tabsize NUM: change size of tabs (default 8.)",
140
141         NULL,
142 };
143
144 /*
145  * Create temporary file if source_file is not a regular file.
146  * Returns temporary file name if one was malloced, NULL if unnecessary.
147  */
148 static char *
149 mktmpcpy(const char *source_file)
150 {
151         struct stat sb;
152         ssize_t rcount;
153         int ifd, ofd;
154         u_char buf[BUFSIZ];
155         char *target_file;
156
157         /* Open input and output. */
158         ifd = open(source_file, O_RDONLY, 0);
159         /* File was opened successfully. */
160         if (ifd != -1) {
161                 if (fstat(ifd, &sb) == -1)
162                         err(2, "error getting file status from %s", source_file);
163
164                 /* Regular file. */
165                 if (S_ISREG(sb.st_mode)) {
166                         close(ifd);
167                         return (NULL);
168                 }
169         } else {
170                 /* If ``-'' does not exist the user meant stdin. */
171                 if (errno == ENOENT && strcmp(source_file, "-") == 0)
172                         ifd = STDIN_FILENO;
173                 else
174                         err(2, "error opening %s", source_file);
175         }
176
177         /* Not a regular file, so copy input into temporary file. */
178         if (asprintf(&target_file, "%s/sdiff.XXXXXXXXXX", tmpdir) == -1)
179                 err(2, "asprintf");
180         if ((ofd = mkstemp(target_file)) == -1) {
181                 warn("error opening %s", target_file);
182                 goto FAIL;
183         }
184         while ((rcount = read(ifd, buf, sizeof(buf))) != -1 &&
185             rcount != 0) {
186                 ssize_t wcount;
187
188                 wcount = write(ofd, buf, (size_t)rcount);
189                 if (-1 == wcount || rcount != wcount) {
190                         warn("error writing to %s", target_file);
191                         goto FAIL;
192                 }
193         }
194         if (rcount == -1) {
195                 warn("error reading from %s", source_file);
196                 goto FAIL;
197         }
198
199         close(ifd);
200         close(ofd);
201
202         return (target_file);
203
204 FAIL:
205         unlink(target_file);
206         exit(2);
207 }
208
209 int
210 main(int argc, char **argv)
211 {
212         FILE *diffpipe=NULL, *file1, *file2;
213         size_t diffargc = 0, wflag = WIDTH;
214         int ch, fd[2] = {-1}, status;
215         pid_t pid=0;
216         const char *outfile = NULL;
217         char **diffargv, *diffprog = DIFF_PATH, *filename1, *filename2,
218              *tmp1, *tmp2, *s1, *s2;
219         int i;
220
221         /*
222          * Process diff flags.
223          */
224         /*
225          * Allocate memory for diff arguments and NULL.
226          * Each flag has at most one argument, so doubling argc gives an
227          * upper limit of how many diff args can be passed.  argv[0],
228          * file1, and file2 won't have arguments so doubling them will
229          * waste some memory; however we need an extra space for the
230          * NULL at the end, so it sort of works out.
231          */
232         if (!(diffargv = calloc(argc, sizeof(char **) * 2)))
233                 err(2, "main");
234
235         /* Add first argument, the program name. */
236         diffargv[diffargc++] = diffprog;
237
238         /* create a dynamic string for merging single-switch options */
239         if ( asprintf(&diffargv[diffargc++], "-")  < 0 )
240                 err(2, "main");
241
242         while ((ch = getopt_long(argc, argv, "aBbdEHI:ilo:stWw:",
243             longopts, NULL)) != -1) {
244                 const char *errstr;
245
246                 switch (ch) {
247                 /* only compatible --long-name-form with diff */
248                 case FCASE_IGNORE_OPT:
249                 case FCASE_SENSITIVE_OPT:
250                 case STRIPCR_OPT:
251                 case TSIZE_OPT:
252                 case 'S':
253                 break;
254                 /* combine no-arg single switches */
255                 case 'a':
256                 case 'B':
257                 case 'b':
258                 case 'd':
259                 case 'E':
260                 case 'i':
261                 case 't':
262                 case 'W':
263                         diffargv[1]  = realloc(diffargv[1], sizeof(char) * strlen(diffargv[1]) + 2);
264                         /*
265                          * In diff, the 'W' option is 'w' and the 'w' is 'W'.
266                          */
267                         if (ch == 'W')
268                                 sprintf(diffargv[1], "%sw", diffargv[1]);
269                         else
270                                 sprintf(diffargv[1], "%s%c", diffargv[1], ch);
271                         break;
272                 case 'H':
273                         diffargv[diffargc++] = "--speed-large-files";
274                         break;
275                 case DIFFPROG_OPT:
276                         diffargv[0] = diffprog = optarg;
277                         break;
278                 case 'I':
279                         Iflag = 1;
280                         diffargv[diffargc++] = "-I";
281                         diffargv[diffargc++] = optarg;
282                         break;
283                 case 'l':
284                         lflag = 1;
285                         break;
286                 case 'o':
287                         outfile = optarg;
288                         break;
289                 case 's':
290                         sflag = 1;
291                         break;
292                 case 'w':
293                         wflag = strtonum(optarg, WIDTH_MIN,
294                             INT_MAX, &errstr);
295                         if (errstr)
296                                 errx(2, "width is %s: %s", errstr, optarg);
297                         break;
298                 case HELP_OPT:
299                         for (i = 0; help_msg[i] != NULL; i++)
300                                 printf("%s\n", help_msg[i]);
301                         exit(0);
302                         break;
303                 default:
304                         usage();
305                         break;
306                 }
307         }
308
309         /* no single switches were used */
310         if (strcmp(diffargv[1], "-") == 0 ) {
311                 for ( i = 1; i < argc-1; i++) {
312                         diffargv[i] = diffargv[i+1];
313                 }
314                 diffargv[diffargc-1] = NULL;
315                 diffargc--;
316         }
317
318         argc -= optind;
319         argv += optind;
320
321         if (argc != 2)
322                 usage();
323
324         if (outfile && (outfp = fopen(outfile, "w")) == NULL)
325                 err(2, "could not open: %s", optarg);
326
327         if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
328                 tmpdir = _PATH_TMP;
329
330         filename1 = argv[0];
331         filename2 = argv[1];
332
333         /*
334          * Create temporary files for diff and sdiff to share if file1
335          * or file2 are not regular files.  This allows sdiff and diff
336          * to read the same inputs if one or both inputs are stdin.
337          *
338          * If any temporary files were created, their names would be
339          * saved in tmp1 or tmp2.  tmp1 should never equal tmp2.
340          */
341         tmp1 = tmp2 = NULL;
342         /* file1 and file2 are the same, so copy to same temp file. */
343         if (strcmp(filename1, filename2) == 0) {
344                 if ((tmp1 = mktmpcpy(filename1)))
345                         filename1 = filename2 = tmp1;
346         /* Copy file1 and file2 into separate temp files. */
347         } else {
348                 if ((tmp1 = mktmpcpy(filename1)))
349                         filename1 = tmp1;
350                 if ((tmp2 = mktmpcpy(filename2)))
351                         filename2 = tmp2;
352         }
353
354         diffargv[diffargc++] = filename1;
355         diffargv[diffargc++] = filename2;
356         /* Add NULL to end of array to indicate end of array. */
357         diffargv[diffargc++] = NULL;
358
359         /* Subtract column divider and divide by two. */
360         width = (wflag - 3) / 2;
361         /* Make sure line_width can fit in size_t. */
362         if (width > (SIZE_MAX - 3) / 2)
363                 errx(2, "width is too large: %zu", width);
364         line_width = width * 2 + 3;
365
366         if (pipe(fd))
367                 err(2, "pipe");
368
369         switch (pid = fork()) {
370         case 0:
371                 /* child */
372                 /* We don't read from the pipe. */
373                 close(fd[0]);
374                 if (dup2(fd[1], STDOUT_FILENO) == -1)
375                         err(2, "child could not duplicate descriptor");
376                 /* Free unused descriptor. */
377                 close(fd[1]);
378                 execvp(diffprog, diffargv);
379                 err(2, "could not execute diff: %s", diffprog);
380                 break;
381         case -1:
382                 err(2, "could not fork");
383                 break;
384         }
385
386         /* parent */
387         /* We don't write to the pipe. */
388         close(fd[1]);
389
390         /* Open pipe to diff command. */
391         if ((diffpipe = fdopen(fd[0], "r")) == NULL)
392                 err(2, "could not open diff pipe");
393
394         if ((file1 = fopen(filename1, "r")) == NULL)
395                 err(2, "could not open %s", filename1);
396         if ((file2 = fopen(filename2, "r")) == NULL)
397                 err(2, "could not open %s", filename2);
398         if (!istextfile(file1) || !istextfile(file2)) {
399                 /* Close open files and pipe, delete temps */
400                 fclose(file1);
401                 fclose(file2);
402                 if (diffpipe != NULL)
403                         fclose(diffpipe);
404                 if (tmp1)
405                         if (unlink(tmp1))
406                                 warn("Error deleting %s.", tmp1);
407                 if (tmp2)
408                         if (unlink(tmp2))
409                                 warn("Error deleting %s.", tmp2);
410                 free(tmp1);
411                 free(tmp2);
412                 binexec(diffprog, filename1, filename2);
413         }
414         /* Line numbers start at one. */
415         file1ln = file2ln = 1;
416
417         /* Read and parse diff output. */
418         while (parsecmd(diffpipe, file1, file2) != EOF)
419                 ;
420         fclose(diffpipe);
421
422         /* Wait for diff to exit. */
423         if (waitpid(pid, &status, 0) == -1 || !WIFEXITED(status) ||
424             WEXITSTATUS(status) >= 2)
425                 err(2, "diff exited abnormally.");
426
427         /* Delete and free unneeded temporary files. */
428         if (tmp1)
429                 if (unlink(tmp1))
430                         warn("Error deleting %s.", tmp1);
431         if (tmp2)
432                 if (unlink(tmp2))
433                         warn("Error deleting %s.", tmp2);
434         free(tmp1);
435         free(tmp2);
436         filename1 = filename2 = tmp1 = tmp2 = NULL;
437
438         /* No more diffs, so print common lines. */
439         if (lflag)
440                 while ((s1 = xfgets(file1)))
441                         enqueue(s1, ' ', NULL);
442         else
443                 for (;;) {
444                         s1 = xfgets(file1);
445                         s2 = xfgets(file2);
446                         if (s1 || s2)
447                                 enqueue(s1, ' ', s2);
448                         else
449                                 break;
450                 }
451         fclose(file1);
452         fclose(file2);
453         /* Process unmodified lines. */
454         processq();
455
456         /* Return diff exit status. */
457         return (WEXITSTATUS(status));
458 }
459
460 /*
461  * When sdiff detects a binary file as input, executes them with
462  * diff to maintain the same behavior as GNU sdiff with binary input.
463  */
464 static void
465 binexec(char *diffprog, char *f1, char *f2)
466 {
467
468         char *args[] = {diffprog, f1, f2, (char *) 0};
469         execv(diffprog, args);
470
471         /* If execv() fails, sdiff's execution will continue below. */
472         errx(1, "Could not execute diff process.\n");
473 }
474
475 /*
476  * Checks whether a file appears to be a text file.
477  */
478 static int
479 istextfile(FILE *f)
480 {
481         int     ch, i;
482
483         if (f == NULL)
484                 return (1);
485         rewind(f);
486         for (i = 0; i <= MAX_CHECK; i++) {
487                 ch = fgetc(f);
488                 if (ch == '\0') {
489                         rewind(f);
490                         return (0);
491                 }
492                 if (ch == EOF)
493                         break;
494         }
495         rewind(f);
496         return (1);
497 }
498
499 /*
500  * Prints an individual column (left or right), taking into account
501  * that tabs are variable-width.  Takes a string, the current column
502  * the cursor is on the screen, and the maximum value of the column.
503  * The column value is updated as we go along.
504  */
505 static void
506 printcol(const char *s, size_t *col, const size_t col_max)
507 {
508
509         for (; *s && *col < col_max; ++s) {
510                 size_t new_col;
511
512                 switch (*s) {
513                 case '\t':
514                         /*
515                          * If rounding to next multiple of eight causes
516                          * an integer overflow, just return.
517                          */
518                         if (*col > SIZE_MAX - 8)
519                                 return;
520
521                         /* Round to next multiple of eight. */
522                         new_col = (*col / 8 + 1) * 8;
523
524                         /*
525                          * If printing the tab goes past the column
526                          * width, don't print it and just quit.
527                          */
528                         if (new_col > col_max)
529                                 return;
530                         *col = new_col;
531                         break;
532                 default:
533                         ++(*col);
534                 }
535                 putchar(*s);
536         }
537 }
538
539 /*
540  * Prompts user to either choose between two strings or edit one, both,
541  * or neither.
542  */
543 static void
544 prompt(const char *s1, const char *s2)
545 {
546         char *cmd;
547
548         /* Print command prompt. */
549         putchar('%');
550
551         /* Get user input. */
552         for (; (cmd = xfgets(stdin)); free(cmd)) {
553                 const char *p;
554
555                 /* Skip leading whitespace. */
556                 for (p = cmd; isspace(*p); ++p)
557                         ;
558                 switch (*p) {
559                 case 'e':
560                         /* Skip `e'. */
561                         ++p;
562                         if (eparse(p, s1, s2) == -1)
563                                 goto USAGE;
564                         break;
565                 case 'l':
566                 case '1':
567                         /* Choose left column as-is. */
568                         if (s1 != NULL)
569                                 fprintf(outfp, "%s\n", s1);
570                         /* End of command parsing. */
571                         break;
572                 case 'q':
573                         goto QUIT;
574                 case 'r':
575                 case '2':
576                         /* Choose right column as-is. */
577                         if (s2 != NULL)
578                                 fprintf(outfp, "%s\n", s2);
579                         /* End of command parsing. */
580                         break;
581                 case 's':
582                         sflag = 1;
583                         goto PROMPT;
584                 case 'v':
585                         sflag = 0;
586                         /* FALLTHROUGH */
587                 default:
588                         /* Interactive usage help. */
589 USAGE:
590                         int_usage();
591 PROMPT:
592                         putchar('%');
593
594                         /* Prompt user again. */
595                         continue;
596                 }
597                 free(cmd);
598                 return;
599         }
600
601         /*
602          * If there was no error, we received an EOF from stdin, so we
603          * should quit.
604          */
605 QUIT:
606         fclose(outfp);
607         exit(0);
608 }
609
610 /*
611  * Takes two strings, separated by a column divider.  NULL strings are
612  * treated as empty columns.  If the divider is the ` ' character, the
613  * second column is not printed (-l flag).  In this case, the second
614  * string must be NULL.  When the second column is NULL, the divider
615  * does not print the trailing space following the divider character.
616  *
617  * Takes into account that tabs can take multiple columns.
618  */
619 static void
620 println(const char *s1, const char div, const char *s2)
621 {
622         size_t col;
623
624         /* Print first column.  Skips if s1 == NULL. */
625         col = 0;
626         if (s1) {
627                 /* Skip angle bracket and space. */
628                 printcol(s1, &col, width);
629
630         }
631
632         /* Otherwise, we pad this column up to width. */
633         for (; col < width; ++col)
634                 putchar(' ');
635
636         /* Only print left column. */
637         if (div == ' ' && !s2) {
638                 printf(" (\n");
639                 return;
640         }
641
642         /*
643          * Print column divider.  If there is no second column, we don't
644          * need to add the space for padding.
645          */
646         if (!s2) {
647                 printf(" %c\n", div);
648                 return;
649         }
650         printf(" %c ", div);
651         col += 3;
652
653         /* Skip angle bracket and space. */
654         printcol(s2, &col, line_width);
655
656         putchar('\n');
657 }
658
659 /*
660  * Reads a line from file and returns as a string.  If EOF is reached,
661  * NULL is returned.  The returned string must be freed afterwards.
662  */
663 static char *
664 xfgets(FILE *file)
665 {
666         size_t linecap;
667         ssize_t l;
668         char *s;
669
670         clearerr(file);
671         linecap = 0;
672         s = NULL;
673
674         if ((l = getline(&s, &linecap, file)) == -1) {
675                 if (ferror(file))
676                         err(2, "error reading file");
677                 return (NULL);
678         }
679
680         if (s[l-1] == '\n')
681                 s[l-1] = '\0';
682
683         return (s);
684 }
685
686 /*
687  * Parse ed commands from diffpipe and print lines from file1 (lines
688  * to change or delete) or file2 (lines to add or change).
689  * Returns EOF or 0.
690  */
691 static int
692 parsecmd(FILE *diffpipe, FILE *file1, FILE *file2)
693 {
694         size_t file1start, file1end, file2start, file2end, n;
695         /* ed command line and pointer to characters in line */
696         char *line, *p, *q;
697         const char *errstr;
698         char c, cmd;
699
700         /* Read ed command. */
701         if (!(line = xfgets(diffpipe)))
702                 return (EOF);
703
704         p = line;
705         /* Go to character after line number. */
706         while (isdigit(*p))
707                 ++p;
708         c = *p;
709         *p++ = 0;
710         file1start = strtonum(line, 0, INT_MAX, &errstr);
711         if (errstr)
712                 errx(2, "file1 start is %s: %s", errstr, line);
713
714         /* A range is specified for file1. */
715         if (c == ',') {
716                 q = p;
717                 /* Go to character after file2end. */
718                 while (isdigit(*p))
719                         ++p;
720                 c = *p;
721                 *p++ = 0;
722                 file1end = strtonum(q, 0, INT_MAX, &errstr);
723                 if (errstr)
724                         errx(2, "file1 end is %s: %s", errstr, line);
725                 if (file1start > file1end)
726                         errx(2, "invalid line range in file1: %s", line);
727         } else
728                 file1end = file1start;
729
730         cmd = c;
731         /* Check that cmd is valid. */
732         if (!(cmd == 'a' || cmd == 'c' || cmd == 'd'))
733                 errx(2, "ed command not recognized: %c: %s", cmd, line);
734
735         q = p;
736         /* Go to character after line number. */
737         while (isdigit(*p))
738                 ++p;
739         c = *p;
740         *p++ = 0;
741         file2start = strtonum(q, 0, INT_MAX, &errstr);
742         if (errstr)
743                 errx(2, "file2 start is %s: %s", errstr, line);
744
745         /*
746          * There should either be a comma signifying a second line
747          * number or the line should just end here.
748          */
749         if (c != ',' && c != '\0')
750                 errx(2, "invalid line range in file2: %c: %s", c, line);
751
752         if (c == ',') {
753
754                 file2end = strtonum(p, 0, INT_MAX, &errstr);
755                 if (errstr)
756                         errx(2, "file2 end is %s: %s", errstr, line);
757                 if (file2start >= file2end)
758                         errx(2, "invalid line range in file2: %s", line);
759         } else
760                 file2end = file2start;
761
762         /* Appends happen _after_ stated line. */
763         if (cmd == 'a') {
764                 if (file1start != file1end)
765                         errx(2, "append cannot have a file1 range: %s",
766                             line);
767                 if (file1start == SIZE_MAX)
768                         errx(2, "file1 line range too high: %s", line);
769                 file1start = ++file1end;
770         }
771         /*
772          * I'm not sure what the deal is with the line numbers for
773          * deletes, though.
774          */
775         else if (cmd == 'd') {
776                 if (file2start != file2end)
777                         errx(2, "delete cannot have a file2 range: %s",
778                             line);
779                 if (file2start == SIZE_MAX)
780                         errx(2, "file2 line range too high: %s", line);
781                 file2start = ++file2end;
782         }
783
784         /*
785          * Continue reading file1 and file2 until we reach line numbers
786          * specified by diff.  Should only happen with -I flag.
787          */
788         for (; file1ln < file1start && file2ln < file2start;
789             ++file1ln, ++file2ln) {
790                 char *s1, *s2;
791
792                 if (!(s1 = xfgets(file1)))
793                         errx(2, "file1 shorter than expected");
794                 if (!(s2 = xfgets(file2)))
795                         errx(2, "file2 shorter than expected");
796
797                 /* If the -l flag was specified, print only left column. */
798                 if (lflag) {
799                         free(s2);
800                         /*
801                          * XXX - If -l and -I are both specified, all
802                          * unchanged or ignored lines are shown with a
803                          * `(' divider.  This matches GNU sdiff, but I
804                          * believe it is a bug.  Just check out:
805                          * gsdiff -l -I '^$' samefile samefile.
806                          */
807                         if (Iflag)
808                                 enqueue(s1, '(', NULL);
809                         else
810                                 enqueue(s1, ' ', NULL);
811                 } else
812                         enqueue(s1, ' ', s2);
813         }
814         /* Ignore deleted lines. */
815         for (; file1ln < file1start; ++file1ln) {
816                 char *s;
817
818                 if (!(s = xfgets(file1)))
819                         errx(2, "file1 shorter than expected");
820
821                 enqueue(s, '(', NULL);
822         }
823         /* Ignore added lines. */
824         for (; file2ln < file2start; ++file2ln) {
825                 char *s;
826
827                 if (!(s = xfgets(file2)))
828                         errx(2, "file2 shorter than expected");
829
830                 /* If -l flag was given, don't print right column. */
831                 if (lflag)
832                         free(s);
833                 else
834                         enqueue(NULL, ')', s);
835         }
836
837         /* Process unmodified or skipped lines. */
838         processq();
839
840         switch (cmd) {
841         case 'a':
842                 printa(file2, file2end);
843                 n = file2end - file2start + 1;
844                 break;
845         case 'c':
846                 printc(file1, file1end, file2, file2end);
847                 n = file1end - file1start + 1 + 1 + file2end - file2start + 1;
848                 break;
849         case 'd':
850                 printd(file1, file1end);
851                 n = file1end - file1start + 1;
852                 break;
853         default:
854                 errx(2, "invalid diff command: %c: %s", cmd, line);
855         }
856         free(line);
857
858         /* Skip to next ed line. */
859         while (n--) {
860                 if (!(line = xfgets(diffpipe)))
861                         errx(2, "diff ended early");
862                 free(line);
863         }
864
865         return (0);
866 }
867
868 /*
869  * Queues up a diff line.
870  */
871 static void
872 enqueue(char *left, char div, char *right)
873 {
874         struct diffline *diffp;
875
876         if (!(diffp = malloc(sizeof(struct diffline))))
877                 err(2, "enqueue");
878         diffp->left = left;
879         diffp->div = div;
880         diffp->right = right;
881         STAILQ_INSERT_TAIL(&diffhead, diffp, diffentries);
882 }
883
884 /*
885  * Free a diffline structure and its elements.
886  */
887 static void
888 freediff(struct diffline *diffp)
889 {
890
891         free(diffp->left);
892         free(diffp->right);
893         free(diffp);
894 }
895
896 /*
897  * Append second string into first.  Repeated appends to the same string
898  * are cached, making this an O(n) function, where n = strlen(append).
899  */
900 static void
901 astrcat(char **s, const char *append)
902 {
903         /* Length of string in previous run. */
904         static size_t offset = 0;
905         size_t newsiz;
906         /*
907          * String from previous run.  Compared to *s to see if we are
908          * dealing with the same string.  If so, we can use offset.
909          */
910         static const char *oldstr = NULL;
911         char *newstr;
912
913         /*
914          * First string is NULL, so just copy append.
915          */
916         if (!*s) {
917                 if (!(*s = strdup(append)))
918                         err(2, "astrcat");
919
920                 /* Keep track of string. */
921                 offset = strlen(*s);
922                 oldstr = *s;
923
924                 return;
925         }
926
927         /*
928          * *s is a string so concatenate.
929          */
930
931         /* Did we process the same string in the last run? */
932         /*
933          * If this is a different string from the one we just processed
934          * cache new string.
935          */
936         if (oldstr != *s) {
937                 offset = strlen(*s);
938                 oldstr = *s;
939         }
940
941         /* Size = strlen(*s) + \n + strlen(append) + '\0'. */
942         newsiz = offset + 1 + strlen(append) + 1;
943
944         /* Resize *s to fit new string. */
945         newstr = realloc(*s, newsiz);
946         if (newstr == NULL)
947                 err(2, "astrcat");
948         *s = newstr;
949
950         /* *s + offset should be end of string. */
951         /* Concatenate. */
952         strlcpy(*s + offset, "\n", newsiz - offset);
953         strlcat(*s + offset, append, newsiz - offset);
954
955         /* New string length should be exactly newsiz - 1 characters. */
956         /* Store generated string's values. */
957         offset = newsiz - 1;
958         oldstr = *s;
959 }
960
961 /*
962  * Process diff set queue, printing, prompting, and saving each diff
963  * line stored in queue.
964  */
965 static void
966 processq(void)
967 {
968         struct diffline *diffp;
969         char divc, *left, *right;
970
971         /* Don't process empty queue. */
972         if (STAILQ_EMPTY(&diffhead))
973                 return;
974
975         /* Remember the divider. */
976         divc = STAILQ_FIRST(&diffhead)->div;
977
978         left = NULL;
979         right = NULL;
980         /*
981          * Go through set of diffs, concatenating each line in left or
982          * right column into two long strings, `left' and `right'.
983          */
984         STAILQ_FOREACH(diffp, &diffhead, diffentries) {
985                 /*
986                  * Print changed lines if -s was given,
987                  * print all lines if -s was not given.
988                  */
989                 if (!sflag || diffp->div == '|' || diffp->div == '<' ||
990                     diffp->div == '>')
991                         println(diffp->left, diffp->div, diffp->right);
992
993                 /* Append new lines to diff set. */
994                 if (diffp->left)
995                         astrcat(&left, diffp->left);
996                 if (diffp->right)
997                         astrcat(&right, diffp->right);
998         }
999
1000         /* Empty queue and free each diff line and its elements. */
1001         while (!STAILQ_EMPTY(&diffhead)) {
1002                 diffp = STAILQ_FIRST(&diffhead);
1003                 STAILQ_REMOVE_HEAD(&diffhead, diffentries);
1004                 freediff(diffp);
1005         }
1006
1007         /* Write to outfp, prompting user if lines are different. */
1008         if (outfp)
1009                 switch (divc) {
1010                 case ' ': case '(': case ')':
1011                         fprintf(outfp, "%s\n", left);
1012                         break;
1013                 case '|': case '<': case '>':
1014                         prompt(left, right);
1015                         break;
1016                 default:
1017                         errx(2, "invalid divider: %c", divc);
1018                 }
1019
1020         /* Free left and right. */
1021         free(left);
1022         free(right);
1023 }
1024
1025 /*
1026  * Print lines following an (a)ppend command.
1027  */
1028 static void
1029 printa(FILE *file, size_t line2)
1030 {
1031         char *line;
1032
1033         for (; file2ln <= line2; ++file2ln) {
1034                 if (!(line = xfgets(file)))
1035                         errx(2, "append ended early");
1036                 enqueue(NULL, '>', line);
1037         }
1038         processq();
1039 }
1040
1041 /*
1042  * Print lines following a (c)hange command, from file1ln to file1end
1043  * and from file2ln to file2end.
1044  */
1045 static void
1046 printc(FILE *file1, size_t file1end, FILE *file2, size_t file2end)
1047 {
1048         struct fileline {
1049                 STAILQ_ENTRY(fileline)   fileentries;
1050                 char                    *line;
1051         };
1052         STAILQ_HEAD(, fileline) delqhead = STAILQ_HEAD_INITIALIZER(delqhead);
1053
1054         /* Read lines to be deleted. */
1055         for (; file1ln <= file1end; ++file1ln) {
1056                 struct fileline *linep;
1057                 char *line1;
1058
1059                 /* Read lines from both. */
1060                 if (!(line1 = xfgets(file1)))
1061                         errx(2, "error reading file1 in delete in change");
1062
1063                 /* Add to delete queue. */
1064                 if (!(linep = malloc(sizeof(struct fileline))))
1065                         err(2, "printc");
1066                 linep->line = line1;
1067                 STAILQ_INSERT_TAIL(&delqhead, linep, fileentries);
1068         }
1069
1070         /* Process changed lines.. */
1071         for (; !STAILQ_EMPTY(&delqhead) && file2ln <= file2end;
1072             ++file2ln) {
1073                 struct fileline *del;
1074                 char *add;
1075
1076                 /* Get add line. */
1077                 if (!(add = xfgets(file2)))
1078                         errx(2, "error reading add in change");
1079
1080                 del = STAILQ_FIRST(&delqhead);
1081                 enqueue(del->line, '|', add);
1082                 STAILQ_REMOVE_HEAD(&delqhead, fileentries);
1083                 /*
1084                  * Free fileline structure but not its elements since
1085                  * they are queued up.
1086                  */
1087                 free(del);
1088         }
1089         processq();
1090
1091         /* Process remaining lines to add. */
1092         for (; file2ln <= file2end; ++file2ln) {
1093                 char *add;
1094
1095                 /* Get add line. */
1096                 if (!(add = xfgets(file2)))
1097                         errx(2, "error reading add in change");
1098
1099                 enqueue(NULL, '>', add);
1100         }
1101         processq();
1102
1103         /* Process remaining lines to delete. */
1104         while (!STAILQ_EMPTY(&delqhead)) {
1105                 struct fileline *filep;
1106
1107                 filep = STAILQ_FIRST(&delqhead);
1108                 enqueue(filep->line, '<', NULL);
1109                 STAILQ_REMOVE_HEAD(&delqhead, fileentries);
1110                 free(filep);
1111         }
1112         processq();
1113 }
1114
1115 /*
1116  * Print deleted lines from file, from file1ln to file1end.
1117  */
1118 static void
1119 printd(FILE *file1, size_t file1end)
1120 {
1121         char *line1;
1122
1123         /* Print out lines file1ln to line2. */
1124         for (; file1ln <= file1end; ++file1ln) {
1125                 if (!(line1 = xfgets(file1)))
1126                         errx(2, "file1 ended early in delete");
1127                 enqueue(line1, '<', NULL);
1128         }
1129         processq();
1130 }
1131
1132 /*
1133  * Interactive mode usage.
1134  */
1135 static void
1136 int_usage(void)
1137 {
1138
1139         puts("e:\tedit blank diff\n"
1140             "eb:\tedit both diffs concatenated\n"
1141             "el:\tedit left diff\n"
1142             "er:\tedit right diff\n"
1143             "l | 1:\tchoose left diff\n"
1144             "r | 2:\tchoose right diff\n"
1145             "s:\tsilent mode--don't print identical lines\n"
1146             "v:\tverbose mode--print identical lines\n"
1147             "q:\tquit");
1148 }
1149
1150 static void
1151 usage(void)
1152 {
1153
1154         fprintf(stderr,
1155             "usage: sdiff [-abdilstHW] [-I regexp] [-o outfile] [-w width] file1"
1156             " file2\n");
1157         exit(2);
1158 }