summaryrefslogtreecommitdiff
path: root/src/merge.c
blob: 9f761d4c0d73f87d037499ef5ee8b170f645e115 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
/*  Merge a patch

    Copyright (C) 2009-2012 Free Software Foundation, Inc.
    Written by Andreas Gruenbacher <agruen@gnu.org>, 2009.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#define XTERN extern
#include <common.h>
#include <minmax.h>
#include <xalloc.h>
#include <inp.h>
#include <pch.h>
#include <util.h>

static lin count_context_lines (void);
static bool context_matches_file (lin, lin);
static void compute_changes (lin, lin, lin, lin, char *, char *);

#define OFFSET lin
#define EQUAL_IDX(x, y) (context_matches_file (x, y))
#include "bestmatch.h"

#define XVECREF_YVECREF_EQUAL(ctxt, x, y) (context_matches_file (x, y))
#define OFFSET lin
#define EXTRA_CONTEXT_FIELDS \
	char *xchar; \
	char *ychar;
#define NOTE_DELETE(ctxt, xoff) ctxt->xchar[xoff] = '-';
#define NOTE_INSERT(ctxt, yoff) ctxt->ychar[yoff] = '+';
#define USE_HEURISTIC 1
#include "diffseq.h"

static lin
locate_merge (lin *matched)
{
    lin first_guess = pch_first () + in_offset;
    lin pat_lines = pch_ptrn_lines ();
    lin context_lines = count_context_lines ();
    lin max_where = input_lines - pat_lines + context_lines + 1;
    lin min_where = last_frozen_line + 1;
    lin max_pos_offset = max_where - first_guess;
    lin max_neg_offset = first_guess - min_where;
    lin max_offset = (max_pos_offset < max_neg_offset
		      ? max_neg_offset : max_pos_offset);
    lin where = first_guess, max_matched = 0;
    lin min, max;
    lin offset;
    bool match_until_eof;

    /* Note: we need to preserve patch's property that it applies hunks at the
       best match closest to their original position in the file.  It is
       common for hunks to apply equally well in several places in a file.
       Applying at the first best match would be a lot easier.
     */

    if (context_lines == 0)
      goto out;  /* locate_hunk() already tried that */

    /* Allow at most CONTEXT_LINES lines to be replaced (replacing counts
       as insert + delete), and require the remaining MIN lines to match.  */
    max = 2 * context_lines;
    min = pat_lines - context_lines;

    if (debug & 1)
      {
	char numbuf0[LINENUM_LENGTH_BOUND + 1];
	char numbuf1[LINENUM_LENGTH_BOUND + 1];
	say ("locating merge: min=%s max=%s ",
	     format_linenum (numbuf0, min),
	     format_linenum (numbuf1, max));
      }

    /* Hunks from the start or end of the file have less context. Anchor them
       to the start or end, trying to make up for this disadvantage.  */
    offset = pch_suffix_context () - pch_prefix_context ();
    if (offset > 0 && pch_first () <= 1)
      max_pos_offset = 0;
    match_until_eof = offset < 0;

    /* Do not try lines <= 0.  */
    if (first_guess <= max_neg_offset)
      max_neg_offset = first_guess - 1;

    for (offset = 0; offset <= max_offset; offset++)
      {
	if (offset <= max_pos_offset)
	  {
	    lin guess = first_guess + offset;
	    lin last;
	    lin changes;

	    changes = bestmatch (1, pat_lines + 1, guess, input_lines + 1,
				 match_until_eof ? input_lines - guess + 1 : min,
				 max, &last);
	    if (changes <= max && max_matched < last - guess)
	      {
		max_matched = last - guess;
		where = guess;
		if (changes == 0)
		  break;
		min = last - guess;
		max = changes - 1;
	      }
	  }
	if (0 < offset && offset <= max_neg_offset)
	  {
	    lin guess = first_guess - offset;
	    lin last;
	    lin changes;

	    changes = bestmatch (1, pat_lines + 1, guess, input_lines + 1,
				 match_until_eof ? input_lines - guess + 1 : min,
				 max, &last);
	    if (changes <= max && max_matched < last - guess)
	      {
		max_matched = last - guess;
		where = guess;
		if (changes == 0)
		  break;
		min = last - guess;
		max = changes - 1;
	      }
	  }
      }
    if (debug & 1)
      {
	char numbuf0[LINENUM_LENGTH_BOUND + 1];
	char numbuf1[LINENUM_LENGTH_BOUND + 1];
	char numbuf2[LINENUM_LENGTH_BOUND + 1];
	say ("where=%s matched=%s changes=%s\n",
	     format_linenum (numbuf0, where),
	     format_linenum (numbuf1, max_matched),
	     format_linenum (numbuf2, max + 1));
      }

  out:
    *matched = max_matched;
    if (where < min_where)
      where = min_where;
    return where;
}

