90
91
from bzrlib.progress import DummyProgress, ProgressPhase
91
92
from bzrlib.revision import NULL_REVISION
92
93
from bzrlib.rio import RioReader, rio_file, Stanza
93
from bzrlib.symbol_versioning import *
94
from bzrlib.textui import show_status
94
from bzrlib.symbol_versioning import (deprecated_passed,
101
from bzrlib.trace import mutter, note
96
102
from bzrlib.transform import build_tree
97
from bzrlib.trace import mutter, note
98
103
from bzrlib.transport import get_transport
99
104
from bzrlib.transport.local import LocalTransport
105
from bzrlib.textui import show_status
101
108
import bzrlib.xml5
111
# the regex removes any weird characters; we don't escape them
112
# but rather just pull them out
113
_gen_file_id_re = re.compile(r'[^\w.]')
114
_gen_id_suffix = None
118
def _next_id_suffix():
119
"""Create a new file id suffix that is reasonably unique.
121
On the first call we combine the current time with 64 bits of randomness
122
to give a highly probably globally unique number. Then each call in the same
123
process adds 1 to a serial number we append to that unique value.
125
# XXX TODO: change bzrlib.add.smart_add to call workingtree.add() rather
126
# than having to move the id randomness out of the inner loop like this.
127
# XXX TODO: for the global randomness this uses we should add the thread-id
128
# before the serial #.
129
global _gen_id_suffix, _gen_id_serial
130
if _gen_id_suffix is None:
131
_gen_id_suffix = "-%s-%s-" % (compact_date(time()), rand_chars(16))
133
return _gen_id_suffix + str(_gen_id_serial)
104
136
def gen_file_id(name):
105
"""Return new file id.
107
This should probably generate proper UUIDs, but for the moment we
108
cope with just randomness because running uuidgen every time is
111
from binascii import hexlify
112
from time import time
115
idx = name.rfind('/')
117
name = name[idx+1 : ]
118
idx = name.rfind('\\')
120
name = name[idx+1 : ]
122
# make it not a hidden file
123
name = name.lstrip('.')
125
# remove any wierd characters; we don't escape them but rather
127
name = re.sub(r'[^\w.]', '', name)
129
s = hexlify(rand_bytes(8))
130
return '-'.join((name, compact_date(time()), s))
137
"""Return new file id for the basename 'name'.
139
The uniqueness is supplied from _next_id_suffix.
141
# The real randomness is in the _next_id_suffix, the
142
# rest of the identifier is just to be nice.
144
# 1) Remove non-ascii word characters to keep the ids portable
145
# 2) squash to lowercase, so the file id doesn't have to
146
# be escaped (case insensitive filesystems would bork for ids
147
# that only differred in case without escaping).
148
# 3) truncate the filename to 20 chars. Long filenames also bork on some
150
# 4) Removing starting '.' characters to prevent the file ids from
151
# being considered hidden.
152
ascii_word_only = _gen_file_id_re.sub('', name.lower())
153
short_no_dots = ascii_word_only.lstrip('.')[:20]
154
return short_no_dots + _next_id_suffix()
133
157
def gen_root_id():
352
408
return pathjoin(self.basedir, filename)
354
410
def basis_tree(self):
355
"""Return RevisionTree for the current last revision."""
356
revision_id = self.last_revision()
357
if revision_id is not None:
411
"""Return RevisionTree for the current last revision.
413
If the left most parent is a ghost then the returned tree will be an
414
empty tree - one obtained by calling repository.revision_tree(None).
417
revision_id = self.get_parent_ids()[0]
419
# no parents, return an empty revision tree.
420
# in the future this should return the tree for
421
# 'empty:' - the implicit root empty tree.
422
return self.branch.repository.revision_tree(None)
359
425
xml = self.read_basis_inventory()
360
inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
363
if inv is not None and inv.revision_id == revision_id:
364
return bzrlib.tree.RevisionTree(self.branch.repository, inv,
366
# FIXME? RBC 20060403 should we cache the inventory here ?
367
return self.branch.repository.revision_tree(revision_id)
426
inv = bzrlib.xml6.serializer_v6.read_inventory_from_string(xml)
427
if inv is not None and inv.revision_id == revision_id:
428
return bzrlib.tree.RevisionTree(self.branch.repository,
430
except (NoSuchFile, errors.BadInventoryFormat):
432
# No cached copy available, retrieve from the repository.
433
# FIXME? RBC 20060403 should we cache the inventory locally
436
return self.branch.repository.revision_tree(revision_id)
437
except errors.RevisionNotPresent:
438
# the basis tree *may* be a ghost or a low level error may have
439
# occured. If the revision is present, its a problem, if its not
441
if self.branch.repository.has_revision(revision_id):
443
# the basis tree is a ghost so return an empty tree.
444
return self.branch.repository.revision_tree(None)
370
447
@deprecated_method(zero_eight)
405
482
return bzrdir.BzrDir.create_standalone_workingtree(directory)
407
def relpath(self, abs):
408
"""Return the local path portion from a given absolute path."""
409
return relpath(self.basedir, abs)
484
def relpath(self, path):
485
"""Return the local path portion from a given path.
487
The path may be absolute or relative. If its a relative path it is
488
interpreted relative to the python current working directory.
490
return relpath(self.basedir, path)
411
492
def has_filename(self, filename):
412
return bzrlib.osutils.lexists(self.abspath(filename))
493
return osutils.lexists(self.abspath(filename))
414
495
def get_file(self, file_id):
415
496
return self.get_file_byname(self.id2path(file_id))
498
def get_file_text(self, file_id):
499
return self.get_file(file_id).read()
417
501
def get_file_byname(self, filename):
418
502
return file(self.abspath(filename), 'rb')
504
def get_parent_ids(self):
505
"""See Tree.get_parent_ids.
507
This implementation reads the pending merges list and last_revision
508
value and uses that to decide what the parents list should be.
510
last_rev = self._last_revision()
516
merges_file = self._control_files.get_utf8('pending-merges')
520
for l in merges_file.readlines():
521
parents.append(l.rstrip('\n'))
420
524
def get_root_id(self):
421
525
"""Return the id of this trees root"""
422
526
inv = self.read_working_inventory()
555
669
raise BzrError("cannot add top-level %r" % f)
557
671
fullpath = normpath(self.abspath(f))
560
673
kind = file_kind(fullpath)
561
674
except OSError, e:
562
675
if e.errno == errno.ENOENT:
563
676
raise NoSuchFile(fullpath)
564
# maybe something better?
565
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
567
677
if not InventoryEntry.versionable_kind(kind):
568
raise BzrError('cannot add: not a versionable file ('
569
'i.e. regular file, symlink or directory): %s' % quotefn(f))
678
raise errors.BadFileKindError(filename=f, kind=kind)
571
679
if file_id is None:
572
file_id = gen_file_id(f)
573
inv.add_path(f, kind=kind, file_id=file_id)
680
inv.add_path(f, kind=kind)
682
inv.add_path(f, kind=kind, file_id=file_id)
575
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
576
684
self._write_inventory(inv)
686
@needs_tree_write_lock
687
def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
688
"""Add revision_id as a parent.
690
This is equivalent to retrieving the current list of parent ids
691
and setting the list to its value plus revision_id.
693
:param revision_id: The revision id to add to the parent list. It may
694
be a ghost revision as long as its not the first parent to be added,
695
or the allow_leftmost_as_ghost parameter is set True.
696
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
698
parents = self.get_parent_ids() + [revision_id]
699
self.set_parent_ids(parents,
700
allow_leftmost_as_ghost=len(parents) > 1 or allow_leftmost_as_ghost)
702
@needs_tree_write_lock
703
def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
704
"""Add revision_id, tree tuple as a parent.
706
This is equivalent to retrieving the current list of parent trees
707
and setting the list to its value plus parent_tuple. See also
708
add_parent_tree_id - if you only have a parent id available it will be
709
simpler to use that api. If you have the parent already available, using
710
this api is preferred.
712
:param parent_tuple: The (revision id, tree) to add to the parent list.
713
If the revision_id is a ghost, pass None for the tree.
714
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
716
parent_ids = self.get_parent_ids() + [parent_tuple[0]]
717
if len(parent_ids) > 1:
718
# the leftmost may have already been a ghost, preserve that if it
720
allow_leftmost_as_ghost = True
721
self.set_parent_ids(parent_ids,
722
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
724
@needs_tree_write_lock
579
725
def add_pending_merge(self, *revision_ids):
580
726
# TODO: Perhaps should check at this point that the
581
727
# history of the revision is actually present?
582
p = self.pending_merges()
728
parents = self.get_parent_ids()
584
730
for rev_id in revision_ids:
731
if rev_id in parents:
733
parents.append(rev_id)
590
self.set_pending_merges(p)
736
self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
738
@deprecated_method(zero_eleven)
593
740
def pending_merges(self):
594
741
"""Return a list of pending merges.
596
743
These are revisions that have been merged into the working
597
744
directory but not yet committed.
600
merges_file = self._control_files.get_utf8('pending-merges')
602
if e.errno != errno.ENOENT:
606
for l in merges_file.readlines():
607
p.append(l.rstrip('\n'))
746
As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
747
instead - which is available on all tree objects.
749
return self.get_parent_ids()[1:]
751
@needs_tree_write_lock
752
def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
753
"""Set the parent ids to revision_ids.
755
See also set_parent_trees. This api will try to retrieve the tree data
756
for each element of revision_ids from the trees repository. If you have
757
tree data already available, it is more efficient to use
758
set_parent_trees rather than set_parent_ids. set_parent_ids is however
759
an easier API to use.
761
:param revision_ids: The revision_ids to set as the parent ids of this
762
working tree. Any of these may be ghosts.
764
if len(revision_ids) > 0:
765
leftmost_id = revision_ids[0]
766
if (not allow_leftmost_as_ghost and not
767
self.branch.repository.has_revision(leftmost_id)):
768
raise errors.GhostRevisionUnusableHere(leftmost_id)
769
self.set_last_revision(leftmost_id)
771
self.set_last_revision(None)
772
merges = revision_ids[1:]
773
self._control_files.put_utf8('pending-merges', '\n'.join(merges))
775
@needs_tree_write_lock
776
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
777
"""Set the parents of the working tree.
779
:param parents_list: A list of (revision_id, tree) tuples.
780
If tree is None, then that element is treated as an unreachable
781
parent tree - i.e. a ghost.
783
# parent trees are not used in current format trees, delegate to
785
self.set_parent_ids([rev for (rev, tree) in parents_list],
786
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
788
@needs_tree_write_lock
611
789
def set_pending_merges(self, rev_list):
612
self._control_files.put_utf8('pending-merges', '\n'.join(rev_list))
790
parents = self.get_parent_ids()
791
leftmost = parents[:1]
792
new_parents = leftmost + rev_list
793
self.set_parent_ids(new_parents)
795
@needs_tree_write_lock
615
796
def set_merge_modified(self, modified_hashes):
616
797
def iter_stanzas():
617
798
for file_id, hash in modified_hashes.iteritems():
618
799
yield Stanza(file_id=file_id, hash=hash)
619
800
self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
802
@needs_tree_write_lock
622
803
def _put_rio(self, filename, stanzas, header):
623
804
my_file = rio_file(stanzas, header)
624
805
self._control_files.put(filename, my_file)
807
@needs_write_lock # because merge pulls data into the branch.
808
def merge_from_branch(self, branch, to_revision=None):
809
"""Merge from a branch into this working tree.
811
:param branch: The branch to merge from.
812
:param to_revision: If non-None, the merge will merge to to_revision, but
813
not beyond it. to_revision does not need to be in the history of
814
the branch when it is supplied. If None, to_revision defaults to
815
branch.last_revision().
817
from bzrlib.merge import Merger, Merge3Merger
818
pb = bzrlib.ui.ui_factory.nested_progress_bar()
820
merger = Merger(self.branch, this_tree=self, pb=pb)
821
merger.pp = ProgressPhase("Merge phase", 5, pb)
822
merger.pp.next_phase()
823
# check that there are no
825
merger.check_basis(check_clean=True, require_commits=False)
826
if to_revision is None:
827
to_revision = branch.last_revision()
828
merger.other_rev_id = to_revision
829
if merger.other_rev_id is None:
830
raise error.NoCommits(branch)
831
self.branch.fetch(branch, last_revision=merger.other_rev_id)
832
merger.other_basis = merger.other_rev_id
833
merger.other_tree = self.branch.repository.revision_tree(
835
merger.pp.next_phase()
837
if merger.base_rev_id == merger.other_rev_id:
838
raise errors.PointlessMerge
839
merger.backup_files = False
840
merger.merge_type = Merge3Merger
841
merger.set_interesting_files(None)
842
merger.show_base = False
843
merger.reprocess = False
844
conflicts = merger.do_merge()
627
851
def merge_modified(self):
666
890
Skips the control directory.
668
892
inv = self._inventory
670
def descend(from_dir_relpath, from_dir_id, dp):
893
# Convert these into local objects to save lookup times
894
pathjoin = osutils.pathjoin
895
file_kind = osutils.file_kind
897
# transport.base ends in a slash, we want the piece
898
# between the last two slashes
899
transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
901
fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
903
# directory file_id, relative path, absolute path, reverse sorted children
904
children = os.listdir(self.basedir)
906
# jam 20060527 The kernel sized tree seems equivalent whether we
907
# use a deque and popleft to keep them sorted, or if we use a plain
908
# list and just reverse() them.
909
children = collections.deque(children)
910
stack = [(inv.root.file_id, u'', self.basedir, children)]
912
from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
915
f = children.popleft()
674
916
## TODO: If we find a subdirectory with its own .bzr
675
917
## directory, then that is a separate tree and we
676
918
## should exclude it.
678
920
# the bzrdir for this tree
679
if self.bzrdir.transport.base.endswith(f + '/'):
921
if transport_base_dir == f:
683
fp = appendpath(from_dir_relpath, f)
924
# we know that from_dir_relpath and from_dir_abspath never end in a slash
925
# and 'f' doesn't begin with one, we can do a string op, rather
926
# than the checks of pathjoin(), all relative paths will have an extra slash
928
fp = from_dir_relpath + '/' + f
686
fap = appendpath(dp, f)
931
fap = from_dir_abspath + '/' + f
688
933
f_ie = inv.get_child(from_dir_id, f)
691
elif self.is_ignored(fp):
936
elif self.is_ignored(fp[1:]):
939
# we may not have found this file, because of a unicode issue
940
f_norm, can_access = osutils.normalized_filename(f)
941
if f == f_norm or not can_access:
942
# No change, so treat this file normally
945
# this file can be accessed by a normalized path
946
# check again if it is versioned
947
# these lines are repeated here for performance
949
fp = from_dir_relpath + '/' + f
950
fap = from_dir_abspath + '/' + f
951
f_ie = inv.get_child(from_dir_id, f)
954
elif self.is_ignored(fp[1:]):
696
959
fk = file_kind(fap)
853
1112
These are files in the working directory that are not versioned or
854
1113
control files or ignored.
856
>>> from bzrlib.bzrdir import ScratchDir
857
>>> d = ScratchDir(files=['foo', 'foo~'])
858
>>> b = d.open_branch()
859
>>> tree = d.open_workingtree()
860
>>> map(str, tree.unknowns())
863
>>> list(b.unknowns())
865
>>> tree.remove('foo')
866
>>> list(b.unknowns())
869
1115
for subp in self.extras():
870
1116
if not self.is_ignored(subp):
1119
@needs_tree_write_lock
1120
def unversion(self, file_ids):
1121
"""Remove the file ids in file_ids from the current versioned set.
1123
When a file_id is unversioned, all of its children are automatically
1126
:param file_ids: The file ids to stop versioning.
1127
:raises: NoSuchId if any fileid is not currently versioned.
1129
for file_id in file_ids:
1130
if self._inventory.has_id(file_id):
1131
self._inventory.remove_recursive_id(file_id)
1133
raise errors.NoSuchId(self, file_id)
1135
# in the future this should just set a dirty bit to wait for the
1136
# final unlock. However, until all methods of workingtree start
1137
# with the current in -memory inventory rather than triggering
1138
# a read, it is more complex - we need to teach read_inventory
1139
# to know when to read, and when to not read first... and possibly
1140
# to save first when the in memory one may be corrupted.
1141
# so for now, we just only write it if it is indeed dirty.
1143
self._write_inventory(self._inventory)
873
1145
@deprecated_method(zero_eight)
874
1146
def iter_conflicts(self):
875
1147
"""List all files in the tree that have text or content conflicts.
940
1225
for subf in os.listdir(dirabs):
942
and (subf not in dir_entry.children)):
1228
if subf not in dir_entry.children:
1229
subf_norm, can_access = osutils.normalized_filename(subf)
1230
if subf_norm != subf and can_access:
1231
if subf_norm not in dir_entry.children:
1232
fl.append(subf_norm)
947
subp = appendpath(path, subf)
1238
subp = pathjoin(path, subf)
1241
def _translate_ignore_rule(self, rule):
1242
"""Translate a single ignore rule to a regex.
1244
There are two types of ignore rules. Those that do not contain a / are
1245
matched against the tail of the filename (that is, they do not care
1246
what directory the file is in.) Rules which do contain a slash must
1247
match the entire path. As a special case, './' at the start of the
1248
string counts as a slash in the string but is removed before matching
1249
(e.g. ./foo.c, ./src/foo.c)
1251
:return: The translated regex.
1253
if rule[:2] in ('./', '.\\'):
1255
result = fnmatch.translate(rule[2:])
1256
elif '/' in rule or '\\' in rule:
1258
result = fnmatch.translate(rule)
1260
# default rule style.
1261
result = "(?:.*/)?(?!.*/)" + fnmatch.translate(rule)
1262
assert result[-1] == '$', "fnmatch.translate did not add the expected $"
1263
return "(" + result + ")"
1265
def _combine_ignore_rules(self, rules):
1266
"""Combine a list of ignore rules into a single regex object.
1268
Each individual rule is combined with | to form a big regex, which then
1269
has $ added to it to form something like ()|()|()$. The group index for
1270
each subregex's outermost group is placed in a dictionary mapping back
1271
to the rule. This allows quick identification of the matching rule that
1273
:return: a list of the compiled regex and the matching-group index
1274
dictionaries. We return a list because python complains if you try to
1275
combine more than 100 regexes.
1280
translated_rules = []
1282
translated_rule = self._translate_ignore_rule(rule)
1283
compiled_rule = re.compile(translated_rule)
1284
groups[next_group] = rule
1285
next_group += compiled_rule.groups
1286
translated_rules.append(translated_rule)
1287
if next_group == 99:
1288
result.append((re.compile("|".join(translated_rules)), groups))
1291
translated_rules = []
1292
if len(translated_rules):
1293
result.append((re.compile("|".join(translated_rules)), groups))
951
1296
def ignored_files(self):
952
1297
"""Yield list of PATH, IGNORE_PATTERN"""
953
1298
for subp in self.extras():
954
1299
pat = self.is_ignored(subp)
959
1303
def get_ignore_list(self):
960
1304
"""Return list of ignore patterns.
962
1306
Cached in the Tree object after the first call.
964
if hasattr(self, '_ignorelist'):
965
return self._ignorelist
967
l = bzrlib.DEFAULT_IGNORE[:]
1308
ignoreset = getattr(self, '_ignoreset', None)
1309
if ignoreset is not None:
1312
ignore_globs = set(bzrlib.DEFAULT_IGNORE)
1313
ignore_globs.update(ignores.get_runtime_ignores())
1315
ignore_globs.update(ignores.get_user_ignores())
968
1317
if self.has_filename(bzrlib.IGNORE_FILENAME):
969
1318
f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
970
l.extend([line.rstrip("\n\r") for line in f.readlines()])
1320
ignore_globs.update(ignores.parse_ignore_file(f))
1324
self._ignoreset = ignore_globs
1325
self._ignore_regex = self._combine_ignore_rules(ignore_globs)
1328
def _get_ignore_rules_as_regex(self):
1329
"""Return a regex of the ignore rules and a mapping dict.
1331
:return: (ignore rules compiled regex, dictionary mapping rule group
1332
indices to original rule.)
1334
if getattr(self, '_ignoreset', None) is None:
1335
self.get_ignore_list()
1336
return self._ignore_regex
975
1338
def is_ignored(self, filename):
976
1339
r"""Check whether the filename matches an ignore pattern.
990
1353
# treat dotfiles correctly and allows * to match /.
991
1354
# Eventually it should be replaced with something more
994
for pat in self.get_ignore_list():
995
if '/' in pat or '\\' in pat:
997
# as a special case, you can put ./ at the start of a
998
# pattern; this is good to match in the top-level
1001
if (pat[:2] == './') or (pat[:2] == '.\\'):
1005
if fnmatch.fnmatchcase(filename, newpat):
1008
if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
1357
rules = self._get_ignore_rules_as_regex()
1358
for regex, mapping in rules:
1359
match = regex.match(filename)
1360
if match is not None:
1361
# one or more of the groups in mapping will have a non-None
1363
groups = match.groups()
1364
rules = [mapping[group] for group in
1365
mapping if groups[group] is not None]
1013
1369
def kind(self, file_id):
1014
1370
return file_kind(self.id2abspath(file_id))
1017
1372
def last_revision(self):
1018
1373
"""Return the last revision id of this working tree.
1020
In early branch formats this was == the branch last_revision,
1375
In early branch formats this was the same as the branch last_revision,
1021
1376
but that cannot be relied upon - for working tree operations,
1022
always use tree.last_revision().
1377
always use tree.last_revision(). This returns the left most parent id,
1378
or None if there are no parents.
1380
This was deprecated as of 0.11. Please use get_parent_ids instead.
1382
return self._last_revision()
1385
def _last_revision(self):
1386
"""helper for get_parent_ids."""
1024
1387
return self.branch.last_revision()
1389
def is_locked(self):
1390
return self._control_files.is_locked()
1026
1392
def lock_read(self):
1027
1393
"""See Branch.lock_read, and WorkingTree.unlock."""
1028
1394
self.branch.lock_read()
1059
1444
if new_revision is None:
1060
1445
self.branch.set_revision_history([])
1062
# current format is locked in with the branch
1063
revision_history = self.branch.revision_history()
1065
position = revision_history.index(new_revision)
1067
raise errors.NoSuchRevision(self.branch, new_revision)
1068
self.branch.set_revision_history(revision_history[:position + 1])
1448
self.branch.generate_revision_history(new_revision)
1449
except errors.NoSuchRevision:
1450
# not present in the repo - dont try to set it deeper than the tip
1451
self.branch.set_revision_history([new_revision])
1071
1454
def _cache_basis_inventory(self, new_revision):
1072
1455
"""Cache new_revision as the basis inventory."""
1456
# TODO: this should allow the ready-to-use inventory to be passed in,
1457
# as commit already has that ready-to-use [while the format is the
1074
1460
# this double handles the inventory - unpack and repack -
1075
1461
# but is easier to understand. We can/should put a conditional
1076
1462
# in here based on whether the inventory is in the latest format
1077
1463
# - perhaps we should repack all inventories on a repository
1079
inv = self.branch.repository.get_inventory(new_revision)
1080
inv.revision_id = new_revision
1081
xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
1465
# the fast path is to copy the raw xml from the repository. If the
1466
# xml contains 'revision_id="', then we assume the right
1467
# revision_id is set. We must check for this full string, because a
1468
# root node id can legitimately look like 'revision_id' but cannot
1470
xml = self.branch.repository.get_inventory_xml(new_revision)
1471
firstline = xml.split('\n', 1)[0]
1472
if (not 'revision_id="' in firstline or
1473
'format="6"' not in firstline):
1474
inv = self.branch.repository.deserialise_inventory(
1476
inv.revision_id = new_revision
1477
xml = bzrlib.xml6.serializer_v6.write_inventory_to_string(inv)
1478
assert isinstance(xml, str), 'serialised xml must be bytestring.'
1083
1479
path = self._basis_inventory_name()
1084
self._control_files.put_utf8(path, xml)
1085
except WeaveRevisionNotPresent:
1481
self._control_files.put(path, sio)
1482
except (errors.NoSuchRevision, errors.RevisionNotPresent):
1088
1485
def read_basis_inventory(self):
1089
1486
"""Read the cached basis inventory."""
1090
1487
path = self._basis_inventory_name()
1091
return self._control_files.get_utf8(path).read()
1488
return self._control_files.get(path).read()
1093
1490
@needs_read_lock
1094
1491
def read_working_inventory(self):
1248
1623
Do a 'normal' merge of the old branch basis if it is relevant.
1250
1625
old_tip = self.branch.update()
1251
if old_tip is not None:
1252
self.add_pending_merge(old_tip)
1253
self.branch.lock_read()
1626
# here if old_tip is not None, it is the old tip of the branch before
1627
# it was updated from the master branch. This should become a pending
1628
# merge in the working tree to preserve the user existing work. we
1629
# cant set that until we update the working trees last revision to be
1630
# one from the new branch, because it will just get absorbed by the
1631
# parent de-duplication logic.
1633
# We MUST save it even if an error occurs, because otherwise the users
1634
# local work is unreferenced and will appear to have been lost.
1256
if self.last_revision() != self.branch.last_revision():
1257
# merge tree state up to new branch tip.
1258
basis = self.basis_tree()
1259
to_tree = self.branch.basis_tree()
1260
result += merge_inner(self.branch,
1264
self.set_last_revision(self.branch.last_revision())
1265
if old_tip and old_tip != self.last_revision():
1266
# our last revision was not the prior branch last reivison
1267
# and we have converted that last revision to a pending merge.
1268
# base is somewhere between the branch tip now
1269
# and the now pending merge
1270
from bzrlib.revision import common_ancestor
1272
base_rev_id = common_ancestor(self.branch.last_revision(),
1274
self.branch.repository)
1275
except errors.NoCommonAncestor:
1277
base_tree = self.branch.repository.revision_tree(base_rev_id)
1278
other_tree = self.branch.repository.revision_tree(old_tip)
1279
result += merge_inner(self.branch,
1285
self.branch.unlock()
1638
last_rev = self.get_parent_ids()[0]
1641
if last_rev != self.branch.last_revision():
1642
# merge tree state up to new branch tip.
1643
basis = self.basis_tree()
1644
to_tree = self.branch.basis_tree()
1645
result += merge_inner(self.branch,
1649
# TODO - dedup parents list with things merged by pull ?
1650
# reuse the tree we've updated to to set the basis:
1651
parent_trees = [(self.branch.last_revision(), to_tree)]
1652
merges = self.get_parent_ids()[1:]
1653
# Ideally we ask the tree for the trees here, that way the working
1654
# tree can decide whether to give us teh entire tree or give us a
1655
# lazy initialised tree. dirstate for instance will have the trees
1656
# in ram already, whereas a last-revision + basis-inventory tree
1657
# will not, but also does not need them when setting parents.
1658
for parent in merges:
1659
parent_trees.append(
1660
(parent, self.branch.repository.revision_tree(parent)))
1661
if old_tip is not None:
1662
parent_trees.append(
1663
(old_tip, self.branch.repository.revision_tree(old_tip)))
1664
self.set_parent_trees(parent_trees)
1665
last_rev = parent_trees[0][0]
1667
# the working tree had the same last-revision as the master
1668
# branch did. We may still have pivot local work from the local
1669
# branch into old_tip:
1670
if old_tip is not None:
1671
self.add_parent_tree_id(old_tip)
1672
if old_tip and old_tip != last_rev:
1673
# our last revision was not the prior branch last revision
1674
# and we have converted that last revision to a pending merge.
1675
# base is somewhere between the branch tip now
1676
# and the now pending merge
1677
from bzrlib.revision import common_ancestor
1679
base_rev_id = common_ancestor(self.branch.last_revision(),
1681
self.branch.repository)
1682
except errors.NoCommonAncestor:
1684
base_tree = self.branch.repository.revision_tree(base_rev_id)
1685
other_tree = self.branch.repository.revision_tree(old_tip)
1686
result += merge_inner(self.branch,
1692
@needs_tree_write_lock
1288
1693
def _write_inventory(self, inv):
1289
1694
"""Write inventory as the current inventory."""
1290
1695
sio = StringIO()