14
14
# along with this program; if not, write to the Free Software
15
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 Branch.working_tree():
32
# TODO: Don't allow WorkingTrees to be constructed for remote branches if
17
# TODO: Don't allow WorkingTrees to be constructed for remote branches.
35
19
# FIXME: I don't know if writing out the cache from the destructor is really a
36
# good idea, because destructors are considered poor taste in Python, and it's
37
# not predictable when it will be written out.
39
# TODO: Give the workingtree sole responsibility for the working inventory;
40
# remove the variable and references to it from the branch. This may require
41
# updating the commit code so as to update the inventory within the working
42
# copy, and making sure there's only one WorkingTree for any directory on disk.
43
# At the momenthey may alias the inventory and have old copies of it in memory.
45
from copy import deepcopy
20
# good idea, because destructors are considered poor taste in Python, and
21
# it's not predictable when it will be written out.
50
from bzrlib.branch import (Branch,
55
from bzrlib.errors import (BzrCheckError,
58
WeaveRevisionNotPresent,
61
from bzrlib.inventory import InventoryEntry
62
from bzrlib.osutils import (appendpath,
73
from bzrlib.trace import mutter
77
def gen_file_id(name):
78
"""Return new file id.
80
This should probably generate proper UUIDs, but for the moment we
81
cope with just randomness because running uuidgen every time is
84
from binascii import hexlify
91
idx = name.rfind('\\')
95
# make it not a hidden file
96
name = name.lstrip('.')
98
# remove any wierd characters; we don't escape them but rather
100
name = re.sub(r'[^\w.]', '', name)
102
s = hexlify(rand_bytes(8))
103
return '-'.join((name, compact_date(time()), s))
107
"""Return a new tree-root file id."""
108
return gen_file_id('TREE_ROOT')
111
class TreeEntry(object):
112
"""An entry that implements the minium interface used by commands.
114
This needs further inspection, it may be better to have
115
InventoryEntries without ids - though that seems wrong. For now,
116
this is a parallel hierarchy to InventoryEntry, and needs to become
117
one of several things: decorates to that hierarchy, children of, or
119
Another note is that these objects are currently only used when there is
120
no InventoryEntry available - i.e. for unversioned objects.
121
Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
124
def __eq__(self, other):
125
# yes, this us ugly, TODO: best practice __eq__ style.
126
return (isinstance(other, TreeEntry)
127
and other.__class__ == self.__class__)
129
def kind_character(self):
133
class TreeDirectory(TreeEntry):
134
"""See TreeEntry. This is a directory in a working tree."""
136
def __eq__(self, other):
137
return (isinstance(other, TreeDirectory)
138
and other.__class__ == self.__class__)
140
def kind_character(self):
144
class TreeFile(TreeEntry):
145
"""See TreeEntry. This is a regular file in a working tree."""
147
def __eq__(self, other):
148
return (isinstance(other, TreeFile)
149
and other.__class__ == self.__class__)
151
def kind_character(self):
155
class TreeLink(TreeEntry):
156
"""See TreeEntry. This is a symlink in a working tree."""
158
def __eq__(self, other):
159
return (isinstance(other, TreeLink)
160
and other.__class__ == self.__class__)
162
def kind_character(self):
26
from errors import BzrCheckError
27
from trace import mutter
166
29
class WorkingTree(bzrlib.tree.Tree):
167
30
"""Working copy tree.
172
35
It is possible for a `WorkingTree` to have a filename which is
173
36
not listed in the Inventory and vice versa.
176
def __init__(self, basedir=u'.', branch=None):
177
"""Construct a WorkingTree for basedir.
179
If the branch is not supplied, it is opened automatically.
180
If the branch is supplied, it must be the branch for this basedir.
181
(branch.base is not cross checked, because for remote branches that
182
would be meaningless).
38
def __init__(self, basedir, inv):
184
39
from bzrlib.hashcache import HashCache
185
40
from bzrlib.trace import note, mutter
186
assert isinstance(basedir, basestring), \
187
"base directory %r is not a string" % basedir
189
branch = Branch.open(basedir)
190
assert isinstance(branch, Branch), \
191
"branch %r is not a Branch" % branch
193
self.basedir = realpath(basedir)
195
self._set_inventory(self.read_working_inventory())
43
self.basedir = basedir
44
self.path2id = inv.path2id
197
46
# update the whole cache up front and write to disk if anything changed;
198
47
# in the future we might want to do this more selectively
199
# two possible ways offer themselves : in self._unlock, write the cache
200
# if needed, or, when the cache sees a change, append it to the hash
201
# cache file, and have the parser take the most recent entry for a
203
48
hc = self._hashcache = HashCache(basedir)
207
52
if hc.needs_write:
208
53
mutter("write hc")
211
def _set_inventory(self, inv):
212
self._inventory = inv
213
self.path2id = self._inventory.path2id
216
def open_containing(path=None):
217
"""Open an existing working tree which has its root about path.
219
This probes for a working tree at path and searches upwards from there.
221
Basically we keep looking up until we find the control directory or
222
run into /. If there isn't one, raises NotBranchError.
223
TODO: give this a new exception.
224
If there is one, it is returned, along with the unused portion of path.
230
if path.find('://') != -1:
231
raise NotBranchError(path=path)
232
path = os.path.abspath(path)
236
return WorkingTree(path), tail
237
except NotBranchError:
240
tail = os.path.join(os.path.basename(path), tail)
242
tail = os.path.basename(path)
243
path = os.path.dirname(path)
244
# FIXME: top in windows is indicated how ???
245
if path == os.path.sep:
246
# reached the root, whatever that may be
247
raise NotBranchError(path=path)
58
if self._hashcache.needs_write:
59
self._hashcache.write()
249
62
def __iter__(self):
250
63
"""Iterate through file_ids for this tree.
255
68
inv = self._inventory
256
69
for path, ie in inv.iter_entries():
257
if bzrlib.osutils.lexists(self.abspath(path)):
70
if os.path.exists(self.abspath(path)):
260
74
def __repr__(self):
261
75
return "<%s of %s>" % (self.__class__.__name__,
262
76
getattr(self, 'basedir', None))
264
80
def abspath(self, filename):
265
81
return os.path.join(self.basedir, filename)
267
def relpath(self, abspath):
268
"""Return the local path portion from a given absolute path."""
269
return relpath(self.basedir, abspath)
271
83
def has_filename(self, filename):
272
return bzrlib.osutils.lexists(self.abspath(filename))
84
return os.path.exists(self.abspath(filename))
274
86
def get_file(self, file_id):
275
87
return self.get_file_byname(self.id2path(file_id))
277
89
def get_file_byname(self, filename):
278
90
return file(self.abspath(filename), 'rb')
280
def get_root_id(self):
281
"""Return the id of this trees root"""
282
inv = self.read_working_inventory()
283
return inv.root.file_id
285
92
def _get_store_filename(self, file_id):
286
## XXX: badly named; this is not in the store at all
287
return self.abspath(self.id2path(file_id))
290
def commit(self, *args, **kw):
291
from bzrlib.commit import Commit
292
Commit().commit(self.branch, *args, **kw)
293
self._set_inventory(self.read_working_inventory())
295
def id2abspath(self, file_id):
296
return self.abspath(self.id2path(file_id))
93
## XXX: badly named; this isn't in the store at all
94
return self.abspath(self.id2path(file_id))
298
97
def has_id(self, file_id):
299
98
# files that have been deleted are excluded
300
99
inv = self._inventory
301
100
if not inv.has_id(file_id):
303
102
path = inv.id2path(file_id)
304
return bzrlib.osutils.lexists(self.abspath(path))
103
return os.path.exists(self.abspath(path))
306
def has_or_had_id(self, file_id):
307
if file_id == self.inventory.root.file_id:
309
return self.inventory.has_id(file_id)
311
106
__contains__ = has_id
313
109
def get_file_size(self, file_id):
314
return os.path.getsize(self.id2abspath(file_id))
110
# is this still called?
111
raise NotImplementedError()
316
114
def get_file_sha1(self, file_id):
317
115
path = self._inventory.id2path(file_id)
318
116
return self._hashcache.get_sha1(path)
320
def is_executable(self, file_id):
322
return self._inventory[file_id].executable
324
path = self._inventory.id2path(file_id)
325
mode = os.lstat(self.abspath(path)).st_mode
326
return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
329
def add(self, files, ids=None):
330
"""Make files versioned.
332
Note that the command line normally calls smart_add instead,
333
which can automatically recurse.
335
This adds the files to the inventory, so that they will be
336
recorded by the next commit.
339
List of paths to add, relative to the base of the tree.
342
If set, use these instead of automatically generated ids.
343
Must be the same length as the list of files, but may
344
contain None for ids that are to be autogenerated.
346
TODO: Perhaps have an option to add the ids even if the files do
349
TODO: Perhaps callback with the ids and paths as they're added.
351
# TODO: Re-adding a file that is removed in the working copy
352
# should probably put it back with the previous ID.
353
if isinstance(files, basestring):
354
assert(ids is None or isinstance(ids, basestring))
360
ids = [None] * len(files)
362
assert(len(ids) == len(files))
364
inv = self.read_working_inventory()
365
for f,file_id in zip(files, ids):
366
if is_control_file(f):
367
raise BzrError("cannot add control file %s" % quotefn(f))
372
raise BzrError("cannot add top-level %r" % f)
374
fullpath = os.path.normpath(self.abspath(f))
377
kind = file_kind(fullpath)
379
# maybe something better?
380
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
382
if not InventoryEntry.versionable_kind(kind):
383
raise BzrError('cannot add: not a versionable file ('
384
'i.e. regular file, symlink or directory): %s' % quotefn(f))
387
file_id = gen_file_id(f)
388
inv.add_path(f, kind=kind, file_id=file_id)
390
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
391
self._write_inventory(inv)
394
def add_pending_merge(self, *revision_ids):
395
# TODO: Perhaps should check at this point that the
396
# history of the revision is actually present?
397
p = self.pending_merges()
399
for rev_id in revision_ids:
405
self.set_pending_merges(p)
407
def pending_merges(self):
408
"""Return a list of pending merges.
410
These are revisions that have been merged into the working
411
directory but not yet committed.
413
cfn = self.branch._rel_controlfilename('pending-merges')
414
if not self.branch._transport.has(cfn):
417
for l in self.branch.controlfile('pending-merges', 'r').readlines():
418
p.append(l.rstrip('\n'))
422
def set_pending_merges(self, rev_list):
423
self.branch.put_controlfile('pending-merges', '\n'.join(rev_list))
425
def get_symlink_target(self, file_id):
426
return os.readlink(self.id2abspath(file_id))
428
119
def file_class(self, filename):
429
120
if self.path2id(filename):
503
184
for ff in descend(fp, f_ie.file_id, fap):
506
for f in descend(u'', inv.root.file_id, self.basedir):
187
for f in descend('', inv.root.file_id, self.basedir):
510
def move(self, from_paths, to_name):
513
to_name must exist in the inventory.
515
If to_name exists and is a directory, the files are moved into
516
it, keeping their old names.
518
Note that to_name is only the last component of the new name;
519
this doesn't change the directory.
521
This returns a list of (from_path, to_path) pairs for each
525
## TODO: Option to move IDs only
526
assert not isinstance(from_paths, basestring)
528
to_abs = self.abspath(to_name)
529
if not isdir(to_abs):
530
raise BzrError("destination %r is not a directory" % to_abs)
531
if not self.has_filename(to_name):
532
raise BzrError("destination %r not in working directory" % to_abs)
533
to_dir_id = inv.path2id(to_name)
534
if to_dir_id == None and to_name != '':
535
raise BzrError("destination %r is not a versioned directory" % to_name)
536
to_dir_ie = inv[to_dir_id]
537
if to_dir_ie.kind not in ('directory', 'root_directory'):
538
raise BzrError("destination %r is not a directory" % to_abs)
540
to_idpath = inv.get_idpath(to_dir_id)
543
if not self.has_filename(f):
544
raise BzrError("%r does not exist in working tree" % f)
545
f_id = inv.path2id(f)
547
raise BzrError("%r is not versioned" % f)
548
name_tail = splitpath(f)[-1]
549
dest_path = appendpath(to_name, name_tail)
550
if self.has_filename(dest_path):
551
raise BzrError("destination %r already exists" % dest_path)
552
if f_id in to_idpath:
553
raise BzrError("can't move %r to a subdirectory of itself" % f)
555
# OK, so there's a race here, it's possible that someone will
556
# create a file in this interval and then the rename might be
557
# left half-done. But we should have caught most problems.
558
orig_inv = deepcopy(self.inventory)
561
name_tail = splitpath(f)[-1]
562
dest_path = appendpath(to_name, name_tail)
563
result.append((f, dest_path))
564
inv.rename(inv.path2id(f), to_dir_id, name_tail)
566
rename(self.abspath(f), self.abspath(dest_path))
568
raise BzrError("failed to rename %r to %r: %s" %
569
(f, dest_path, e[1]),
570
["rename rolled back"])
572
# restore the inventory on error
573
self._set_inventory(orig_inv)
575
self._write_inventory(inv)
579
def rename_one(self, from_rel, to_rel):
582
This can change the directory or the filename or both.
585
if not self.has_filename(from_rel):
586
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
587
if self.has_filename(to_rel):
588
raise BzrError("can't rename: new working file %r already exists" % to_rel)
590
file_id = inv.path2id(from_rel)
592
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
595
from_parent = entry.parent_id
596
from_name = entry.name
598
if inv.path2id(to_rel):
599
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
601
to_dir, to_tail = os.path.split(to_rel)
602
to_dir_id = inv.path2id(to_dir)
603
if to_dir_id == None and to_dir != '':
604
raise BzrError("can't determine destination directory id for %r" % to_dir)
606
mutter("rename_one:")
607
mutter(" file_id {%s}" % file_id)
608
mutter(" from_rel %r" % from_rel)
609
mutter(" to_rel %r" % to_rel)
610
mutter(" to_dir %r" % to_dir)
611
mutter(" to_dir_id {%s}" % to_dir_id)
613
inv.rename(file_id, to_dir_id, to_tail)
615
from_abs = self.abspath(from_rel)
616
to_abs = self.abspath(to_rel)
618
rename(from_abs, to_abs)
620
inv.rename(file_id, from_parent, from_name)
621
raise BzrError("failed to rename %r to %r: %s"
622
% (from_abs, to_abs, e[1]),
623
["rename rolled back"])
624
self._write_inventory(inv)
627
192
def unknowns(self):
628
"""Return all unknown files.
630
These are files in the working directory that are not versioned or
631
control files or ignored.
633
>>> from bzrlib.branch import ScratchBranch
634
>>> b = ScratchBranch(files=['foo', 'foo~'])
635
>>> tree = WorkingTree(b.base, b)
636
>>> map(str, tree.unknowns())
639
>>> list(b.unknowns())
641
>>> tree.remove('foo')
642
>>> list(b.unknowns())
645
193
for subp in self.extras():
646
194
if not self.is_ignored(subp):
649
def iter_conflicts(self):
651
for path in (s[0] for s in self.list_files()):
652
stem = get_conflicted_stem(path)
655
if stem not in conflicted:
660
def pull(self, source, overwrite=False):
661
from bzrlib.merge import merge_inner
664
old_revision_history = self.branch.revision_history()
665
count = self.branch.pull(source, overwrite)
666
new_revision_history = self.branch.revision_history()
667
if new_revision_history != old_revision_history:
668
if len(old_revision_history):
669
other_revision = old_revision_history[-1]
671
other_revision = None
672
merge_inner(self.branch,
673
self.branch.basis_tree(),
674
self.branch.revision_tree(other_revision))
679
198
def extras(self):
680
199
"""Yield all unknown files in this WorkingTree.
770
def kind(self, file_id):
771
return file_kind(self.id2abspath(file_id))
774
"""See Branch.lock_read, and WorkingTree.unlock."""
775
return self.branch.lock_read()
777
def lock_write(self):
778
"""See Branch.lock_write, and WorkingTree.unlock."""
779
return self.branch.lock_write()
781
def _basis_inventory_name(self, revision_id):
782
return 'basis-inventory.%s' % revision_id
784
def set_last_revision(self, new_revision, old_revision=None):
787
path = self._basis_inventory_name(old_revision)
788
path = self.branch._rel_controlfilename(path)
789
self.branch._transport.delete(path)
793
xml = self.branch.get_inventory_xml(new_revision)
794
path = self._basis_inventory_name(new_revision)
795
self.branch.put_controlfile(path, xml)
796
except WeaveRevisionNotPresent:
799
def read_basis_inventory(self, revision_id):
800
"""Read the cached basis inventory."""
801
path = self._basis_inventory_name(revision_id)
802
return self.branch.controlfile(path, 'r').read()
805
def read_working_inventory(self):
806
"""Read the working inventory."""
807
# ElementTree does its own conversion from UTF-8, so open in
809
f = self.branch.controlfile('inventory', 'rb')
810
return bzrlib.xml5.serializer_v5.read_inventory(f)
813
def remove(self, files, verbose=False):
814
"""Remove nominated files from the working inventory..
816
This does not remove their text. This does not run on XXX on what? RBC
818
TODO: Refuse to remove modified files unless --force is given?
820
TODO: Do something useful with directories.
822
TODO: Should this remove the text or not? Tough call; not
823
removing may be useful and the user can just use use rm, and
824
is the opposite of add. Removing it is consistent with most
825
other tools. Maybe an option.
827
## TODO: Normalize names
828
## TODO: Remove nested loops; better scalability
829
if isinstance(files, basestring):
834
# do this before any modifications
838
# TODO: Perhaps make this just a warning, and continue?
839
# This tends to happen when
840
raise NotVersionedError(path=f)
841
mutter("remove inventory entry %s {%s}", quotefn(f), fid)
843
# having remove it, it must be either ignored or unknown
844
if self.is_ignored(f):
848
show_status(new_status, inv[fid].kind, quotefn(f))
851
self._write_inventory(inv)
854
def revert(self, filenames, old_tree=None, backups=True):
855
from bzrlib.merge import merge_inner
857
old_tree = self.branch.basis_tree()
858
merge_inner(self.branch, old_tree,
859
self, ignore_zero=True,
860
backup_files=backups,
861
interesting_files=filenames)
862
if not len(filenames):
863
self.set_pending_merges([])
866
def set_inventory(self, new_inventory_list):
867
from bzrlib.inventory import (Inventory,
872
inv = Inventory(self.get_root_id())
873
for path, file_id, parent, kind in new_inventory_list:
874
name = os.path.basename(path)
877
# fixme, there should be a factory function inv,add_??
878
if kind == 'directory':
879
inv.add(InventoryDirectory(file_id, name, parent))
881
inv.add(InventoryFile(file_id, name, parent))
882
elif kind == 'symlink':
883
inv.add(InventoryLink(file_id, name, parent))
885
raise BzrError("unknown kind %r" % kind)
886
self._write_inventory(inv)
889
def set_root_id(self, file_id):
890
"""Set the root id for this tree."""
891
inv = self.read_working_inventory()
892
orig_root_id = inv.root.file_id
893
del inv._byid[inv.root.file_id]
894
inv.root.file_id = file_id
895
inv._byid[inv.root.file_id] = inv.root
898
if entry.parent_id in (None, orig_root_id):
899
entry.parent_id = inv.root.file_id
900
self._write_inventory(inv)
903
"""See Branch.unlock.
905
WorkingTree locking just uses the Branch locking facilities.
906
This is current because all working trees have an embedded branch
907
within them. IF in the future, we were to make branch data shareable
908
between multiple working trees, i.e. via shared storage, then we
909
would probably want to lock both the local tree, and the branch.
911
return self.branch.unlock()
914
def _write_inventory(self, inv):
915
"""Write inventory as the current inventory."""
916
from cStringIO import StringIO
917
from bzrlib.atomicfile import AtomicFile
919
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
921
f = AtomicFile(self.branch.controlfilename('inventory'))
927
self._set_inventory(inv)
928
mutter('wrote working inventory')
931
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
932
def get_conflicted_stem(path):
933
for suffix in CONFLICT_SUFFIXES:
934
if path.endswith(suffix):
935
return path[:-len(suffix)]
b'\\ No newline at end of file'