1
# Copyright (C) 2005 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""WorkingTree object and friends.
19
A WorkingTree represents the editable working copy of a branch.
20
Operations which represent the WorkingTree are also done here,
21
such as renaming or adding files. The WorkingTree has an inventory
22
which is updated by these operations. A commit produces a
23
new revision based on the workingtree and its inventory.
25
At the moment every WorkingTree has its own branch. Remote
26
WorkingTrees aren't supported.
28
To get a WorkingTree, call bzrdir.open_workingtree() or
29
WorkingTree.open(dir).
33
# FIXME: I don't know if writing out the cache from the destructor is really a
34
# good idea, because destructors are considered poor taste in Python, and it's
35
# not predictable when it will be written out.
37
# TODO: Give the workingtree sole responsibility for the working inventory;
38
# remove the variable and references to it from the branch. This may require
39
# updating the commit code so as to update the inventory within the working
40
# copy, and making sure there's only one WorkingTree for any directory on disk.
41
# At the momenthey may alias the inventory and have old copies of it in memory.
43
from copy import deepcopy
44
from cStringIO import StringIO
51
from bzrlib.atomicfile import AtomicFile
52
from bzrlib.branch import (Branch,
54
import bzrlib.bzrdir as bzrdir
55
from bzrlib.decorators import needs_read_lock, needs_write_lock
56
import bzrlib.errors as errors
57
from bzrlib.errors import (BzrCheckError,
60
WeaveRevisionNotPresent,
64
from bzrlib.inventory import InventoryEntry
65
from bzrlib.lockable_files import LockableFiles
66
from bzrlib.merge import merge_inner, transform_tree
67
from bzrlib.osutils import (appendpath,
82
from bzrlib.symbol_versioning import *
83
from bzrlib.textui import show_status
85
from bzrlib.trace import mutter
86
from bzrlib.transport import get_transport
87
from bzrlib.transport.local import LocalTransport
91
def gen_file_id(name):
92
"""Return new file id.
94
This should probably generate proper UUIDs, but for the moment we
95
cope with just randomness because running uuidgen every time is
98
from binascii import hexlify
102
idx = name.rfind('/')
104
name = name[idx+1 : ]
105
idx = name.rfind('\\')
107
name = name[idx+1 : ]
109
# make it not a hidden file
110
name = name.lstrip('.')
112
# remove any wierd characters; we don't escape them but rather
114
name = re.sub(r'[^\w.]', '', name)
116
s = hexlify(rand_bytes(8))
117
return '-'.join((name, compact_date(time()), s))
121
"""Return a new tree-root file id."""
122
return gen_file_id('TREE_ROOT')
125
class TreeEntry(object):
126
"""An entry that implements the minium interface used by commands.
128
This needs further inspection, it may be better to have
129
InventoryEntries without ids - though that seems wrong. For now,
130
this is a parallel hierarchy to InventoryEntry, and needs to become
131
one of several things: decorates to that hierarchy, children of, or
133
Another note is that these objects are currently only used when there is
134
no InventoryEntry available - i.e. for unversioned objects.
135
Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
138
def __eq__(self, other):
139
# yes, this us ugly, TODO: best practice __eq__ style.
140
return (isinstance(other, TreeEntry)
141
and other.__class__ == self.__class__)
143
def kind_character(self):
147
class TreeDirectory(TreeEntry):
148
"""See TreeEntry. This is a directory in a working tree."""
150
def __eq__(self, other):
151
return (isinstance(other, TreeDirectory)
152
and other.__class__ == self.__class__)
154
def kind_character(self):
158
class TreeFile(TreeEntry):
159
"""See TreeEntry. This is a regular file in a working tree."""
161
def __eq__(self, other):
162
return (isinstance(other, TreeFile)
163
and other.__class__ == self.__class__)
165
def kind_character(self):
169
class TreeLink(TreeEntry):
170
"""See TreeEntry. This is a symlink in a working tree."""
172
def __eq__(self, other):
173
return (isinstance(other, TreeLink)
174
and other.__class__ == self.__class__)
176
def kind_character(self):
180
class WorkingTree(bzrlib.tree.Tree):
181
"""Working copy tree.
183
The inventory is held in the `Branch` working-inventory, and the
184
files are in a directory on disk.
186
It is possible for a `WorkingTree` to have a filename which is
187
not listed in the Inventory and vice versa.
190
def __init__(self, basedir='.',
197
"""Construct a WorkingTree for basedir.
199
If the branch is not supplied, it is opened automatically.
200
If the branch is supplied, it must be the branch for this basedir.
201
(branch.base is not cross checked, because for remote branches that
202
would be meaningless).
204
self._format = _format
205
self.bzrdir = _bzrdir
207
# created via open etc.
208
wt = WorkingTree.open(basedir)
209
self.branch = wt.branch
210
self.basedir = wt.basedir
211
self._control_files = wt._control_files
212
self._hashcache = wt._hashcache
213
self._set_inventory(wt._inventory)
214
self._format = wt._format
215
self.bzrdir = wt.bzrdir
216
from bzrlib.hashcache import HashCache
217
from bzrlib.trace import note, mutter
218
assert isinstance(basedir, basestring), \
219
"base directory %r is not a string" % basedir
220
basedir = safe_unicode(basedir)
221
mutter("openeing working tree %r", basedir)
223
branch = Branch.open(basedir)
224
assert isinstance(branch, Branch), \
225
"branch %r is not a Branch" % branch
227
self.basedir = realpath(basedir)
228
# if branch is at our basedir and is a format 6 or less
229
if isinstance(self._format, WorkingTreeFormat2):
230
# share control object
231
self._control_files = self.branch.control_files
232
elif _control_files is not None:
233
assert False, "not done yet"
234
# self._control_files = _control_files
236
# only ready for format 3
237
assert isinstance(self._format, WorkingTreeFormat3)
238
self._control_files = LockableFiles(
239
self.bzrdir.get_workingtree_transport(None),
242
# update the whole cache up front and write to disk if anything changed;
243
# in the future we might want to do this more selectively
244
# two possible ways offer themselves : in self._unlock, write the cache
245
# if needed, or, when the cache sees a change, append it to the hash
246
# cache file, and have the parser take the most recent entry for a
248
cache_filename = self.bzrdir.get_workingtree_transport(None).abspath('stat-cache')
249
hc = self._hashcache = HashCache(basedir, cache_filename, self._control_files._file_mode)
251
# is this scan needed ? it makes things kinda slow.
258
if _inventory is None:
259
self._set_inventory(self.read_working_inventory())
261
self._set_inventory(_inventory)
263
def _set_inventory(self, inv):
264
self._inventory = inv
265
self.path2id = self._inventory.path2id
268
def open(path=None, _unsupported=False):
269
"""Open an existing working tree at path.
273
path = os.path.getcwdu()
274
control = bzrdir.BzrDir.open(path, _unsupported)
275
return control.open_workingtree(_unsupported)
278
def open_containing(path=None):
279
"""Open an existing working tree which has its root about path.
281
This probes for a working tree at path and searches upwards from there.
283
Basically we keep looking up until we find the control directory or
284
run into /. If there isn't one, raises NotBranchError.
285
TODO: give this a new exception.
286
If there is one, it is returned, along with the unused portion of path.
290
control, relpath = bzrdir.BzrDir.open_containing(path)
291
return control.open_workingtree(), relpath
294
def open_downlevel(path=None):
295
"""Open an unsupported working tree.
297
Only intended for advanced situations like upgrading part of a bzrdir.
299
return WorkingTree.open(path, _unsupported=True)
302
"""Iterate through file_ids for this tree.
304
file_ids are in a WorkingTree if they are in the working inventory
305
and the working file exists.
307
inv = self._inventory
308
for path, ie in inv.iter_entries():
309
if bzrlib.osutils.lexists(self.abspath(path)):
313
return "<%s of %s>" % (self.__class__.__name__,
314
getattr(self, 'basedir', None))
316
def abspath(self, filename):
317
return pathjoin(self.basedir, filename)
319
def basis_tree(self):
320
"""Return RevisionTree for the current last revision."""
321
revision_id = self.last_revision()
322
if revision_id is not None:
324
xml = self.read_basis_inventory(revision_id)
325
inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
326
return bzrlib.tree.RevisionTree(self.branch.repository, inv,
330
return self.branch.repository.revision_tree(revision_id)
333
@deprecated_method(zero_eight)
334
def create(branch, directory):
335
"""Create a workingtree for branch at directory.
337
If existing_directory already exists it must have a .bzr directory.
338
If it does not exist, it will be created.
340
This returns a new WorkingTree object for the new checkout.
342
TODO FIXME RBC 20060124 when we have checkout formats in place this
343
should accept an optional revisionid to checkout [and reject this if
344
checking out into the same dir as a pre-checkout-aware branch format.]
346
XXX: When BzrDir is present, these should be created through that
349
warn('delete WorkingTree.create', stacklevel=3)
350
transport = get_transport(directory)
351
if branch.bzrdir.root_transport.base == transport.base:
353
return branch.bzrdir.create_workingtree()
354
# different directory,
355
# create a branch reference
356
# and now a working tree.
357
raise NotImplementedError
360
@deprecated_method(zero_eight)
361
def create_standalone(directory):
362
"""Create a checkout and a branch and a repo at directory.
364
Directory must exist and be empty.
366
please use BzrDir.create_standalone_workingtree
368
return bzrdir.BzrDir.create_standalone_workingtree(directory)
370
def relpath(self, abs):
371
"""Return the local path portion from a given absolute path."""
372
return relpath(self.basedir, abs)
374
def has_filename(self, filename):
375
return bzrlib.osutils.lexists(self.abspath(filename))
377
def get_file(self, file_id):
378
return self.get_file_byname(self.id2path(file_id))
380
def get_file_byname(self, filename):
381
return file(self.abspath(filename), 'rb')
383
def get_root_id(self):
384
"""Return the id of this trees root"""
385
inv = self.read_working_inventory()
386
return inv.root.file_id
388
def _get_store_filename(self, file_id):
389
## XXX: badly named; this is not in the store at all
390
return self.abspath(self.id2path(file_id))
393
def clone(self, to_bzrdir, revision_id=None, basis=None):
394
"""Duplicate this working tree into to_bzr, including all state.
396
Specifically modified files are kept as modified, but
397
ignored and unknown files are discarded.
399
If you want to make a new line of development, see bzrdir.sprout()
402
If not None, the cloned tree will have its last revision set to
403
revision, and and difference between the source trees last revision
404
and this one merged in.
407
If not None, a closer copy of a tree which may have some files in
408
common, and which file content should be preferentially copied from.
410
# assumes the target bzr dir format is compatible.
411
result = self._format.initialize(to_bzrdir)
412
self.copy_content_into(result, revision_id)
416
def copy_content_into(self, tree, revision_id=None):
417
"""Copy the current content and user files of this tree into tree."""
418
if revision_id is None:
419
transform_tree(tree, self)
421
# TODO now merge from tree.last_revision to revision
422
transform_tree(tree, self)
423
tree.set_last_revision(revision_id)
426
def commit(self, *args, **kwargs):
427
from bzrlib.commit import Commit
428
# args for wt.commit start at message from the Commit.commit method,
429
# but with branch a kwarg now, passing in args as is results in the
430
#message being used for the branch
431
args = (DEPRECATED_PARAMETER, ) + args
432
Commit().commit(working_tree=self, *args, **kwargs)
433
self._set_inventory(self.read_working_inventory())
435
def id2abspath(self, file_id):
436
return self.abspath(self.id2path(file_id))
438
def has_id(self, file_id):
439
# files that have been deleted are excluded
440
inv = self._inventory
441
if not inv.has_id(file_id):
443
path = inv.id2path(file_id)
444
return bzrlib.osutils.lexists(self.abspath(path))
446
def has_or_had_id(self, file_id):
447
if file_id == self.inventory.root.file_id:
449
return self.inventory.has_id(file_id)
451
__contains__ = has_id
453
def get_file_size(self, file_id):
454
return os.path.getsize(self.id2abspath(file_id))
457
def get_file_sha1(self, file_id):
458
path = self._inventory.id2path(file_id)
459
return self._hashcache.get_sha1(path)
461
def is_executable(self, file_id):
463
return self._inventory[file_id].executable
465
path = self._inventory.id2path(file_id)
466
mode = os.lstat(self.abspath(path)).st_mode
467
return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
470
def add(self, files, ids=None):
471
"""Make files versioned.
473
Note that the command line normally calls smart_add instead,
474
which can automatically recurse.
476
This adds the files to the inventory, so that they will be
477
recorded by the next commit.
480
List of paths to add, relative to the base of the tree.
483
If set, use these instead of automatically generated ids.
484
Must be the same length as the list of files, but may
485
contain None for ids that are to be autogenerated.
487
TODO: Perhaps have an option to add the ids even if the files do
490
TODO: Perhaps callback with the ids and paths as they're added.
492
# TODO: Re-adding a file that is removed in the working copy
493
# should probably put it back with the previous ID.
494
if isinstance(files, basestring):
495
assert(ids is None or isinstance(ids, basestring))
501
ids = [None] * len(files)
503
assert(len(ids) == len(files))
505
inv = self.read_working_inventory()
506
for f,file_id in zip(files, ids):
507
if is_control_file(f):
508
raise BzrError("cannot add control file %s" % quotefn(f))
513
raise BzrError("cannot add top-level %r" % f)
515
fullpath = normpath(self.abspath(f))
518
kind = file_kind(fullpath)
520
if e.errno == errno.ENOENT:
521
raise NoSuchFile(fullpath)
522
# maybe something better?
523
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
525
if not InventoryEntry.versionable_kind(kind):
526
raise BzrError('cannot add: not a versionable file ('
527
'i.e. regular file, symlink or directory): %s' % quotefn(f))
530
file_id = gen_file_id(f)
531
inv.add_path(f, kind=kind, file_id=file_id)
533
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
534
self._write_inventory(inv)
537
def add_pending_merge(self, *revision_ids):
538
# TODO: Perhaps should check at this point that the
539
# history of the revision is actually present?
540
p = self.pending_merges()
542
for rev_id in revision_ids:
548
self.set_pending_merges(p)
551
def pending_merges(self):
552
"""Return a list of pending merges.
554
These are revisions that have been merged into the working
555
directory but not yet committed.
558
merges_file = self._control_files.get_utf8('pending-merges')
560
if e.errno != errno.ENOENT:
564
for l in merges_file.readlines():
565
p.append(l.rstrip('\n'))
569
def set_pending_merges(self, rev_list):
570
self._control_files.put_utf8('pending-merges', '\n'.join(rev_list))
572
def get_symlink_target(self, file_id):
573
return os.readlink(self.id2abspath(file_id))
575
def file_class(self, filename):
576
if self.path2id(filename):
578
elif self.is_ignored(filename):
583
def list_files(self):
584
"""Recursively list all files as (path, class, kind, id).
586
Lists, but does not descend into unversioned directories.
588
This does not include files that have been deleted in this
591
Skips the control directory.
593
inv = self._inventory
595
def descend(from_dir_relpath, from_dir_id, dp):
599
## TODO: If we find a subdirectory with its own .bzr
600
## directory, then that is a separate tree and we
601
## should exclude it.
602
if bzrlib.BZRDIR == f:
606
fp = appendpath(from_dir_relpath, f)
609
fap = appendpath(dp, f)
611
f_ie = inv.get_child(from_dir_id, f)
614
elif self.is_ignored(fp):
623
raise BzrCheckError("file %r entered as kind %r id %r, "
625
% (fap, f_ie.kind, f_ie.file_id, fk))
627
# make a last minute entry
631
if fk == 'directory':
632
entry = TreeDirectory()
635
elif fk == 'symlink':
640
yield fp, c, fk, (f_ie and f_ie.file_id), entry
642
if fk != 'directory':
646
# don't descend unversioned directories
649
for ff in descend(fp, f_ie.file_id, fap):
652
for f in descend(u'', inv.root.file_id, self.basedir):
656
def move(self, from_paths, to_name):
659
to_name must exist in the inventory.
661
If to_name exists and is a directory, the files are moved into
662
it, keeping their old names.
664
Note that to_name is only the last component of the new name;
665
this doesn't change the directory.
667
This returns a list of (from_path, to_path) pairs for each
671
## TODO: Option to move IDs only
672
assert not isinstance(from_paths, basestring)
674
to_abs = self.abspath(to_name)
675
if not isdir(to_abs):
676
raise BzrError("destination %r is not a directory" % to_abs)
677
if not self.has_filename(to_name):
678
raise BzrError("destination %r not in working directory" % to_abs)
679
to_dir_id = inv.path2id(to_name)
680
if to_dir_id == None and to_name != '':
681
raise BzrError("destination %r is not a versioned directory" % to_name)
682
to_dir_ie = inv[to_dir_id]
683
if to_dir_ie.kind not in ('directory', 'root_directory'):
684
raise BzrError("destination %r is not a directory" % to_abs)
686
to_idpath = inv.get_idpath(to_dir_id)
689
if not self.has_filename(f):
690
raise BzrError("%r does not exist in working tree" % f)
691
f_id = inv.path2id(f)
693
raise BzrError("%r is not versioned" % f)
694
name_tail = splitpath(f)[-1]
695
dest_path = appendpath(to_name, name_tail)
696
if self.has_filename(dest_path):
697
raise BzrError("destination %r already exists" % dest_path)
698
if f_id in to_idpath:
699
raise BzrError("can't move %r to a subdirectory of itself" % f)
701
# OK, so there's a race here, it's possible that someone will
702
# create a file in this interval and then the rename might be
703
# left half-done. But we should have caught most problems.
704
orig_inv = deepcopy(self.inventory)
707
name_tail = splitpath(f)[-1]
708
dest_path = appendpath(to_name, name_tail)
709
result.append((f, dest_path))
710
inv.rename(inv.path2id(f), to_dir_id, name_tail)
712
rename(self.abspath(f), self.abspath(dest_path))
714
raise BzrError("failed to rename %r to %r: %s" %
715
(f, dest_path, e[1]),
716
["rename rolled back"])
718
# restore the inventory on error
719
self._set_inventory(orig_inv)
721
self._write_inventory(inv)
725
def rename_one(self, from_rel, to_rel):
728
This can change the directory or the filename or both.
731
if not self.has_filename(from_rel):
732
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
733
if self.has_filename(to_rel):
734
raise BzrError("can't rename: new working file %r already exists" % to_rel)
736
file_id = inv.path2id(from_rel)
738
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
741
from_parent = entry.parent_id
742
from_name = entry.name
744
if inv.path2id(to_rel):
745
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
747
to_dir, to_tail = os.path.split(to_rel)
748
to_dir_id = inv.path2id(to_dir)
749
if to_dir_id == None and to_dir != '':
750
raise BzrError("can't determine destination directory id for %r" % to_dir)
752
mutter("rename_one:")
753
mutter(" file_id {%s}" % file_id)
754
mutter(" from_rel %r" % from_rel)
755
mutter(" to_rel %r" % to_rel)
756
mutter(" to_dir %r" % to_dir)
757
mutter(" to_dir_id {%s}" % to_dir_id)
759
inv.rename(file_id, to_dir_id, to_tail)
761
from_abs = self.abspath(from_rel)
762
to_abs = self.abspath(to_rel)
764
rename(from_abs, to_abs)
766
inv.rename(file_id, from_parent, from_name)
767
raise BzrError("failed to rename %r to %r: %s"
768
% (from_abs, to_abs, e[1]),
769
["rename rolled back"])
770
self._write_inventory(inv)
774
"""Return all unknown files.
776
These are files in the working directory that are not versioned or
777
control files or ignored.
779
>>> from bzrlib.bzrdir import ScratchDir
780
>>> d = ScratchDir(files=['foo', 'foo~'])
781
>>> b = d.open_branch()
782
>>> tree = WorkingTree(b.base, b)
783
>>> map(str, tree.unknowns())
786
>>> list(b.unknowns())
788
>>> tree.remove('foo')
789
>>> list(b.unknowns())
792
for subp in self.extras():
793
if not self.is_ignored(subp):
796
def iter_conflicts(self):
798
for path in (s[0] for s in self.list_files()):
799
stem = get_conflicted_stem(path)
802
if stem not in conflicted:
807
def pull(self, source, overwrite=False):
810
old_revision_history = self.branch.revision_history()
811
count = self.branch.pull(source, overwrite)
812
new_revision_history = self.branch.revision_history()
813
if new_revision_history != old_revision_history:
814
if len(old_revision_history):
815
other_revision = old_revision_history[-1]
817
other_revision = None
818
repository = self.branch.repository
819
merge_inner(self.branch,
821
repository.revision_tree(other_revision),
823
self.set_last_revision(self.branch.last_revision())
829
"""Yield all unknown files in this WorkingTree.
831
If there are any unknown directories then only the directory is
832
returned, not all its children. But if there are unknown files
833
under a versioned subdirectory, they are returned.
835
Currently returned depth-first, sorted by name within directories.
837
## TODO: Work from given directory downwards
838
for path, dir_entry in self.inventory.directories():
839
mutter("search for unknowns in %r", path)
840
dirabs = self.abspath(path)
841
if not isdir(dirabs):
842
# e.g. directory deleted
846
for subf in os.listdir(dirabs):
848
and (subf not in dir_entry.children)):
853
subp = appendpath(path, subf)
857
def ignored_files(self):
858
"""Yield list of PATH, IGNORE_PATTERN"""
859
for subp in self.extras():
860
pat = self.is_ignored(subp)
865
def get_ignore_list(self):
866
"""Return list of ignore patterns.
868
Cached in the Tree object after the first call.
870
if hasattr(self, '_ignorelist'):
871
return self._ignorelist
873
l = bzrlib.DEFAULT_IGNORE[:]
874
if self.has_filename(bzrlib.IGNORE_FILENAME):
875
f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
876
l.extend([line.rstrip("\n\r") for line in f.readlines()])
881
def is_ignored(self, filename):
882
r"""Check whether the filename matches an ignore pattern.
884
Patterns containing '/' or '\' need to match the whole path;
885
others match against only the last component.
887
If the file is ignored, returns the pattern which caused it to
888
be ignored, otherwise None. So this can simply be used as a
889
boolean if desired."""
891
# TODO: Use '**' to match directories, and other extended
892
# globbing stuff from cvs/rsync.
894
# XXX: fnmatch is actually not quite what we want: it's only
895
# approximately the same as real Unix fnmatch, and doesn't
896
# treat dotfiles correctly and allows * to match /.
897
# Eventually it should be replaced with something more
900
for pat in self.get_ignore_list():
901
if '/' in pat or '\\' in pat:
903
# as a special case, you can put ./ at the start of a
904
# pattern; this is good to match in the top-level
907
if (pat[:2] == './') or (pat[:2] == '.\\'):
911
if fnmatch.fnmatchcase(filename, newpat):
914
if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
919
def kind(self, file_id):
920
return file_kind(self.id2abspath(file_id))
922
def last_revision(self):
923
"""Return the last revision id of this working tree.
925
In early branch formats this was == the branch last_revision,
926
but that cannot be relied upon - for working tree operations,
927
always use tree.last_revision().
929
return self.branch.last_revision()
932
"""See Branch.lock_read, and WorkingTree.unlock."""
933
self.branch.lock_read()
935
return self._control_files.lock_read()
940
def lock_write(self):
941
"""See Branch.lock_write, and WorkingTree.unlock."""
942
self.branch.lock_write()
944
return self._control_files.lock_write()
949
def _basis_inventory_name(self, revision_id):
950
return 'basis-inventory.%s' % revision_id
952
def set_last_revision(self, new_revision, old_revision=None):
953
if old_revision is not None:
955
path = self._basis_inventory_name(old_revision)
956
path = self._control_files._escape(path)
957
self._control_files._transport.delete(path)
960
if new_revision is None:
961
self.branch.set_revision_history([])
963
# current format is locked in with the branch
964
revision_history = self.branch.revision_history()
966
position = revision_history.index(new_revision)
968
raise errors.NoSuchRevision(self.branch, new_revision)
969
self.branch.set_revision_history(revision_history[:position + 1])
971
xml = self.branch.repository.get_inventory_xml(new_revision)
972
path = self._basis_inventory_name(new_revision)
973
self._control_files.put_utf8(path, xml)
974
except WeaveRevisionNotPresent:
977
def read_basis_inventory(self, revision_id):
978
"""Read the cached basis inventory."""
979
path = self._basis_inventory_name(revision_id)
980
return self._control_files.get_utf8(path).read()
983
def read_working_inventory(self):
984
"""Read the working inventory."""
985
# ElementTree does its own conversion from UTF-8, so open in
987
result = bzrlib.xml5.serializer_v5.read_inventory(
988
self._control_files.get('inventory'))
989
self._set_inventory(result)
993
def remove(self, files, verbose=False):
994
"""Remove nominated files from the working inventory..
996
This does not remove their text. This does not run on XXX on what? RBC
998
TODO: Refuse to remove modified files unless --force is given?
1000
TODO: Do something useful with directories.
1002
TODO: Should this remove the text or not? Tough call; not
1003
removing may be useful and the user can just use use rm, and
1004
is the opposite of add. Removing it is consistent with most
1005
other tools. Maybe an option.
1007
## TODO: Normalize names
1008
## TODO: Remove nested loops; better scalability
1009
if isinstance(files, basestring):
1012
inv = self.inventory
1014
# do this before any modifications
1016
fid = inv.path2id(f)
1018
# TODO: Perhaps make this just a warning, and continue?
1019
# This tends to happen when
1020
raise NotVersionedError(path=f)
1021
mutter("remove inventory entry %s {%s}", quotefn(f), fid)
1023
# having remove it, it must be either ignored or unknown
1024
if self.is_ignored(f):
1028
show_status(new_status, inv[fid].kind, quotefn(f))
1031
self._write_inventory(inv)
1034
def revert(self, filenames, old_tree=None, backups=True):
1035
from bzrlib.merge import merge_inner
1036
if old_tree is None:
1037
old_tree = self.basis_tree()
1038
merge_inner(self.branch, old_tree,
1039
self, ignore_zero=True,
1040
backup_files=backups,
1041
interesting_files=filenames,
1043
if not len(filenames):
1044
self.set_pending_merges([])
1047
def set_inventory(self, new_inventory_list):
1048
from bzrlib.inventory import (Inventory,
1053
inv = Inventory(self.get_root_id())
1054
for path, file_id, parent, kind in new_inventory_list:
1055
name = os.path.basename(path)
1058
# fixme, there should be a factory function inv,add_??
1059
if kind == 'directory':
1060
inv.add(InventoryDirectory(file_id, name, parent))
1061
elif kind == 'file':
1062
inv.add(InventoryFile(file_id, name, parent))
1063
elif kind == 'symlink':
1064
inv.add(InventoryLink(file_id, name, parent))
1066
raise BzrError("unknown kind %r" % kind)
1067
self._write_inventory(inv)
1070
def set_root_id(self, file_id):
1071
"""Set the root id for this tree."""
1072
inv = self.read_working_inventory()
1073
orig_root_id = inv.root.file_id
1074
del inv._byid[inv.root.file_id]
1075
inv.root.file_id = file_id
1076
inv._byid[inv.root.file_id] = inv.root
1079
if entry.parent_id == orig_root_id:
1080
entry.parent_id = inv.root.file_id
1081
self._write_inventory(inv)
1084
"""See Branch.unlock.
1086
WorkingTree locking just uses the Branch locking facilities.
1087
This is current because all working trees have an embedded branch
1088
within them. IF in the future, we were to make branch data shareable
1089
between multiple working trees, i.e. via shared storage, then we
1090
would probably want to lock both the local tree, and the branch.
1092
# FIXME: We want to write out the hashcache only when the last lock on
1093
# this working copy is released. Peeking at the lock count is a bit
1094
# of a nasty hack; probably it's better to have a transaction object,
1095
# which can do some finalization when it's either successfully or
1096
# unsuccessfully completed. (Denys's original patch did that.)
1097
# RBC 20060206 hookinhg into transaction will couple lock and transaction
1098
# wrongly. Hookinh into unllock on the control files object is fine though.
1100
# TODO: split this per format so there is no ugly if block
1101
if self._hashcache.needs_write and (
1102
self._control_files._lock_count==1 or
1103
(self._control_files is self.branch.control_files and
1104
self._control_files._lock_count==2)):
1105
self._hashcache.write()
1106
# reverse order of locking.
1107
result = self._control_files.unlock()
1109
self.branch.unlock()
1114
def _write_inventory(self, inv):
1115
"""Write inventory as the current inventory."""
1117
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
1119
self._control_files.put('inventory', sio)
1120
self._set_inventory(inv)
1121
mutter('wrote working inventory')
1124
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
1125
def get_conflicted_stem(path):
1126
for suffix in CONFLICT_SUFFIXES:
1127
if path.endswith(suffix):
1128
return path[:-len(suffix)]
1130
def is_control_file(filename):
1131
## FIXME: better check
1132
filename = normpath(filename)
1133
while filename != '':
1134
head, tail = os.path.split(filename)
1135
## mutter('check %r for control file' % ((head, tail),))
1136
if tail == bzrlib.BZRDIR:
1138
if filename == head:
1144
class WorkingTreeFormat(object):
1145
"""An encapsulation of the initialization and open routines for a format.
1147
Formats provide three things:
1148
* An initialization routine,
1152
Formats are placed in an dict by their format string for reference
1153
during workingtree opening. Its not required that these be instances, they
1154
can be classes themselves with class methods - it simply depends on
1155
whether state is needed for a given format or not.
1157
Once a format is deprecated, just deprecate the initialize and open
1158
methods on the format class. Do not deprecate the object, as the
1159
object will be created every time regardless.
1162
_default_format = None
1163
"""The default format used for new trees."""
1166
"""The known formats."""
1169
def find_format(klass, a_bzrdir):
1170
"""Return the format for the working tree object in a_bzrdir."""
1172
transport = a_bzrdir.get_workingtree_transport(None)
1173
format_string = transport.get("format").read()
1174
return klass._formats[format_string]
1176
raise errors.NotBranchError(path=transport.base)
1178
raise errors.UnknownFormatError(format_string)
1181
def get_default_format(klass):
1182
"""Return the current default format."""
1183
return klass._default_format
1185
def get_format_string(self):
1186
"""Return the ASCII format string that identifies this format."""
1187
raise NotImplementedError(self.get_format_string)
1189
def is_supported(self):
1190
"""Is this format supported?
1192
Supported formats can be initialized and opened.
1193
Unsupported formats may not support initialization or committing or
1194
some other features depending on the reason for not being supported.
1199
def register_format(klass, format):
1200
klass._formats[format.get_format_string()] = format
1203
def set_default_format(klass, format):
1204
klass._default_format = format
1207
def unregister_format(klass, format):
1208
assert klass._formats[format.get_format_string()] is format
1209
del klass._formats[format.get_format_string()]
1213
class WorkingTreeFormat2(WorkingTreeFormat):
1214
"""The second working tree format.
1216
This format modified the hash cache from the format 1 hash cache.
1219
def initialize(self, a_bzrdir):
1220
"""See WorkingTreeFormat.initialize()."""
1221
if not isinstance(a_bzrdir.transport, LocalTransport):
1222
raise errors.NotLocalUrl(a_bzrdir.transport.base)
1223
branch = a_bzrdir.open_branch()
1224
revision = branch.last_revision()
1225
basis_tree = branch.repository.revision_tree(revision)
1226
inv = basis_tree.inventory
1227
wt = WorkingTree(a_bzrdir.root_transport.base,
1233
wt._write_inventory(inv)
1234
wt.set_root_id(inv.root.file_id)
1235
wt.set_last_revision(revision)
1236
wt.set_pending_merges([])
1241
super(WorkingTreeFormat2, self).__init__()
1242
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1244
def open(self, a_bzrdir, _found=False):
1245
"""Return the WorkingTree object for a_bzrdir
1247
_found is a private parameter, do not use it. It is used to indicate
1248
if format probing has already been done.
1251
# we are being called directly and must probe.
1252
raise NotImplementedError
1253
if not isinstance(a_bzrdir.transport, LocalTransport):
1254
raise errors.NotLocalUrl(a_bzrdir.transport.base)
1255
return WorkingTree(a_bzrdir.root_transport.base,
1261
class WorkingTreeFormat3(WorkingTreeFormat):
1262
"""The second working tree format updated to record a format marker.
1264
This format modified the hash cache from the format 1 hash cache.
1267
def get_format_string(self):
1268
"""See WorkingTreeFormat.get_format_string()."""
1269
return "Bazaar-NG Working Tree format 3"
1271
def initialize(self, a_bzrdir):
1272
"""See WorkingTreeFormat.initialize()."""
1273
if not isinstance(a_bzrdir.transport, LocalTransport):
1274
raise errors.NotLocalUrl(a_bzrdir.transport.base)
1275
transport = a_bzrdir.get_workingtree_transport(self)
1276
control_files = LockableFiles(transport, 'lock')
1277
control_files.put_utf8('format', self.get_format_string())
1278
branch = a_bzrdir.open_branch()
1279
revision = branch.last_revision()
1280
basis_tree = branch.repository.revision_tree(revision)
1281
inv = basis_tree.inventory
1282
wt = WorkingTree(a_bzrdir.root_transport.base,
1288
wt._write_inventory(inv)
1289
wt.set_root_id(inv.root.file_id)
1290
wt.set_last_revision(revision)
1291
wt.set_pending_merges([])
1296
super(WorkingTreeFormat3, self).__init__()
1297
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1299
def open(self, a_bzrdir, _found=False):
1300
"""Return the WorkingTree object for a_bzrdir
1302
_found is a private parameter, do not use it. It is used to indicate
1303
if format probing has already been done.
1306
# we are being called directly and must probe.
1307
raise NotImplementedError
1308
if not isinstance(a_bzrdir.transport, LocalTransport):
1309
raise errors.NotLocalUrl(a_bzrdir.transport.base)
1310
return WorkingTree(a_bzrdir.root_transport.base,
1316
# formats which have no format string are not discoverable
1317
# and not independently creatable, so are not registered.
1318
__default_format = WorkingTreeFormat3()
1319
WorkingTreeFormat.register_format(__default_format)
1320
WorkingTreeFormat.set_default_format(__default_format)
1321
_legacy_formats = [WorkingTreeFormat2(),
1325
class WorkingTreeTestProviderAdapter(object):
1326
"""A tool to generate a suite testing multiple workingtree formats at once.
1328
This is done by copying the test once for each transport and injecting
1329
the transport_server, transport_readonly_server, and workingtree_format
1330
classes into each copy. Each copy is also given a new id() to make it
1334
def __init__(self, transport_server, transport_readonly_server, formats):
1335
self._transport_server = transport_server
1336
self._transport_readonly_server = transport_readonly_server
1337
self._formats = formats
1339
def adapt(self, test):
1340
from bzrlib.tests import TestSuite
1341
result = TestSuite()
1342
for workingtree_format, bzrdir_format in self._formats:
1343
new_test = deepcopy(test)
1344
new_test.transport_server = self._transport_server
1345
new_test.transport_readonly_server = self._transport_readonly_server
1346
new_test.bzrdir_format = bzrdir_format
1347
new_test.workingtree_format = workingtree_format
1348
def make_new_test_id():
1349
new_id = "%s(%s)" % (new_test.id(), workingtree_format.__class__.__name__)
1350
return lambda: new_id
1351
new_test.id = make_new_test_id()
1352
result.addTest(new_test)