monotone

monotone Mtn Source Tree

Root/diff_patch.cc

1// Copyright (C) 2002 Graydon Hoare <graydon@pobox.com>
2//
3// This program is made available under the GNU GPL version 2.0 or
4// greater. See the accompanying file COPYING for details.
5//
6// This program is distributed WITHOUT ANY WARRANTY; without even the
7// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
8// PURPOSE.
9
10
11#include "base.hh"
12#include <algorithm>
13#include <iterator>
14#include <map>
15#include "vector.hh"
16
17#include <boost/shared_ptr.hpp>
18#include <boost/scoped_ptr.hpp>
19#include "diff_patch.hh"
20#include "interner.hh"
21#include "lcs.hh"
22#include "roster.hh"
23#include "safe_map.hh"
24#include "sanity.hh"
25#include "xdelta.hh"
26#include "simplestring_xform.hh"
27#include "vocab.hh"
28#include "revision.hh"
29#include "constants.hh"
30#include "file_io.hh"
31#include "pcrewrap.hh"
32#include "lua_hooks.hh"
33#include "database.hh"
34#include "transforms.hh"
35
36using std::make_pair;
37using std::map;
38using std::min;
39using std::max;
40using std::ostream;
41using std::ostream_iterator;
42using std::string;
43using std::swap;
44using std::vector;
45
46using boost::shared_ptr;
47
48//
49// a 3-way merge works like this:
50//
51// /----> right
52// ancestor
53// \----> left
54//
55// first you compute the edit list "EDITS(ancestor,left)".
56//
57// then you make an offset table "leftpos" which describes positions in
58// "ancestor" as they map to "left"; that is, for 0 < apos <
59// ancestor.size(), we have
60//
61// left[leftpos[apos]] == ancestor[apos]
62//
63// you do this by walking through the edit list and either jumping the
64// current index ahead an extra position, on an insert, or remaining still,
65// on a delete. on an insert *or* a delete, you push the current index back
66// onto the leftpos array.
67//
68// next you compute the edit list "EDITS(ancestor,right)".
69//
70// you then go through this edit list applying the edits to left, rather
71// than ancestor, and using the table leftpos to map the position of each
72// edit to an appropriate spot in left. this means you walk a "curr_left"
73// index through the edits, and for each edit e:
74//
75// - if e is a delete (and e.pos is a position in ancestor)
76// - increment curr_left without copying anything to "merged"
77//
78// - if e is an insert (and e.pos is a position in right)
79// - copy right[e.pos] to "merged"
80// - leave curr_left alone
81//
82// - when advancing to apos (and apos is a position in ancestor)
83// - copy left[curr_left] to merged while curr_left < leftpos[apos]
84//
85//
86// the practical upshot is that you apply the delta from ancestor->right
87// to the adjusted contexts in left, producing something vaguely like
88// the concatenation of delta(ancestor,left) :: delta(ancestor,right).
89//
90// NB: this is, as far as I can tell, what diff3 does. I don't think I'm
91// infringing on anyone's fancy patents here.
92//
93
94typedef enum { preserved = 0, deleted = 1, changed = 2 } edit_t;
95static const char etab[3][10] =
96 {
97 "preserved",
98 "deleted",
99 "changed"
100 };
101
102struct extent
103{
104 extent(size_t p, size_t l, edit_t t)
105 : pos(p), len(l), type(t)
106 {}
107 size_t pos;
108 size_t len;
109 edit_t type;
110};
111
112void calculate_extents(vector<long, QA(long)> const & a_b_edits,
113 vector<long, QA(long)> const & b,
114 vector<long, QA(long)> & prefix,
115 vector<extent> & extents,
116 vector<long, QA(long)> & suffix,
117 size_t const a_len,
118 interner<long> & intern)
119{
120 extents.reserve(a_len * 2);
121
122 size_t a_pos = 0, b_pos = 0;
123
124 for (vector<long, QA(long)>::const_iterator i = a_b_edits.begin();
125 i != a_b_edits.end(); ++i)
126 {
127 // L(FL("edit: %d") % *i);
128 if (*i < 0)
129 {
130 // negative elements code the negation of the one-based index into A
131 // of the element to be deleted
132 size_t a_deleted = (-1 - *i);
133
134 // fill positions out to the deletion point
135 while (a_pos < a_deleted)
136 {
137 a_pos++;
138 extents.push_back(extent(b_pos++, 1, preserved));
139 }
140
141 // L(FL(" -- delete at A-pos %d (B-pos = %d)") % a_deleted % b_pos);
142
143 // skip the deleted line
144 a_pos++;
145 extents.push_back(extent(b_pos, 0, deleted));
146 }
147 else
148 {
149 // positive elements code the one-based index into B of the element to
150 // be inserted
151 size_t b_inserted = (*i - 1);
152
153 // fill positions out to the insertion point
154 while (b_pos < b_inserted)
155 {
156 a_pos++;
157 extents.push_back(extent(b_pos++, 1, preserved));
158 }
159
160 // L(FL(" -- insert at B-pos %d (A-pos = %d) : '%s'")
161 // % b_inserted % a_pos % intern.lookup(b.at(b_inserted)));
162
163 // record that there was an insertion, but a_pos did not move.
164 if ((b_pos == 0 && extents.empty())
165 || (b_pos == prefix.size()))
166 {
167 prefix.push_back(b.at(b_pos));
168 }
169 else if (a_len == a_pos)
170 {
171 suffix.push_back(b.at(b_pos));
172 }
173 else
174 {
175 // make the insertion
176 extents.back().type = changed;
177 extents.back().len++;
178 }
179 b_pos++;
180 }
181 }
182
183 while (extents.size() < a_len)
184 extents.push_back(extent(b_pos++, 1, preserved));
185}
186
187void normalize_extents(vector<extent> & a_b_map,
188 vector<long, QA(long)> const & a,
189 vector<long, QA(long)> const & b)
190{
191 for (size_t i = 0; i < a_b_map.size(); ++i)
192 {
193 if (i > 0)
194 {
195 size_t j = i;
196 while (j > 0
197 && (a_b_map.at(j-1).type == preserved)
198 && (a_b_map.at(j).type == changed)
199 && (a.at(j) == b.at(a_b_map.at(j).pos + a_b_map.at(j).len - 1)))
200 {
201 // This is implied by (a_b_map.at(j-1).type == preserved)
202 I(a.at(j-1) == b.at(a_b_map.at(j-1).pos));
203
204 // Coming into loop we have:
205 // i
206 // z --pres--> z 0
207 // o --pres--> o 1
208 // a --chng--> a 2 The important thing here is that 'a' in
209 // t the LHS matches with ...
210 // u
211 // v
212 // a ... the a on the RHS here. Hence we can
213 // q --pres--> q 3 'shift' the entire 'changed' block
214 // e --chng--> d 4 upwards, leaving a 'preserved' line
215 // g --pres--> g 5 'a'->'a'
216 //
217 // Want to end up with:
218 // i
219 // z --pres--> z 0
220 // o --chng--> o 1
221 // a
222 // t
223 // u
224 // v
225 // a --pres--> a 2
226 // q --pres--> q 3
227 // e --chng--> d 4
228 // g --pres--> g 5
229 //
230 // Now all the 'changed' extents are normalised to the
231 // earliest possible position.
232
233 L(FL("exchanging preserved extent [%d+%d] with changed extent [%d+%d]")
234 % a_b_map.at(j-1).pos
235 % a_b_map.at(j-1).len
236 % a_b_map.at(j).pos
237 % a_b_map.at(j).len);
238
239 swap(a_b_map.at(j-1).len, a_b_map.at(j).len);
240 swap(a_b_map.at(j-1).type, a_b_map.at(j).type);
241
242 // Adjust position of the later, preserved extent. It should
243 // better point to the second 'a' in the above example.
244 a_b_map.at(j).pos = a_b_map.at(j-1).pos + a_b_map.at(j-1).len;
245
246 --j;
247 }
248 }
249 }
250
251 for (size_t i = 0; i < a_b_map.size(); ++i)
252 {
253 if (i > 0)
254 {
255 size_t j = i;
256 while (j > 0
257 && a_b_map.at(j).type == changed
258 && a_b_map.at(j-1).type == changed
259 && a_b_map.at(j).len > 1
260 && a_b_map.at(j-1).pos + a_b_map.at(j-1).len == a_b_map.at(j).pos)
261 {
262 // step 1: move a chunk from this insert extent to its
263 // predecessor
264 size_t piece = a_b_map.at(j).len - 1;
265 // L(FL("moving change piece of len %d from pos %d to pos %d")
266 // % piece
267 // % a_b_map.at(j).pos
268 // % a_b_map.at(j-1).pos);
269 a_b_map.at(j).len = 1;
270 a_b_map.at(j).pos += piece;
271 a_b_map.at(j-1).len += piece;
272
273 // step 2: if this extent (now of length 1) has become a "changed"
274 // extent identical to its previous state, switch it to a "preserved"
275 // extent.
276 if (b.at(a_b_map.at(j).pos) == a.at(j))
277 {
278 // L(FL("changing normalized 'changed' extent at %d to 'preserved'")
279 // % a_b_map.at(j).pos);
280 a_b_map.at(j).type = preserved;
281 }
282 --j;
283 }
284 }
285 }
286}
287
288
289void merge_extents(vector<extent> const & a_b_map,
290 vector<extent> const & a_c_map,
291 vector<long, QA(long)> const & b,
292 vector<long, QA(long)> const & c,
293 interner<long> const & in,
294 vector<long, QA(long)> & merged)
295{
296 I(a_b_map.size() == a_c_map.size());
297
298 vector<extent>::const_iterator i = a_b_map.begin();
299 vector<extent>::const_iterator j = a_c_map.begin();
300 merged.reserve(a_b_map.size() * 2);
301
302 // for (; i != a_b_map.end(); ++i, ++j)
303 // {
304
305 // L(FL("trying to merge: [%s %d %d] vs. [%s %d %d]")
306 // % etab[i->type] % i->pos % i->len
307 // % etab[j->type] % j->pos % j->len);
308 // }
309
310 // i = a_b_map.begin();
311 // j = a_c_map.begin();
312
313 for (; i != a_b_map.end(); ++i, ++j)
314 {
315
316 // L(FL("trying to merge: [%s %d %d] vs. [%s %d %d]")
317 // % etab[i->type] % i->pos % i->len
318 // % etab[j->type] % j->pos % j->len);
319
320 // mutual, identical preserves / inserts / changes
321 if (((i->type == changed && j->type == changed)
322 || (i->type == preserved && j->type == preserved))
323 && i->len == j->len)
324 {
325 for (size_t k = 0; k < i->len; ++k)
326 {
327 if (b.at(i->pos + k) != c.at(j->pos + k))
328 {
329 L(FL("conflicting edits: %s %d[%d] '%s' vs. %s %d[%d] '%s'")
330 % etab[i->type] % i->pos % k % in.lookup(b.at(i->pos + k))
331 % etab[j->type] % j->pos % k % in.lookup(c.at(j->pos + k)));
332 throw conflict();
333 }
334 merged.push_back(b.at(i->pos + k));
335 }
336 }
337
338 // mutual or single-edge deletes
339 else if ((i->type == deleted && j->type == deleted)
340 || (i->type == deleted && j->type == preserved)
341 || (i->type == preserved && j->type == deleted))
342 {
343 // do nothing
344 }
345
346 // single-edge insert / changes
347 else if (i->type == changed && j->type == preserved)
348 for (size_t k = 0; k < i->len; ++k)
349 merged.push_back(b.at(i->pos + k));
350
351 else if (i->type == preserved && j->type == changed)
352 for (size_t k = 0; k < j->len; ++k)
353 merged.push_back(c.at(j->pos + k));
354
355 else
356 {
357 L(FL("conflicting edits: [%s %d %d] vs. [%s %d %d]")
358 % etab[i->type] % i->pos % i->len
359 % etab[j->type] % j->pos % j->len);
360 throw conflict();
361 }
362
363 // if (merged.empty())
364 // L(FL(" --> EMPTY"));
365 // else
366 // L(FL(" --> [%d]: %s") % (merged.size() - 1) % in.lookup(merged.back()));
367 }
368}
369
370
371void merge_via_edit_scripts(vector<string> const & ancestor,
372 vector<string> const & left,
373 vector<string> const & right,
374 vector<string> & merged)
375{
376 vector<long, QA(long)> anc_interned;
377 vector<long, QA(long)> left_interned, right_interned;
378 vector<long, QA(long)> left_edits, right_edits;
379 vector<long, QA(long)> left_prefix, right_prefix;
380 vector<long, QA(long)> left_suffix, right_suffix;
381 vector<extent> left_extents, right_extents;
382 vector<long, QA(long)> merged_interned;
383 interner<long> in;
384
385 // for (int i = 0; i < min(min(left.size(), right.size()), ancestor.size()); ++i)
386 // {
387 // cerr << '[' << i << "] " << left[i] << ' ' << ancestor[i] << ' ' << right[i] << '\n';
388 // }
389
390 anc_interned.reserve(ancestor.size());
391 for (vector<string>::const_iterator i = ancestor.begin();
392 i != ancestor.end(); ++i)
393 anc_interned.push_back(in.intern(*i));
394
395 left_interned.reserve(left.size());
396 for (vector<string>::const_iterator i = left.begin();
397 i != left.end(); ++i)
398 left_interned.push_back(in.intern(*i));
399
400 right_interned.reserve(right.size());
401 for (vector<string>::const_iterator i = right.begin();
402 i != right.end(); ++i)
403 right_interned.push_back(in.intern(*i));
404
405 L(FL("calculating left edit script on %d -> %d lines")
406 % anc_interned.size() % left_interned.size());
407
408 edit_script(anc_interned.begin(), anc_interned.end(),
409 left_interned.begin(), left_interned.end(),
410 min(ancestor.size(), left.size()),
411 left_edits);
412
413 L(FL("calculating right edit script on %d -> %d lines")
414 % anc_interned.size() % right_interned.size());
415
416 edit_script(anc_interned.begin(), anc_interned.end(),
417 right_interned.begin(), right_interned.end(),
418 min(ancestor.size(), right.size()),
419 right_edits);
420
421 L(FL("calculating left extents on %d edits") % left_edits.size());
422 calculate_extents(left_edits, left_interned,
423 left_prefix, left_extents, left_suffix,
424 anc_interned.size(), in);
425
426 L(FL("calculating right extents on %d edits") % right_edits.size());
427 calculate_extents(right_edits, right_interned,
428 right_prefix, right_extents, right_suffix,
429 anc_interned.size(), in);
430
431 L(FL("normalizing %d right extents") % right_extents.size());
432 normalize_extents(right_extents, anc_interned, right_interned);
433
434 L(FL("normalizing %d left extents") % left_extents.size());
435 normalize_extents(left_extents, anc_interned, left_interned);
436
437
438 if ((!right_prefix.empty()) && (!left_prefix.empty()))
439 {
440 L(FL("conflicting prefixes"));
441 throw conflict();
442 }
443
444 if ((!right_suffix.empty()) && (!left_suffix.empty()))
445 {
446 L(FL("conflicting suffixes"));
447 throw conflict();
448 }
449
450 L(FL("merging %d left, %d right extents")
451 % left_extents.size() % right_extents.size());
452
453 copy(left_prefix.begin(), left_prefix.end(), back_inserter(merged_interned));
454 copy(right_prefix.begin(), right_prefix.end(), back_inserter(merged_interned));
455
456 merge_extents(left_extents, right_extents,
457 left_interned, right_interned,
458 in, merged_interned);
459
460 copy(left_suffix.begin(), left_suffix.end(), back_inserter(merged_interned));
461 copy(right_suffix.begin(), right_suffix.end(), back_inserter(merged_interned));
462
463 merged.reserve(merged_interned.size());
464 for (vector<long, QA(long)>::const_iterator i = merged_interned.begin();
465 i != merged_interned.end(); ++i)
466 merged.push_back(in.lookup(*i));
467}
468
469
470bool merge3(vector<string> const & ancestor,
471 vector<string> const & left,
472 vector<string> const & right,
473 vector<string> & merged)
474{
475 try
476 {
477 merge_via_edit_scripts(ancestor, left, right, merged);
478 }
479 catch(conflict &)
480 {
481 L(FL("conflict detected. no merge."));
482 return false;
483 }
484 return true;
485}
486
487
488///////////////////////////////////////////////////////////////////////////
489// content_merge_database_adaptor
490///////////////////////////////////////////////////////////////////////////
491
492
493content_merge_database_adaptor::content_merge_database_adaptor(database & db,
494 revision_id const & left,
495 revision_id const & right,
496 marking_map const & left_mm,
497 marking_map const & right_mm)
498 : db(db), left_mm(left_mm), right_mm(right_mm)
499{
500 // FIXME: possibly refactor to run this lazily, as we don't
501 // need to find common ancestors if we're never actually
502 // called on to do content merging.
503 find_common_ancestor_for_merge(db, left, right, lca);
504}
505
506void
507content_merge_database_adaptor::record_merge(file_id const & left_ident,
508 file_id const & right_ident,
509 file_id const & merged_ident,
510 file_data const & left_data,
511 file_data const & right_data,
512 file_data const & merged_data)
513{
514 L(FL("recording successful merge of %s <-> %s into %s")
515 % left_ident
516 % right_ident
517 % merged_ident);
518
519 transaction_guard guard(db);
520
521 if (!(left_ident == merged_ident))
522 {
523 delta left_delta;
524 diff(left_data.inner(), merged_data.inner(), left_delta);
525 db.put_file_version(left_ident, merged_ident, file_delta(left_delta));
526 }
527 if (!(right_ident == merged_ident))
528 {
529 delta right_delta;
530 diff(right_data.inner(), merged_data.inner(), right_delta);
531 db.put_file_version(right_ident, merged_ident, file_delta(right_delta));
532 }
533 guard.commit();
534}
535
536static void
537load_and_cache_roster(database & db, revision_id const & rid,
538 map<revision_id, shared_ptr<roster_t const> > & rmap,
539 shared_ptr<roster_t const> & rout)
540{
541 map<revision_id, shared_ptr<roster_t const> >::const_iterator i = rmap.find(rid);
542 if (i != rmap.end())
543 rout = i->second;
544 else
545 {
546 cached_roster cr;
547 db.get_roster(rid, cr);
548 safe_insert(rmap, make_pair(rid, cr.first));
549 rout = cr.first;
550 }
551}
552
553void
554content_merge_database_adaptor::get_ancestral_roster(node_id nid,
555 revision_id & rid,
556 shared_ptr<roster_t const> & anc)
557{
558 // Given a file, if the lca is nonzero and its roster contains the file,
559 // then we use its roster. Otherwise we use the roster at the file's
560 // birth revision, which is the "per-file worst case" lca.
561
562 // Begin by loading any non-empty file lca roster
563 rid = lca;
564 if (!lca.inner()().empty())
565 load_and_cache_roster(db, lca, rosters, anc);
566
567 // If there is no LCA, or the LCA's roster doesn't contain the file,
568 // then use the file's birth roster.
569 if (!anc || !anc->has_node(nid))
570 {
571 marking_map::const_iterator lmm = left_mm.find(nid);
572 marking_map::const_iterator rmm = right_mm.find(nid);
573
574 MM(left_mm);
575 MM(right_mm);
576
577 if (lmm == left_mm.end())
578 {
579 I(rmm != right_mm.end());
580 rid = rmm->second.birth_revision;
581 }
582 else if (rmm == right_mm.end())
583 {
584 I(lmm != left_mm.end());
585 rid = lmm->second.birth_revision;
586 }
587 else
588 {
589 I(lmm->second.birth_revision == rmm->second.birth_revision);
590 rid = lmm->second.birth_revision;
591 }
592
593 load_and_cache_roster(db, rid, rosters, anc);
594 }
595 I(anc);
596}
597
598void
599content_merge_database_adaptor::get_version(file_id const & ident,
600 file_data & dat) const
601{
602 db.get_file_version(ident, dat);
603}
604
605
606///////////////////////////////////////////////////////////////////////////
607// content_merge_workspace_adaptor
608///////////////////////////////////////////////////////////////////////////
609
610void
611content_merge_workspace_adaptor::cache_roster(revision_id const & rid,
612 boost::shared_ptr<roster_t const> roster)
613{
614 rosters.insert(std::make_pair(rid, roster));
615}
616
617void
618content_merge_workspace_adaptor::record_merge(file_id const & left_id,
619 file_id const & right_id,
620 file_id const & merged_id,
621 file_data const & left_data,
622 file_data const & right_data,
623 file_data const & merged_data)
624{
625 L(FL("temporarily recording merge of %s <-> %s into %s")
626 % left_id
627 % right_id
628 % merged_id);
629 // this is an insert instead of a safe_insert because it is perfectly
630 // legal (though rare) to have multiple merges resolve to the same file
631 // contents.
632 temporary_store.insert(make_pair(merged_id, merged_data));
633}
634
635void
636content_merge_workspace_adaptor::get_ancestral_roster(node_id nid,
637 revision_id & rid,
638 shared_ptr<roster_t const> & anc)
639{
640 // Begin by loading any non-empty file lca roster
641 if (base->has_node(nid))
642 {
643 rid = lca;
644 anc = base;
645 }
646 else
647 {
648 marking_map::const_iterator lmm = left_mm.find(nid);
649 marking_map::const_iterator rmm = right_mm.find(nid);
650
651 MM(left_mm);
652 MM(right_mm);
653
654 if (lmm == left_mm.end())
655 {
656 I(rmm != right_mm.end());
657 rid = rmm->second.birth_revision;
658 }
659 else if (rmm == right_mm.end())
660 {
661 I(lmm != left_mm.end());
662 rid = lmm->second.birth_revision;
663 }
664 else
665 {
666 I(lmm->second.birth_revision == rmm->second.birth_revision);
667 rid = lmm->second.birth_revision;
668 }
669
670 load_and_cache_roster(db, rid, rosters, anc);
671 }
672 I(anc);
673}
674
675void
676content_merge_workspace_adaptor::get_version(file_id const & ident,
677 file_data & dat) const
678{
679 map<file_id,file_data>::const_iterator i = temporary_store.find(ident);
680 if (i != temporary_store.end())
681 dat = i->second;
682 else if (db.file_version_exists(ident))
683 db.get_file_version(ident, dat);
684 else
685 {
686 data tmp;
687 file_id fid;
688 map<file_id, file_path>::const_iterator i = content_paths.find(ident);
689 I(i != content_paths.end());
690
691 require_path_is_file(i->second,
692 F("file '%s' does not exist in workspace") % i->second,
693 F("'%s' in workspace is a directory, not a file") % i->second);
694 read_data(i->second, tmp);
695 calculate_ident(file_data(tmp), fid);
696 E(fid == ident,
697 F("file %s in workspace has id %s, wanted %s")
698 % i->second
699 % fid
700 % ident);
701 dat = file_data(tmp);
702 }
703}
704
705
706///////////////////////////////////////////////////////////////////////////
707// content_merge_checkout_adaptor
708///////////////////////////////////////////////////////////////////////////
709
710void
711content_merge_checkout_adaptor::record_merge(file_id const & left_ident,
712 file_id const & right_ident,
713 file_id const & merged_ident,
714 file_data const & left_data,
715 file_data const & right_data,
716 file_data const & merged_data)
717{
718 I(false);
719}
720
721void
722content_merge_checkout_adaptor::get_ancestral_roster(node_id nid,
723 revision_id & rid,
724 shared_ptr<roster_t const> & anc)
725{
726 I(false);
727}
728
729void
730content_merge_checkout_adaptor::get_version(file_id const & ident,
731 file_data & dat) const
732{
733 db.get_file_version(ident, dat);
734}
735
736
737///////////////////////////////////////////////////////////////////////////
738// content_merger
739///////////////////////////////////////////////////////////////////////////
740
741string
742content_merger::get_file_encoding(file_path const & path,
743 roster_t const & ros)
744{
745 attr_value v;
746 if (ros.get_attr(path, attr_key(constants::encoding_attribute), v))
747 return v();
748 return constants::default_encoding;
749}
750
751bool
752content_merger::attribute_manual_merge(file_path const & path,
753 roster_t const & ros)
754{
755 attr_value v;
756 if (ros.get_attr(path, attr_key(constants::manual_merge_attribute), v)
757 && v() == "true")
758 return true;
759 return false; // default: enable auto merge
760}
761
762bool
763content_merger::try_auto_merge(file_path const & anc_path,
764 file_path const & left_path,
765 file_path const & right_path,
766 file_path const & merged_path,
767 file_id const & ancestor_id,
768 file_id const & left_id,
769 file_id const & right_id,
770 file_id & merged_id)
771{
772 // This version of try_to_merge_files should only be called when there is a
773 // real merge3 to perform.
774 I(!null_id(ancestor_id));
775 I(!null_id(left_id));
776 I(!null_id(right_id));
777
778 L(FL("trying auto merge '%s' %s <-> %s (ancestor: %s)")
779 % merged_path
780 % left_id
781 % right_id
782 % ancestor_id);
783
784 if (left_id == right_id)
785 {
786 L(FL("files are identical"));
787 merged_id = left_id;
788 return true;
789 }
790
791 file_data left_data, right_data, ancestor_data;
792 data left_unpacked, ancestor_unpacked, right_unpacked, merged_unpacked;
793
794 adaptor.get_version(left_id, left_data);
795 adaptor.get_version(ancestor_id, ancestor_data);
796 adaptor.get_version(right_id, right_data);
797
798 left_unpacked = left_data.inner();
799 ancestor_unpacked = ancestor_data.inner();
800 right_unpacked = right_data.inner();
801
802 if (!attribute_manual_merge(left_path, left_ros) &&
803 !attribute_manual_merge(right_path, right_ros))
804 {
805 // both files mergeable by monotone internal algorithm, try to merge
806 // note: the ancestor is not considered for manual merging. Forcing the
807 // user to merge manually just because of an ancestor mistakenly marked
808 // manual seems too harsh
809 string left_encoding, anc_encoding, right_encoding;
810 left_encoding = this->get_file_encoding(left_path, left_ros);
811 anc_encoding = this->get_file_encoding(anc_path, anc_ros);
812 right_encoding = this->get_file_encoding(right_path, right_ros);
813
814 vector<string> left_lines, ancestor_lines, right_lines, merged_lines;
815 split_into_lines(left_unpacked(), left_encoding, left_lines);
816 split_into_lines(ancestor_unpacked(), anc_encoding, ancestor_lines);
817 split_into_lines(right_unpacked(), right_encoding, right_lines);
818
819 if (merge3(ancestor_lines, left_lines, right_lines, merged_lines))
820 {
821 file_id tmp_id;
822 file_data merge_data;
823 string tmp;
824
825 L(FL("internal 3-way merged ok"));
826 join_lines(merged_lines, tmp);
827 merge_data = file_data(tmp);
828 calculate_ident(merge_data, merged_id);
829
830 adaptor.record_merge(left_id, right_id, merged_id,
831 left_data, right_data, merge_data);
832
833 return true;
834 }
835 }
836
837 return false;
838}
839
840bool
841content_merger::try_user_merge(file_path const & anc_path,
842 file_path const & left_path,
843 file_path const & right_path,
844 file_path const & merged_path,
845 file_id const & ancestor_id,
846 file_id const & left_id,
847 file_id const & right_id,
848 file_id & merged_id)
849{
850 // This version of try_to_merge_files should only be called when there is a
851 // real merge3 to perform.
852 I(!null_id(ancestor_id));
853 I(!null_id(left_id));
854 I(!null_id(right_id));
855
856 L(FL("trying user merge '%s' %s <-> %s (ancestor: %s)")
857 % merged_path
858 % left_id
859 % right_id
860 % ancestor_id);
861
862 if (left_id == right_id)
863 {
864 L(FL("files are identical"));
865 merged_id = left_id;
866 return true;
867 }
868
869 file_data left_data, right_data, ancestor_data;
870 data left_unpacked, ancestor_unpacked, right_unpacked, merged_unpacked;
871
872 adaptor.get_version(left_id, left_data);
873 adaptor.get_version(ancestor_id, ancestor_data);
874 adaptor.get_version(right_id, right_data);
875
876 left_unpacked = left_data.inner();
877 ancestor_unpacked = ancestor_data.inner();
878 right_unpacked = right_data.inner();
879
880 P(F("help required for 3-way merge\n"
881 "[ancestor] %s\n"
882 "[ left] %s\n"
883 "[ right] %s\n"
884 "[ merged] %s")
885 % anc_path
886 % left_path
887 % right_path
888 % merged_path);
889
890 if (lua.hook_merge3(anc_path, left_path, right_path, merged_path,
891 ancestor_unpacked, left_unpacked,
892 right_unpacked, merged_unpacked))
893 {
894 file_data merge_data(merged_unpacked);
895
896 L(FL("lua merge3 hook merged ok"));
897 calculate_ident(merge_data, merged_id);
898
899 adaptor.record_merge(left_id, right_id, merged_id,
900 left_data, right_data, merge_data);
901 return true;
902 }
903
904 return false;
905}
906
907// the remaining part of this file just handles printing out various
908// diff formats for the case where someone wants to *read* a diff
909// rather than apply it.
910
911struct hunk_consumer
912{
913 vector<string> const & a;
914 vector<string> const & b;
915 size_t ctx;
916 ostream & ost;
917 boost::scoped_ptr<pcre::regex const> encloser_re;
918 size_t a_begin, b_begin, a_len, b_len;
919 long skew;
920
921 vector<string>::const_reverse_iterator encloser_last_match;
922 vector<string>::const_reverse_iterator encloser_last_search;
923
924 virtual void flush_hunk(size_t pos) = 0;
925 virtual void advance_to(size_t newpos) = 0;
926 virtual void insert_at(size_t b_pos) = 0;
927 virtual void delete_at(size_t a_pos) = 0;
928 virtual void find_encloser(size_t pos, string & encloser);
929 virtual ~hunk_consumer() {}
930 hunk_consumer(vector<string> const & a,
931 vector<string> const & b,
932 size_t ctx,
933 ostream & ost,
934 string const & encloser_pattern)
935 : a(a), b(b), ctx(ctx), ost(ost), encloser_re(0),
936 a_begin(0), b_begin(0), a_len(0), b_len(0), skew(0),
937 encloser_last_match(a.rend()), encloser_last_search(a.rend())
938 {
939 if (encloser_pattern != "")
940 encloser_re.reset(new pcre::regex(encloser_pattern));
941 }
942};
943
944/* Find, and write to ENCLOSER, the nearest line before POS which matches
945 ENCLOSER_PATTERN. We remember the last line scanned, and the matched, to
946 avoid duplication of effort. */
947
948void
949hunk_consumer::find_encloser(size_t pos, string & encloser)
950{
951 typedef vector<string>::const_reverse_iterator riter;
952
953 // Precondition: encloser_last_search <= pos <= a.size().
954 I(pos <= a.size());
955 // static_cast<> to silence compiler unsigned vs. signed comparison
956 // warning, after first making sure that the static_cast is safe.
957 I(a.rend() - encloser_last_search >= 0);
958 I(pos >= static_cast<size_t>(a.rend() - encloser_last_search));
959
960 if (!encloser_re)
961 return;
962
963 riter last = encloser_last_search;
964 riter i = riter(a.begin() + pos);
965
966 encloser_last_search = i;
967
968 // i is a reverse_iterator, so this loop goes backward through the vector.
969 for (; i != last; i++)
970 if (encloser_re->match(*i))
971 {
972 encloser_last_match = i;
973 break;
974 }
975
976 if (encloser_last_match == a.rend())
977 return;
978
979 L(FL("find_encloser: from %u matching %d, \"%s\"")
980 % pos % (a.rend() - encloser_last_match) % *encloser_last_match);
981
982 // the number 40 is chosen to match GNU diff. it could safely be
983 // increased up to about 60 without overflowing the standard
984 // terminal width.
985 encloser = string(" ") + (*encloser_last_match).substr(0, 40);
986}
987
988void walk_hunk_consumer(vector<long, QA(long)> const & lcs,
989 vector<long, QA(long)> const & lines1,
990 vector<long, QA(long)> const & lines2,
991 hunk_consumer & cons)
992{
993
994 size_t a = 0, b = 0;
995 if (lcs.begin() == lcs.end())
996 {
997 // degenerate case: files have nothing in common
998 cons.advance_to(0);
999 while (a < lines1.size())
1000 cons.delete_at(a++);
1001 while (b < lines2.size())
1002 cons.insert_at(b++);
1003 cons.flush_hunk(a);
1004 }
1005 else
1006 {
1007 // normal case: files have something in common
1008 for (vector<long, QA(long)>::const_iterator i = lcs.begin();
1009 i != lcs.end(); ++i, ++a, ++b)
1010 {
1011 if (idx(lines1, a) == *i && idx(lines2, b) == *i)
1012 continue;
1013
1014 cons.advance_to(a);
1015 while (idx(lines1,a) != *i)
1016 cons.delete_at(a++);
1017 while (idx(lines2,b) != *i)
1018 cons.insert_at(b++);
1019 }
1020 if (a < lines1.size())
1021 {
1022 cons.advance_to(a);
1023 while(a < lines1.size())
1024 cons.delete_at(a++);
1025 }
1026 if (b < lines2.size())
1027 {
1028 cons.advance_to(a);
1029 while(b < lines2.size())
1030 cons.insert_at(b++);
1031 }
1032 cons.flush_hunk(a);
1033 }
1034}
1035
1036struct unidiff_hunk_writer : public hunk_consumer
1037{
1038 vector<string> hunk;
1039
1040 virtual void flush_hunk(size_t pos);
1041 virtual void advance_to(size_t newpos);
1042 virtual void insert_at(size_t b_pos);
1043 virtual void delete_at(size_t a_pos);
1044 virtual ~unidiff_hunk_writer() {}
1045 unidiff_hunk_writer(vector<string> const & a,
1046 vector<string> const & b,
1047 size_t ctx,
1048 ostream & ost,
1049 string const & encloser_pattern)
1050 : hunk_consumer(a, b, ctx, ost, encloser_pattern)
1051 {}
1052};
1053
1054void unidiff_hunk_writer::insert_at(size_t b_pos)
1055{
1056 b_len++;
1057 hunk.push_back(string("+") + b[b_pos]);
1058}
1059
1060void unidiff_hunk_writer::delete_at(size_t a_pos)
1061{
1062 a_len++;
1063 hunk.push_back(string("-") + a[a_pos]);
1064}
1065
1066void unidiff_hunk_writer::flush_hunk(size_t pos)
1067{
1068 if (hunk.size() > 0)
1069 {
1070 // insert trailing context
1071 size_t a_pos = a_begin + a_len;
1072 for (size_t i = 0; (i < ctx) && (a_pos + i < a.size()); ++i)
1073 {
1074 hunk.push_back(string(" ") + a[a_pos + i]);
1075 a_len++;
1076 b_len++;
1077 }
1078
1079 // write hunk to stream
1080 if (a_len == 0)
1081 ost << "@@ -0,0";
1082 else
1083 {
1084 ost << "@@ -" << a_begin+1;
1085 if (a_len > 1)
1086 ost << ',' << a_len;
1087 }
1088
1089 if (b_len == 0)
1090 ost << " +0,0";
1091 else
1092 {
1093 ost << " +" << b_begin+1;
1094 if (b_len > 1)
1095 ost << ',' << b_len;
1096 }
1097
1098 {
1099 string encloser;
1100 ptrdiff_t first_mod = 0;
1101 vector<string>::const_iterator i;
1102 for (i = hunk.begin(); i != hunk.end(); i++)
1103 if ((*i)[0] != ' ')
1104 {
1105 first_mod = i - hunk.begin();
1106 break;
1107 }
1108
1109 find_encloser(a_begin + first_mod, encloser);
1110 ost << " @@" << encloser << '\n';
1111 }
1112 copy(hunk.begin(), hunk.end(), ostream_iterator<string>(ost, "\n"));
1113 }
1114
1115 // reset hunk
1116 hunk.clear();
1117 skew += b_len - a_len;
1118 a_begin = pos;
1119 b_begin = pos + skew;
1120 a_len = 0;
1121 b_len = 0;
1122}
1123
1124void unidiff_hunk_writer::advance_to(size_t newpos)
1125{
1126 if (a_begin + a_len + (2 * ctx) < newpos || hunk.empty())
1127 {
1128 flush_hunk(newpos);
1129
1130 // insert new leading context
1131 for (size_t p = max(ctx, newpos) - ctx;
1132 p < min(a.size(), newpos); ++p)
1133 {
1134 hunk.push_back(string(" ") + a[p]);
1135 a_begin--; a_len++;
1136 b_begin--; b_len++;
1137 }
1138 }
1139 else
1140 {
1141 // pad intermediate context
1142 while(a_begin + a_len < newpos)
1143 {
1144 hunk.push_back(string(" ") + a[a_begin + a_len]);
1145 a_len++;
1146 b_len++;
1147 }
1148 }
1149}
1150
1151struct cxtdiff_hunk_writer : public hunk_consumer
1152{
1153 // For context diffs, we have to queue up calls to insert_at/delete_at
1154 // until we hit an advance_to, so that we can get the tags right: an
1155 // unpaired insert gets a + in the left margin, an unpaired delete a -,
1156 // but if they are paired, they both get !. Hence, we have both the
1157 // 'inserts' and 'deletes' queues of line numbers, and the 'from_file' and
1158 // 'to_file' queues of line strings.
1159 vector<size_t> inserts;
1160 vector<size_t> deletes;
1161 vector<string> from_file;
1162 vector<string> to_file;
1163 bool have_insertions;
1164 bool have_deletions;
1165
1166 virtual void flush_hunk(size_t pos);
1167 virtual void advance_to(size_t newpos);
1168 virtual void insert_at(size_t b_pos);
1169 virtual void delete_at(size_t a_pos);
1170 void flush_pending_mods();
1171 virtual ~cxtdiff_hunk_writer() {}
1172 cxtdiff_hunk_writer(vector<string> const & a,
1173 vector<string> const & b,
1174 size_t ctx,
1175 ostream & ost,
1176 string const & encloser_pattern)
1177 : hunk_consumer(a, b, ctx, ost, encloser_pattern),
1178 have_insertions(false), have_deletions(false)
1179 {}
1180};
1181
1182void cxtdiff_hunk_writer::insert_at(size_t b_pos)
1183{
1184 inserts.push_back(b_pos);
1185 have_insertions = true;
1186}
1187
1188void cxtdiff_hunk_writer::delete_at(size_t a_pos)
1189{
1190 deletes.push_back(a_pos);
1191 have_deletions = true;
1192}
1193
1194void cxtdiff_hunk_writer::flush_hunk(size_t pos)
1195{
1196 flush_pending_mods();
1197
1198 if (have_deletions || have_insertions)
1199 {
1200 // insert trailing context
1201 size_t ctx_start = a_begin + a_len;
1202 for (size_t i = 0; (i < ctx) && (ctx_start + i < a.size()); ++i)
1203 {
1204 from_file.push_back(string(" ") + a[ctx_start + i]);
1205 a_len++;
1206 }
1207
1208 ctx_start = b_begin + b_len;
1209 for (size_t i = 0; (i < ctx) && (ctx_start + i < b.size()); ++i)
1210 {
1211 to_file.push_back(string(" ") + b[ctx_start + i]);
1212 b_len++;
1213 }
1214
1215 {
1216 string encloser;
1217 ptrdiff_t first_insert = b_len;
1218 ptrdiff_t first_delete = a_len;
1219 vector<string>::const_iterator i;
1220
1221 if (have_deletions)
1222 for (i = from_file.begin(); i != from_file.end(); i++)
1223 if ((*i)[0] != ' ')
1224 {
1225 first_delete = i - from_file.begin();
1226 break;
1227 }
1228 if (have_insertions)
1229 for (i = to_file.begin(); i != to_file.end(); i++)
1230 if ((*i)[0] != ' ')
1231 {
1232 first_insert = i - to_file.begin();
1233 break;
1234 }
1235
1236 find_encloser(a_begin + min(first_insert, first_delete),
1237 encloser);
1238
1239 ost << "***************" << encloser << '\n';
1240 }
1241
1242 ost << "*** " << (a_begin + 1) << ',' << (a_begin + a_len) << " ****\n";
1243 if (have_deletions)
1244 copy(from_file.begin(), from_file.end(), ostream_iterator<string>(ost, "\n"));
1245
1246 ost << "--- " << (b_begin + 1) << ',' << (b_begin + b_len) << " ----\n";
1247 if (have_insertions)
1248 copy(to_file.begin(), to_file.end(), ostream_iterator<string>(ost, "\n"));
1249 }
1250
1251 // reset hunk
1252 to_file.clear();
1253 from_file.clear();
1254 have_insertions = false;
1255 have_deletions = false;
1256 skew += b_len - a_len;
1257 a_begin = pos;
1258 b_begin = pos + skew;
1259 a_len = 0;
1260 b_len = 0;
1261}
1262
1263void cxtdiff_hunk_writer::flush_pending_mods()
1264{
1265 // nothing to flush?
1266 if (inserts.empty() && deletes.empty())
1267 return;
1268
1269 string prefix;
1270
1271 // if we have just insertions to flush, prefix them with "+"; if
1272 // just deletions, prefix with "-"; if both, prefix with "!"
1273 if (inserts.empty() && !deletes.empty())
1274 prefix = "-";
1275 else if (deletes.empty() && !inserts.empty())
1276 prefix = "+";
1277 else
1278 prefix = "!";
1279
1280 for (vector<size_t>::const_iterator i = deletes.begin();
1281 i != deletes.end(); ++i)
1282 {
1283 from_file.push_back(prefix + string(" ") + a[*i]);
1284 a_len++;
1285 }
1286 for (vector<size_t>::const_iterator i = inserts.begin();
1287 i != inserts.end(); ++i)
1288 {
1289 to_file.push_back(prefix + string(" ") + b[*i]);
1290 b_len++;
1291 }
1292
1293 // clear pending mods
1294 inserts.clear();
1295 deletes.clear();
1296}
1297
1298void cxtdiff_hunk_writer::advance_to(size_t newpos)
1299{
1300 // We must first flush out pending mods because otherwise our calculation
1301 // of whether we need to generate a new hunk header will be way off.
1302 // It is correct (i.e. consistent with diff(1)) to reset the +/-/!
1303 // generation algorithm between sub-components of a single hunk.
1304 flush_pending_mods();
1305
1306 if (a_begin + a_len + (2 * ctx) < newpos)
1307 {
1308 flush_hunk(newpos);
1309
1310 // insert new leading context
1311 if (newpos - ctx < a.size())
1312 {
1313 for (size_t i = ctx; i > 0; --i)
1314 {
1315 // The original test was (newpos - i < 0), but since newpos
1316 // is size_t (unsigned), it will never go negative. Testing
1317 // that newpos is smaller than i is the same test, really.
1318 if (newpos < i)
1319 continue;
1320
1321 // note that context diffs prefix common text with two
1322 // spaces, whereas unified diffs use a single space
1323 from_file.push_back(string(" ") + a[newpos - i]);
1324 to_file.push_back(string(" ") + a[newpos - i]);
1325 a_begin--; a_len++;
1326 b_begin--; b_len++;
1327 }
1328 }
1329 }
1330 else
1331 // pad intermediate context
1332 while (a_begin + a_len < newpos)
1333 {
1334 from_file.push_back(string(" ") + a[a_begin + a_len]);
1335 to_file.push_back(string(" ") + a[a_begin + a_len]);
1336 a_len++;
1337 b_len++;
1338 }
1339}
1340
1341void
1342make_diff(string const & filename1,
1343 string const & filename2,
1344 file_id const & id1,
1345 file_id const & id2,
1346 data const & data1,
1347 data const & data2,
1348 ostream & ost,
1349 diff_type type,
1350 string const & pattern)
1351{
1352 if (guess_binary(data1()) || guess_binary(data2()))
1353 {
1354 ost << "# " << filename2 << " is binary\n";
1355 return;
1356 }
1357
1358 vector<string> lines1, lines2;
1359 split_into_lines(data1(), lines1, true);
1360 split_into_lines(data2(), lines2, true);
1361
1362 vector<long, QA(long)> left_interned;
1363 vector<long, QA(long)> right_interned;
1364 vector<long, QA(long)> lcs;
1365
1366 interner<long> in;
1367
1368 left_interned.reserve(lines1.size());
1369 for (vector<string>::const_iterator i = lines1.begin();
1370 i != lines1.end(); ++i)
1371 left_interned.push_back(in.intern(*i));
1372
1373 right_interned.reserve(lines2.size());
1374 for (vector<string>::const_iterator i = lines2.begin();
1375 i != lines2.end(); ++i)
1376 right_interned.push_back(in.intern(*i));
1377
1378 lcs.reserve(min(lines1.size(),lines2.size()));
1379 longest_common_subsequence(left_interned.begin(), left_interned.end(),
1380 right_interned.begin(), right_interned.end(),
1381 min(lines1.size(), lines2.size()),
1382 back_inserter(lcs));
1383
1384 // The existence of various hacky diff parsers in the world somewhat
1385 // constrains what output we can use. Here are some notes on how various
1386 // tools interpret the header lines of a diff file:
1387 //
1388 // interdiff/filterdiff (patchutils):
1389 // Attempt to parse a timestamp after each whitespace. If they succeed,
1390 // then they take the filename as everything up to the whitespace they
1391 // succeeded at, and the timestamp as everything after. If they fail,
1392 // then they take the filename to be everything up to the first
1393 // whitespace. Have hardcoded that /dev/null and timestamps at the
1394 // epoch (in any timezone) indicate a file that did not exist.
1395 //
1396 // filterdiff filters on the first filename line. interdiff matches on
1397 // the first filename line.
1398 // PatchReader perl library (used by Bugzilla):
1399 // Takes the filename to be everything up to the first tab; requires
1400 // that there be a tab. Determines the filename based on the first
1401 // filename line.
1402 // diffstat:
1403 // Can handle pretty much everything; tries to read up to the first tab
1404 // to get the filename. Knows that "/dev/null", "", and anything
1405 // beginning "/tmp/" are meaningless. Uses the second filename line.
1406 // patch:
1407 // If there is a tab, considers everything up to that tab to be the
1408 // filename. If there is not a tab, considers everything up to the
1409 // first whitespace to be the filename.
1410 //
1411 // Contains comment: 'If the [file]name is "/dev/null", ignore the name
1412 // and mark the file as being nonexistent. The name "/dev/null" appears
1413 // in patches regardless of how NULL_DEVICE is spelled.' Also detects
1414 // timestamps at the epoch as indicating that a file does not exist.
1415 //
1416 // Uses the first filename line as the target, unless it is /dev/null or
1417 // has an epoch timestamp in which case it uses the second.
1418 // trac:
1419 // Anything up to the first whitespace, or end of line, is considered
1420 // filename. Does not care about timestamp. Uses the shorter of the
1421 // two filenames as the filename (!).
1422 //
1423 // Conclusions:
1424 // -- You must have a tab, both to prevent PatchReader blowing up, and
1425 // to make it possible to have filenames with spaces in them.
1426 // (Filenames with tabs in them are always impossible to properly
1427 // express; FIXME what should be done if one occurs?)
1428 // -- What comes after that tab matters not at all, though it probably
1429 // shouldn't look like a timestamp, or have any trailing part that
1430 // looks like a timestamp, unless it really is a timestamp. Simply
1431 // having a trailing tab should work fine.
1432 // -- If you need to express that some file does not exist, you should
1433 // use /dev/null as the path. patch(1) goes so far as to claim that
1434 // this is part of the diff format definition.
1435 // -- If you want your patches to actually _work_ with patch(1), then
1436 // renames are basically hopeless (you can do them by hand _after_
1437 // running patch), adds work so long as the first line says either
1438 // the new file's name or "/dev/null", nothing else, and deletes work
1439 // if the new file name is "/dev/null", nothing else. (ATM we don't
1440 // write out patches for deletes anyway.)
1441 switch (type)
1442 {
1443 case unified_diff:
1444 {
1445 ost << "--- " << filename1 << '\t'
1446 << id1 << '\n';
1447 ost << "+++ " << filename2 << '\t'
1448 << id2 << '\n';
1449
1450 unidiff_hunk_writer hunks(lines1, lines2, 3, ost, pattern);
1451 walk_hunk_consumer(lcs, left_interned, right_interned, hunks);
1452 break;
1453 }
1454 case context_diff:
1455 {
1456 ost << "*** " << filename1 << '\t'
1457 << id1 << '\n';
1458 ost << "--- " << filename2 << '\t'
1459 << id2 << '\n';
1460
1461 cxtdiff_hunk_writer hunks(lines1, lines2, 3, ost, pattern);
1462 walk_hunk_consumer(lcs, left_interned, right_interned, hunks);
1463 break;
1464 }
1465 default:
1466 {
1467 // should never reach this; the external_diff type is not
1468 // handled by this function.
1469 I(false);
1470 }
1471 }
1472}
1473
1474#ifdef BUILD_UNIT_TESTS
1475#include "unit_tests.hh"
1476#include "lexical_cast.hh"
1477#include "randomfile.hh"
1478
1479using std::cerr;
1480using std::cout;
1481using std::stringstream;
1482
1483using boost::lexical_cast;
1484
1485static void dump_incorrect_merge(vector<string> const & expected,
1486 vector<string> const & got,
1487 string const & prefix)
1488{
1489 size_t mx = expected.size();
1490 if (mx < got.size())
1491 mx = got.size();
1492 for (size_t i = 0; i < mx; ++i)
1493 {
1494 cerr << "bad merge: " << i << " [" << prefix << "]\t";
1495
1496 if (i < expected.size())
1497 cerr << '[' << expected[i] << "]\t";
1498 else
1499 cerr << "[--nil--]\t";
1500
1501 if (i < got.size())
1502 cerr << '[' << got[i] << "]\t";
1503 else
1504 cerr << "[--nil--]\t";
1505
1506 cerr << '\n';
1507 }
1508}
1509
1510// high tech randomizing test
1511UNIT_TEST(diff_patch, randomizing_merge)
1512{
1513 randomizer rng;
1514 for (int i = 0; i < 30; ++i)
1515 {
1516 vector<string> anc, d1, d2, m1, m2, gm;
1517
1518 file_randomizer::build_random_fork(anc, d1, d2, gm, (10 + 2 * i), rng);
1519
1520 UNIT_TEST_CHECK(merge3(anc, d1, d2, m1));
1521 if (gm != m1)
1522 dump_incorrect_merge (gm, m1, "random_merge 1");
1523 UNIT_TEST_CHECK(gm == m1);
1524
1525 UNIT_TEST_CHECK(merge3(anc, d2, d1, m2));
1526 if (gm != m2)
1527 dump_incorrect_merge (gm, m2, "random_merge 2");
1528 UNIT_TEST_CHECK(gm == m2);
1529 }
1530}
1531
1532
1533// old boring tests
1534UNIT_TEST(diff_patch, merge_prepend)
1535{
1536 UNIT_TEST_CHECKPOINT("prepend test");
1537 vector<string> anc, d1, d2, m1, m2, gm;
1538 for (int i = 10; i < 20; ++i)
1539 {
1540 d2.push_back(lexical_cast<string>(i));
1541 gm.push_back(lexical_cast<string>(i));
1542 }
1543
1544 for (int i = 0; i < 10; ++i)
1545 {
1546 anc.push_back(lexical_cast<string>(i));
1547 d1.push_back(lexical_cast<string>(i));
1548 d2.push_back(lexical_cast<string>(i));
1549 gm.push_back(lexical_cast<string>(i));
1550 }
1551
1552 UNIT_TEST_CHECK(merge3(anc, d1, d2, m1));
1553 if (gm != m1)
1554 dump_incorrect_merge (gm, m1, "merge_prepend 1");
1555 UNIT_TEST_CHECK(gm == m1);
1556
1557
1558 UNIT_TEST_CHECK(merge3(anc, d2, d1, m2));
1559 if (gm != m2)
1560 dump_incorrect_merge (gm, m2, "merge_prepend 2");
1561 UNIT_TEST_CHECK(gm == m2);
1562}
1563
1564UNIT_TEST(diff_patch, merge_append)
1565{
1566 UNIT_TEST_CHECKPOINT("append test");
1567 vector<string> anc, d1, d2, m1, m2, gm;
1568 for (int i = 0; i < 10; ++i)
1569 anc.push_back(lexical_cast<string>(i));
1570
1571 d1 = anc;
1572 d2 = anc;
1573 gm = anc;
1574
1575 for (int i = 10; i < 20; ++i)
1576 {
1577 d2.push_back(lexical_cast<string>(i));
1578 gm.push_back(lexical_cast<string>(i));
1579 }
1580
1581 UNIT_TEST_CHECK(merge3(anc, d1, d2, m1));
1582 if (gm != m1)
1583 dump_incorrect_merge (gm, m1, "merge_append 1");
1584 UNIT_TEST_CHECK(gm == m1);
1585
1586 UNIT_TEST_CHECK(merge3(anc, d2, d1, m2));
1587 if (gm != m2)
1588 dump_incorrect_merge (gm, m2, "merge_append 2");
1589 UNIT_TEST_CHECK(gm == m2);
1590
1591
1592}
1593
1594UNIT_TEST(diff_patch, merge_additions)
1595{
1596 UNIT_TEST_CHECKPOINT("additions test");
1597 string ancestor("I like oatmeal\nI like orange juice\nI like toast");
1598 string desc1("I like oatmeal\nI don't like spam\nI like orange juice\nI like toast");
1599 string confl("I like oatmeal\nI don't like tuna\nI like orange juice\nI like toast");
1600 string desc2("I like oatmeal\nI like orange juice\nI don't like tuna\nI like toast");
1601 string good_merge("I like oatmeal\nI don't like spam\nI like orange juice\nI don't like tuna\nI like toast");
1602 vector<string> anc, d1, cf, d2, m1, m2, gm;
1603
1604 split_into_lines(ancestor, anc);
1605 split_into_lines(desc1, d1);
1606 split_into_lines(confl, cf);
1607 split_into_lines(desc2, d2);
1608 split_into_lines(good_merge, gm);
1609
1610 UNIT_TEST_CHECK(merge3(anc, d1, d2, m1));
1611 if (gm != m1)
1612 dump_incorrect_merge (gm, m1, "merge_addition 1");
1613 UNIT_TEST_CHECK(gm == m1);
1614
1615 UNIT_TEST_CHECK(merge3(anc, d2, d1, m2));
1616 if (gm != m2)
1617 dump_incorrect_merge (gm, m2, "merge_addition 2");
1618 UNIT_TEST_CHECK(gm == m2);
1619
1620 UNIT_TEST_CHECK(!merge3(anc, d1, cf, m1));
1621}
1622
1623UNIT_TEST(diff_patch, merge_deletions)
1624{
1625 string ancestor("I like oatmeal\nI like orange juice\nI like toast");
1626 string desc2("I like oatmeal\nI like toast");
1627
1628 vector<string> anc, d1, d2, m1, m2, gm;
1629
1630 split_into_lines(ancestor, anc);
1631 split_into_lines(desc2, d2);
1632 d1 = anc;
1633 gm = d2;
1634
1635 UNIT_TEST_CHECK(merge3(anc, d1, d2, m1));
1636 if (gm != m1)
1637 dump_incorrect_merge (gm, m1, "merge_deletion 1");
1638 UNIT_TEST_CHECK(gm == m1);
1639
1640 UNIT_TEST_CHECK(merge3(anc, d2, d1, m2));
1641 if (gm != m2)
1642 dump_incorrect_merge (gm, m2, "merge_deletion 2");
1643 UNIT_TEST_CHECK(gm == m2);
1644}
1645
1646#endif // BUILD_UNIT_TESTS
1647
1648// Local Variables:
1649// mode: C++
1650// fill-column: 76
1651// c-file-style: "gnu"
1652// indent-tabs-mode: nil
1653// End:
1654// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status