205
224
return self._parents == other._parents \
206
225
and self._weave == other._weave \
207
226
and self._sha1s == other._sha1s
210
228
def __ne__(self, other):
211
229
return not self.__eq__(other)
231
@deprecated_method(zero_eight)
232
def idx_to_name(self, index):
233
"""Old public interface, the public interface is all names now."""
236
def _idx_to_name(self, version):
237
return self._names[version]
239
@deprecated_method(zero_eight)
214
240
def lookup(self, name):
241
"""Backwards compatibility thunk:
243
Return name, as name is valid in the api now, and spew deprecation
248
def _lookup(self, name):
249
"""Convert symbolic version name to index."""
216
251
return self._name_map[name]
218
raise WeaveError("name %s not present in weave %s" %
219
(name, self._weave_name))
222
def add(self, name, parents, text):
253
raise RevisionNotPresent(name, self._weave_name)
255
@deprecated_method(zero_eight)
256
def iter_names(self):
257
"""Deprecated convenience function, please see VersionedFile.names()."""
258
return iter(self.names())
260
@deprecated_method(zero_eight)
262
"""See Weave.versions for the current api."""
263
return self.versions()
266
"""See VersionedFile.versions."""
267
return self._names[:]
269
def has_version(self, version_id):
270
"""See VersionedFile.has_version."""
271
return (version_id in self._name_map)
273
__contains__ = has_version
275
def get_delta(self, version_id):
276
"""See VersionedFile.get_delta."""
277
return self.get_deltas([version_id])[version_id]
279
def get_deltas(self, version_ids):
280
"""See VersionedFile.get_deltas."""
281
version_ids = self.get_ancestry(version_ids)
282
for version_id in version_ids:
283
if not self.has_version(version_id):
284
raise RevisionNotPresent(version_id, self)
285
# try extracting all versions; parallel extraction is used
286
nv = self.num_versions()
292
last_parent_lines = {}
294
parent_inclusions = {}
299
# its simplest to generate a full set of prepared variables.
301
name = self._names[i]
302
sha1s[name] = self.get_sha1(name)
303
parents_list = self.get_parents(name)
305
parent = parents_list[0]
306
parents[name] = parent
307
parent_inclusions[name] = inclusions[parent]
310
parent_inclusions[name] = set()
311
# we want to emit start, finish, replacement_length, replacement_lines tuples.
312
diff_hunks[name] = []
313
current_hunks[name] = [0, 0, 0, []] # #start, finish, repl_length, repl_tuples
314
parent_linenums[name] = 0
316
parent_noeols[name] = False
317
last_parent_lines[name] = None
318
new_inc = set([name])
319
for p in self._parents[i]:
320
new_inc.update(inclusions[self._idx_to_name(p)])
321
# debug only, known good so far.
322
#assert set(new_inc) == set(self.get_ancestry(name)), \
323
# 'failed %s != %s' % (set(new_inc), set(self.get_ancestry(name)))
324
inclusions[name] = new_inc
326
nlines = len(self._weave)
328
for lineno, inserted, deletes, line in self._walk_internal():
329
# a line is active in a version if:
330
# insert is in the versions inclusions
332
# deleteset & the versions inclusions is an empty set.
333
# so - if we have a included by mapping - version is included by
334
# children, we get a list of children to examine for deletes affect
335
# ing them, which is less than the entire set of children.
336
for version_id in version_ids:
337
# The active inclusion must be an ancestor,
338
# and no ancestors must have deleted this line,
339
# because we don't support resurrection.
340
parent_inclusion = parent_inclusions[version_id]
341
inclusion = inclusions[version_id]
342
parent_active = inserted in parent_inclusion and not (deletes & parent_inclusion)
343
version_active = inserted in inclusion and not (deletes & inclusion)
344
if not parent_active and not version_active:
345
# unrelated line of ancestry
347
elif parent_active and version_active:
349
parent_linenum = parent_linenums[version_id]
350
if current_hunks[version_id] != [parent_linenum, parent_linenum, 0, []]:
351
diff_hunks[version_id].append(tuple(current_hunks[version_id]))
353
current_hunks[version_id] = [parent_linenum, parent_linenum, 0, []]
354
parent_linenums[version_id] = parent_linenum
357
noeols[version_id] = True
360
elif parent_active and not version_active:
362
current_hunks[version_id][1] += 1
363
parent_linenums[version_id] += 1
364
last_parent_lines[version_id] = line
365
elif not parent_active and version_active:
367
# noeol only occurs at the end of a file because we
368
# diff linewise. We want to show noeol changes as a
369
# empty diff unless the actual eol-less content changed.
372
if last_parent_lines[version_id][-1] != '\n':
373
parent_noeols[version_id] = True
374
except (TypeError, IndexError):
377
if theline[-1] != '\n':
378
noeols[version_id] = True
382
parent_should_go = False
384
if parent_noeols[version_id] == noeols[version_id]:
385
# no noeol toggle, so trust the weaves statement
386
# that this line is changed.
388
if parent_noeols[version_id]:
389
theline = theline + '\n'
390
elif parent_noeols[version_id]:
391
# parent has no eol, we do:
392
# our line is new, report as such..
394
elif noeols[version_id]:
395
# append a eol so that it looks like
397
theline = theline + '\n'
398
if parents[version_id] is not None:
399
#if last_parent_lines[version_id] is not None:
400
parent_should_go = True
401
if last_parent_lines[version_id] != theline:
404
#parent_should_go = False
406
current_hunks[version_id][2] += 1
407
current_hunks[version_id][3].append((inserted, theline))
409
# last hunk last parent line is not eaten
410
current_hunks[version_id][1] -= 1
411
if current_hunks[version_id][1] < 0:
412
current_hunks[version_id][1] = 0
413
# import pdb;pdb.set_trace()
414
# assert current_hunks[version_id][1] >= 0
418
version = self._idx_to_name(i)
419
if current_hunks[version] != [0, 0, 0, []]:
420
diff_hunks[version].append(tuple(current_hunks[version]))
422
for version_id in version_ids:
423
result[version_id] = (
427
diff_hunks[version_id],
431
def get_parents(self, version_id):
432
"""See VersionedFile.get_parent."""
433
return map(self._idx_to_name, self._parents[self._lookup(version_id)])
435
def _check_repeated_add(self, name, parents, text, sha1):
436
"""Check that a duplicated add is OK.
438
If it is, return the (old) index; otherwise raise an exception.
440
idx = self._lookup(name)
441
if sorted(self._parents[idx]) != sorted(parents) \
442
or sha1 != self._sha1s[idx]:
443
raise RevisionAlreadyPresent(name, self._weave_name)
446
@deprecated_method(zero_eight)
447
def add_identical(self, old_rev_id, new_rev_id, parents):
448
"""Please use Weave.clone_text now."""
449
return self.clone_text(new_rev_id, old_rev_id, parents)
451
def _add_lines(self, version_id, parents, lines, parent_texts):
452
"""See VersionedFile.add_lines."""
453
return self._add(version_id, lines, map(self._lookup, parents))
455
@deprecated_method(zero_eight)
456
def add(self, name, parents, text, sha1=None):
457
"""See VersionedFile.add_lines for the non deprecated api."""
458
return self._add(name, text, map(self._maybe_lookup, parents), sha1)
460
def _add(self, version_id, lines, parents, sha1=None):
223
461
"""Add a single text on top of the weave.
225
463
Returns the index number of the newly added version.
228
466
Symbolic name for this version.
229
467
(Typically the revision-id of the revision that added it.)
232
470
List or set of direct parent version numbers.
235
Sequence of lines to be added in the new version."""
237
assert isinstance(name, basestring)
238
if name in self._name_map:
239
raise WeaveError("name %r already present in weave" % name)
473
Sequence of lines to be added in the new version.
476
assert isinstance(version_id, basestring)
477
self._check_lines_not_unicode(lines)
478
self._check_lines_are_lines(lines)
480
sha1 = sha_strings(lines)
481
if version_id in self._name_map:
482
return self._check_repeated_add(version_id, parents, lines, sha1)
241
484
self._check_versions(parents)
242
## self._check_lines(text)
485
## self._check_lines(lines)
243
486
new_version = len(self._parents)
250
488
# if we abort after here the (in-memory) weave will be corrupt because only
251
489
# some fields are updated
490
# XXX: FIXME implement a succeed-or-fail of the rest of this routine.
491
# - Robert Collins 20060226
252
492
self._parents.append(parents[:])
253
493
self._sha1s.append(sha1)
254
self._names.append(name)
255
self._name_map[name] = new_version
494
self._names.append(version_id)
495
self._name_map[version_id] = new_version
399
632
except IndexError:
400
633
raise IndexError("invalid version number %r" % i)
635
def _compatible_parents(self, my_parents, other_parents):
636
"""During join check that other_parents are joinable with my_parents.
638
Joinable is defined as 'is a subset of' - supersets may require
639
regeneration of diffs, but subsets do not.
641
return len(other_parents.difference(my_parents)) == 0
643
def annotate(self, version_id):
644
if isinstance(version_id, int):
645
warnings.warn('Weave.annotate(int) is deprecated. Please use version names'
646
' in all circumstances as of 0.8',
651
for origin, lineno, text in self._extract([version_id]):
652
result.append((origin, text))
655
return super(Weave, self).annotate(version_id)
403
def annotate(self, index):
404
return list(self.annotate_iter(index))
407
def annotate_iter(self, version):
408
"""Yield list of (index-id, line) pairs for the specified version.
657
def annotate_iter(self, version_id):
658
"""Yield list of (version-id, line) pairs for the specified version.
410
660
The index indicates when the line originated in the weave."""
411
for origin, lineno, text in self._extract([version]):
661
incls = [self._lookup(version_id)]
662
for origin, lineno, text in self._extract(incls):
663
yield self._idx_to_name(origin), text
665
@deprecated_method(zero_eight)
419
(lineno, insert, deletes, text)
420
for each literal line.
667
"""_walk has become visit, a supported api."""
668
return self._walk_internal()
670
def iter_lines_added_or_present_in_versions(self, version_ids=None,
672
"""See VersionedFile.iter_lines_added_or_present_in_versions()."""
673
if version_ids is None:
674
version_ids = self.versions()
675
version_ids = set(version_ids)
676
for lineno, inserted, deletes, line in self._walk_internal(version_ids):
677
# if inserted not in version_ids then it was inserted before the
678
# versions we care about, but because weaves cannot represent ghosts
679
# properly, we do not filter down to that
680
# if inserted not in version_ids: continue
686
#@deprecated_method(zero_eight)
687
def walk(self, version_ids=None):
688
"""See VersionedFile.walk."""
689
return self._walk_internal(version_ids)
691
def _walk_internal(self, version_ids=None):
692
"""Helper method for weave actions."""
497
assert isinstance(l, basestring)
848
assert l.__class__ in (str, unicode)
498
849
if isactive is None:
499
850
isactive = (not dset) and istack and (istack[-1] in included)
501
852
result.append((istack[-1], lineno, l))
505
raise WFE("unclosed insertion blocks at end of weave",
855
raise WeaveFormatError("unclosed insertion blocks "
856
"at end of weave: %s" % istack)
508
raise WFE("unclosed deletion blocks at end of weave",
515
def get_iter(self, version):
516
"""Yield lines for the specified version."""
517
for origin, lineno, line in self._extract([version]):
521
def get_text(self, version):
522
assert isinstance(version, int)
524
s.writelines(self.get_iter(version))
528
def get(self, index):
529
return list(self.get_iter(index))
532
def mash_iter(self, included):
533
"""Return composed version of multiple included versions."""
534
for origin, lineno, text in self._extract(included):
538
def dump(self, to_file):
539
from pprint import pprint
540
print >>to_file, "Weave._weave = ",
541
pprint(self._weave, to_file)
542
print >>to_file, "Weave._parents = ",
543
pprint(self._parents, to_file)
858
raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
862
@deprecated_method(zero_eight)
863
def get_iter(self, name_or_index):
864
"""Deprecated, please do not use. Lookups are not not needed.
866
Please use get_lines now.
868
return iter(self.get_lines(self._maybe_lookup(name_or_index)))
870
@deprecated_method(zero_eight)
871
def maybe_lookup(self, name_or_index):
872
"""Deprecated, please do not use. Lookups are not not needed."""
873
return self._maybe_lookup(name_or_index)
875
def _maybe_lookup(self, name_or_index):
876
"""Convert possible symbolic name to index, or pass through indexes.
880
if isinstance(name_or_index, (int, long)):
883
return self._lookup(name_or_index)
885
@deprecated_method(zero_eight)
886
def get(self, version_id):
887
"""Please use either Weave.get_text or Weave.get_lines as desired."""
888
return self.get_lines(version_id)
890
def get_lines(self, version_id):
891
"""See VersionedFile.get_lines()."""
892
int_index = self._maybe_lookup(version_id)
893
result = [line for (origin, lineno, line) in self._extract([int_index])]
894
expected_sha1 = self._sha1s[int_index]
895
measured_sha1 = sha_strings(result)
896
if measured_sha1 != expected_sha1:
897
raise errors.WeaveInvalidChecksum(
898
'file %s, revision %s, expected: %s, measured %s'
899
% (self._weave_name, version_id,
900
expected_sha1, measured_sha1))
903
def get_sha1(self, version_id):
904
"""See VersionedFile.get_sha1()."""
905
return self._sha1s[self._lookup(version_id)]
907
@deprecated_method(zero_eight)
547
908
def numversions(self):
909
"""How many versions are in this weave?
911
Deprecated in favour of num_versions.
913
return self.num_versions()
915
def num_versions(self):
916
"""How many versions are in this weave?"""
548
917
l = len(self._parents)
549
918
assert l == len(self._sha1s)
554
return self.numversions()
921
__len__ = num_versions
557
923
def check(self, progress_bar=None):
558
# check no circular inclusions
559
for version in range(self.numversions()):
924
# TODO evaluate performance hit of using string sets in this routine.
925
# TODO: check no circular inclusions
926
# TODO: create a nested progress bar
927
for version in range(self.num_versions()):
560
928
inclusions = list(self._parents[version])
562
930
inclusions.sort()
564
932
raise WeaveFormatError("invalid included version %d for index %d"
565
933
% (inclusions[-1], version))
567
# try extracting all versions; this is a bit slow and parallel
568
# extraction could be used
569
nv = self.numversions()
570
for version in range(nv):
935
# try extracting all versions; parallel extraction is used
936
nv = self.num_versions()
941
# For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
942
# The problem is that set membership is much more expensive
943
name = self._idx_to_name(i)
944
sha1s[name] = sha.new()
946
new_inc = set([name])
947
for p in self._parents[i]:
948
new_inc.update(inclusions[self._idx_to_name(p)])
950
assert set(new_inc) == set(self.get_ancestry(name)), \
951
'failed %s != %s' % (set(new_inc), set(self.get_ancestry(name)))
952
inclusions[name] = new_inc
954
nlines = len(self._weave)
956
update_text = 'checking weave'
958
short_name = os.path.basename(self._weave_name)
959
update_text = 'checking %s' % (short_name,)
960
update_text = update_text[:25]
962
for lineno, insert, deleteset, line in self._walk_internal():
572
progress_bar.update('checking text', version, nv)
574
for l in self.get_iter(version):
577
expected = self._sha1s[version]
964
progress_bar.update(update_text, lineno, nlines)
966
for name, name_inclusions in inclusions.items():
967
# The active inclusion must be an ancestor,
968
# and no ancestors must have deleted this line,
969
# because we don't support resurrection.
970
if (insert in name_inclusions) and not (deleteset & name_inclusions):
971
sha1s[name].update(line)
974
version = self._idx_to_name(i)
975
hd = sha1s[version].hexdigest()
976
expected = self._sha1s[i]
578
977
if hd != expected:
579
raise WeaveError("mismatched sha1 for version %d; "
580
"got %s, expected %s"
581
% (version, hd, expected))
978
raise errors.WeaveInvalidChecksum(
979
"mismatched sha1 for version %s: "
980
"got %s, expected %s"
981
% (version, hd, expected))
583
983
# TODO: check insertions are properly nested, that there are
584
984
# no lines outside of insertion blocks, that deletions are
585
985
# properly paired, etc.
589
def merge(self, merge_versions):
590
"""Automerge and mark conflicts between versions.
592
This returns a sequence, each entry describing alternatives
593
for a chunk of the file. Each of the alternatives is given as
596
If there is a chunk of the file where there's no diagreement,
597
only one alternative is given.
600
# approach: find the included versions common to all the
602
raise NotImplementedError()
606
def _delta(self, included, lines):
607
"""Return changes from basis to new revision.
609
The old text for comparison is the union of included revisions.
611
This is used in inserting a new text.
613
Delta is returned as a sequence of
614
(weave1, weave2, newlines).
616
This indicates that weave1:weave2 of the old weave should be
617
replaced by the sequence of lines in newlines. Note that
618
these line numbers are positions in the total weave and don't
619
correspond to the lines in any extracted version, or even the
620
extracted union of included versions.
622
If line1=line2, this is a pure insert; if newlines=[] this is a
623
pure delete. (Similar to difflib.)
628
def plan_merge(self, ver_a, ver_b):
629
"""Return pseudo-annotation indicating how the two versions merge.
631
This is computed between versions a and b and their common
634
Weave lines present in none of them are skipped entirely.
636
inc_a = self.inclusions([ver_a])
637
inc_b = self.inclusions([ver_b])
638
inc_c = inc_a & inc_b
640
for lineno, insert, deleteset, line in self._walk():
641
if deleteset & inc_c:
642
# killed in parent; can't be in either a or b
643
# not relevant to our work
644
yield 'killed-base', line
645
elif insert in inc_c:
646
# was inserted in base
647
killed_a = bool(deleteset & inc_a)
648
killed_b = bool(deleteset & inc_b)
649
if killed_a and killed_b:
650
yield 'killed-both', line
652
yield 'killed-a', line
654
yield 'killed-b', line
656
yield 'unchanged', line
657
elif insert in inc_a:
658
if deleteset & inc_a:
659
yield 'ghost-a', line
663
elif insert in inc_b:
664
if deleteset & inc_b:
665
yield 'ghost-b', line
669
# not in either revision
670
yield 'irrelevant', line
672
yield 'unchanged', '' # terminator
676
def weave_merge(self, plan):
681
for state, line in plan:
682
if state == 'unchanged' or state == 'killed-both':
683
# resync and flush queued conflicts changes if any
684
if not lines_a and not lines_b:
686
elif ch_a and not ch_b:
688
for l in lines_a: yield l
689
elif ch_b and not ch_a:
690
for l in lines_b: yield l
691
elif lines_a == lines_b:
692
for l in lines_a: yield l
695
for l in lines_a: yield l
697
for l in lines_b: yield l
704
if state == 'unchanged':
707
elif state == 'killed-a':
710
elif state == 'killed-b':
713
elif state == 'new-a':
716
elif state == 'new-b':
720
assert state in ('irrelevant', 'ghost-a', 'ghost-b', 'killed-base',
987
def _join(self, other, pb, msg, version_ids, ignore_missing):
988
"""Worker routine for join()."""
989
if not other.versions():
990
return # nothing to update, easy
993
# versions is never none, InterWeave checks this.
996
# two loops so that we do not change ourselves before verifying it
998
# work through in index order to make sure we get all dependencies
1001
# get the selected versions only that are in other.versions.
1002
version_ids = set(other.versions()).intersection(set(version_ids))
1003
# pull in the referenced graph.
1004
version_ids = other.get_ancestry(version_ids)
1005
pending_graph = [(version, other.get_parents(version)) for
1006
version in version_ids]
1007
for name in topo_sort(pending_graph):
1008
other_idx = other._name_map[name]
1009
# returns True if we have it, False if we need it.
1010
if not self._check_version_consistent(other, other_idx, name):
1011
names_to_join.append((other_idx, name))
1020
for other_idx, name in names_to_join:
1021
# TODO: If all the parents of the other version are already
1022
# present then we can avoid some work by just taking the delta
1023
# and adjusting the offsets.
1024
new_parents = self._imported_parents(other, other_idx)
1025
sha1 = other._sha1s[other_idx]
1030
pb.update(msg, merged, len(names_to_join))
1032
lines = other.get_lines(other_idx)
1033
self._add(name, lines, new_parents, sha1)
1035
mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
1036
merged, processed, self._weave_name, time.time()-time0))
1038
def _imported_parents(self, other, other_idx):
1039
"""Return list of parents in self corresponding to indexes in other."""
1041
for parent_idx in other._parents[other_idx]:
1042
parent_name = other._names[parent_idx]
1043
if parent_name not in self._name_map:
1044
# should not be possible
1045
raise WeaveError("missing parent {%s} of {%s} in %r"
1046
% (parent_name, other._name_map[other_idx], self))
1047
new_parents.append(self._name_map[parent_name])
1050
def _check_version_consistent(self, other, other_idx, name):
1051
"""Check if a version in consistent in this and other.
1053
To be consistent it must have:
1056
* the same direct parents (by name, not index, and disregarding
1059
If present & correct return True;
1060
if not present in self return False;
1061
if inconsistent raise error."""
1062
this_idx = self._name_map.get(name, -1)
1064
if self._sha1s[this_idx] != other._sha1s[other_idx]:
1065
raise errors.WeaveTextDiffers(name, self, other)
1066
self_parents = self._parents[this_idx]
1067
other_parents = other._parents[other_idx]
1068
n1 = set([self._names[i] for i in self_parents])
1069
n2 = set([other._names[i] for i in other_parents])
1070
if not self._compatible_parents(n1, n2):
1071
raise WeaveParentMismatch("inconsistent parents "
1072
"for version {%s}: %s vs %s" % (name, n1, n2))
1078
@deprecated_method(zero_eight)
1079
def reweave(self, other, pb=None, msg=None):
1080
"""reweave has been superseded by plain use of join."""
1081
return self.join(other, pb, msg)
1083
def _reweave(self, other, pb, msg):
1084
"""Reweave self with other - internal helper for join().
1086
:param other: The other weave to merge
1087
:param pb: An optional progress bar, indicating how far done we are
1088
:param msg: An optional message for the progress
1090
new_weave = _reweave(self, other, pb=pb, msg=msg)
1091
self._copy_weave_content(new_weave)
1093
def _copy_weave_content(self, otherweave):
1094
"""adsorb the content from otherweave."""
1095
for attr in self.__slots__:
1096
if attr != '_weave_name':
1097
setattr(self, attr, copy(getattr(otherweave, attr)))
1100
class WeaveFile(Weave):
1101
"""A WeaveFile represents a Weave on disk and writes on change."""
1103
WEAVE_SUFFIX = '.weave'
1105
def __init__(self, name, transport, filemode=None, create=False, access_mode='w'):
1106
"""Create a WeaveFile.
1108
:param create: If not True, only open an existing knit.
1110
super(WeaveFile, self).__init__(name, access_mode)
1111
self._transport = transport
1112
self._filemode = filemode
1114
_read_weave_v5(self._transport.get(name + WeaveFile.WEAVE_SUFFIX), self)
1115
except errors.NoSuchFile:
1121
def _add_lines(self, version_id, parents, lines, parent_texts):
1122
"""Add a version and save the weave."""
1123
result = super(WeaveFile, self)._add_lines(version_id, parents, lines,
1128
def _clone_text(self, new_version_id, old_version_id, parents):
1129
"""See VersionedFile.clone_text."""
1130
super(WeaveFile, self)._clone_text(new_version_id, old_version_id, parents)
1133
def copy_to(self, name, transport):
1134
"""See VersionedFile.copy_to()."""
1135
# as we are all in memory always, just serialise to the new place.
1137
write_weave_v5(self, sio)
1139
transport.put_file(name + WeaveFile.WEAVE_SUFFIX, sio, self._filemode)
1141
def create_empty(self, name, transport, filemode=None):
1142
return WeaveFile(name, transport, filemode, create=True)
1145
"""Save the weave."""
1146
self._check_write_ok()
1148
write_weave_v5(self, sio)
1150
self._transport.put_file(self._weave_name + WeaveFile.WEAVE_SUFFIX,
1156
"""See VersionedFile.get_suffixes()."""
1157
return [WeaveFile.WEAVE_SUFFIX]
1159
def join(self, other, pb=None, msg=None, version_ids=None,
1160
ignore_missing=False):
1161
"""Join other into self and save."""
1162
super(WeaveFile, self).join(other, pb, msg, version_ids, ignore_missing)
1166
@deprecated_function(zero_eight)
1167
def reweave(wa, wb, pb=None, msg=None):
1168
"""reweaving is deprecation, please just use weave.join()."""
1169
_reweave(wa, wb, pb, msg)
1171
def _reweave(wa, wb, pb=None, msg=None):
1172
"""Combine two weaves and return the result.
1174
This works even if a revision R has different parents in
1175
wa and wb. In the resulting weave all the parents are given.
1177
This is done by just building up a new weave, maintaining ordering
1178
of the versions in the two inputs. More efficient approaches
1179
might be possible but it should only be necessary to do
1180
this operation rarely, when a new previously ghost version is
1183
:param pb: An optional progress bar, indicating how far done we are
1184
:param msg: An optional message for the progress
1188
queue_a = range(wa.num_versions())
1189
queue_b = range(wb.num_versions())
1190
# first determine combined parents of all versions
1191
# map from version name -> all parent names
1192
combined_parents = _reweave_parent_graphs(wa, wb)
1193
mutter("combined parents: %r", combined_parents)
1194
order = topo_sort(combined_parents.iteritems())
1195
mutter("order to reweave: %r", order)
1200
for idx, name in enumerate(order):
1202
pb.update(msg, idx, len(order))
1203
if name in wa._name_map:
1204
lines = wa.get_lines(name)
1205
if name in wb._name_map:
1206
lines_b = wb.get_lines(name)
1207
if lines != lines_b:
1208
mutter('Weaves differ on content. rev_id {%s}', name)
1209
mutter('weaves: %s, %s', wa._weave_name, wb._weave_name)
1211
lines = list(difflib.unified_diff(lines, lines_b,
1212
wa._weave_name, wb._weave_name))
1213
mutter('lines:\n%s', ''.join(lines))
1214
raise errors.WeaveTextDiffers(name, wa, wb)
1216
lines = wb.get_lines(name)
1217
wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
1220
def _reweave_parent_graphs(wa, wb):
1221
"""Return combined parent ancestry for two weaves.
1223
Returned as a list of (version_name, set(parent_names))"""
1225
for weave in [wa, wb]:
1226
for idx, name in enumerate(weave._names):
1227
p = combined.setdefault(name, set())
1228
p.update(map(weave._idx_to_name, weave._parents[idx]))
730
1232
def weave_toc(w):
901
1413
print ' '.join(map(str, w._parents[int(argv[3])]))
903
1415
elif cmd == 'plan-merge':
1416
# replaced by 'bzr weave-plan-merge'
905
1418
for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
907
1420
print '%14s | %s' % (state, line),
909
1421
elif cmd == 'merge':
1422
# replaced by 'bzr weave-merge-text'
911
1424
p = w.plan_merge(int(argv[3]), int(argv[4]))
912
1425
sys.stdout.writelines(w.weave_merge(p))
914
elif cmd == 'mash-merge':
920
v1, v2 = map(int, argv[3:5])
922
basis = w.inclusions([v1]).intersection(w.inclusions([v2]))
924
base_lines = list(w.mash_iter(basis))
925
a_lines = list(w.get(v1))
926
b_lines = list(w.get(v2))
928
from bzrlib.merge3 import Merge3
929
m3 = Merge3(base_lines, a_lines, b_lines)
931
name_a = 'version %d' % v1
932
name_b = 'version %d' % v2
933
sys.stdout.writelines(m3.merge_lines(name_a=name_a, name_b=name_b))
935
1427
raise ValueError('unknown command %r' % cmd)
939
def profile_main(argv):
940
import tempfile, hotshot, hotshot.stats
942
prof_f = tempfile.NamedTemporaryFile()
944
prof = hotshot.Profile(prof_f.name)
946
ret = prof.runcall(main, argv)
949
stats = hotshot.stats.load(prof_f.name)
951
stats.sort_stats('cumulative')
952
## XXX: Might like to write to stderr or the trace file instead but
953
## print_stats seems hardcoded to stdout
954
stats.print_stats(20)
959
1430
if __name__ == '__main__':
961
if '--profile' in sys.argv:
963
args.remove('--profile')
964
sys.exit(profile_main(args))
966
sys.exit(main(sys.argv))
1432
sys.exit(main(sys.argv))
1435
class InterWeave(InterVersionedFile):
1436
"""Optimised code paths for weave to weave operations."""
1438
_matching_file_from_factory = staticmethod(WeaveFile)
1439
_matching_file_to_factory = staticmethod(WeaveFile)
1442
def is_compatible(source, target):
1443
"""Be compatible with weaves."""
1445
return (isinstance(source, Weave) and
1446
isinstance(target, Weave))
1447
except AttributeError:
1450
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1451
"""See InterVersionedFile.join."""
1452
version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1453
if self.target.versions() == [] and version_ids is None:
1454
self.target._copy_weave_content(self.source)
1457
self.target._join(self.source, pb, msg, version_ids, ignore_missing)
1458
except errors.WeaveParentMismatch:
1459
self.target._reweave(self.source, pb, msg)
1462
InterVersionedFile.register_optimiser(InterWeave)