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, Inventory
65
from bzrlib.lockable_files import LockableFiles
66
from bzrlib.merge import merge_inner, transform_tree
67
from bzrlib.osutils import (appendpath,
84
from bzrlib.progress import DummyProgress
85
from bzrlib.revision import NULL_REVISION
86
import bzrlib.splatfile as splatfile
87
from bzrlib.symbol_versioning import *
88
from bzrlib.textui import show_status
90
from bzrlib.trace import mutter
91
from bzrlib.transform import build_tree
92
from bzrlib.transport import get_transport
93
from bzrlib.transport.local import LocalTransport
98
def gen_file_id(name):
99
"""Return new file id.
101
This should probably generate proper UUIDs, but for the moment we
102
cope with just randomness because running uuidgen every time is
105
from binascii import hexlify
106
from time import time
109
idx = name.rfind('/')
111
name = name[idx+1 : ]
112
idx = name.rfind('\\')
114
name = name[idx+1 : ]
116
# make it not a hidden file
117
name = name.lstrip('.')
119
# remove any wierd characters; we don't escape them but rather
121
name = re.sub(r'[^\w.]', '', name)
123
s = hexlify(rand_bytes(8))
124
return '-'.join((name, compact_date(time()), s))
128
"""Return a new tree-root file id."""
129
return gen_file_id('TREE_ROOT')
132
class TreeEntry(object):
133
"""An entry that implements the minium interface used by commands.
135
This needs further inspection, it may be better to have
136
InventoryEntries without ids - though that seems wrong. For now,
137
this is a parallel hierarchy to InventoryEntry, and needs to become
138
one of several things: decorates to that hierarchy, children of, or
140
Another note is that these objects are currently only used when there is
141
no InventoryEntry available - i.e. for unversioned objects.
142
Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
145
def __eq__(self, other):
146
# yes, this us ugly, TODO: best practice __eq__ style.
147
return (isinstance(other, TreeEntry)
148
and other.__class__ == self.__class__)
150
def kind_character(self):
154
class TreeDirectory(TreeEntry):
155
"""See TreeEntry. This is a directory in a working tree."""
157
def __eq__(self, other):
158
return (isinstance(other, TreeDirectory)
159
and other.__class__ == self.__class__)
161
def kind_character(self):
165
class TreeFile(TreeEntry):
166
"""See TreeEntry. This is a regular file in a working tree."""
168
def __eq__(self, other):
169
return (isinstance(other, TreeFile)
170
and other.__class__ == self.__class__)
172
def kind_character(self):
176
class TreeLink(TreeEntry):
177
"""See TreeEntry. This is a symlink in a working tree."""
179
def __eq__(self, other):
180
return (isinstance(other, TreeLink)
181
and other.__class__ == self.__class__)
183
def kind_character(self):
187
class WorkingTree(bzrlib.tree.Tree):
188
"""Working copy tree.
190
The inventory is held in the `Branch` working-inventory, and the
191
files are in a directory on disk.
193
It is possible for a `WorkingTree` to have a filename which is
194
not listed in the Inventory and vice versa.
197
def __init__(self, basedir='.',
198
branch=DEPRECATED_PARAMETER,
204
"""Construct a WorkingTree for basedir.
206
If the branch is not supplied, it is opened automatically.
207
If the branch is supplied, it must be the branch for this basedir.
208
(branch.base is not cross checked, because for remote branches that
209
would be meaningless).
211
self._format = _format
212
self.bzrdir = _bzrdir
214
# not created via open etc.
215
warn("WorkingTree() is deprecated as of bzr version 0.8. "
216
"Please use bzrdir.open_workingtree or WorkingTree.open().",
219
wt = WorkingTree.open(basedir)
220
self.branch = wt.branch
221
self.basedir = wt.basedir
222
self._control_files = wt._control_files
223
self._hashcache = wt._hashcache
224
self._set_inventory(wt._inventory)
225
self._format = wt._format
226
self.bzrdir = wt.bzrdir
227
from bzrlib.hashcache import HashCache
228
from bzrlib.trace import note, mutter
229
assert isinstance(basedir, basestring), \
230
"base directory %r is not a string" % basedir
231
basedir = safe_unicode(basedir)
232
mutter("opening working tree %r", basedir)
233
if deprecated_passed(branch):
235
warn("WorkingTree(..., branch=XXX) is deprecated as of bzr 0.8."
236
" Please use bzrdir.open_workingtree() or WorkingTree.open().",
242
self.branch = self.bzrdir.open_branch()
243
assert isinstance(self.branch, Branch), \
244
"branch %r is not a Branch" % self.branch
245
self.basedir = realpath(basedir)
246
# if branch is at our basedir and is a format 6 or less
247
if isinstance(self._format, WorkingTreeFormat2):
248
# share control object
249
self._control_files = self.branch.control_files
250
elif _control_files is not None:
251
assert False, "not done yet"
252
# self._control_files = _control_files
254
# only ready for format 3
255
assert isinstance(self._format, WorkingTreeFormat3)
256
self._control_files = LockableFiles(
257
self.bzrdir.get_workingtree_transport(None),
260
# update the whole cache up front and write to disk if anything changed;
261
# in the future we might want to do this more selectively
262
# two possible ways offer themselves : in self._unlock, write the cache
263
# if needed, or, when the cache sees a change, append it to the hash
264
# cache file, and have the parser take the most recent entry for a
266
cache_filename = self.bzrdir.get_workingtree_transport(None).abspath('stat-cache')
267
hc = self._hashcache = HashCache(basedir, cache_filename, self._control_files._file_mode)
269
# is this scan needed ? it makes things kinda slow.
276
if _inventory is None:
277
self._set_inventory(self.read_working_inventory())
279
self._set_inventory(_inventory)
281
def _set_inventory(self, inv):
282
self._inventory = inv
283
self.path2id = self._inventory.path2id
285
def is_control_filename(self, filename):
286
"""True if filename is the name of a control file in this tree.
288
This is true IF and ONLY IF the filename is part of the meta data
289
that bzr controls in this tree. I.E. a random .bzr directory placed
290
on disk will not be a control file for this tree.
293
self.bzrdir.transport.relpath(self.abspath(filename))
295
except errors.PathNotChild:
299
def open(path=None, _unsupported=False):
300
"""Open an existing working tree at path.
304
path = os.path.getcwdu()
305
control = bzrdir.BzrDir.open(path, _unsupported)
306
return control.open_workingtree(_unsupported)
309
def open_containing(path=None):
310
"""Open an existing working tree which has its root about path.
312
This probes for a working tree at path and searches upwards from there.
314
Basically we keep looking up until we find the control directory or
315
run into /. If there isn't one, raises NotBranchError.
316
TODO: give this a new exception.
317
If there is one, it is returned, along with the unused portion of path.
321
control, relpath = bzrdir.BzrDir.open_containing(path)
322
return control.open_workingtree(), relpath
325
def open_downlevel(path=None):
326
"""Open an unsupported working tree.
328
Only intended for advanced situations like upgrading part of a bzrdir.
330
return WorkingTree.open(path, _unsupported=True)
333
"""Iterate through file_ids for this tree.
335
file_ids are in a WorkingTree if they are in the working inventory
336
and the working file exists.
338
inv = self._inventory
339
for path, ie in inv.iter_entries():
340
if bzrlib.osutils.lexists(self.abspath(path)):
344
return "<%s of %s>" % (self.__class__.__name__,
345
getattr(self, 'basedir', None))
347
def abspath(self, filename):
348
return pathjoin(self.basedir, filename)
350
def basis_tree(self):
351
"""Return RevisionTree for the current last revision."""
352
revision_id = self.last_revision()
353
if revision_id is not None:
355
xml = self.read_basis_inventory(revision_id)
356
inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
357
return bzrlib.tree.RevisionTree(self.branch.repository, inv,
361
return self.branch.repository.revision_tree(revision_id)
364
@deprecated_method(zero_eight)
365
def create(branch, directory):
366
"""Create a workingtree for branch at directory.
368
If existing_directory already exists it must have a .bzr directory.
369
If it does not exist, it will be created.
371
This returns a new WorkingTree object for the new checkout.
373
TODO FIXME RBC 20060124 when we have checkout formats in place this
374
should accept an optional revisionid to checkout [and reject this if
375
checking out into the same dir as a pre-checkout-aware branch format.]
377
XXX: When BzrDir is present, these should be created through that
380
warn('delete WorkingTree.create', stacklevel=3)
381
transport = get_transport(directory)
382
if branch.bzrdir.root_transport.base == transport.base:
384
return branch.bzrdir.create_workingtree()
385
# different directory,
386
# create a branch reference
387
# and now a working tree.
388
raise NotImplementedError
391
@deprecated_method(zero_eight)
392
def create_standalone(directory):
393
"""Create a checkout and a branch and a repo at directory.
395
Directory must exist and be empty.
397
please use BzrDir.create_standalone_workingtree
399
return bzrdir.BzrDir.create_standalone_workingtree(directory)
401
def relpath(self, abs):
402
"""Return the local path portion from a given absolute path."""
403
return relpath(self.basedir, abs)
405
def has_filename(self, filename):
406
return bzrlib.osutils.lexists(self.abspath(filename))
408
def get_file(self, file_id):
409
return self.get_file_byname(self.id2path(file_id))
411
def get_file_byname(self, filename):
412
return file(self.abspath(filename), 'rb')
414
def get_root_id(self):
415
"""Return the id of this trees root"""
416
inv = self.read_working_inventory()
417
return inv.root.file_id
419
def _get_store_filename(self, file_id):
420
## XXX: badly named; this is not in the store at all
421
return self.abspath(self.id2path(file_id))
424
def clone(self, to_bzrdir, revision_id=None, basis=None):
425
"""Duplicate this working tree into to_bzr, including all state.
427
Specifically modified files are kept as modified, but
428
ignored and unknown files are discarded.
430
If you want to make a new line of development, see bzrdir.sprout()
433
If not None, the cloned tree will have its last revision set to
434
revision, and and difference between the source trees last revision
435
and this one merged in.
438
If not None, a closer copy of a tree which may have some files in
439
common, and which file content should be preferentially copied from.
441
# assumes the target bzr dir format is compatible.
442
result = self._format.initialize(to_bzrdir)
443
self.copy_content_into(result, revision_id)
447
def copy_content_into(self, tree, revision_id=None):
448
"""Copy the current content and user files of this tree into tree."""
449
if revision_id is None:
450
transform_tree(tree, self)
452
# TODO now merge from tree.last_revision to revision
453
transform_tree(tree, self)
454
tree.set_last_revision(revision_id)
457
def commit(self, *args, **kwargs):
458
from bzrlib.commit import Commit
459
# args for wt.commit start at message from the Commit.commit method,
460
# but with branch a kwarg now, passing in args as is results in the
461
#message being used for the branch
462
args = (DEPRECATED_PARAMETER, ) + args
463
Commit().commit(working_tree=self, *args, **kwargs)
464
self._set_inventory(self.read_working_inventory())
466
def id2abspath(self, file_id):
467
return self.abspath(self.id2path(file_id))
469
def has_id(self, file_id):
470
# files that have been deleted are excluded
471
inv = self._inventory
472
if not inv.has_id(file_id):
474
path = inv.id2path(file_id)
475
return bzrlib.osutils.lexists(self.abspath(path))
477
def has_or_had_id(self, file_id):
478
if file_id == self.inventory.root.file_id:
480
return self.inventory.has_id(file_id)
482
__contains__ = has_id
484
def get_file_size(self, file_id):
485
return os.path.getsize(self.id2abspath(file_id))
488
def get_file_sha1(self, file_id):
489
path = self._inventory.id2path(file_id)
490
return self._hashcache.get_sha1(path)
492
def is_executable(self, file_id):
493
if not supports_executable():
494
return self._inventory[file_id].executable
496
path = self._inventory.id2path(file_id)
497
mode = os.lstat(self.abspath(path)).st_mode
498
return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
501
def add(self, files, ids=None):
502
"""Make files versioned.
504
Note that the command line normally calls smart_add instead,
505
which can automatically recurse.
507
This adds the files to the inventory, so that they will be
508
recorded by the next commit.
511
List of paths to add, relative to the base of the tree.
514
If set, use these instead of automatically generated ids.
515
Must be the same length as the list of files, but may
516
contain None for ids that are to be autogenerated.
518
TODO: Perhaps have an option to add the ids even if the files do
521
TODO: Perhaps callback with the ids and paths as they're added.
523
# TODO: Re-adding a file that is removed in the working copy
524
# should probably put it back with the previous ID.
525
if isinstance(files, basestring):
526
assert(ids is None or isinstance(ids, basestring))
532
ids = [None] * len(files)
534
assert(len(ids) == len(files))
536
inv = self.read_working_inventory()
537
for f,file_id in zip(files, ids):
538
if self.is_control_filename(f):
539
raise BzrError("cannot add control file %s" % quotefn(f))
544
raise BzrError("cannot add top-level %r" % f)
546
fullpath = normpath(self.abspath(f))
549
kind = file_kind(fullpath)
551
if e.errno == errno.ENOENT:
552
raise NoSuchFile(fullpath)
553
# maybe something better?
554
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
556
if not InventoryEntry.versionable_kind(kind):
557
raise BzrError('cannot add: not a versionable file ('
558
'i.e. regular file, symlink or directory): %s' % quotefn(f))
561
file_id = gen_file_id(f)
562
inv.add_path(f, kind=kind, file_id=file_id)
564
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
565
self._write_inventory(inv)
568
def add_pending_merge(self, *revision_ids):
569
# TODO: Perhaps should check at this point that the
570
# history of the revision is actually present?
571
p = self.pending_merges()
573
for rev_id in revision_ids:
579
self.set_pending_merges(p)
582
def pending_merges(self):
583
"""Return a list of pending merges.
585
These are revisions that have been merged into the working
586
directory but not yet committed.
589
merges_file = self._control_files.get_utf8('pending-merges')
591
if e.errno != errno.ENOENT:
595
for l in merges_file.readlines():
596
p.append(l.rstrip('\n'))
600
def set_pending_merges(self, rev_list):
601
self._control_files.put_utf8('pending-merges', '\n'.join(rev_list))
604
def set_merge_modified(self, modified_hashes):
606
splatfile.dump_dict(my_file, modified_hashes)
608
self._control_files.put('merge-hashes', my_file)
611
def merge_modified(self):
613
hashfile = self._control_files.get('merge-hashes')
616
merge_hashes = splatfile.read_dict(hashfile)
617
return dict([(f,h) for f,h in merge_hashes.items() if
618
h == self.get_file_sha1(f)])
620
def get_symlink_target(self, file_id):
621
return os.readlink(self.id2abspath(file_id))
623
def file_class(self, filename):
624
if self.path2id(filename):
626
elif self.is_ignored(filename):
631
def list_files(self):
632
"""Recursively list all files as (path, class, kind, id).
634
Lists, but does not descend into unversioned directories.
636
This does not include files that have been deleted in this
639
Skips the control directory.
641
inv = self._inventory
643
def descend(from_dir_relpath, from_dir_id, dp):
647
## TODO: If we find a subdirectory with its own .bzr
648
## directory, then that is a separate tree and we
649
## should exclude it.
651
# the bzrdir for this tree
652
if self.bzrdir.transport.base.endswith(f + '/'):
656
fp = appendpath(from_dir_relpath, f)
659
fap = appendpath(dp, f)
661
f_ie = inv.get_child(from_dir_id, f)
664
elif self.is_ignored(fp):
673
raise BzrCheckError("file %r entered as kind %r id %r, "
675
% (fap, f_ie.kind, f_ie.file_id, fk))
677
# make a last minute entry
681
if fk == 'directory':
682
entry = TreeDirectory()
685
elif fk == 'symlink':
690
yield fp, c, fk, (f_ie and f_ie.file_id), entry
692
if fk != 'directory':
696
# don't descend unversioned directories
699
for ff in descend(fp, f_ie.file_id, fap):
702
for f in descend(u'', inv.root.file_id, self.basedir):
706
def move(self, from_paths, to_name):
709
to_name must exist in the inventory.
711
If to_name exists and is a directory, the files are moved into
712
it, keeping their old names.
714
Note that to_name is only the last component of the new name;
715
this doesn't change the directory.
717
This returns a list of (from_path, to_path) pairs for each
721
## TODO: Option to move IDs only
722
assert not isinstance(from_paths, basestring)
724
to_abs = self.abspath(to_name)
725
if not isdir(to_abs):
726
raise BzrError("destination %r is not a directory" % to_abs)
727
if not self.has_filename(to_name):
728
raise BzrError("destination %r not in working directory" % to_abs)
729
to_dir_id = inv.path2id(to_name)
730
if to_dir_id == None and to_name != '':
731
raise BzrError("destination %r is not a versioned directory" % to_name)
732
to_dir_ie = inv[to_dir_id]
733
if to_dir_ie.kind not in ('directory', 'root_directory'):
734
raise BzrError("destination %r is not a directory" % to_abs)
736
to_idpath = inv.get_idpath(to_dir_id)
739
if not self.has_filename(f):
740
raise BzrError("%r does not exist in working tree" % f)
741
f_id = inv.path2id(f)
743
raise BzrError("%r is not versioned" % f)
744
name_tail = splitpath(f)[-1]
745
dest_path = appendpath(to_name, name_tail)
746
if self.has_filename(dest_path):
747
raise BzrError("destination %r already exists" % dest_path)
748
if f_id in to_idpath:
749
raise BzrError("can't move %r to a subdirectory of itself" % f)
751
# OK, so there's a race here, it's possible that someone will
752
# create a file in this interval and then the rename might be
753
# left half-done. But we should have caught most problems.
754
orig_inv = deepcopy(self.inventory)
757
name_tail = splitpath(f)[-1]
758
dest_path = appendpath(to_name, name_tail)
759
result.append((f, dest_path))
760
inv.rename(inv.path2id(f), to_dir_id, name_tail)
762
rename(self.abspath(f), self.abspath(dest_path))
764
raise BzrError("failed to rename %r to %r: %s" %
765
(f, dest_path, e[1]),
766
["rename rolled back"])
768
# restore the inventory on error
769
self._set_inventory(orig_inv)
771
self._write_inventory(inv)
775
def rename_one(self, from_rel, to_rel):
778
This can change the directory or the filename or both.
781
if not self.has_filename(from_rel):
782
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
783
if self.has_filename(to_rel):
784
raise BzrError("can't rename: new working file %r already exists" % to_rel)
786
file_id = inv.path2id(from_rel)
788
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
791
from_parent = entry.parent_id
792
from_name = entry.name
794
if inv.path2id(to_rel):
795
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
797
to_dir, to_tail = os.path.split(to_rel)
798
to_dir_id = inv.path2id(to_dir)
799
if to_dir_id == None and to_dir != '':
800
raise BzrError("can't determine destination directory id for %r" % to_dir)
802
mutter("rename_one:")
803
mutter(" file_id {%s}" % file_id)
804
mutter(" from_rel %r" % from_rel)
805
mutter(" to_rel %r" % to_rel)
806
mutter(" to_dir %r" % to_dir)
807
mutter(" to_dir_id {%s}" % to_dir_id)
809
inv.rename(file_id, to_dir_id, to_tail)
811
from_abs = self.abspath(from_rel)
812
to_abs = self.abspath(to_rel)
814
rename(from_abs, to_abs)
816
inv.rename(file_id, from_parent, from_name)
817
raise BzrError("failed to rename %r to %r: %s"
818
% (from_abs, to_abs, e[1]),
819
["rename rolled back"])
820
self._write_inventory(inv)
824
"""Return all unknown files.
826
These are files in the working directory that are not versioned or
827
control files or ignored.
829
>>> from bzrlib.bzrdir import ScratchDir
830
>>> d = ScratchDir(files=['foo', 'foo~'])
831
>>> b = d.open_branch()
832
>>> tree = d.open_workingtree()
833
>>> map(str, tree.unknowns())
836
>>> list(b.unknowns())
838
>>> tree.remove('foo')
839
>>> list(b.unknowns())
842
for subp in self.extras():
843
if not self.is_ignored(subp):
846
def iter_conflicts(self):
848
for path in (s[0] for s in self.list_files()):
849
stem = get_conflicted_stem(path)
852
if stem not in conflicted:
857
def pull(self, source, overwrite=False, stop_revision=None):
860
old_revision_history = self.branch.revision_history()
861
basis_tree = self.basis_tree()
862
count = self.branch.pull(source, overwrite, stop_revision)
863
new_revision_history = self.branch.revision_history()
864
if new_revision_history != old_revision_history:
865
if len(old_revision_history):
866
other_revision = old_revision_history[-1]
868
other_revision = None
869
repository = self.branch.repository
870
merge_inner(self.branch,
871
self.branch.basis_tree(),
874
pb=bzrlib.ui.ui_factory.progress_bar())
875
self.set_last_revision(self.branch.last_revision())
881
"""Yield all unknown files in this WorkingTree.
883
If there are any unknown directories then only the directory is
884
returned, not all its children. But if there are unknown files
885
under a versioned subdirectory, they are returned.
887
Currently returned depth-first, sorted by name within directories.
889
## TODO: Work from given directory downwards
890
for path, dir_entry in self.inventory.directories():
891
mutter("search for unknowns in %r", path)
892
dirabs = self.abspath(path)
893
if not isdir(dirabs):
894
# e.g. directory deleted
898
for subf in os.listdir(dirabs):
900
and (subf not in dir_entry.children)):
905
subp = appendpath(path, subf)
909
def ignored_files(self):
910
"""Yield list of PATH, IGNORE_PATTERN"""
911
for subp in self.extras():
912
pat = self.is_ignored(subp)
917
def get_ignore_list(self):
918
"""Return list of ignore patterns.
920
Cached in the Tree object after the first call.
922
if hasattr(self, '_ignorelist'):
923
return self._ignorelist
925
l = bzrlib.DEFAULT_IGNORE[:]
926
if self.has_filename(bzrlib.IGNORE_FILENAME):
927
f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
928
l.extend([line.rstrip("\n\r") for line in f.readlines()])
933
def is_ignored(self, filename):
934
r"""Check whether the filename matches an ignore pattern.
936
Patterns containing '/' or '\' need to match the whole path;
937
others match against only the last component.
939
If the file is ignored, returns the pattern which caused it to
940
be ignored, otherwise None. So this can simply be used as a
941
boolean if desired."""
943
# TODO: Use '**' to match directories, and other extended
944
# globbing stuff from cvs/rsync.
946
# XXX: fnmatch is actually not quite what we want: it's only
947
# approximately the same as real Unix fnmatch, and doesn't
948
# treat dotfiles correctly and allows * to match /.
949
# Eventually it should be replaced with something more
952
for pat in self.get_ignore_list():
953
if '/' in pat or '\\' in pat:
955
# as a special case, you can put ./ at the start of a
956
# pattern; this is good to match in the top-level
959
if (pat[:2] == './') or (pat[:2] == '.\\'):
963
if fnmatch.fnmatchcase(filename, newpat):
966
if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
971
def kind(self, file_id):
972
return file_kind(self.id2abspath(file_id))
975
def last_revision(self):
976
"""Return the last revision id of this working tree.
978
In early branch formats this was == the branch last_revision,
979
but that cannot be relied upon - for working tree operations,
980
always use tree.last_revision().
982
return self.branch.last_revision()
985
"""See Branch.lock_read, and WorkingTree.unlock."""
986
self.branch.lock_read()
988
return self._control_files.lock_read()
993
def lock_write(self):
994
"""See Branch.lock_write, and WorkingTree.unlock."""
995
self.branch.lock_write()
997
return self._control_files.lock_write()
1002
def _basis_inventory_name(self, revision_id):
1003
return 'basis-inventory.%s' % revision_id
1006
def set_last_revision(self, new_revision, old_revision=None):
1007
"""Change the last revision in the working tree."""
1008
self._remove_old_basis(old_revision)
1009
if self._change_last_revision(new_revision):
1010
self._cache_basis_inventory(new_revision)
1012
def _change_last_revision(self, new_revision):
1013
"""Template method part of set_last_revision to perform the change."""
1014
if new_revision is None:
1015
self.branch.set_revision_history([])
1017
# current format is locked in with the branch
1018
revision_history = self.branch.revision_history()
1020
position = revision_history.index(new_revision)
1022
raise errors.NoSuchRevision(self.branch, new_revision)
1023
self.branch.set_revision_history(revision_history[:position + 1])
1026
def _cache_basis_inventory(self, new_revision):
1027
"""Cache new_revision as the basis inventory."""
1029
xml = self.branch.repository.get_inventory_xml(new_revision)
1030
path = self._basis_inventory_name(new_revision)
1031
self._control_files.put_utf8(path, xml)
1032
except WeaveRevisionNotPresent:
1035
def _remove_old_basis(self, old_revision):
1036
"""Remove the old basis inventory 'old_revision'."""
1037
if old_revision is not None:
1039
path = self._basis_inventory_name(old_revision)
1040
path = self._control_files._escape(path)
1041
self._control_files._transport.delete(path)
1045
def read_basis_inventory(self, revision_id):
1046
"""Read the cached basis inventory."""
1047
path = self._basis_inventory_name(revision_id)
1048
return self._control_files.get_utf8(path).read()
1051
def read_working_inventory(self):
1052
"""Read the working inventory."""
1053
# ElementTree does its own conversion from UTF-8, so open in
1055
result = bzrlib.xml5.serializer_v5.read_inventory(
1056
self._control_files.get('inventory'))
1057
self._set_inventory(result)
1061
def remove(self, files, verbose=False):
1062
"""Remove nominated files from the working inventory..
1064
This does not remove their text. This does not run on XXX on what? RBC
1066
TODO: Refuse to remove modified files unless --force is given?
1068
TODO: Do something useful with directories.
1070
TODO: Should this remove the text or not? Tough call; not
1071
removing may be useful and the user can just use use rm, and
1072
is the opposite of add. Removing it is consistent with most
1073
other tools. Maybe an option.
1075
## TODO: Normalize names
1076
## TODO: Remove nested loops; better scalability
1077
if isinstance(files, basestring):
1080
inv = self.inventory
1082
# do this before any modifications
1084
fid = inv.path2id(f)
1086
# TODO: Perhaps make this just a warning, and continue?
1087
# This tends to happen when
1088
raise NotVersionedError(path=f)
1089
mutter("remove inventory entry %s {%s}", quotefn(f), fid)
1091
# having remove it, it must be either ignored or unknown
1092
if self.is_ignored(f):
1096
show_status(new_status, inv[fid].kind, quotefn(f))
1099
self._write_inventory(inv)
1102
def revert(self, filenames, old_tree=None, backups=True,
1103
pb=DummyProgress()):
1104
from transform import revert
1105
if old_tree is None:
1106
old_tree = self.basis_tree()
1107
revert(self, old_tree, filenames, backups, pb)
1108
if not len(filenames):
1109
self.set_pending_merges([])
1112
def set_inventory(self, new_inventory_list):
1113
from bzrlib.inventory import (Inventory,
1118
inv = Inventory(self.get_root_id())
1119
for path, file_id, parent, kind in new_inventory_list:
1120
name = os.path.basename(path)
1123
# fixme, there should be a factory function inv,add_??
1124
if kind == 'directory':
1125
inv.add(InventoryDirectory(file_id, name, parent))
1126
elif kind == 'file':
1127
inv.add(InventoryFile(file_id, name, parent))
1128
elif kind == 'symlink':
1129
inv.add(InventoryLink(file_id, name, parent))
1131
raise BzrError("unknown kind %r" % kind)
1132
self._write_inventory(inv)
1135
def set_root_id(self, file_id):
1136
"""Set the root id for this tree."""
1137
inv = self.read_working_inventory()
1138
orig_root_id = inv.root.file_id
1139
del inv._byid[inv.root.file_id]
1140
inv.root.file_id = file_id
1141
inv._byid[inv.root.file_id] = inv.root
1144
if entry.parent_id == orig_root_id:
1145
entry.parent_id = inv.root.file_id
1146
self._write_inventory(inv)
1149
"""See Branch.unlock.
1151
WorkingTree locking just uses the Branch locking facilities.
1152
This is current because all working trees have an embedded branch
1153
within them. IF in the future, we were to make branch data shareable
1154
between multiple working trees, i.e. via shared storage, then we
1155
would probably want to lock both the local tree, and the branch.
1157
# FIXME: We want to write out the hashcache only when the last lock on
1158
# this working copy is released. Peeking at the lock count is a bit
1159
# of a nasty hack; probably it's better to have a transaction object,
1160
# which can do some finalization when it's either successfully or
1161
# unsuccessfully completed. (Denys's original patch did that.)
1162
# RBC 20060206 hookinhg into transaction will couple lock and transaction
1163
# wrongly. Hookinh into unllock on the control files object is fine though.
1165
# TODO: split this per format so there is no ugly if block
1166
if self._hashcache.needs_write and (
1167
# dedicated lock files
1168
self._control_files._lock_count==1 or
1170
(self._control_files is self.branch.control_files and
1171
self._control_files._lock_count==3)):
1172
self._hashcache.write()
1173
# reverse order of locking.
1174
result = self._control_files.unlock()
1176
self.branch.unlock()
1182
self.branch.lock_read()
1184
if self.last_revision() == self.branch.last_revision():
1186
basis = self.basis_tree()
1187
to_tree = self.branch.basis_tree()
1188
result = merge_inner(self.branch,
1192
self.set_last_revision(self.branch.last_revision())
1195
self.branch.unlock()
1198
def _write_inventory(self, inv):
1199
"""Write inventory as the current inventory."""
1201
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
1203
self._control_files.put('inventory', sio)
1204
self._set_inventory(inv)
1205
mutter('wrote working inventory')
1208
class WorkingTree3(WorkingTree):
1209
"""This is the Format 3 working tree.
1211
This differs from the base WorkingTree by:
1212
- having its own file lock
1213
- having its own last-revision property.
1217
def last_revision(self):
1218
"""See WorkingTree.last_revision."""
1220
return self._control_files.get_utf8('last-revision').read()
1224
def _change_last_revision(self, revision_id):
1225
"""See WorkingTree._change_last_revision."""
1226
if revision_id is None or revision_id == NULL_REVISION:
1228
self._control_files._transport.delete('last-revision')
1229
except errors.NoSuchFile:
1234
self.branch.revision_history().index(revision_id)
1236
raise errors.NoSuchRevision(self.branch, revision_id)
1237
self._control_files.put_utf8('last-revision', revision_id)
1241
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
1242
def get_conflicted_stem(path):
1243
for suffix in CONFLICT_SUFFIXES:
1244
if path.endswith(suffix):
1245
return path[:-len(suffix)]
1247
@deprecated_function(zero_eight)
1248
def is_control_file(filename):
1249
"""See WorkingTree.is_control_filename(filename)."""
1250
## FIXME: better check
1251
filename = normpath(filename)
1252
while filename != '':
1253
head, tail = os.path.split(filename)
1254
## mutter('check %r for control file' % ((head, tail),))
1257
if filename == head:
1263
class WorkingTreeFormat(object):
1264
"""An encapsulation of the initialization and open routines for a format.
1266
Formats provide three things:
1267
* An initialization routine,
1271
Formats are placed in an dict by their format string for reference
1272
during workingtree opening. Its not required that these be instances, they
1273
can be classes themselves with class methods - it simply depends on
1274
whether state is needed for a given format or not.
1276
Once a format is deprecated, just deprecate the initialize and open
1277
methods on the format class. Do not deprecate the object, as the
1278
object will be created every time regardless.
1281
_default_format = None
1282
"""The default format used for new trees."""
1285
"""The known formats."""
1288
def find_format(klass, a_bzrdir):
1289
"""Return the format for the working tree object in a_bzrdir."""
1291
transport = a_bzrdir.get_workingtree_transport(None)
1292
format_string = transport.get("format").read()
1293
return klass._formats[format_string]
1295
raise errors.NoWorkingTree(base=transport.base)
1297
raise errors.UnknownFormatError(format_string)
1300
def get_default_format(klass):
1301
"""Return the current default format."""
1302
return klass._default_format
1304
def get_format_string(self):
1305
"""Return the ASCII format string that identifies this format."""
1306
raise NotImplementedError(self.get_format_string)
1308
def is_supported(self):
1309
"""Is this format supported?
1311
Supported formats can be initialized and opened.
1312
Unsupported formats may not support initialization or committing or
1313
some other features depending on the reason for not being supported.
1318
def register_format(klass, format):
1319
klass._formats[format.get_format_string()] = format
1322
def set_default_format(klass, format):
1323
klass._default_format = format
1326
def unregister_format(klass, format):
1327
assert klass._formats[format.get_format_string()] is format
1328
del klass._formats[format.get_format_string()]
1332
class WorkingTreeFormat2(WorkingTreeFormat):
1333
"""The second working tree format.
1335
This format modified the hash cache from the format 1 hash cache.
1338
def initialize(self, a_bzrdir, revision_id=None):
1339
"""See WorkingTreeFormat.initialize()."""
1340
if not isinstance(a_bzrdir.transport, LocalTransport):
1341
raise errors.NotLocalUrl(a_bzrdir.transport.base)
1342
branch = a_bzrdir.open_branch()
1343
if revision_id is not None:
1346
revision_history = branch.revision_history()
1348
position = revision_history.index(revision_id)
1350
raise errors.NoSuchRevision(branch, revision_id)
1351
branch.set_revision_history(revision_history[:position + 1])
1354
revision = branch.last_revision()
1356
wt = WorkingTree(a_bzrdir.root_transport.base,
1362
wt._write_inventory(inv)
1363
wt.set_root_id(inv.root.file_id)
1364
wt.set_last_revision(revision)
1365
wt.set_pending_merges([])
1366
build_tree(wt.basis_tree(), wt)
1370
super(WorkingTreeFormat2, self).__init__()
1371
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1373
def open(self, a_bzrdir, _found=False):
1374
"""Return the WorkingTree object for a_bzrdir
1376
_found is a private parameter, do not use it. It is used to indicate
1377
if format probing has already been done.
1380
# we are being called directly and must probe.
1381
raise NotImplementedError
1382
if not isinstance(a_bzrdir.transport, LocalTransport):
1383
raise errors.NotLocalUrl(a_bzrdir.transport.base)
1384
return WorkingTree(a_bzrdir.root_transport.base,
1390
class WorkingTreeFormat3(WorkingTreeFormat):
1391
"""The second working tree format updated to record a format marker.
1393
This format modified the hash cache from the format 1 hash cache.
1396
def get_format_string(self):
1397
"""See WorkingTreeFormat.get_format_string()."""
1398
return "Bazaar-NG Working Tree format 3"
1400
def initialize(self, a_bzrdir, revision_id=None):
1401
"""See WorkingTreeFormat.initialize().
1403
revision_id allows creating a working tree at a differnet
1404
revision than the branch is at.
1406
if not isinstance(a_bzrdir.transport, LocalTransport):
1407
raise errors.NotLocalUrl(a_bzrdir.transport.base)
1408
transport = a_bzrdir.get_workingtree_transport(self)
1409
control_files = LockableFiles(transport, 'lock')
1410
control_files.put_utf8('format', self.get_format_string())
1411
branch = a_bzrdir.open_branch()
1412
if revision_id is None:
1413
revision_id = branch.last_revision()
1415
wt = WorkingTree3(a_bzrdir.root_transport.base,
1421
wt._write_inventory(inv)
1422
wt.set_root_id(inv.root.file_id)
1423
wt.set_last_revision(revision_id)
1424
wt.set_pending_merges([])
1425
build_tree(wt.basis_tree(), wt)
1429
super(WorkingTreeFormat3, self).__init__()
1430
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1432
def open(self, a_bzrdir, _found=False):
1433
"""Return the WorkingTree object for a_bzrdir
1435
_found is a private parameter, do not use it. It is used to indicate
1436
if format probing has already been done.
1439
# we are being called directly and must probe.
1440
raise NotImplementedError
1441
if not isinstance(a_bzrdir.transport, LocalTransport):
1442
raise errors.NotLocalUrl(a_bzrdir.transport.base)
1443
return WorkingTree3(a_bzrdir.root_transport.base,
1449
return self.get_format_string()
1452
# formats which have no format string are not discoverable
1453
# and not independently creatable, so are not registered.
1454
__default_format = WorkingTreeFormat3()
1455
WorkingTreeFormat.register_format(__default_format)
1456
WorkingTreeFormat.set_default_format(__default_format)
1457
_legacy_formats = [WorkingTreeFormat2(),
1461
class WorkingTreeTestProviderAdapter(object):
1462
"""A tool to generate a suite testing multiple workingtree formats at once.
1464
This is done by copying the test once for each transport and injecting
1465
the transport_server, transport_readonly_server, and workingtree_format
1466
classes into each copy. Each copy is also given a new id() to make it
1470
def __init__(self, transport_server, transport_readonly_server, formats):
1471
self._transport_server = transport_server
1472
self._transport_readonly_server = transport_readonly_server
1473
self._formats = formats
1475
def adapt(self, test):
1476
from bzrlib.tests import TestSuite
1477
result = TestSuite()
1478
for workingtree_format, bzrdir_format in self._formats:
1479
new_test = deepcopy(test)
1480
new_test.transport_server = self._transport_server
1481
new_test.transport_readonly_server = self._transport_readonly_server
1482
new_test.bzrdir_format = bzrdir_format
1483
new_test.workingtree_format = workingtree_format
1484
def make_new_test_id():
1485
new_id = "%s(%s)" % (new_test.id(), workingtree_format.__class__.__name__)
1486
return lambda: new_id
1487
new_test.id = make_new_test_id()
1488
result.addTest(new_test)