Debian Codegraph @

src/diff3.c

raw
1 /* GNU diff3 - compare three files line by line
2
3 Copyright (C) 1988-1989, 1992-1996, 1998, 2001-2002, 2004, 2006, 2009-2013,
4 2015-2025 Free Software Foundation, Inc.
5
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18
19 /* As of GCC 11.2.1, gcc -Wanalyzer-too-complex reports that this
20 program's code is too complicated for gcc -fanalyzer.
21 FIXME: Compile with -DANALYZER_NULL_DEFERENCE and see whether the
22 resulting diagnostics are false alarms. */
23 #if 10 <= __GNUC__ && !ANALYZER_NULL_DEREFERENCE
24 # pragma GCC diagnostic ignored "-Wanalyzer-null-dereference"
25 #endif
26
27 #include "system.h"
28 #include "paths.h"
29
30 #include <c-ctype.h>
31 #include <c-stack.h>
32 #include <cmpbuf.h>
33 #include <diagnose.h>
34 #include <error.h>
35 #include <exitfail.h>
36 #include <file-type.h>
37 #include <getopt.h>
38 #include <progname.h>
39 #include <quote.h>
40 #include <system-quote.h>
41 #include <unlocked-io.h>
42 #include <version-etc.h>
43 #include <xalloc.h>
44 #include <xfreopen.h>
45 #include <xstdopen.h>
46
47 #include <stdio.h>
48
49 /* The official name of this program (e.g., no 'g' prefix). */
50 static char const PROGRAM_NAME[] = "diff3";
51
52 #define AUTHORS \
53 _("Randy Smith")
54
55 /* Internal data structures and macros for the diff3 program; includes
56 data structures for both diff3 diffs and normal diffs. */
57
58 /* Different files within a three way diff. */
59 enum { FILE0, FILE1, FILE2 };
60
61 /* A three way diff is built from two two-way diffs; the file which
62 the two two-way diffs share is: */
63 enum { FILEC = FILE2 };
64
65 /* Different files within a two way diff.
66 FC is the common file, FO the other file. */
67 enum { FO, FC };
68
69 /* The ranges are indexed by */
70 enum { RANGE_START, RANGE_END };
71
72 enum diff_type {
73 DIFF_ERROR, /* Should not be used */
74 DIFF_ADD, /* Two way diff add */
75 DIFF_CHANGE, /* Two way diff change */
76 DIFF_DELETE, /* Two way diff delete */
77 DIFF_ALL, /* All three are different */
78 DIFF_1ST, /* Only the first is different */
79 DIFF_2ND, /* Only the second */
80 DIFF_3RD /* Only the third */
81 };
82
83 /* Two way diff */
84 struct diff_block {
85 lin ranges[2][2]; /* Ranges are inclusive */
86 char **lines[2]; /* The actual lines (may contain nulls) */
87 idx_t *lengths[2]; /* Line lengths (including newlines, if any) */
88 struct diff_block *next;
89 };
90
91 /* Three way diff */
92
93 struct diff3_block {
94 enum diff_type correspond; /* Type of diff */
95 lin ranges[3][2]; /* Ranges are inclusive */
96 char **lines[3]; /* The actual lines (may contain nulls) */
97 idx_t *lengths[3]; /* Line lengths (including newlines, if any) */
98 struct diff3_block *next;
99 };
100
101 /* The following are macros, not functions, as they may be used as
102 lvalues, or they may be polymorphic in that they work with either
103 diff or diff3 blocks. */
104
105 /* Access the ranges on a diff or diff3 block. */
106 #define D_LOWLINE(diff, filenum) \
107 ((diff)->ranges[filenum][RANGE_START])
108 #define D_HIGHLINE(diff, filenum) \
109 ((diff)->ranges[filenum][RANGE_END])
110 #define D_NUMLINES(diff, filenum) \
111 (D_HIGHLINE (diff, filenum) - D_LOWLINE (diff, filenum) + 1)
112
113 /* Access the line numbers in a file in a diff or diff3 block by relative line
114 numbers (i.e. line number within the diff itself). Note that these
115 are lvalues and can be used for assignment. */
116 #define D_RELNUM(diff, filenum, linenum) \
117 ((diff)->lines[filenum][linenum])
118 #define D_RELLEN(diff, filenum, linenum) \
119 ((diff)->lengths[filenum][linenum])
120
121 /* And get at them directly, when that should be necessary. */
122 #define D_LINEARRAY(diff, filenum) \
123 ((diff)->lines[filenum])
124 #define D_LENARRAY(diff, filenum) \
125 ((diff)->lengths[filenum])
126
127 /* Next diff or diff3 block. */
128 #define D_NEXT(diff) ((diff)->next)
129
130 /* Access the type of a diff3 block. */
131 #define D3_TYPE(diff) ((diff)->correspond)
132
133 /* Line mappings based on diff or diff3 blocks. The first maps off
134 the top of the diff, the second off of the bottom. */
135 #define D_HIGH_MAPLINE(diff, fromfile, tofile, linenum) \
136 ((linenum) \
137 - D_HIGHLINE (diff, fromfile) \
138 + D_HIGHLINE (diff, tofile))
139
140 #define D_LOW_MAPLINE(diff, fromfile, tofile, linenum) \
141 ((linenum) \
142 - D_LOWLINE (diff, fromfile) \
143 + D_LOWLINE (diff, tofile))
144
145 /* Options variables for flags set on command line. */
146
147 /* If nonzero, treat all files as text files, never as binary. */
148 static bool text;
149
150 /* Remove trailing carriage returns from input. */
151 static bool strip_trailing_cr;
152
153 /* If nonzero, write out an ed script instead of the standard diff3 format. */
154 static bool edscript;
155
156 /* If nonzero, in the case of overlapping diffs (type DIFF_ALL),
157 preserve the lines which would normally be deleted from
158 file 1 with a special flagging mechanism. */
159 static bool flagging;
160
161 /* Use a tab to align output lines (-T). */
162 static bool initial_tab;
163
164 /* If nonzero, do not output information for overlapping diffs. */
165 static bool simple_only;
166
167 /* If nonzero, do not output information for non-overlapping diffs. */
168 static bool overlap_only;
169
170 /* If nonzero, show information for DIFF_2ND diffs. */
171 static bool show_2nd;
172
173 /* If nonzero, include ':wq' at the end of the script
174 to write out the file being edited. */
175 static bool finalwrite;
176
177 /* If nonzero, output a merged file. */
178 static bool merge;
179
180 static char *read_diff (char const *, char const *, char **);
181 static char *scan_diff_line (char *, char **, idx_t *, char *, char);
182 static enum diff_type process_diff_control (char **, struct diff_block *);
183 static bool compare_line_list (char *const[], idx_t const[],
184 char *const[], idx_t const[], lin);
185 static bool copy_stringlist (char *const[], idx_t const[], char *[], idx_t[], lin);
186 static bool output_diff3_edscript (FILE *, struct diff3_block *, int const[3], int const[3], char const *, char const *, char const *);
187 static bool output_diff3_merge (FILE *, FILE *, struct diff3_block *, int const[3], int const[3], char const *, char const *, char const *);
188 static struct diff3_block *create_diff3_block (lin, lin, lin, lin, lin, lin);
189 static struct diff3_block *make_3way_diff (struct diff_block *, struct diff_block *);
190 static struct diff3_block *reverse_diff3_blocklist (struct diff3_block *);
191 static struct diff3_block *using_to_diff3_block (struct diff_block *[2], struct diff_block *[2], int, int, struct diff3_block const *);
192 static struct diff_block *process_diff (char const *, char const *);
193 static void check_stdout (void);
194 static _Noreturn void fatal (char const *);
195 static void output_diff3 (FILE *, struct diff3_block *, int const[3], int const[3]);
196 static _Noreturn void perror_with_exit (char const *);
197 static void usage (void);
198
199 static char const *diff_program = DEFAULT_DIFF_PROGRAM;
200
201 /* Values for long options that do not have single-letter equivalents. */
202 enum
203 {
204 DIFF_PROGRAM_OPTION = CHAR_MAX + 1,
205 HELP_OPTION,
206 STRIP_TRAILING_CR_OPTION
207 };
208
209 static char const shortopts[] = "aeimvx3AEL:TX";
210 static struct option const longopts[] =
211 {
212 {"diff-program", 1, 0, DIFF_PROGRAM_OPTION},
213 {"easy-only", 0, 0, '3'},
214 {"ed", 0, 0, 'e'},
215 {"help", 0, 0, HELP_OPTION},
216 {"initial-tab", 0, 0, 'T'},
217 {"label", 1, 0, 'L'},
218 {"merge", 0, 0, 'm'},
219 {"overlap-only", 0, 0, 'x'},
220 {"show-all", 0, 0, 'A'},
221 {"show-overlap", 0, 0, 'E'},
222 {"strip-trailing-cr", 0, 0, STRIP_TRAILING_CR_OPTION},
223 {"text", 0, 0, 'a'},
224 {"version", 0, 0, 'v'},
225 {0, 0, 0, 0}
226 };
227
228 int
229 main (int argc, char **argv)
230 {
231 exit_failure = EXIT_TROUBLE;
232 initialize_main (&argc, &argv);
233 set_program_name (argv[0]);
234 setlocale (LC_ALL, "");
235 bindtextdomain (PACKAGE, LOCALEDIR);
236 bindtextdomain ("gnulib", GNULIB_LOCALEDIR);
237 textdomain (PACKAGE);
238 c_stack_action (nullptr);
239 xstdopen ();
240
241 /* Parse command line options. */
242
243 int incompat = 0;
244 enum { OPTION_3, OPTION_A, OPTION_E, OPTION_X, OPTION_e, OPTION_x };
245 int tag_count = 0;
246 char *tag_strings[3];
247
248 for (int c;
249 0 <= (c = getopt_long (argc, argv, shortopts, longopts, 0)); )
250 switch (c)
251 {
252 case 'a':
253 text = true;
254 break;
255 case 'A':
256 show_2nd = true;
257 flagging = true;
258 incompat |= 1 << OPTION_A;
259 break;
260 case 'x':
261 overlap_only = true;
262 incompat |= 1 << OPTION_x;
263 break;
264 case '3':
265 simple_only = true;
266 incompat |= 1 << OPTION_3;
267 break;
268 case 'i':
269 finalwrite = true;
270 break;
271 case 'm':
272 merge = true;
273 break;
274 case 'X':
275 overlap_only = true;
276 incompat |= 1 << OPTION_X;
277 break;
278 case 'E':
279 flagging = true;
280 incompat |= 1 << OPTION_E;
281 break;
282 case 'e':
283 incompat |= 1 << OPTION_e;
284 break;
285 case 'T':
286 initial_tab = true;
287 break;
288 case STRIP_TRAILING_CR_OPTION:
289 strip_trailing_cr = true;
290 break;
291 case 'v':
292 version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version,
293 AUTHORS, nullptr);
294 check_stdout ();
295 return EXIT_SUCCESS;
296 case DIFF_PROGRAM_OPTION:
297 diff_program = optarg;
298 break;
299 case HELP_OPTION:
300 usage ();
301 check_stdout ();
302 return EXIT_SUCCESS;
303 case 'L':
304 /* Handle up to three -L options. */
305 if (tag_count < 3)
306 {
307 tag_strings[tag_count++] = optarg;
308 break;
309 }
310 try_help ("too many file label options", nullptr);
311 default:
312 try_help (nullptr, nullptr);
313 }
314
315 /* -AeExX3 without -m implies ed script. */
316 edscript = !!incompat & !merge;
317
318 show_2nd |= !incompat & merge; /* -m without -AeExX3 implies -A. */
319 flagging |= !incompat & merge;
320
321 if (incompat & (incompat - 1) /* Ensure at most one of -AeExX3. */
322 || finalwrite & merge /* -i -m would rewrite input file. */
323 || (tag_count && ! flagging)) /* -L requires one of -AEX. */
324 try_help ("incompatible options", nullptr);
325
326 if (argc - optind != 3)
327 {
328 if (argc - optind < 3)
329 try_help ("missing operand after %s", quote (argv[argc - 1]));
330 else
331 try_help ("extra operand %s", quote (argv[optind + 3]));
332 }
333
334 char **file = &argv[optind];
335
336 for (int i = tag_count; i < 3; i++)
337 tag_strings[i] = file[i];
338
339 /* Always compare file1 to file2, even if file2 is "-".
340 This is needed for -mAeExX3. Using the file0 as
341 the common file would produce wrong results, because if the
342 file0-file1 diffs didn't line up with the file0-file2 diffs
343 (which is entirely possible since we don't use diff's -n option),
344 diff3 might report phantom changes from file1 to file2.
345
346 Also, try to compare file0 to file1, because this is where
347 changes are expected to come from. Diffing between these pairs
348 of files is more likely to avoid phantom changes from file0 to file1.
349
350 Historically, the default common file was file2, so some older
351 applications (e.g. Emacs ediff) used file2 as the ancestor. So,
352 for compatibility, if this is a 3-way diff (not a merge or
353 edscript), prefer file2 as the common file. */
354
355 int common = 2 - (edscript | merge);
356
357 if (STREQ (file[common], "-"))
358 {
359 /* Sigh. We've got standard input as the common file. We can't
360 call diff twice on stdin. Use the other arg as the common
361 file instead. */
362 common = 3 - common;
363 if (STREQ (file[0], "-") || STREQ (file[common], "-"))
364 fatal ("'-' specified for more than one input file");
365 }
366
367 int mapping[3] = { 0, 3 - common, common };
368 int rev_mapping[3];
369 for (int i = 0; i < 3; i++)
370 rev_mapping[mapping[i]] = i;
371
372 #ifdef SIGCHLD
373 /* System V fork+wait does not work if SIGCHLD is ignored. */
374 signal (SIGCHLD, SIG_DFL);
375 #endif
376
377 /* Invoke diff twice on two pairs of input files, combine the two
378 diffs, and output them. */
379
380 char *commonname = file[rev_mapping[FILEC]];
381 struct diff_block
382 *thread1 = process_diff (file[rev_mapping[FILE1]], commonname),
383 *thread0 = process_diff (file[rev_mapping[FILE0]], commonname);
384
385 struct diff3_block *diff3 = make_3way_diff (thread0, thread1);
386
387 /* Although THREAD0 and THREAD1 and some associated storage could
388 now be freed, freeing now is more likely to harm than help, as
389 from here on diff3 merely outputs and exits. Perhaps some
390 freeing could be done inside process_diff as it processes,
391 though it's low priority to look into this. */
392
393 bool conflicts_found;
394
395 if (edscript)
396 conflicts_found
397 = output_diff3_edscript (stdout, diff3, mapping, rev_mapping,
398 tag_strings[0], tag_strings[1], tag_strings[2]);
399 else if (merge)
400 {
401 xfreopen (file[rev_mapping[FILE0]], "re", stdin);
402 conflicts_found
403 = output_diff3_merge (stdin, stdout, diff3, mapping, rev_mapping,
404 tag_strings[0], tag_strings[1], tag_strings[2]);
405 if (ferror (stdin))
406 fatal ("read failed");
407 }
408 else
409 {
410 output_diff3 (stdout, diff3, mapping, rev_mapping);
411 conflicts_found = false;
412 }
413
414 check_stdout ();
415 exit (conflicts_found);
416 }
417
418 static void
419 check_stdout (void)
420 {
421 if (ferror (stdout))
422 fatal ("write failed");
423 else if (fclose (stdout) != 0)
424 perror_with_exit (_("standard output"));
425 }
426
427 static char const *const option_help_msgid[] = {
428 N_("-A, --show-all output all changes, bracketing conflicts"),
429 "",
430 N_("-e, --ed output ed script incorporating changes\n"
431 " from OLDFILE to YOURFILE into MYFILE"),
432 N_("-E, --show-overlap like -e, but bracket conflicts"),
433 N_("-3, --easy-only like -e, but incorporate only nonoverlapping changes"),
434 N_("-x, --overlap-only like -e, but incorporate only overlapping changes"),
435 N_("-X like -x, but bracket conflicts"),
436 N_("-i append 'w' and 'q' commands to ed scripts"),
437 "",
438 N_("-m, --merge output actual merged file, according to\n"
439 " -A if no other options are given"),
440 "",
441 N_("-a, --text treat all files as text"),
442 N_(" --strip-trailing-cr strip trailing carriage return on input"),
443 N_("-T, --initial-tab make tabs line up by prepending a tab"),
444 N_(" --diff-program=PROGRAM use PROGRAM to compare files"),
445 N_("-L, --label=LABEL use LABEL instead of file name\n"
446 " (can be repeated up to three times)"),
447 "",
448 N_(" --help display this help and exit"),
449 N_("-v, --version output version information and exit"),
450 nullptr
451 };
452
453 static void
454 usage (void)
455 {
456 printf (_("Usage: %s [OPTION]... MYFILE OLDFILE YOURFILE\n"),
457 squote (0, program_name));
458 printf ("%s\n\n", _("Compare three files line by line."));
459
460 fputs (_("\
461 Mandatory arguments to long options are mandatory for short options too.\n\
462 "), stdout);
463 for (char const *const *p = option_help_msgid; *p; p++)
464 if (**p)
465 printf (" %s\n", _(*p));
466 else
467 putchar ('\n');
468 fputs (_("\n\
469 The default output format is a somewhat human-readable representation of\n\
470 the changes.\n\
471 \n\
472 The -e, -E, -x, -X (and corresponding long) options cause an ed script\n\
473 to be output instead of the default.\n\
474 \n\
475 Finally, the -m (--merge) option causes diff3 to do the merge internally\n\
476 and output the actual merged file. For unusual input, this is more\n\
477 robust than using ed.\n"), stdout);
478 printf ("\n%s\n%s\n",
479 _("If a FILE is '-', read standard input."),
480 _("Exit status is 0 if successful, 1 if conflicts, 2 if trouble."));
481 emit_bug_reporting_address ();
482 }
483
484 /* Combine the two diffs together into one.
485 Here is the algorithm:
486
487 File2 is shared in common between the two diffs.
488 Diff02 is the diff between 0 and 2.
489 Diff12 is the diff between 1 and 2.
490
491 1) Find the range for the first block in File2.
492 a) Take the lowest of the two ranges (in File2) in the two
493 current blocks (one from each diff) as being the low
494 water mark. Assign the upper end of this block as
495 being the high water mark and move the current block up
496 one. Mark the block just moved over as to be used.
497 b) Check the next block in the diff that the high water
498 mark is *not* from.
499
500 *If* the high water mark is above
501 the low end of the range in that block,
502
503 mark that block as to be used and move the current
504 block up. Set the high water mark to the max of
505 the high end of this block and the current. Repeat b.
506
507 2) Find the corresponding ranges in File0 (from the blocks
508 in diff02; line per line outside of diffs) and in File1.
509 Create a diff3_block, reserving space as indicated by the ranges.
510
511 3) Copy all of the pointers for file2 in. At least for now,
512 do memcmp's between corresponding strings in the two diffs.
513
514 4) Copy all of the pointers for file0 and 1 in. Get what is
515 needed from file2 (when there isn't a diff block, it's
516 identical to file2 within the range between diff blocks).
517
518 5) If the diff blocks used came from only one of the two
519 strings of diffs, then that file (i.e. the one other than
520 the common file in that diff) is the odd person out. If
521 diff blocks are used from both sets, check to see if files
522 0 and 1 match:
523
524 Same number of lines? If so, do a set of memcmp's (if
525 a memcmp matches; copy the pointer over; it'll be easier
526 later during comparisons). If they match, 0 & 1 are the
527 same. If not, all three different.
528
529 Then do it again, until the blocks are exhausted. */
530
531
532 /* Make a three way diff (chain of diff3_block's) from two two way
533 diffs (chains of diff_block's). Assume that each of the two diffs
534 passed are onto the same file (i.e. that each of the diffs were
535 made "to" the same file). Return a three way diff pointer with
536 numbering FILE0 = the other file in diff02, FILE1 = the other file
537 in diff12, and FILEC = the common file. */
538
539 static struct diff3_block *
540 make_3way_diff (struct diff_block *thread0, struct diff_block *thread1)
541 {
542 /* Work on the two diffs passed to it as threads. Thread number 0
543 is diff02, thread number 1 is diff12. USING is the base of the
544 list of blocks to be used to construct each block of the three
545 way diff; if no blocks from a particular thread are to be used,
546 that element of USING is 0. LAST_USING contains the last
547 elements on each of the using lists.
548
549 HIGH_WATER_MARK is the highest line number in the common file
550 described in any of the diffs in either of the USING lists.
551 HIGH_WATER_THREAD names the thread. Similarly BASE_WATER_MARK
552 and BASE_WATER_THREAD describe the lowest line number in the
553 common file described in any of the diffs in either of the USING
554 lists. HIGH_WATER_DIFF is the diff from which the
555 HIGH_WATER_MARK was taken.
556
557 HIGH_WATER_DIFF should always be equal to
558 LAST_USING[HIGH_WATER_THREAD]. OTHER_DIFF is the next diff to
559 check for higher water, and should always be equal to
560 CURRENT[HIGH_WATER_THREAD ^ 1]. OTHER_THREAD is the thread in
561 which the OTHER_DIFF is, and hence should always be equal to
562 HIGH_WATER_THREAD ^ 1.
563
564 LAST_DIFF is the last diff block produced by this routine, for
565 line correspondence purposes between that diff and the one
566 currently being worked on. It is ZERO_DIFF before any blocks
567 have been created. */
568
569 struct diff_block *current[2] = {thread0, thread1};
570
571 struct diff3_block *result = nullptr;
572 struct diff3_block **result_end = &result;
573 static struct diff3_block const zero_diff3;
574 struct diff3_block const *last_diff3 = &zero_diff3;
575
576 /* Sniff up the threads until we reach the end */
577
578 while (current[0] || current[1])
579 {
580 struct diff_block *using[2] = {nullptr, nullptr};
581 struct diff_block *last_using[2] = {nullptr, nullptr};
582
583 /* Setup low and high water threads, diffs, and marks. */
584 int base_water_thread
585 = (!current[0] ? 1
586 : !current[1] ? 0
587 : D_LOWLINE (current[0], FC) > D_LOWLINE (current[1], FC));
588 int high_water_thread = base_water_thread;
589
590 struct diff_block *high_water_diff = current[high_water_thread];
591
592 lin high_water_mark = D_HIGHLINE (high_water_diff, FC);
593
594 /* Make the diff you just got info from into the using class */
595 using[high_water_thread]
596 = last_using[high_water_thread]
597 = high_water_diff;
598 current[high_water_thread] = high_water_diff->next;
599 last_using[high_water_thread]->next = nullptr;
600
601 /* And mark the other diff */
602 int other_thread = high_water_thread ^ 0x1;
603 struct diff_block *other_diff = current[other_thread];
604
605 /* Shuffle up the ladder, checking the other diff to see if it
606 needs to be incorporated. */
607 while (other_diff
608 && D_LOWLINE (other_diff, FC) <= high_water_mark + 1)
609 {
610 /* Incorporate this diff into the using list. Note that
611 this doesn't take it off the current list */
612 if (using[other_thread])
613 last_using[other_thread]->next = other_diff;
614 else
615 using[other_thread] = other_diff;
616 last_using[other_thread] = other_diff;
617
618 /* Take it off the current list. Note that this following
619 code assumes that other_diff enters it equal to
620 current[high_water_thread ^ 0x1] */
621 current[other_thread] = current[other_thread]->next;
622 other_diff->next = nullptr;
623
624 /* Set the high_water stuff
625 If this comparison is equal, then this is the last pass
626 through this loop; since diff blocks within a given
627 thread cannot overlap, the high_water_mark will be
628 *below* the range_start of either of the next diffs. */
629
630 if (high_water_mark < D_HIGHLINE (other_diff, FC))
631 {
632 high_water_thread ^= 1;
633 high_water_mark = D_HIGHLINE (other_diff, FC);
634 }
635
636 /* Set the other diff */
637 other_thread = high_water_thread ^ 0x1;
638 other_diff = current[other_thread];
639 }
640
641 /* The using lists contain a list of all of the blocks to be
642 included in this diff3_block. Create it. */
643
644 struct diff3_block *tmpblock
645 = using_to_diff3_block (using, last_using, base_water_thread,
646 high_water_thread, last_diff3);
647
648 if (!tmpblock)
649 fatal ("internal error: screwup in format of diff blocks");
650
651 /* Put it on the list. */
652 *result_end = tmpblock;
653 result_end = &tmpblock->next;
654
655 /* Set up corresponding lines correctly. */
656 last_diff3 = tmpblock;
657 }
658 return result;
659 }
660
661 /* Take two lists of blocks (from two separate diff threads) and put
662 them together into one diff3 block. Return a pointer to this diff3
663 block or 0 for failure.
664
665 All arguments besides using are for the convenience of the routine;
666 they could be derived from the using array. LAST_USING is a pair
667 of pointers to the last blocks in the using structure. LOW_THREAD
668 and HIGH_THREAD tell which threads contain the lowest and highest
669 line numbers for File0. LAST_DIFF3 contains the last diff produced
670 in the calling routine. This is used for lines mappings that
671 would still be identical to the state that diff ended in.
672
673 A distinction should be made in this routine between the two diffs
674 that are part of a normal two diff block, and the three diffs that
675 are part of a diff3_block. */
676
677 static struct diff3_block *
678 using_to_diff3_block (struct diff_block *using[2],
679 struct diff_block *last_using[2],
680 int low_thread, int high_thread,
681 struct diff3_block const *last_diff3)
682 {
683 /* Find the range in the common file. */
684 lin lowc = D_LOWLINE (using[low_thread], FC);
685 lin highc = D_HIGHLINE (last_using[high_thread], FC);
686
687 /* Find the ranges in the other files.
688 If using[d] is null, that means that the file to which that diff
689 refers is equivalent to the common file over this range. */
690
691 lin low[2], high[2];
692 for (int d = 0; d < 2; d++)
693 if (using[d])
694 {
695 low[d] = D_LOW_MAPLINE (using[d], FC, FO, lowc);
696 high[d] = D_HIGH_MAPLINE (last_using[d], FC, FO, highc);
697 }
698 else
699 {
700 low[d] = D_HIGH_MAPLINE (last_diff3, FILEC, FILE0 + d, lowc);
701 high[d] = D_HIGH_MAPLINE (last_diff3, FILEC, FILE0 + d, highc);
702 }
703
704 /* Create a block with the appropriate sizes */
705 struct diff3_block *result
706 = create_diff3_block (low[0], high[0], low[1], high[1], lowc, highc);
707
708 /* Copy information for the common file.
709 Return a null pointer if any of the compares failed. */
710
711 for (int d = 0; d < 2; d++)
712 for (struct diff_block *ptr = using[d]; ptr; ptr = D_NEXT (ptr))
713 {
714 lin result_offset = D_LOWLINE (ptr, FC) - lowc;
715
716 if (!copy_stringlist (D_LINEARRAY (ptr, FC),
717 D_LENARRAY (ptr, FC),
718 D_LINEARRAY (result, FILEC) + result_offset,
719 D_LENARRAY (result, FILEC) + result_offset,
720 D_NUMLINES (ptr, FC)))
721 return nullptr;
722 }
723
724 /* Copy information for file d. First deal with anything that might be
725 before the first diff. */
726
727 for (int d = 0; d < 2; d++)
728 {
729 struct diff_block *u = using[d];
730 lin lo = low[d], hi = high[d];
731
732 for (lin i = 0;
733 i + lo < (u ? D_LOWLINE (u, FO) : hi + 1);
734 i++)
735 {
736 D_RELNUM (result, FILE0 + d, i) = D_RELNUM (result, FILEC, i);
737 D_RELLEN (result, FILE0 + d, i) = D_RELLEN (result, FILEC, i);
738 }
739
740 for (struct diff_block *ptr = u; ptr; ptr = D_NEXT (ptr))
741 {
742 lin result_offset = D_LOWLINE (ptr, FO) - lo;
743
744 if (!copy_stringlist (D_LINEARRAY (ptr, FO),
745 D_LENARRAY (ptr, FO),
746 D_LINEARRAY (result, FILE0 + d) + result_offset,
747 D_LENARRAY (result, FILE0 + d) + result_offset,
748 D_NUMLINES (ptr, FO)))
749 return nullptr;
750
751 /* Catch the lines between here and the next diff */
752 lin linec = D_HIGHLINE (ptr, FC) + 1 - lowc;
753 for (lin i = D_HIGHLINE (ptr, FO) + 1 - lo;
754 i < (D_NEXT (ptr) ? D_LOWLINE (D_NEXT (ptr), FO) : hi + 1) - lo;
755 i++)
756 {
757 D_RELNUM (result, FILE0 + d, i) = D_RELNUM (result, FILEC, linec);
758 D_RELLEN (result, FILE0 + d, i) = D_RELLEN (result, FILEC, linec);
759 linec++;
760 }
761 }
762 }
763
764 /* Set correspond */
765 if (!using[0])
766 D3_TYPE (result) = DIFF_2ND;
767 else if (!using[1])
768 D3_TYPE (result) = DIFF_1ST;
769 else
770 {
771 lin nl0 = D_NUMLINES (result, FILE0);
772 lin nl1 = D_NUMLINES (result, FILE1);
773
774 if (nl0 != nl1
775 || !compare_line_list (D_LINEARRAY (result, FILE0),
776 D_LENARRAY (result, FILE0),
777 D_LINEARRAY (result, FILE1),
778 D_LENARRAY (result, FILE1),
779 nl0))
780 D3_TYPE (result) = DIFF_ALL;
781 else
782 D3_TYPE (result) = DIFF_3RD;
783 }
784
785 return result;
786 }
787
788 /* Copy pointers from a list of strings to a different list of
789 strings. If a spot in the second list is already filled, make sure
790 that it is filled with the same string; if not, return false, the copy
791 incomplete. Upon successful completion of the copy, return true. */
792
793 static bool
794 copy_stringlist (char *const fromptrs[], idx_t const fromlengths[],
795 char *toptrs[], idx_t tolengths[],
796 lin copynum)
797 {
798 char *const *f = fromptrs;
799 char **t = toptrs;
800 idx_t const *fl = fromlengths;
801 idx_t *tl = tolengths;
802
803 while (copynum--)
804 {
805 if (*t)
806 {
807 if (*fl != *tl || memcmp (*f, *t, *fl) != 0)
808 return false;
809 }
810 else
811 {
812 *t = *f;
813 *tl = *fl;
814 }
815
816 t++; f++; tl++; fl++;
817 }
818
819 return true;
820 }
821
822 /* Create a diff3_block, with ranges as specified in the arguments.
823 Allocate the arrays for the various pointers (and zero them) based
824 on the arguments passed. Return the block as a result. */
825
826 static struct diff3_block *
827 create_diff3_block (lin low0, lin high0,
828 lin low1, lin high1,
829 lin low2, lin high2)
830 {
831 struct diff3_block *result = xmalloc (sizeof *result);
832
833 D3_TYPE (result) = DIFF_ERROR;
834 D_NEXT (result) = nullptr;
835
836 /* Assign ranges */
837 D_LOWLINE (result, FILE0) = low0;
838 D_HIGHLINE (result, FILE0) = high0;
839 D_LOWLINE (result, FILE1) = low1;
840 D_HIGHLINE (result, FILE1) = high1;
841 D_LOWLINE (result, FILE2) = low2;
842 D_HIGHLINE (result, FILE2) = high2;
843
844 /* Allocate and zero space */
845 lin numlines = D_NUMLINES (result, FILE0);
846 if (numlines)
847 {
848 D_LINEARRAY (result, FILE0) = xicalloc (numlines, sizeof (char *));
849 D_LENARRAY (result, FILE0) = xicalloc (numlines, sizeof (idx_t));
850 }
851 else
852 {
853 D_LINEARRAY (result, FILE0) = nullptr;
854 D_LENARRAY (result, FILE0) = nullptr;
855 }
856
857 numlines = D_NUMLINES (result, FILE1);
858 if (numlines)
859 {
860 D_LINEARRAY (result, FILE1) = xicalloc (numlines, sizeof (char *));
861 D_LENARRAY (result, FILE1) = xicalloc (numlines, sizeof (idx_t));
862 }
863 else
864 {
865 D_LINEARRAY (result, FILE1) = nullptr;
866 D_LENARRAY (result, FILE1) = nullptr;
867 }
868
869 numlines = D_NUMLINES (result, FILE2);
870 if (numlines)
871 {
872 D_LINEARRAY (result, FILE2) = xicalloc (numlines, sizeof (char *));
873 D_LENARRAY (result, FILE2) = xicalloc (numlines, sizeof (idx_t));
874 }
875 else
876 {
877 D_LINEARRAY (result, FILE2) = nullptr;
878 D_LENARRAY (result, FILE2) = nullptr;
879 }
880
881 /* Return */
882 return result;
883 }
884
885 /* Compare two lists of lines of text.
886 Return true if they are equivalent, false if not. */
887
888 static bool
889 compare_line_list (char *const list1[], idx_t const lengths1[],
890 char *const list2[], idx_t const lengths2[],
891 lin nl)
892 {
893 char *const *l1 = list1;
894 char *const *l2 = list2;
895 idx_t const *lgths1 = lengths1;
896 idx_t const *lgths2 = lengths2;
897
898 while (nl--)
899 if (!*l1 || !*l2 || *lgths1 != *lgths2++
900 || memcmp (*l1++, *l2++, *lgths1++) != 0)
901 return false;
902 return true;
903 }
904
905 /* Input and parse two way diffs. */
906
907 static struct diff_block *
908 process_diff (char const *filea, char const *fileb)
909 {
910 struct diff_block *block_list;
911 struct diff_block **block_list_end = &block_list;
912
913 char *scan_diff;
914 char *diff_limit = read_diff (filea, fileb, &scan_diff);
915
916 while (scan_diff < diff_limit)
917 {
918 struct diff_block *bptr = xmalloc (sizeof *bptr);
919 bptr->lines[0] = bptr->lines[1] = nullptr;
920 bptr->lengths[0] = bptr->lengths[1] = nullptr;
921
922 enum diff_type dt = process_diff_control (&scan_diff, bptr);
923 if (dt == DIFF_ERROR || *scan_diff != '\n')
924 {
925 fprintf (stderr, _("%s: diff failed: "), squote (0, program_name));
926 do
927 {
928 putc (*scan_diff, stderr);
929 }
930 while (*scan_diff++ != '\n');
931 exit (EXIT_TROUBLE);
932 }
933 scan_diff++;
934
935 /* Force appropriate ranges to be null, if necessary */
936 switch (dt)
937 {
938 case DIFF_ADD:
939 bptr->ranges[0][0]++;
940 break;
941 case DIFF_DELETE:
942 bptr->ranges[1][0]++;
943 break;
944 case DIFF_CHANGE:
945 break;
946 default:
947 fatal ("internal error: invalid diff type in process_diff");
948 break;
949 }
950
951 /* Allocate space for the pointers for the lines from filea, and
952 parcel them out among these pointers */
953 if (dt != DIFF_ADD)
954 {
955 lin numlines = D_NUMLINES (bptr, 0);
956 bptr->lines[0] = xinmalloc (numlines, sizeof *bptr->lines[0]);
957 bptr->lengths[0] = xinmalloc (numlines, sizeof *bptr->lengths[0]);
958 for (lin i = 0; i < numlines; i++)
959 scan_diff = scan_diff_line (scan_diff,
960 &(bptr->lines[0][i]),
961 &(bptr->lengths[0][i]),
962 diff_limit,
963 '<');
964 }
965
966 /* Get past the separator for changes */
967 if (dt == DIFF_CHANGE)
968 {
969 if (strncmp (scan_diff, "---\n", 4))
970 fatal ("invalid diff format; invalid change separator");
971 scan_diff += 4;
972 }
973
974 /* Allocate space for the pointers for the lines from fileb, and
975 parcel them out among these pointers */
976 if (dt != DIFF_DELETE)
977 {
978 lin numlines = D_NUMLINES (bptr, 1);
979 bptr->lines[1] = xinmalloc (numlines, sizeof *bptr->lines[1]);
980 bptr->lengths[1] = xinmalloc (numlines, sizeof *bptr->lengths[1]);
981 for (lin i = 0; i < numlines; i++)
982 scan_diff = scan_diff_line (scan_diff,
983 &(bptr->lines[1][i]),
984 &(bptr->lengths[1][i]),
985 diff_limit,
986 '>');
987 }
988
989 /* Place this block on the blocklist. */
990 *block_list_end = bptr;
991 block_list_end = &bptr->next;
992 }
993
994 *block_list_end = nullptr;
995 return block_list;
996 }
997
998 /* Skip tabs and spaces, and return the first character after them. */
999
1000 static char * ATTRIBUTE_PURE
1001 skipwhite (char *s)
1002 {
1003 while (*s == ' ' || *s == '\t')
1004 s++;
1005 return s;
1006 }
1007
1008 /* Read a nonnegative line number from S, returning the address of the
1009 first character after the line number, and storing the number into *PNUM.
1010 Return a null pointer if S does not point to a valid line number. */
1011
1012 static char *
1013 readnum (char *s, lin *pnum)
1014 {
1015 unsigned char c = *s;
1016 lin num = 0;
1017
1018 if (! c_isdigit (c))
1019 return nullptr;
1020
1021 do
1022 {
1023 num = c - '0' + num * 10;
1024 c = *++s;
1025 }
1026 while (c_isdigit (c));
1027
1028 *pnum = num;
1029 return s;
1030 }
1031
1032 /* Parse a normal format diff control string. Return the type of the
1033 diff (DIFF_ERROR if the format is bad). All of the other important
1034 information is filled into to the structure pointed to by db, and
1035 the string pointer (whose location is passed to this routine) is
1036 updated to point beyond the end of the string parsed. Note that
1037 only the ranges in the diff_block will be set by this routine.
1038
1039 If some specific pair of numbers has been reduced to a single
1040 number, then both corresponding numbers in the diff block are set
1041 to that number. In general these numbers are interpreted as ranges
1042 inclusive, unless being used by the DIFF_ADD or DIFF_DELETE commands.
1043 It is assumed that these will be special cased in a superior routine. */
1044
1045 static enum diff_type
1046 process_diff_control (char **string, struct diff_block *db)
1047 {
1048 char *s = *string;
1049
1050 /* Read first set of digits */
1051 s = readnum (skipwhite (s), &db->ranges[0][RANGE_START]);
1052 if (! s)
1053 return DIFF_ERROR;
1054
1055 /* Was that the only digit? */
1056 s = skipwhite (s);
1057 if (*s == ',')
1058 {
1059 s = readnum (s + 1, &db->ranges[0][RANGE_END]);
1060 if (! s)
1061 return DIFF_ERROR;
1062 }
1063 else
1064 db->ranges[0][RANGE_END] = db->ranges[0][RANGE_START];
1065
1066 /* Get the letter */
1067 s = skipwhite (s);
1068 enum diff_type type;
1069 switch (*s)
1070 {
1071 case 'a':
1072 type = DIFF_ADD;
1073 break;
1074 case 'c':
1075 type = DIFF_CHANGE;
1076 break;
1077 case 'd':
1078 type = DIFF_DELETE;
1079 break;
1080 default:
1081 return DIFF_ERROR; /* Bad format */
1082 }
1083 s++; /* Past letter */
1084
1085 /* Read second set of digits */
1086 s = readnum (skipwhite (s), &db->ranges[1][RANGE_START]);
1087 if (! s)
1088 return DIFF_ERROR;
1089
1090 /* Was that the only digit? */
1091 s = skipwhite (s);
1092 if (*s == ',')
1093 {
1094 s = readnum (s + 1, &db->ranges[1][RANGE_END]);
1095 if (! s)
1096 return DIFF_ERROR;
1097 s = skipwhite (s); /* To move to end */
1098 }
1099 else
1100 db->ranges[1][RANGE_END] = db->ranges[1][RANGE_START];
1101
1102 *string = s;
1103 return type;
1104 }
1105
1106 static char *
1107 read_diff (char const *filea,
1108 char const *fileb,
1109 char **output_placement)
1110 {
1111 char const *argv[10];
1112 char const **ap = argv;
1113 *ap++ = diff_program;
1114 if (text)
1115 *ap++ = "-a";
1116 if (strip_trailing_cr)
1117 *ap++ = "--strip-trailing-cr";
1118 *ap++ = "--horizon-lines=100";
1119 *ap++ = "---no-directory";
1120 *ap++ = "--";
1121 *ap++ = filea;
1122 *ap++ = fileb;
1123 *ap = nullptr;
1124
1125 #if HAVE_WORKING_FORK
1126
1127 int fds[2];
1128 if (pipe (fds) != 0)
1129 perror_with_exit ("pipe");
1130
1131 pid_t pid = fork ();
1132 if (pid == 0)
1133 {
1134 /* Child */
1135 close (fds[0]);
1136 if (fds[1] != STDOUT_FILENO)
1137 {
1138 dup2 (fds[1], STDOUT_FILENO);
1139 close (fds[1]);
1140 }
1141
1142 /* The cast to (char **) is needed for portability to older
1143 hosts with a nonstandard prototype for execvp. */
1144 execvp (diff_program, (char **) argv);
1145
1146 _exit (errno == ENOENT ? 127 : 126);
1147 }
1148
1149 if (pid == -1)
1150 perror_with_exit ("fork");
1151
1152 close (fds[1]); /* Prevent erroneous lack of EOF */
1153 int fd = fds[0];
1154
1155 #else
1156
1157 char *command = system_quote_argv (SCI_SYSTEM, (char **) argv);
1158 errno = 0;
1159 FILE *fpipe = popen (command, "r");
1160 if (!fpipe)
1161 perror_with_exit (command);
1162 free (command);
1163 int fd = fileno (fpipe);
1164
1165 #endif
1166
1167 struct stat pipestat;
1168 idx_t current_chunk_size;
1169 if (fstat (fd, &pipestat) < 0
1170 || ST_BLKSIZE (pipestat) <= 0
1171 || ckd_add (&current_chunk_size, ST_BLKSIZE (pipestat), 0))
1172 current_chunk_size = 8 * 1024;
1173 char *diff_result = ximalloc (current_chunk_size);
1174 idx_t total = 0;
1175
1176 for (;;)
1177 {
1178 idx_t bytes_to_read = current_chunk_size - total;
1179 ptrdiff_t bytes = block_read (fd, diff_result + total, bytes_to_read);
1180 total += bytes;
1181 if (bytes != bytes_to_read)
1182 {
1183 if (bytes < 0)
1184 perror_with_exit (_("read failed"));
1185 break;
1186 }
1187 diff_result = xpalloc (diff_result, &current_chunk_size, 1, -1, 1);
1188 }
1189
1190 if (total != 0 && diff_result[total-1] != '\n')
1191 fatal ("invalid diff format; incomplete last line");
1192
1193 *output_placement = diff_result;
1194
1195 int werrno = 0;
1196 int wstatus;
1197 #if ! HAVE_WORKING_FORK
1198
1199 wstatus = pclose (fpipe);
1200 if (wstatus == -1)
1201 werrno = errno;
1202
1203 #else
1204
1205 if (close (fd) != 0)
1206 perror_with_exit ("close");
1207 if (waitpid (pid, &wstatus, 0) < 0)
1208 perror_with_exit ("waitpid");
1209
1210 #endif
1211
1212 int status = (! werrno && WIFEXITED (wstatus)
1213 ? WEXITSTATUS (wstatus) : INT_MAX);
1214
1215 if (EXIT_TROUBLE <= status)
1216 error (EXIT_TROUBLE, werrno,
1217 _(status == 126
1218 ? "subsidiary program %s could not be invoked"
1219 : status == 127
1220 ? "subsidiary program %s not found"
1221 : status == INT_MAX
1222 ? "subsidiary program %s failed"
1223 : "subsidiary program %s failed (exit status %d)"),
1224 quote (diff_program), status);
1225
1226 return diff_result + total;
1227 }
1228
1229
1230 /* Scan a regular diff line (consisting of > or <, followed by a
1231 space, followed by text (including nulls) up to a newline.
1232
1233 This next routine began life as a macro and many parameters in it
1234 are used as call-by-reference values. */
1235 static char *
1236 scan_diff_line (char *scan_ptr, char **set_start, idx_t *set_length,
1237 char *limit, char leadingchar)
1238 {
1239 if (!(scan_ptr[0] == leadingchar
1240 && scan_ptr[1] == ' '))
1241 fatal ("invalid diff format; incorrect leading line chars");
1242
1243 char *line_ptr = *set_start = scan_ptr + 2;
1244 while (*line_ptr++ != '\n')
1245 continue;
1246
1247 /* Include newline if the original line ended in a newline,
1248 or if an edit script is being generated.
1249 Copy any missing newline message to stderr if an edit script is being
1250 generated, because edit scripts cannot handle missing newlines.
1251 Return the beginning of the next line. */
1252 *set_length = line_ptr - *set_start;
1253 if (line_ptr < limit && *line_ptr == '\\')
1254 {
1255 if (edscript)
1256 fprintf (stderr, "%s:", squote (0, program_name));
1257 else
1258 --*set_length;
1259 line_ptr++;
1260 do
1261 {
1262 if (edscript)
1263 putc (*line_ptr, stderr);
1264 }
1265 while (*line_ptr++ != '\n');
1266 }
1267
1268 return line_ptr;
1269 }
1270
1271 /* Output a three way diff passed as a list of diff3_block's. The
1272 argument MAPPING is indexed by external file number (in the
1273 argument list) and contains the internal file number (from the diff
1274 passed). This is important because the user expects outputs in
1275 terms of the argument list number, and the diff passed may have
1276 been done slightly differently (if the last argument was "-", for
1277 example). REV_MAPPING is the inverse of MAPPING. */
1278
1279 static void
1280 output_diff3 (FILE *outputfile, struct diff3_block *diff,
1281 int const mapping[3], int const rev_mapping[3])
1282 {
1283 int dontprint;
1284 static int skew_increment[3] = { 2, 3, 1 }; /* 0==>2==>1==>3 */
1285 char const *line_prefix = initial_tab ? "\t" : " ";
1286
1287 for (struct diff3_block *ptr = diff; ptr; ptr = D_NEXT (ptr))
1288 {
1289 char x[2];
1290 int oddoneout;
1291
1292 switch (ptr->correspond)
1293 {
1294 case DIFF_ALL:
1295 x[0] = 0;
1296 dontprint = 3; /* Print them all */
1297 oddoneout = 3; /* Nobody's odder than anyone else */
1298 break;
1299 case DIFF_1ST:
1300 case DIFF_2ND:
1301 case DIFF_3RD:
1302 oddoneout = rev_mapping[ptr->correspond - DIFF_1ST];
1303
1304 x[0] = oddoneout + '1';
1305 x[1] = 0;
1306 dontprint = oddoneout == 0;
1307 break;
1308 default:
1309 fatal ("internal error: invalid diff type passed to output");
1310 }
1311 fprintf (outputfile, "====%s\n", x);
1312
1313 /* Go 0, 2, 1 if the first and third outputs are equivalent. */
1314 for (int i = 0; i < 3;
1315 i = (oddoneout == 1 ? skew_increment[i] : i + 1))
1316 {
1317 int realfile = mapping[i];
1318 lin low_t = D_LOWLINE (ptr, realfile);
1319 lin high_t = D_HIGHLINE (ptr, realfile);
1320
1321 fprintf (outputfile, "%d:", i + 1);
1322 switch (low_t - high_t)
1323 {
1324 case 1:
1325 fprintf (outputfile, "%"pI"da\n", low_t - 1);
1326 break;
1327 case 0:
1328 fprintf (outputfile, "%"pI"dc\n", low_t);
1329 break;
1330 default:
1331 fprintf (outputfile, "%"pI"d,%"pI"dc\n", low_t, high_t);
1332 break;
1333 }
1334
1335 if (i == dontprint) continue;
1336
1337 if (low_t <= high_t)
1338 for (lin line = 0; ; line++)
1339 {
1340 fputs (line_prefix, outputfile);
1341 char *cp = D_RELNUM (ptr, realfile, line);
1342 idx_t length = D_RELLEN (ptr, realfile, line);
1343 fwrite (cp, sizeof (char), length, outputfile);
1344 if (high_t - low_t <= line)
1345 {
1346 if (cp[length - 1] != '\n')
1347 fprintf (outputfile, "\n\\ %s\n",
1348 _("No newline at end of file"));
1349 break;
1350 }
1351 }
1352 }
1353 }
1354 }
1355
1356
1357 /* Output to OUTPUTFILE the lines of B taken from FILENUM. Double any
1358 initial '.'s; yield nonzero if any initial '.'s were doubled. */
1359
1360 static bool
1361 dotlines (FILE *outputfile, struct diff3_block *b, int filenum)
1362 {
1363 bool leading_dot = false;
1364
1365 for (lin i = 0;
1366 i < D_NUMLINES (b, filenum);
1367 i++)
1368 {
1369 char *line = D_RELNUM (b, filenum, i);
1370 if (line[0] == '.')
1371 {
1372 leading_dot = true;
1373 fputc ('.', outputfile);
1374 }
1375 fwrite (line, sizeof (char),
1376 D_RELLEN (b, filenum, i), outputfile);
1377 }
1378
1379 return leading_dot;
1380 }
1381
1382 /* Output to OUTPUTFILE a '.' line. If LEADING_DOT is true, also
1383 output a command that removes initial '.'s starting with line START
1384 and continuing for NUM lines. */
1385
1386 static void
1387 undotlines (FILE *outputfile, bool leading_dot, lin start, lin num)
1388 {
1389 fputs (".\n", outputfile);
1390 if (leading_dot)
1391 {
1392 if (num == 1)
1393 fprintf (outputfile, "%"pI"ds/^\\.//\n", start);
1394 else
1395 fprintf (outputfile, "%"pI"d,%"pI"ds/^\\.//\n", start, start + num - 1);
1396 }
1397 }
1398
1399 /* Output a diff3 set of blocks as an ed script. This script applies
1400 the changes between file's 2 & 3 to file 1. Take the precise
1401 format of the ed script to be output from global variables set
1402 during options processing. Reverse the order of
1403 the set of diff3 blocks in DIFF; this gets
1404 around the problems involved with changing line numbers in an ed
1405 script.
1406
1407 As in 'output_diff3', the variable MAPPING maps from file number
1408 according to the argument list to file number according to the diff
1409 passed. All files listed below are in terms of the argument list.
1410 REV_MAPPING is the inverse of MAPPING.
1411
1412 FILE0, FILE1 and FILE2 are the strings to print as the names of the
1413 three files. These may be the actual names, or may be the
1414 arguments specified with -L.
1415
1416 Return true if conflicts were found. */
1417
1418 static bool
1419 output_diff3_edscript (FILE *outputfile, struct diff3_block *diff,
1420 int const mapping[3], int const rev_mapping[3],
1421 char const *file0, char const *file1, char const *file2)
1422 {
1423 bool conflicts_found = false;
1424
1425 for (struct diff3_block *b = reverse_diff3_blocklist (diff); b; b = b->next)
1426 {
1427 /* Must do mapping correctly. */
1428 enum diff_type type
1429 = (b->correspond == DIFF_ALL
1430 ? DIFF_ALL
1431 : DIFF_1ST + rev_mapping[b->correspond - DIFF_1ST]);
1432
1433 /* If we aren't supposed to do this output block, skip it. */
1434 bool conflict;
1435 switch (type)
1436 {
1437 default: continue;
1438 case DIFF_2ND: if (!show_2nd) continue; conflict = true; break;
1439 case DIFF_3RD: if (overlap_only) continue; conflict = false; break;
1440 case DIFF_ALL: if (simple_only) continue; conflict = flagging; break;
1441 }
1442
1443 lin low0 = D_LOWLINE (b, mapping[FILE0]);
1444 lin high0 = D_HIGHLINE (b, mapping[FILE0]);
1445
1446 if (conflict)
1447 {
1448 conflicts_found = true;
1449
1450
1451 /* Mark end of conflict. */
1452
1453 fprintf (outputfile, "%"pI"da\n", high0);
1454 bool leading_dot = false;
1455 if (type == DIFF_ALL)
1456 {
1457 if (show_2nd)
1458 {
1459 /* Append lines from FILE1. */
1460 fprintf (outputfile, "||||||| %s\n", file1);
1461 leading_dot = dotlines (outputfile, b, mapping[FILE1]);
1462 }
1463 /* Append lines from FILE2. */
1464 fputs ("=======\n", outputfile);
1465 leading_dot |= dotlines (outputfile, b, mapping[FILE2]);
1466 }
1467 fprintf (outputfile, ">>>>>>> %s\n", file2);
1468 undotlines (outputfile, leading_dot, high0 + 2,
1469 (D_NUMLINES (b, mapping[FILE1])
1470 + D_NUMLINES (b, mapping[FILE2]) + 1));
1471
1472
1473 /* Mark start of conflict. */
1474
1475 fprintf (outputfile, "%"pI"da\n<<<<<<< %s\n", low0 - 1,
1476 type == DIFF_ALL ? file0 : file1);
1477 leading_dot = false;
1478 if (type == DIFF_2ND)
1479 {
1480 /* Prepend lines from FILE1. */
1481 leading_dot = dotlines (outputfile, b, mapping[FILE1]);
1482 fputs ("=======\n", outputfile);
1483 }
1484 undotlines (outputfile, leading_dot, low0 + 1,
1485 D_NUMLINES (b, mapping[FILE1]));
1486 }
1487 else if (D_NUMLINES (b, mapping[FILE2]) == 0)
1488 /* Write out a delete */
1489 {
1490 if (low0 == high0)
1491 fprintf (outputfile, "%"pI"dd\n", low0);
1492 else
1493 fprintf (outputfile, "%"pI"d,%"pI"dd\n", low0, high0);
1494 }
1495 else
1496 /* Write out an add or change */
1497 {
1498 switch (high0 - low0)
1499 {
1500 case -1:
1501 fprintf (outputfile, "%"pI"da\n", high0);
1502 break;
1503 case 0:
1504 fprintf (outputfile, "%"pI"dc\n", high0);
1505 break;
1506 default:
1507 fprintf (outputfile, "%"pI"d,%"pI"dc\n", low0, high0);
1508 break;
1509 }
1510
1511 undotlines (outputfile, dotlines (outputfile, b, mapping[FILE2]),
1512 low0, D_NUMLINES (b, mapping[FILE2]));
1513 }
1514 }
1515 if (finalwrite)
1516 fputs ("w\nq\n", outputfile);
1517 return conflicts_found;
1518 }
1519
1520 /* Read from INFILE and output to OUTPUTFILE a set of diff3_blocks
1521 DIFF as a merged file. This acts like 'ed file0
1522 <[output_diff3_edscript]', except that it works even for binary
1523 data or incomplete lines.
1524
1525 As before, MAPPING maps from arg list file number to diff file
1526 number, REV_MAPPING is its inverse, and FILE0, FILE1, and FILE2 are
1527 the names of the files.
1528
1529 Return true if conflicts were found. */
1530
1531 static bool
1532 output_diff3_merge (FILE *infile, FILE *outputfile, struct diff3_block *diff,
1533 int const mapping[3], int const rev_mapping[3],
1534 char const *file0, char const *file1, char const *file2)
1535 {
1536 bool conflicts_found = false;
1537 lin linesread = 0;
1538
1539 for (struct diff3_block *b = diff; b; b = b->next)
1540 {
1541 /* Must do mapping correctly. */
1542 enum diff_type type
1543 = ((b->correspond == DIFF_ALL)
1544 ? DIFF_ALL
1545 : DIFF_1ST + rev_mapping[b->correspond - DIFF_1ST]);
1546 char const *format_2nd = "<<<<<<< %s\n";
1547
1548 /* If we aren't supposed to do this output block, skip it. */
1549 bool conflict;
1550 switch (type)
1551 {
1552 default: continue;
1553 case DIFF_2ND: if (!show_2nd) continue; conflict = true; break;
1554 case DIFF_3RD: if (overlap_only) continue; conflict = false; break;
1555 case DIFF_ALL: if (simple_only) continue; conflict = flagging;
1556 format_2nd = "||||||| %s\n";
1557 break;
1558 }
1559
1560 /* Copy I0 lines from file 0. */
1561 lin i0 = D_LOWLINE (b, FILE0) - linesread - 1;
1562 linesread += i0;
1563 while (0 <= --i0)
1564 while (true)
1565 {
1566 int c = getc (infile);
1567 if (c == EOF)
1568 {
1569 if (ferror (infile))
1570 perror_with_exit (_("read failed"));
1571 else if (feof (infile))
1572 fatal ("input file shrank");
1573 }
1574 putc (c, outputfile);
1575 if (c == '\n')
1576 break;
1577 }
1578
1579 if (conflict)
1580 {
1581 conflicts_found = true;
1582
1583 if (type == DIFF_ALL)
1584 {
1585 /* Put in lines from FILE0 with bracket. */
1586 fprintf (outputfile, "<<<<<<< %s\n", file0);
1587 for (lin i = 0;
1588 i < D_NUMLINES (b, mapping[FILE0]);
1589 i++)
1590 fwrite (D_RELNUM (b, mapping[FILE0], i), sizeof (char),
1591 D_RELLEN (b, mapping[FILE0], i), outputfile);
1592 }
1593
1594 if (show_2nd)
1595 {
1596 /* Put in lines from FILE1 with bracket. */
1597 fprintf (outputfile, format_2nd, file1);
1598 for (lin i = 0;
1599 i < D_NUMLINES (b, mapping[FILE1]);
1600 i++)
1601 fwrite (D_RELNUM (b, mapping[FILE1], i), sizeof (char),
1602 D_RELLEN (b, mapping[FILE1], i), outputfile);
1603 }
1604
1605 fputs ("=======\n", outputfile);
1606 }
1607
1608 /* Put in lines from FILE2. */
1609 for (lin i = 0;
1610 i < D_NUMLINES (b, mapping[FILE2]);
1611 i++)
1612 fwrite (D_RELNUM (b, mapping[FILE2], i), sizeof (char),
1613 D_RELLEN (b, mapping[FILE2], i), outputfile);
1614
1615 if (conflict)
1616 fprintf (outputfile, ">>>>>>> %s\n", file2);
1617
1618 /* Skip I1 lines in file 0. */
1619 lin i1 = D_NUMLINES (b, FILE0);
1620 linesread += i1;
1621 while (0 <= --i1)
1622 for (int c; (c = getc (infile)) != '\n'; )
1623 if (c == EOF)
1624 {
1625 if (ferror (infile))
1626 perror_with_exit (_("read failed"));
1627 else if (feof (infile))
1628 {
1629 if (i1 || b->next)
1630 fatal ("input file shrank");
1631 return conflicts_found;
1632 }
1633 }
1634 }
1635 /* Copy rest of common file. */
1636 for (int c;
1637 (c = getc (infile)) != EOF || !(ferror (infile) | feof (infile)); )
1638 putc (c, outputfile);
1639 return conflicts_found;
1640 }
1641
1642 /* Reverse the order of the list of diff3 blocks. */
1643
1644 static struct diff3_block *
1645 reverse_diff3_blocklist (struct diff3_block *diff)
1646 {
1647 struct diff3_block *prev = nullptr;
1648
1649 for (struct diff3_block *tmp = diff; tmp; )
1650 {
1651 struct diff3_block *next = tmp->next;
1652 tmp->next = prev;
1653 prev = tmp;
1654 tmp = next;
1655 }
1656
1657 return prev;
1658 }
1659
1660 static void
1661 fatal (char const *msgid)
1662 {
1663 error (EXIT_TROUBLE, 0, "%s", _(msgid));
1664 }
1665
1666 static void
1667 perror_with_exit (char const *string)
1668 {
1669 error (EXIT_TROUBLE, errno, "%s", string);
1670 }