static void
print_linerange (lin from, lin to)
{
  char numbuf0[LINENUM_LENGTH_BOUND + 1];
  char numbuf1[LINENUM_LENGTH_BOUND + 1];

  if (to <= from)
    printf ("%s",
	    format_linenum (numbuf0, from));
  else
    printf ("%s-%s",
	    format_linenum (numbuf0, from),
	    format_linenum (numbuf1, to));
}

static void
merge_result (bool *first_result, int hunk, char const *what, lin from, lin to)
{
  static char const *last_what;

  if (*first_result && what)
    {
      printf ("Hunk #%d %s at ", hunk, what);
      last_what = what;
    }
  else if (! what)
    {
      if (! *first_result)
	{
	  fputs (".\n", stdout);
	  fflush (stdout);
	  last_what = 0;
	}
      return;
    }
  else if (last_what == what)
    fputs (",", stdout);
  else
    printf (", %s at ", what);
  print_linerange (from + out_offset, to + out_offset);
  *first_result = false;
}

bool
merge_hunk (int hunk, struct outstate *outstate, lin where, bool *somefailed)
{
  bool applies_cleanly;
  bool first_result = true;
  bool already_applied;
  FILE *fp = outstate->ofp;
  lin old = 1;
  lin firstold = pch_ptrn_lines ();
  lin new = firstold + 1;
  lin firstnew = pch_end ();
  lin in;
  lin firstin;
  char *oldin;
  lin matched;
  lin lastwhere;

  /* Convert '!' markers into '-' and '+' to simplify things here.  */
  pch_normalize (UNI_DIFF);

  assert (pch_char (firstnew + 1) == '^');
  while (pch_char (new) == '=' || pch_char (new) == '\n')
    new++;

  if (where)
    {
      applies_cleanly = true;
      matched = pch_ptrn_lines ();
    }
  else
    {
      where = locate_merge (&matched);
      applies_cleanly = false;
    }

  in = firstold + 2;
  oldin = xmalloc (in + matched + 1);
  memset (oldin, ' ', in + matched);
  oldin[0] = '*';
  oldin[in - 1] = '=';
  oldin[in + matched] = '^';
  compute_changes (old, in - 1, where, where + matched,
		   oldin + old, oldin + in);

  if (debug & 2)
    {
      char numbuf0[LINENUM_LENGTH_BOUND + 1];
      char numbuf1[LINENUM_LENGTH_BOUND + 1];
      lin n;

      fputc ('\n', stderr);
      for (n = 0; n <= in + matched; n++)
	{
	  fprintf (stderr, "%s %c",
		  format_linenum (numbuf0, n),
		  oldin[n]);
	  if (n == 0)
	    fprintf(stderr, " %s,%s\n",
		    format_linenum (numbuf0, pch_first()),
		    format_linenum (numbuf1, pch_ptrn_lines()));
	  else if (n <= firstold)
	    fprintf (stderr, " |%.*s",
		     (int) pch_line_len (n), pfetch (n));
	  else if (n == in - 1)
	    fprintf(stderr, " %s,%s\n",
		    format_linenum (numbuf0, where),
		    format_linenum (numbuf1, matched));
	  else if (n >= in && n < in + matched)
	    {
	      size_t size;
	      const char *line;

	      line = ifetch (where + n - in, false, &size);
	      fprintf (stderr, " |%.*s",
		       (int) size, line);
	    }
	  else
	    fputc('\n', stderr);
	}
      fflush (stderr);
    }

  if (last_frozen_line < where - 1)
    if (! copy_till (outstate, where - 1))
      return false;

  for (;;)
    {
      firstold = old;
      firstnew = new;
      firstin = in;

      if (pch_char (old) == '-' || pch_char (new) == '+')
	{
	  lin lines;

	  while (pch_char (old) == '-')
	    {
	      if (oldin[old] == '-' || oldin[in] == '+')
		goto conflict;
	      else if (oldin[old] == ' ')
		{
		  assert (oldin[in] == ' ');
		  in++;
		}
	      old++;
	    }
	  if (oldin[old] == '-' || oldin[in] == '+')
	    goto conflict;
	  while (pch_char (new) == '+')
	    new++;

	  lines = new - firstnew;
	  if (verbosity == VERBOSE
	      || ((verbosity != SILENT) && ! applies_cleanly))
	    merge_result (&first_result, hunk, "merged",
			  where, where + lines - 1);
	  last_frozen_line += (old - firstold);
	  where += (old - firstold);
	  out_offset += new - firstnew;

	  if (firstnew < new)
	    {
	      while (firstnew < new)
		{
		  outstate->after_newline = pch_write_line (firstnew, fp);
		  firstnew++;
		}
	      outstate->zero_output = false;
	    }
	}
      else if (pch_char (old) == ' ')
	{
	  if (oldin[old] == '-')
	    {
	      while (pch_char (old) == ' ')
		{
		  if (oldin[old] != '-')
		    break;
		  if (pch_char (new) == '+')
		    goto conflict;
		  else
		    assert (pch_char (new) == ' ');
		  old++;
		  new++;
		}
	      if (pch_char (old) == '-' || pch_char (new) == '+')
		goto conflict;
	    }
	  else if (oldin[in] == '+')
	    {
	      while (oldin[in] == '+')
		in++;

	      /* Take these lines from the input file.  */
	      where += in - firstin;
	      if (! copy_till (outstate, where - 1))
		return false;
	    }
	  else if (oldin[old] == ' ')
	    {
	      while (pch_char (old) == ' '
		     && oldin[old] == ' '
		     && pch_char (new) == ' '
		     && oldin[in] == ' ')
		{
		  old++;
		  new++;
		  in++;
		}

	      /* Take these lines from the input file.  */
	      where += (in - firstin);
	      if (! copy_till (outstate, where - 1))
		return false;
	    }
	}
      else
	{
	  assert (pch_char (old) == '=' && pch_char (new) == '^');
	  /* Nothing more left to merge.  */
	  break;
	}
      continue;

    conflict:
      /* Find the end of the conflict.  */
      for (;;)
	{
	  if (pch_char (old) == '-')
	    {
	      while (oldin[in] == '+')
		in++;
	      if (oldin[old] == ' ')
		{
		  assert (oldin[in] == ' ');
		  in++;
		}
	      old++;
	    }
	  else if (oldin[old] == '-')
	    {
	      while (pch_char (new) == '+')
		new++;
	      if (pch_char (old) == ' ')
		{
		  assert (pch_char (new) == ' ');
		  new++;
		}
	      old++;
	    }
	  else if (pch_char (new) == '+')
	    while (pch_char (new) == '+')
	      new++;
	  else if (oldin[in] == '+')
	    while (oldin[in] == '+')
	      in++;
	  else
	    break;
	}
      assert (((pch_char (old) == ' ' && pch_char (new) == ' ')
	       || (pch_char (old) == '=' && pch_char (new) == '^'))
	      && ((oldin[old] == ' ' && oldin[in] == ' ')
		  || (oldin[old] == '=' && oldin[in] == '^')));

      /* Output common prefix lines.  */
      for (lastwhere = where;
	   firstin < in && firstnew < new
	     && context_matches_file (firstnew, lastwhere);
	   firstin++, firstnew++, lastwhere++)
	/* do nothing */ ;
      already_applied = (firstin == in && firstnew == new);
      if (already_applied)
	merge_result (&first_result, hunk, "already applied",
		      where, lastwhere - 1);
      if (conflict_style == MERGE_DIFF3)
	{
	  lin common_prefix = lastwhere - where;

	  /* Forget about common prefix lines.  */
	  firstin -= common_prefix;
	  firstnew -= common_prefix;
	  lastwhere -= common_prefix;
	}
      if (where != lastwhere)
	{
	  where = lastwhere;
	  if (! copy_till (outstate, where - 1))
	    return false;
	}

      if (! already_applied)
	{
	  lin common_suffix = 0;
	  lin lines;

	  if (conflict_style == MERGE_MERGE)
	    {
	      /* Remember common suffix lines.  */
	      for (lastwhere = where + (in - firstin);
		   firstin < in && firstnew < new
		   && context_matches_file (new - 1, lastwhere - 1);
		   in--, new--, lastwhere--, common_suffix++)
		/* do nothing */ ;
	    }

	  lines = 3 + (in - firstin) + (new - firstnew);
	  if (conflict_style == MERGE_DIFF3)
	    lines += 1 + (old - firstold);
	  merge_result (&first_result, hunk, "NOT MERGED",
			where, where + lines - 1);
	  out_offset += lines - (in - firstin);

	  fputs (outstate->after_newline + "\n<<<<<<<\n", fp);
	  outstate->after_newline = true;
	  if (firstin < in)
	    {
	      where += (in - firstin);
	      if (! copy_till (outstate, where - 1))
		return false;
	    }

	  if (conflict_style == MERGE_DIFF3)
	    {
	      fputs (outstate->after_newline + "\n|||||||\n", fp);
	      outstate->after_newline = true;
	      while (firstold < old)
		{
		  outstate->after_newline = pch_write_line (firstold, fp);
		  firstold++;
		}
	    }

	  fputs (outstate->after_newline + "\n=======\n", fp);
	  outstate->after_newline = true;
	  while (firstnew < new)
	    {
	      outstate->after_newline = pch_write_line (firstnew, fp);
	      firstnew++;
	    }
	  fputs (outstate->after_newline + "\n>>>>>>>\n", fp);
	  outstate->after_newline = true;
	  outstate->zero_output = false;
	  if (ferror (fp))
	    write_fatal ();

	  /* Output common suffix lines.  */
	  if (common_suffix)
	    {
	      where += common_suffix;
	      if (! copy_till (outstate, where - 1))
		return false;
	      in += common_suffix;
	      new += common_suffix;
	    }
	  *somefailed = true;
	}
    }
  merge_result (&first_result, 0, 0, 0, 0);

  assert (last_frozen_line == where - 1);
  free (oldin);
  return true;
}

