monotone

monotone Mtn Source Tree

Root/diff_patch.cc

1// copyright (C) 2002, 2003 graydon hoare <graydon@pobox.com>
2// all rights reserved.
3// licensed to the public under the terms of the GNU GPL (>= 2)
4// see the file COPYING for details
5
6#include <algorithm>
7#include <iterator>
8#include <vector>
9#include <string>
10#include <iostream>
11
12#include "config.h"
13#include "diff_patch.hh"
14#include "interner.hh"
15#include "lcs.hh"
16#include "manifest.hh"
17#include "packet.hh"
18#include "sanity.hh"
19#include "transforms.hh"
20#include "vocab.hh"
21
22using namespace std;
23
24//
25// a 3-way merge works like this:
26//
27// /----> right
28// ancestor
29// \----> left
30//
31// first you compute the edit list "EDITS(ancestor,left)".
32//
33// then you make an offset table "leftpos" which describes positions in
34// "ancestor" as they map to "left"; that is, for 0 < apos <
35// ancestor.size(), we have
36//
37// left[leftpos[apos]] == ancestor[apos]
38//
39// you do this by walking through the edit list and either jumping the
40// current index ahead an extra position, on an insert, or remaining still,
41// on a delete. on an insert *or* a delete, you push the current index back
42// onto the leftpos array.
43//
44// next you compute the edit list "EDITS(ancestor,right)".
45//
46// you then go through this edit list applying the edits to left, rather
47// than ancestor, and using the table leftpos to map the position of each
48// edit to an appropriate spot in left. this means you walk a "curr_left"
49// index through the edits, and for each edit e:
50//
51// - if e is a delete (and e.pos is a position in ancestor)
52// - increment curr_left without copying anything to "merged"
53//
54// - if e is an insert (and e.pos is a position in right)
55// - copy right[e.pos] to "merged"
56// - leave curr_left alone
57//
58// - when advancing to apos (and apos is a position in ancestor)
59// - copy left[curr_left] to merged while curr_left < leftpos[apos]
60//
61//
62// the practical upshot is that you apply the delta from ancestor->right
63// to the adjusted contexts in left, producing something vaguely like
64// the concatenation of delta(ancestor,left) :: delta(ancestor,right).
65//
66// NB: this is, as far as I can tell, what diff3 does. I don't think I'm
67// infringing on anyone's fancy patents here.
68//
69
70typedef enum { preserved = 0, deleted = 1, changed = 2 } edit_t;
71static char *etab[3] =
72 {
73 "preserved",
74 "deleted",
75 "changed"
76 };
77
78struct extent
79{
80 extent(size_t p, size_t l, edit_t t)
81 : pos(p), len(l), type(t)
82 {}
83 size_t pos;
84 size_t len;
85 edit_t type;
86};
87
88void calculate_extents(vector<long, QA(long)> const & a_b_edits,
89 vector<long, QA(long)> const & b,
90 vector<long, QA(long)> & prefix,
91 vector<extent> & extents,
92 vector<long, QA(long)> & suffix,
93 size_t const a_len,
94 interner<long> & intern)
95{
96 extents.reserve(a_len * 2);
97
98 size_t a_pos = 0, b_pos = 0;
99
100 for (vector<long, QA(long)>::const_iterator i = a_b_edits.begin();
101 i != a_b_edits.end(); ++i)
102 {
103 // L(F("edit: %d") % *i);
104 if (*i < 0)
105 {
106 // negative elements code the negation of the one-based index into A
107 // of the element to be deleted
108 size_t a_deleted = (-1 - *i);
109
110 // fill positions out to the deletion point
111 while (a_pos < a_deleted)
112 {
113 a_pos++;
114 extents.push_back(extent(b_pos++, 1, preserved));
115 }
116
117 // L(F(" -- delete at A-pos %d (B-pos = %d)\n") % a_deleted % b_pos);
118
119 // skip the deleted line
120 a_pos++;
121 extents.push_back(extent(b_pos, 0, deleted));
122 }
123 else
124 {
125 // positive elements code the one-based index into B of the element to
126 // be inserted
127 size_t b_inserted = (*i - 1);
128
129 // fill positions out to the insertion point
130 while (b_pos < b_inserted)
131 {
132 a_pos++;
133 extents.push_back(extent(b_pos++, 1, preserved));
134 }
135
136 // L(F(" -- insert at B-pos %d (A-pos = %d) : '%s'\n")
137 // % b_inserted % a_pos % intern.lookup(b.at(b_inserted)));
138
139 // record that there was an insertion, but a_pos did not move.
140 if ((b_pos == 0 && extents.empty())
141 || (b_pos == prefix.size()))
142 {
143 prefix.push_back(b.at(b_pos));
144 }
145 else if (a_len == a_pos)
146 {
147 suffix.push_back(b.at(b_pos));
148 }
149 else
150 {
151 // make the insertion
152 extents.back().type = changed;
153 extents.back().len++;
154 }
155 b_pos++;
156 }
157 }
158
159 while (extents.size() < a_len)
160 extents.push_back(extent(b_pos++, 1, preserved));
161}
162
163void normalize_extents(vector<extent> & a_b_map,
164 vector<long, QA(long)> const & a,
165 vector<long, QA(long)> const & b)
166{
167 for (size_t i = 0; i < a_b_map.size(); ++i)
168 {
169 if (i > 0)
170 {
171 size_t j = i;
172 while (j > 0
173 && (a_b_map.at(j-1).type == preserved)
174 && (a_b_map.at(j).type == changed)
175 && (a.at(j) == b.at(a_b_map.at(j).pos + a_b_map.at(j).len - 1)))
176 {
177 // This is implied by (a_b_map.at(j-1).type == preserved)
178 I(a.at(j-1) == b.at(a_b_map.at(j-1).pos));
179
180 // Coming into loop we have:
181 // i
182 // z --pres--> z 0
183 // o --pres--> o 1
184 // a --chng--> a 2 The important thing here is that 'a' in
185 // t the LHS matches with ...
186 // u
187 // v
188 // a ... the a on the RHS here. Hence we can
189 // q --pres--> q 3 'shift' the entire 'changed' block
190 // e --chng--> d 4 upwards, leaving a 'preserved' line
191 // g --pres--> g 5 'a'->'a'
192 //
193 // Want to end up with:
194 // i
195 // z --pres--> z 0
196 // o --chng--> o 1
197 // a
198 // t
199 // u
200 // v
201 // a --pres--> a 2
202 // q --pres--> q 3
203 // e --chng--> d 4
204 // g --pres--> g 5
205 //
206 // Now all the 'changed' extents are normalised to the
207 // earliest possible position.
208
209 L(F("exchanging preserved extent [%d+%d] with changed extent [%d+%d]\n")
210 % a_b_map.at(j-1).pos
211 % a_b_map.at(j-1).len
212 % a_b_map.at(j).pos
213 % a_b_map.at(j).len);
214
215 swap(a_b_map.at(j-1).len, a_b_map.at(j).len);
216 swap(a_b_map.at(j-1).type, a_b_map.at(j).type);
217 --j;
218 }
219 }
220 }
221
222 for (size_t i = 0; i < a_b_map.size(); ++i)
223 {
224 if (i > 0)
225 {
226 size_t j = i;
227 while (j > 0
228 && a_b_map.at(j).type == changed
229 && a_b_map.at(j-1).type == changed
230 && a_b_map.at(j).len > 1
231 && a_b_map.at(j-1).pos + a_b_map.at(j-1).len == a_b_map.at(j).pos)
232 {
233 // step 1: move a chunk from this insert extent to its
234 // predecessor
235 size_t piece = a_b_map.at(j).len - 1;
236 // L(F("moving change piece of len %d from pos %d to pos %d\n")
237 // % piece
238 // % a_b_map.at(j).pos
239 // % a_b_map.at(j-1).pos);
240 a_b_map.at(j).len = 1;
241 a_b_map.at(j).pos += piece;
242 a_b_map.at(j-1).len += piece;
243
244 // step 2: if this extent (now of length 1) has become a "changed"
245 // extent identical to its previous state, switch it to a "preserved"
246 // extent.
247 if (b.at(a_b_map.at(j).pos) == a.at(j))
248 {
249 // L(F("changing normalized 'changed' extent at %d to 'preserved'\n")
250 // % a_b_map.at(j).pos);
251 a_b_map.at(j).type = preserved;
252 }
253 --j;
254 }
255 }
256 }
257}
258
259
260void merge_extents(vector<extent> const & a_b_map,
261 vector<extent> const & a_c_map,
262 vector<long, QA(long)> const & b,
263 vector<long, QA(long)> const & c,
264 interner<long> const & in,
265 vector<long, QA(long)> & merged)
266{
267 I(a_b_map.size() == a_c_map.size());
268
269 vector<extent>::const_iterator i = a_b_map.begin();
270 vector<extent>::const_iterator j = a_c_map.begin();
271 merged.reserve(a_b_map.size() * 2);
272
273 // for (; i != a_b_map.end(); ++i, ++j)
274 // {
275
276 // L(F("trying to merge: [%s %d %d] vs. [%s %d %d] \n")
277 // % etab[i->type] % i->pos % i->len
278 // % etab[j->type] % j->pos % j->len);
279 // }
280
281 // i = a_b_map.begin();
282 // j = a_c_map.begin();
283
284 for (; i != a_b_map.end(); ++i, ++j)
285 {
286
287 // L(F("trying to merge: [%s %d %d] vs. [%s %d %d] \n")
288 // % etab[i->type] % i->pos % i->len
289 // % etab[j->type] % j->pos % j->len);
290
291 // mutual, identical preserves / inserts / changes
292 if (((i->type == changed && j->type == changed)
293 || (i->type == preserved && j->type == preserved))
294 && i->len == j->len)
295 {
296 for (size_t k = 0; k < i->len; ++k)
297 {
298 if (b.at(i->pos + k) != c.at(j->pos + k))
299 {
300 L(F("conflicting edits: %s %d[%d] '%s' vs. %s %d[%d] '%s'\n")
301 % etab[i->type] % i->pos % k % in.lookup(b.at(i->pos + k))
302 % etab[j->type] % j->pos % k % in.lookup(c.at(j->pos + k)));
303 throw conflict();
304 }
305 merged.push_back(b.at(i->pos + k));
306 }
307 }
308
309 // mutual or single-edge deletes
310 else if ((i->type == deleted && j->type == deleted)
311 || (i->type == deleted && j->type == preserved)
312 || (i->type == preserved && j->type == deleted))
313 {
314 // do nothing
315 }
316
317 // single-edge insert / changes
318 else if (i->type == changed && j->type == preserved)
319 for (size_t k = 0; k < i->len; ++k)
320 merged.push_back(b.at(i->pos + k));
321
322 else if (i->type == preserved && j->type == changed)
323 for (size_t k = 0; k < j->len; ++k)
324 merged.push_back(c.at(j->pos + k));
325
326 else
327 {
328 L(F("conflicting edits: [%s %d %d] vs. [%s %d %d]\n")
329 % etab[i->type] % i->pos % i->len
330 % etab[j->type] % j->pos % j->len);
331 throw conflict();
332 }
333
334 // if (merged.empty())
335 // L(F(" --> EMPTY\n"));
336 // else
337 // L(F(" --> [%d]: %s\n") % (merged.size() - 1) % in.lookup(merged.back()));
338 }
339}
340
341
342void merge_via_edit_scripts(vector<string> const & ancestor,
343 vector<string> const & left,
344 vector<string> const & right,
345 vector<string> & merged)
346{
347 vector<long, QA(long)> anc_interned;
348 vector<long, QA(long)> left_interned, right_interned;
349 vector<long, QA(long)> left_edits, right_edits;
350 vector<long, QA(long)> left_prefix, right_prefix;
351 vector<long, QA(long)> left_suffix, right_suffix;
352 vector<extent> left_extents, right_extents;
353 vector<long, QA(long)> merged_interned;
354 interner<long> in;
355
356 // for (int i = 0; i < std::min(std::min(left.size(), right.size()), ancestor.size()); ++i)
357 // {
358 // std::cerr << "[" << i << "] " << left[i] << " " << ancestor[i] << " " << right[i] << endl;
359 // }
360
361 anc_interned.reserve(ancestor.size());
362 for (vector<string>::const_iterator i = ancestor.begin();
363 i != ancestor.end(); ++i)
364 anc_interned.push_back(in.intern(*i));
365
366 left_interned.reserve(left.size());
367 for (vector<string>::const_iterator i = left.begin();
368 i != left.end(); ++i)
369 left_interned.push_back(in.intern(*i));
370
371 right_interned.reserve(right.size());
372 for (vector<string>::const_iterator i = right.begin();
373 i != right.end(); ++i)
374 right_interned.push_back(in.intern(*i));
375
376 L(F("calculating left edit script on %d -> %d lines\n")
377 % anc_interned.size() % left_interned.size());
378
379 edit_script(anc_interned.begin(), anc_interned.end(),
380 left_interned.begin(), left_interned.end(),
381 std::min(ancestor.size(), left.size()),
382 left_edits);
383
384 L(F("calculating right edit script on %d -> %d lines\n")
385 % anc_interned.size() % right_interned.size());
386
387 edit_script(anc_interned.begin(), anc_interned.end(),
388 right_interned.begin(), right_interned.end(),
389 std::min(ancestor.size(), right.size()),
390 right_edits);
391
392 L(F("calculating left extents on %d edits\n") % left_edits.size());
393 calculate_extents(left_edits, left_interned,
394 left_prefix, left_extents, left_suffix,
395 anc_interned.size(), in);
396
397 L(F("calculating right extents on %d edits\n") % right_edits.size());
398 calculate_extents(right_edits, right_interned,
399 right_prefix, right_extents, right_suffix,
400 anc_interned.size(), in);
401
402 L(F("normalizing %d right extents\n") % right_extents.size());
403 normalize_extents(right_extents, anc_interned, right_interned);
404
405 L(F("normalizing %d left extents\n") % left_extents.size());
406 normalize_extents(left_extents, anc_interned, left_interned);
407
408
409 if ((!right_prefix.empty()) && (!left_prefix.empty()))
410 {
411 L(F("conflicting prefixes\n"));
412 throw conflict();
413 }
414
415 if ((!right_suffix.empty()) && (!left_suffix.empty()))
416 {
417 L(F("conflicting suffixes\n"));
418 throw conflict();
419 }
420
421 L(F("merging %d left, %d right extents\n")
422 % left_extents.size() % right_extents.size());
423
424 copy(left_prefix.begin(), left_prefix.end(), back_inserter(merged_interned));
425 copy(right_prefix.begin(), right_prefix.end(), back_inserter(merged_interned));
426
427 merge_extents(left_extents, right_extents,
428 left_interned, right_interned,
429 in, merged_interned);
430
431 copy(left_suffix.begin(), left_suffix.end(), back_inserter(merged_interned));
432 copy(right_suffix.begin(), right_suffix.end(), back_inserter(merged_interned));
433
434 merged.reserve(merged_interned.size());
435 for (vector<long, QA(long)>::const_iterator i = merged_interned.begin();
436 i != merged_interned.end(); ++i)
437 merged.push_back(in.lookup(*i));
438}
439
440
441bool merge3(vector<string> const & ancestor,
442 vector<string> const & left,
443 vector<string> const & right,
444 vector<string> & merged)
445{
446 try
447 {
448 merge_via_edit_scripts(ancestor, left, right, merged);
449 }
450 catch(conflict & c)
451 {
452 L(F("conflict detected. no merge.\n"));
453 return false;
454 }
455 return true;
456}
457
458
459merge_provider::merge_provider(app_state & app,
460 manifest_map const & anc_man,
461 manifest_map const & left_man,
462 manifest_map const & right_man)
463 : app(app), anc_man(anc_man), left_man(left_man), right_man(right_man)
464{}
465
466void merge_provider::record_merge(file_id const & left_ident,
467 file_id const & right_ident,
468 file_id const & merged_ident,
469 file_data const & left_data,
470 file_data const & merged_data)
471{
472 L(F("recording successful merge of %s <-> %s into %s\n")
473 % left_ident % right_ident % merged_ident);
474
475 delta merge_delta;
476 transaction_guard guard(app.db);
477
478 diff(left_data.inner(), merged_data.inner(), merge_delta);
479 packet_db_writer dbw(app);
480 dbw.consume_file_delta (left_ident, merged_ident, file_delta(merge_delta));
481 guard.commit();
482}
483
484void merge_provider::get_version(file_path const & path,
485 file_id const & ident,
486 file_data & dat)
487{
488 app.db.get_file_version(ident, dat);
489}
490
491std::string merge_provider::get_file_encoding(file_path const & path,
492 manifest_map const & man)
493{
494 std::string enc;
495 if (get_attribute_from_db(path, encoding_attribute, man, enc, app))
496 return enc;
497 else
498 return default_encoding;
499}
500
501bool merge_provider::attribute_manual_merge(file_path const & path,
502 manifest_map const & man)
503{
504 std::string mmf;
505 if (get_attribute_from_db(path, manual_merge_attribute, man, mmf, app))
506 {
507 return mmf == std::string("true");
508 }
509 else
510 return false; // default: enable auto merge
511}
512
513bool merge_provider::try_to_merge_files(file_path const & anc_path,
514 file_path const & left_path,
515 file_path const & right_path,
516 file_path const & merged_path,
517 file_id const & ancestor_id,
518 file_id const & left_id,
519 file_id const & right_id,
520 file_id & merged_id)
521{
522 // This version of try_to_merge_files should only be called when there is a
523 // real merge3 to perform.
524 I(!null_id(ancestor_id));
525 I(!null_id(left_id));
526 I(!null_id(right_id));
527
528 L(F("trying to merge %s <-> %s (ancestor: %s)\n")
529 % left_id % right_id % ancestor_id);
530
531 if (left_id == right_id)
532 {
533 L(F("files are identical\n"));
534 merged_id = left_id;
535 return true;
536 }
537
538 file_data left_data, right_data, ancestor_data;
539 data left_unpacked, ancestor_unpacked, right_unpacked, merged_unpacked;
540
541 this->get_version(left_path, left_id, left_data);
542 this->get_version(anc_path, ancestor_id, ancestor_data);
543 this->get_version(right_path, right_id, right_data);
544
545 left_unpacked = left_data.inner();
546 ancestor_unpacked = ancestor_data.inner();
547 right_unpacked = right_data.inner();
548
549 if (!attribute_manual_merge(left_path, left_man) &&
550 !attribute_manual_merge(right_path, right_man))
551 {
552 // both files mergeable by monotone internal algorithm, try to merge
553 // note: the ancestor is not considered for manual merging. Forcing the
554 // user to merge manually just because of an ancestor mistakenly marked
555 // manual seems too harsh
556 string left_encoding, anc_encoding, right_encoding;
557 left_encoding = this->get_file_encoding(left_path, left_man);
558 anc_encoding = this->get_file_encoding(anc_path, anc_man);
559 right_encoding = this->get_file_encoding(right_path, right_man);
560
561 vector<string> left_lines, ancestor_lines, right_lines, merged_lines;
562 split_into_lines(left_unpacked(), left_encoding, left_lines);
563 split_into_lines(ancestor_unpacked(), anc_encoding, ancestor_lines);
564 split_into_lines(right_unpacked(), right_encoding, right_lines);
565
566 if (merge3(ancestor_lines,
567 left_lines,
568 right_lines,
569 merged_lines))
570 {
571 hexenc<id> tmp_id;
572 file_data merge_data;
573 string tmp;
574
575 L(F("internal 3-way merged ok\n"));
576 join_lines(merged_lines, tmp);
577 calculate_ident(data(tmp), tmp_id);
578 file_id merged_fid(tmp_id);
579 merge_data = file_data(tmp);
580
581 merged_id = merged_fid;
582 record_merge(left_id, right_id, merged_fid,
583 left_data, merge_data);
584
585 return true;
586 }
587 }
588
589 P(F("help required for 3-way merge\n"
590 "[ancestor] %s\n"
591 "[ left] %s\n"
592 "[ right] %s\n"
593 "[ merged] %s\n")
594 % anc_path
595 % left_path
596 % right_path
597 % merged_path);
598
599 if (app.lua.hook_merge3(anc_path, left_path, right_path, merged_path,
600 ancestor_unpacked, left_unpacked,
601 right_unpacked, merged_unpacked))
602 {
603 hexenc<id> tmp_id;
604 file_data merge_data;
605
606 L(F("lua merge3 hook merged ok\n"));
607 calculate_ident(merged_unpacked, tmp_id);
608 file_id merged_fid(tmp_id);
609 merge_data = file_data(merged_unpacked);
610
611 merged_id = merged_fid;
612 record_merge(left_id, right_id, merged_fid,
613 left_data, merge_data);
614 return true;
615 }
616
617 return false;
618}
619
620bool merge_provider::try_to_merge_files(file_path const & left_path,
621 file_path const & right_path,
622 file_path const & merged_path,
623 file_id const & left_id,
624 file_id const & right_id,
625 file_id & merged_id)
626{
627 I(!null_id(left_id));
628 I(!null_id(right_id));
629
630 file_data left_data, right_data;
631 data left_unpacked, right_unpacked, merged_unpacked;
632
633 L(F("trying to merge %s <-> %s\n")
634 % left_id % right_id);
635
636 if (left_id == right_id)
637 {
638 L(F("files are identical\n"));
639 merged_id = left_id;
640 return true;
641 }
642
643 this->get_version(left_path, left_id, left_data);
644 this->get_version(right_path, right_id, right_data);
645
646 left_unpacked = left_data.inner();
647 right_unpacked = right_data.inner();
648
649 P(F("help required for 2-way merge\n"
650 "[ left] %s\n"
651 "[ right] %s\n"
652 "[ merged] %s\n")
653 % left_path
654 % right_path
655 % merged_path);
656
657 if (app.lua.hook_merge2(left_path, right_path, merged_path,
658 left_unpacked, right_unpacked, merged_unpacked))
659 {
660 hexenc<id> tmp_id;
661 file_data merge_data;
662
663 L(F("lua merge2 hook merged ok\n"));
664 calculate_ident(merged_unpacked, tmp_id);
665 file_id merged_fid(tmp_id);
666 merge_data = file_data(merged_unpacked);
667
668 merged_id = merged_fid;
669 record_merge(left_id, right_id, merged_fid,
670 left_data, merge_data);
671 return true;
672 }
673
674 return false;
675}
676
677
678// during the "update" command, the only real differences from merging
679// are that we take our right versions from the filesystem, not the db,
680// and we only record the merges in a transient, in-memory table.
681
682update_merge_provider::update_merge_provider(app_state & app,
683 manifest_map const & anc_man,
684 manifest_map const & left_man,
685 manifest_map const & right_man)
686 : merge_provider(app, anc_man, left_man, right_man) {}
687
688void update_merge_provider::record_merge(file_id const & left_id,
689 file_id const & right_id,
690 file_id const & merged_id,
691 file_data const & left_data,
692 file_data const & merged_data)
693{
694 L(F("temporarily recording merge of %s <-> %s into %s\n")
695 % left_id % right_id % merged_id);
696 I(temporary_store.find(merged_id) == temporary_store.end());
697 temporary_store.insert(make_pair(merged_id, merged_data));
698}
699
700void update_merge_provider::get_version(file_path const & path,
701 file_id const & ident,
702 file_data & dat)
703{
704 if (app.db.file_version_exists(ident))
705 app.db.get_file_version(ident, dat);
706 else
707 {
708 data tmp;
709 file_id fid;
710 require_path_is_file(path,
711 F("file '%s' does not exist in working copy") % path,
712 F("'%s' in working copy is a directory, not a file") % path);
713 read_localized_data(path, tmp, app.lua);
714 calculate_ident(tmp, fid);
715 N(fid == ident,
716 F("file %s in working copy has id %s, wanted %s")
717 % path % fid % ident);
718 dat = tmp;
719 }
720}
721
722std::string update_merge_provider::get_file_encoding(file_path const & path,
723 manifest_map const & man)
724{
725 std::string enc;
726 if (get_attribute_from_working_copy(path, encoding_attribute, enc))
727 return enc;
728 else if (get_attribute_from_db(path, encoding_attribute, man, enc, app))
729 return enc;
730 else
731 return default_encoding;
732}
733
734bool update_merge_provider::attribute_manual_merge(file_path const & path,
735 manifest_map const & man)
736{
737 std::string mmf;
738 if (get_attribute_from_working_copy(path, manual_merge_attribute, mmf))
739 return mmf == std::string("true");
740 else if (get_attribute_from_db(path, manual_merge_attribute, man, mmf, app))
741 return mmf == std::string("true");
742 else
743 return false; // default: enable auto merge
744}
745
746// the remaining part of this file just handles printing out various
747// diff formats for the case where someone wants to *read* a diff
748// rather than apply it.
749
750struct hunk_consumer
751{
752 virtual void flush_hunk(size_t pos) = 0;
753 virtual void advance_to(size_t newpos) = 0;
754 virtual void insert_at(size_t b_pos) = 0;
755 virtual void delete_at(size_t a_pos) = 0;
756 virtual ~hunk_consumer() {}
757};
758
759void walk_hunk_consumer(vector<long, QA(long)> const & lcs,
760 vector<long, QA(long)> const & lines1,
761 vector<long, QA(long)> const & lines2,
762 hunk_consumer & cons)
763{
764
765 size_t a = 0, b = 0;
766 if (lcs.begin() == lcs.end())
767 {
768 // degenerate case: files have nothing in common
769 cons.advance_to(0);
770 while (a < lines1.size())
771 cons.delete_at(a++);
772 while (b < lines2.size())
773 cons.insert_at(b++);
774 cons.flush_hunk(a);
775 }
776 else
777 {
778 // normal case: files have something in common
779 for (vector<long, QA(long)>::const_iterator i = lcs.begin();
780 i != lcs.end(); ++i, ++a, ++b)
781 {
782 if (idx(lines1, a) == *i && idx(lines2, b) == *i)
783 continue;
784
785 cons.advance_to(a);
786 while (idx(lines1,a) != *i)
787 cons.delete_at(a++);
788 while (idx(lines2,b) != *i)
789 cons.insert_at(b++);
790 }
791 if (b < lines2.size())
792 {
793 cons.advance_to(a);
794 while(b < lines2.size())
795 cons.insert_at(b++);
796 }
797 if (a < lines1.size())
798 {
799 cons.advance_to(a);
800 while(a < lines1.size())
801 cons.delete_at(a++);
802 }
803 cons.flush_hunk(a);
804 }
805}
806
807struct unidiff_hunk_writer : public hunk_consumer
808{
809 vector<string> const & a;
810 vector<string> const & b;
811 size_t ctx;
812 ostream & ost;
813 size_t a_begin, b_begin, a_len, b_len;
814 long skew;
815 vector<string> hunk;
816 unidiff_hunk_writer(vector<string> const & a,
817 vector<string> const & b,
818 size_t ctx,
819 ostream & ost);
820 virtual void flush_hunk(size_t pos);
821 virtual void advance_to(size_t newpos);
822 virtual void insert_at(size_t b_pos);
823 virtual void delete_at(size_t a_pos);
824 virtual ~unidiff_hunk_writer() {}
825};
826
827unidiff_hunk_writer::unidiff_hunk_writer(vector<string> const & a,
828 vector<string> const & b,
829 size_t ctx,
830 ostream & ost)
831: a(a), b(b), ctx(ctx), ost(ost),
832 a_begin(0), b_begin(0),
833 a_len(0), b_len(0), skew(0)
834{}
835
836void unidiff_hunk_writer::insert_at(size_t b_pos)
837{
838 b_len++;
839 hunk.push_back(string("+") + b[b_pos]);
840}
841
842void unidiff_hunk_writer::delete_at(size_t a_pos)
843{
844 a_len++;
845 hunk.push_back(string("-") + a[a_pos]);
846}
847
848void unidiff_hunk_writer::flush_hunk(size_t pos)
849{
850 if (hunk.size() > 0)
851 {
852 // insert trailing context
853 size_t a_pos = a_begin + a_len;
854 for (size_t i = 0; (i < ctx) && (a_pos + i < a.size()); ++i)
855 {
856 hunk.push_back(string(" ") + a[a_pos + i]);
857 a_len++;
858 b_len++;
859 }
860
861 // write hunk to stream
862 if (a_len == 0)
863 ost << "@@ -0,0";
864 else
865 {
866 ost << "@@ -" << a_begin+1;
867 if (a_len > 1)
868 ost << "," << a_len;
869 }
870
871 if (b_len == 0)
872 ost << " +0,0";
873 else
874 {
875 ost << " +" << b_begin+1;
876 if (b_len > 1)
877 ost << "," << b_len;
878 }
879 ost << " @@" << endl;
880
881 copy(hunk.begin(), hunk.end(), ostream_iterator<string>(ost, "\n"));
882 }
883
884 // reset hunk
885 hunk.clear();
886 skew += b_len - a_len;
887 a_begin = pos;
888 b_begin = pos + skew;
889 a_len = 0;
890 b_len = 0;
891}
892
893void unidiff_hunk_writer::advance_to(size_t newpos)
894{
895 if (a_begin + a_len + (2 * ctx) < newpos)
896 {
897 flush_hunk(newpos);
898
899 // insert new leading context
900 if (newpos - ctx < a.size())
901 {
902 for (int i = ctx; i > 0; --i)
903 {
904 if (newpos - i < 0)
905 continue;
906 hunk.push_back(string(" ") + a[newpos - i]);
907 a_begin--; a_len++;
908 b_begin--; b_len++;
909 }
910 }
911 }
912 else
913 {
914 // pad intermediate context
915 while(a_begin + a_len < newpos)
916 {
917 hunk.push_back(string(" ") + a[a_begin + a_len]);
918 a_len++;
919 b_len++;
920 }
921 }
922}
923
924struct cxtdiff_hunk_writer : public hunk_consumer
925{
926 vector<string> const & a;
927 vector<string> const & b;
928 size_t ctx;
929 ostream & ost;
930 size_t a_begin, b_begin, a_len, b_len;
931 long skew;
932 vector<size_t> inserts;
933 vector<size_t> deletes;
934 vector<string> from_file;
935 vector<string> to_file;
936 bool have_insertions;
937 bool have_deletions;
938 cxtdiff_hunk_writer(vector<string> const & a,
939 vector<string> const & b,
940 size_t ctx,
941 ostream & ost);
942 virtual void flush_hunk(size_t pos);
943 virtual void advance_to(size_t newpos);
944 virtual void insert_at(size_t b_pos);
945 virtual void delete_at(size_t a_pos);
946 void flush_pending_mods();
947 virtual ~cxtdiff_hunk_writer() {}
948};
949
950cxtdiff_hunk_writer::cxtdiff_hunk_writer(vector<string> const & a,
951 vector<string> const & b,
952 size_t ctx,
953 ostream & ost)
954 : a(a), b(b), ctx(ctx), ost(ost),
955 a_begin(0), b_begin(0),
956 a_len(0), b_len(0), skew(0),
957 have_insertions(false), have_deletions(false)
958{}
959
960void cxtdiff_hunk_writer::insert_at(size_t b_pos)
961{
962 inserts.push_back(b_pos);
963 have_insertions = true;
964}
965
966void cxtdiff_hunk_writer::delete_at(size_t a_pos)
967{
968 deletes.push_back(a_pos);
969 have_deletions = true;
970}
971
972void cxtdiff_hunk_writer::flush_hunk(size_t pos)
973{
974 flush_pending_mods();
975
976 if (have_deletions || have_insertions)
977 {
978 // insert trailing context
979 size_t ctx_start = a_begin + a_len;
980 for (size_t i = 0; (i < ctx) && (ctx_start + i < a.size()); ++i)
981 {
982 from_file.push_back(string(" ") + a[ctx_start + i]);
983 a_len++;
984 }
985
986 ctx_start = b_begin + b_len;
987 for (size_t i = 0; (i < ctx) && (ctx_start + i < b.size()); ++i)
988 {
989 to_file.push_back(string(" ") + b[ctx_start + i]);
990 b_len++;
991 }
992
993 ost << "***************" << endl;
994
995 ost << "*** " << (a_begin + 1) << "," << (a_begin + a_len) << " ****" << endl;
996 if (have_deletions)
997 copy(from_file.begin(), from_file.end(), ostream_iterator<string>(ost, "\n"));
998
999 ost << "--- " << (b_begin + 1) << "," << (b_begin + b_len) << " ----" << endl;
1000 if (have_insertions)
1001 copy(to_file.begin(), to_file.end(), ostream_iterator<string>(ost, "\n"));
1002 }
1003
1004 // reset hunk
1005 to_file.clear();
1006 from_file.clear();
1007 have_insertions = false;
1008 have_deletions = false;
1009 skew += b_len - a_len;
1010 a_begin = pos;
1011 b_begin = pos + skew;
1012 a_len = 0;
1013 b_len = 0;
1014}
1015
1016void cxtdiff_hunk_writer::flush_pending_mods()
1017{
1018 // nothing to flush?
1019 if (inserts.empty() && deletes.empty())
1020 return;
1021
1022 string prefix;
1023
1024 // if we have just insertions to flush, prefix them with "+"; if
1025 // just deletions, prefix with "-"; if both, prefix with "!"
1026 if (inserts.empty() && !deletes.empty())
1027 prefix = "-";
1028 else if (deletes.empty() && !inserts.empty())
1029 prefix = "+";
1030 else
1031 prefix = "!";
1032
1033 for (vector<size_t>::const_iterator i = deletes.begin();
1034 i != deletes.end(); ++i)
1035 {
1036 from_file.push_back(prefix + string(" ") + a[*i]);
1037 a_len++;
1038 }
1039 for (vector<size_t>::const_iterator i = inserts.begin();
1040 i != inserts.end(); ++i)
1041 {
1042 to_file.push_back(prefix + string(" ") + b[*i]);
1043 b_len++;
1044 }
1045
1046 // clear pending mods
1047 inserts.clear();
1048 deletes.clear();
1049}
1050
1051void cxtdiff_hunk_writer::advance_to(size_t newpos)
1052{
1053 if (a_begin + a_len + (2 * ctx) < newpos)
1054 {
1055 flush_hunk(newpos);
1056
1057 // insert new leading context
1058 if (newpos - ctx < a.size())
1059 {
1060 for (int i = ctx; i > 0; --i)
1061 {
1062 if (newpos - i < 0)
1063 continue;
1064
1065 // note that context diffs prefix common text with two
1066 // spaces, whereas unified diffs use a single space
1067 from_file.push_back(string(" ") + a[newpos - i]);
1068 to_file.push_back(string(" ") + a[newpos - i]);
1069 a_begin--; a_len++;
1070 b_begin--; b_len++;
1071 }
1072 }
1073 }
1074 else
1075 {
1076 flush_pending_mods();
1077 // pad intermediate context
1078 while (a_begin + a_len < newpos)
1079 {
1080 from_file.push_back(string(" ") + a[a_begin + a_len]);
1081 to_file.push_back(string(" ") + a[a_begin + a_len]);
1082 a_len++;
1083 b_len++;
1084 }
1085 }
1086}
1087
1088void make_diff(string const & filename1,
1089 string const & filename2,
1090 file_id const & id1,
1091 file_id const & id2,
1092 vector<string> const & lines1,
1093 vector<string> const & lines2,
1094 ostream & ost,
1095 diff_type type)
1096{
1097 vector<long, QA(long)> left_interned;
1098 vector<long, QA(long)> right_interned;
1099 vector<long, QA(long)> lcs;
1100
1101 interner<long> in;
1102
1103 left_interned.reserve(lines1.size());
1104 for (vector<string>::const_iterator i = lines1.begin();
1105 i != lines1.end(); ++i)
1106 left_interned.push_back(in.intern(*i));
1107
1108 right_interned.reserve(lines2.size());
1109 for (vector<string>::const_iterator i = lines2.begin();
1110 i != lines2.end(); ++i)
1111 right_interned.push_back(in.intern(*i));
1112
1113 lcs.reserve(std::min(lines1.size(),lines2.size()));
1114 longest_common_subsequence(left_interned.begin(), left_interned.end(),
1115 right_interned.begin(), right_interned.end(),
1116 std::min(lines1.size(), lines2.size()),
1117 back_inserter(lcs));
1118
1119 switch (type)
1120 {
1121 case unified_diff:
1122 {
1123 ost << "--- " << filename1 << "\t" << id1 << endl;
1124 ost << "+++ " << filename2 << "\t" << id2 << endl;
1125
1126 unidiff_hunk_writer hunks(lines1, lines2, 3, ost);
1127 walk_hunk_consumer(lcs, left_interned, right_interned, hunks);
1128 break;
1129 }
1130 case context_diff:
1131 {
1132 ost << "*** " << filename1 << "\t" << id1 << endl;
1133 ost << "--- " << filename2 << "\t" << id2 << endl;
1134
1135 cxtdiff_hunk_writer hunks(lines1, lines2, 3, ost);
1136 walk_hunk_consumer(lcs, left_interned, right_interned, hunks);
1137 break;
1138 }
1139 default:
1140 {
1141 // should never reach this; the external_diff type is not
1142 // handled by this function.
1143 I(false);
1144 }
1145 }
1146}
1147
1148#ifdef BUILD_UNIT_TESTS
1149#include "unit_tests.hh"
1150#include "transforms.hh"
1151#include <boost/lexical_cast.hpp>
1152#include "randomfile.hh"
1153
1154using boost::lexical_cast;
1155
1156static void dump_incorrect_merge(vector<string> const & expected,
1157 vector<string> const & got,
1158 string const & prefix)
1159{
1160 size_t mx = expected.size();
1161 if (mx < got.size())
1162 mx = got.size();
1163 for (size_t i = 0; i < mx; ++i)
1164 {
1165 cerr << "bad merge: " << i << " [" << prefix << "]\t";
1166
1167 if (i < expected.size())
1168 cerr << "[" << expected[i] << "]\t";
1169 else
1170 cerr << "[--nil--]\t";
1171
1172 if (i < got.size())
1173 cerr << "[" << got[i] << "]\t";
1174 else
1175 cerr << "[--nil--]\t";
1176
1177 cerr << endl;
1178 }
1179}
1180
1181// regression blockers go here
1182static void unidiff_append_test()
1183{
1184 string src(string("#include \"hello.h\"\n")
1185 + "\n"
1186 + "void say_hello()\n"
1187 + "{\n"
1188 + " printf(\"hello, world\\n\");\n"
1189 + "}\n"
1190 + "\n"
1191 + "int main()\n"
1192 + "{\n"
1193 + " say_hello();\n"
1194 + "}\n");
1195
1196 string dst(string("#include \"hello.h\"\n")
1197 + "\n"
1198 + "void say_hello()\n"
1199 + "{\n"
1200 + " printf(\"hello, world\\n\");\n"
1201 + "}\n"
1202 + "\n"
1203 + "int main()\n"
1204 + "{\n"
1205 + " say_hello();\n"
1206 + "}\n"
1207 + "\n"
1208 + "void say_goodbye()\n"
1209 + "{\n"
1210 + " printf(\"goodbye\\n\");\n"
1211 + "}\n"
1212 + "\n");
1213
1214 string ud(string("--- hello.c\t0123456789abcdef0123456789abcdef01234567\n")
1215 + "+++ hello.c\tabcdef0123456789abcdef0123456789abcdef01\n"
1216 + "@@ -9,3 +9,9 @@\n"
1217 + " {\n"
1218 + " say_hello();\n"
1219 + " }\n"
1220 + "+\n"
1221 + "+void say_goodbye()\n"
1222 + "+{\n"
1223 + "+ printf(\"goodbye\\n\");\n"
1224 + "+}\n"
1225 + "+\n");
1226
1227 vector<string> src_lines, dst_lines;
1228 split_into_lines(src, src_lines);
1229 split_into_lines(dst, dst_lines);
1230 stringstream sst;
1231 make_diff("hello.c", "hello.c",
1232 file_id(id("0123456789abcdef0123456789abcdef01234567")),
1233 file_id(id("abcdef0123456789abcdef0123456789abcdef01")),
1234 src_lines, dst_lines, sst, unified_diff);
1235 cout << sst.str() << std::endl;
1236 BOOST_CHECK(sst.str() == ud);
1237}
1238
1239
1240// high tech randomizing test
1241
1242static void randomizing_merge_test()
1243{
1244 for (int i = 0; i < 30; ++i)
1245 {
1246 vector<string> anc, d1, d2, m1, m2, gm;
1247
1248 file_randomizer::build_random_fork(anc, d1, d2, gm,
1249 i * 1023, (10 + 2 * i));
1250
1251 BOOST_CHECK(merge3(anc, d1, d2, m1));
1252 if (gm != m1)
1253 dump_incorrect_merge (gm, m1, "random_merge 1");
1254 BOOST_CHECK(gm == m1);
1255
1256 BOOST_CHECK(merge3(anc, d2, d1, m2));
1257 if (gm != m2)
1258 dump_incorrect_merge (gm, m2, "random_merge 2");
1259 BOOST_CHECK(gm == m2);
1260 }
1261}
1262
1263
1264// old boring tests
1265
1266static void merge_prepend_test()
1267{
1268 BOOST_CHECKPOINT("prepend test");
1269 vector<string> anc, d1, d2, m1, m2, gm;
1270 for (int i = 10; i < 20; ++i)
1271 {
1272 d2.push_back(lexical_cast<string>(i));
1273 gm.push_back(lexical_cast<string>(i));
1274 }
1275
1276 for (int i = 0; i < 10; ++i)
1277 {
1278 anc.push_back(lexical_cast<string>(i));
1279 d1.push_back(lexical_cast<string>(i));
1280 d2.push_back(lexical_cast<string>(i));
1281 gm.push_back(lexical_cast<string>(i));
1282 }
1283
1284 BOOST_CHECK(merge3(anc, d1, d2, m1));
1285 if (gm != m1)
1286 dump_incorrect_merge (gm, m1, "merge_prepend 1");
1287 BOOST_CHECK(gm == m1);
1288
1289
1290 BOOST_CHECK(merge3(anc, d2, d1, m2));
1291 if (gm != m2)
1292 dump_incorrect_merge (gm, m2, "merge_prepend 2");
1293 BOOST_CHECK(gm == m2);
1294}
1295
1296
1297static void merge_append_test()
1298{
1299 BOOST_CHECKPOINT("append test");
1300 vector<string> anc, d1, d2, m1, m2, gm;
1301 for (int i = 0; i < 10; ++i)
1302 anc.push_back(lexical_cast<string>(i));
1303
1304 d1 = anc;
1305 d2 = anc;
1306 gm = anc;
1307
1308 for (int i = 10; i < 20; ++i)
1309 {
1310 d2.push_back(lexical_cast<string>(i));
1311 gm.push_back(lexical_cast<string>(i));
1312 }
1313
1314 BOOST_CHECK(merge3(anc, d1, d2, m1));
1315 if (gm != m1)
1316 dump_incorrect_merge (gm, m1, "merge_append 1");
1317 BOOST_CHECK(gm == m1);
1318
1319 BOOST_CHECK(merge3(anc, d2, d1, m2));
1320 if (gm != m2)
1321 dump_incorrect_merge (gm, m2, "merge_append 2");
1322 BOOST_CHECK(gm == m2);
1323
1324
1325}
1326
1327static void merge_additions_test()
1328{
1329 BOOST_CHECKPOINT("additions test");
1330 string ancestor("I like oatmeal\nI like orange juice\nI like toast");
1331 string desc1("I like oatmeal\nI don't like spam\nI like orange juice\nI like toast");
1332 string confl("I like oatmeal\nI don't like tuna\nI like orange juice\nI like toast");
1333 string desc2("I like oatmeal\nI like orange juice\nI don't like tuna\nI like toast");
1334 string good_merge("I like oatmeal\nI don't like spam\nI like orange juice\nI don't like tuna\nI like toast");
1335 vector<string> anc, d1, cf, d2, m1, m2, gm;
1336
1337 split_into_lines(ancestor, anc);
1338 split_into_lines(desc1, d1);
1339 split_into_lines(confl, cf);
1340 split_into_lines(desc2, d2);
1341 split_into_lines(good_merge, gm);
1342
1343 BOOST_CHECK(merge3(anc, d1, d2, m1));
1344 if (gm != m1)
1345 dump_incorrect_merge (gm, m1, "merge_addition 1");
1346 BOOST_CHECK(gm == m1);
1347
1348 BOOST_CHECK(merge3(anc, d2, d1, m2));
1349 if (gm != m2)
1350 dump_incorrect_merge (gm, m2, "merge_addition 2");
1351 BOOST_CHECK(gm == m2);
1352
1353 BOOST_CHECK(!merge3(anc, d1, cf, m1));
1354}
1355
1356static void merge_deletions_test()
1357{
1358 string ancestor("I like oatmeal\nI like orange juice\nI like toast");
1359 string desc2("I like oatmeal\nI like toast");
1360
1361 vector<string> anc, d1, d2, m1, m2, gm;
1362
1363 split_into_lines(ancestor, anc);
1364 split_into_lines(desc2, d2);
1365 d1 = anc;
1366 gm = d2;
1367
1368 BOOST_CHECK(merge3(anc, d1, d2, m1));
1369 if (gm != m1)
1370 dump_incorrect_merge (gm, m1, "merge_deletion 1");
1371 BOOST_CHECK(gm == m1);
1372
1373 BOOST_CHECK(merge3(anc, d2, d1, m2));
1374 if (gm != m2)
1375 dump_incorrect_merge (gm, m2, "merge_deletion 2");
1376 BOOST_CHECK(gm == m2);
1377}
1378
1379
1380void add_diff_patch_tests(test_suite * suite)
1381{
1382 I(suite);
1383 suite->add(BOOST_TEST_CASE(&unidiff_append_test));
1384 suite->add(BOOST_TEST_CASE(&merge_prepend_test));
1385 suite->add(BOOST_TEST_CASE(&merge_append_test));
1386 suite->add(BOOST_TEST_CASE(&merge_additions_test));
1387 suite->add(BOOST_TEST_CASE(&merge_deletions_test));
1388 suite->add(BOOST_TEST_CASE(&randomizing_merge_test));
1389}
1390
1391
1392#endif // BUILD_UNIT_TESTS

Archive Download this file

Branches

Tags

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