static lin
count_context_lines (void)
{
  lin old;
  lin lastold = pch_ptrn_lines ();
  lin context;

  for (context = 0, old = 1; old <= lastold; old++)
    if (pch_char (old) == ' ')
      context++;
  return context;
}

static bool
context_matches_file (lin old, lin where)
{
  size_t size;
  const char *line;

  line = ifetch (where, false, &size);
  return size &&
	 (canonicalize_ws ?
	  similar (pfetch (old), pch_line_len (old), line, size) :
	  (size == pch_line_len (old) &&
	   memcmp (line, pfetch (old), size) == 0));
}

static void
compute_changes (lin xmin, lin xmax, lin ymin, lin ymax,
		 char *xchar, char *ychar)
{
  struct context ctxt;
  lin diags;

  ctxt.xchar = xchar - xmin;
  ctxt.ychar = ychar - ymin;

  diags = xmax + ymax + 3;
  ctxt.fdiag = xmalloc (2 * diags * sizeof (*ctxt.fdiag));
  ctxt.bdiag = ctxt.fdiag + diags;
  ctxt.fdiag += ymax + 1;
  ctxt.bdiag += ymax + 1;

  ctxt.heuristic = true;

  compareseq (xmin, xmax, ymin, ymax, &ctxt);

  ctxt.fdiag -= ymax + 1;
  free (ctxt.fdiag);
}