42
42
# copy, and making sure there's only one WorkingTree for any directory on disk.
43
43
# At the momenthey may alias the inventory and have old copies of it in memory.
45
from copy import deepcopy
49
from bzrlib.branch import Branch, needs_read_lock, needs_write_lock, quotefn
50
from bzrlib.branch import (Branch,
55
from bzrlib.errors import (BzrCheckError,
58
WeaveRevisionNotPresent,
61
from bzrlib.inventory import InventoryEntry
51
62
from bzrlib.osutils import (appendpath,
57
from bzrlib.errors import BzrCheckError, DivergedBranches, NotVersionedError
76
from bzrlib.textui import show_status
58
78
from bzrlib.trace import mutter
82
def gen_file_id(name):
83
"""Return new file id.
85
This should probably generate proper UUIDs, but for the moment we
86
cope with just randomness because running uuidgen every time is
89
from binascii import hexlify
96
idx = name.rfind('\\')
100
# make it not a hidden file
101
name = name.lstrip('.')
103
# remove any wierd characters; we don't escape them but rather
105
name = re.sub(r'[^\w.]', '', name)
107
s = hexlify(rand_bytes(8))
108
return '-'.join((name, compact_date(time()), s))
112
"""Return a new tree-root file id."""
113
return gen_file_id('TREE_ROOT')
62
116
class TreeEntry(object):
63
117
"""An entry that implements the minium interface used by commands.
159
211
mutter("write hc")
214
self._set_inventory(self.read_working_inventory())
216
def _set_inventory(self, inv):
217
self._inventory = inv
218
self.path2id = self._inventory.path2id
221
def open_containing(path=None):
222
"""Open an existing working tree which has its root about path.
224
This probes for a working tree at path and searches upwards from there.
226
Basically we keep looking up until we find the control directory or
227
run into /. If there isn't one, raises NotBranchError.
228
TODO: give this a new exception.
229
If there is one, it is returned, along with the unused portion of path.
235
if path.find('://') != -1:
236
raise NotBranchError(path=path)
241
return WorkingTree(path), tail
242
except NotBranchError:
245
tail = pathjoin(os.path.basename(path), tail)
247
tail = os.path.basename(path)
249
path = os.path.dirname(path)
251
# reached the root, whatever that may be
252
raise NotBranchError(path=path)
162
254
def __iter__(self):
163
255
"""Iterate through file_ids for this tree.
170
262
if bzrlib.osutils.lexists(self.abspath(path)):
174
265
def __repr__(self):
175
266
return "<%s of %s>" % (self.__class__.__name__,
176
267
getattr(self, 'basedir', None))
180
269
def abspath(self, filename):
181
return os.path.join(self.basedir, filename)
270
return pathjoin(self.basedir, filename)
183
def relpath(self, abspath):
272
def relpath(self, abs):
184
273
"""Return the local path portion from a given absolute path."""
185
return relpath(self.basedir, abspath)
274
return relpath(self.basedir, abs)
187
276
def has_filename(self, filename):
188
277
return bzrlib.osutils.lexists(self.abspath(filename))
199
288
return inv.root.file_id
201
290
def _get_store_filename(self, file_id):
202
## XXX: badly named; this isn't in the store at all
291
## XXX: badly named; this is not in the store at all
203
292
return self.abspath(self.id2path(file_id))
205
294
@needs_write_lock
206
295
def commit(self, *args, **kw):
207
296
from bzrlib.commit import Commit
208
297
Commit().commit(self.branch, *args, **kw)
209
self._inventory = self.read_working_inventory()
298
self._set_inventory(self.read_working_inventory())
211
300
def id2abspath(self, file_id):
212
301
return self.abspath(self.id2path(file_id))
215
303
def has_id(self, file_id):
216
304
# files that have been deleted are excluded
217
305
inv = self._inventory
245
332
return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
247
334
@needs_write_lock
335
def add(self, files, ids=None):
336
"""Make files versioned.
338
Note that the command line normally calls smart_add instead,
339
which can automatically recurse.
341
This adds the files to the inventory, so that they will be
342
recorded by the next commit.
345
List of paths to add, relative to the base of the tree.
348
If set, use these instead of automatically generated ids.
349
Must be the same length as the list of files, but may
350
contain None for ids that are to be autogenerated.
352
TODO: Perhaps have an option to add the ids even if the files do
355
TODO: Perhaps callback with the ids and paths as they're added.
357
# TODO: Re-adding a file that is removed in the working copy
358
# should probably put it back with the previous ID.
359
if isinstance(files, basestring):
360
assert(ids is None or isinstance(ids, basestring))
366
ids = [None] * len(files)
368
assert(len(ids) == len(files))
370
inv = self.read_working_inventory()
371
for f,file_id in zip(files, ids):
372
if is_control_file(f):
373
raise BzrError("cannot add control file %s" % quotefn(f))
378
raise BzrError("cannot add top-level %r" % f)
380
fullpath = normpath(self.abspath(f))
383
kind = file_kind(fullpath)
385
# maybe something better?
386
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
388
if not InventoryEntry.versionable_kind(kind):
389
raise BzrError('cannot add: not a versionable file ('
390
'i.e. regular file, symlink or directory): %s' % quotefn(f))
393
file_id = gen_file_id(f)
394
inv.add_path(f, kind=kind, file_id=file_id)
396
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
397
self._write_inventory(inv)
248
400
def add_pending_merge(self, *revision_ids):
249
401
# TODO: Perhaps should check at this point that the
250
402
# history of the revision is actually present?
357
509
for ff in descend(fp, f_ie.file_id, fap):
360
for f in descend('', inv.root.file_id, self.basedir):
512
for f in descend(u'', inv.root.file_id, self.basedir):
516
def move(self, from_paths, to_name):
519
to_name must exist in the inventory.
521
If to_name exists and is a directory, the files are moved into
522
it, keeping their old names.
524
Note that to_name is only the last component of the new name;
525
this doesn't change the directory.
527
This returns a list of (from_path, to_path) pairs for each
531
## TODO: Option to move IDs only
532
assert not isinstance(from_paths, basestring)
534
to_abs = self.abspath(to_name)
535
if not isdir(to_abs):
536
raise BzrError("destination %r is not a directory" % to_abs)
537
if not self.has_filename(to_name):
538
raise BzrError("destination %r not in working directory" % to_abs)
539
to_dir_id = inv.path2id(to_name)
540
if to_dir_id == None and to_name != '':
541
raise BzrError("destination %r is not a versioned directory" % to_name)
542
to_dir_ie = inv[to_dir_id]
543
if to_dir_ie.kind not in ('directory', 'root_directory'):
544
raise BzrError("destination %r is not a directory" % to_abs)
546
to_idpath = inv.get_idpath(to_dir_id)
549
if not self.has_filename(f):
550
raise BzrError("%r does not exist in working tree" % f)
551
f_id = inv.path2id(f)
553
raise BzrError("%r is not versioned" % f)
554
name_tail = splitpath(f)[-1]
555
dest_path = appendpath(to_name, name_tail)
556
if self.has_filename(dest_path):
557
raise BzrError("destination %r already exists" % dest_path)
558
if f_id in to_idpath:
559
raise BzrError("can't move %r to a subdirectory of itself" % f)
561
# OK, so there's a race here, it's possible that someone will
562
# create a file in this interval and then the rename might be
563
# left half-done. But we should have caught most problems.
564
orig_inv = deepcopy(self.inventory)
567
name_tail = splitpath(f)[-1]
568
dest_path = appendpath(to_name, name_tail)
569
result.append((f, dest_path))
570
inv.rename(inv.path2id(f), to_dir_id, name_tail)
572
rename(self.abspath(f), self.abspath(dest_path))
574
raise BzrError("failed to rename %r to %r: %s" %
575
(f, dest_path, e[1]),
576
["rename rolled back"])
578
# restore the inventory on error
579
self._set_inventory(orig_inv)
581
self._write_inventory(inv)
585
def rename_one(self, from_rel, to_rel):
588
This can change the directory or the filename or both.
591
if not self.has_filename(from_rel):
592
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
593
if self.has_filename(to_rel):
594
raise BzrError("can't rename: new working file %r already exists" % to_rel)
596
file_id = inv.path2id(from_rel)
598
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
601
from_parent = entry.parent_id
602
from_name = entry.name
604
if inv.path2id(to_rel):
605
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
607
to_dir, to_tail = os.path.split(to_rel)
608
to_dir_id = inv.path2id(to_dir)
609
if to_dir_id == None and to_dir != '':
610
raise BzrError("can't determine destination directory id for %r" % to_dir)
612
mutter("rename_one:")
613
mutter(" file_id {%s}" % file_id)
614
mutter(" from_rel %r" % from_rel)
615
mutter(" to_rel %r" % to_rel)
616
mutter(" to_dir %r" % to_dir)
617
mutter(" to_dir_id {%s}" % to_dir_id)
619
inv.rename(file_id, to_dir_id, to_tail)
621
from_abs = self.abspath(from_rel)
622
to_abs = self.abspath(to_rel)
624
rename(from_abs, to_abs)
626
inv.rename(file_id, from_parent, from_name)
627
raise BzrError("failed to rename %r to %r: %s"
628
% (from_abs, to_abs, e[1]),
629
["rename rolled back"])
630
self._write_inventory(inv)
365
633
def unknowns(self):
634
"""Return all unknown files.
636
These are files in the working directory that are not versioned or
637
control files or ignored.
639
>>> from bzrlib.branch import ScratchBranch
640
>>> b = ScratchBranch(files=['foo', 'foo~'])
641
>>> tree = WorkingTree(b.base, b)
642
>>> map(str, tree.unknowns())
645
>>> list(b.unknowns())
647
>>> tree.remove('foo')
648
>>> list(b.unknowns())
366
651
for subp in self.extras():
367
652
if not self.is_ignored(subp):
498
784
"""See Branch.lock_write, and WorkingTree.unlock."""
499
785
return self.branch.lock_write()
787
def _basis_inventory_name(self, revision_id):
788
return 'basis-inventory.%s' % revision_id
790
def set_last_revision(self, new_revision, old_revision=None):
793
path = self._basis_inventory_name(old_revision)
794
path = self.branch._rel_controlfilename(path)
795
self.branch._transport.delete(path)
799
xml = self.branch.get_inventory_xml(new_revision)
800
path = self._basis_inventory_name(new_revision)
801
self.branch.put_controlfile(path, xml)
802
except WeaveRevisionNotPresent:
805
def read_basis_inventory(self, revision_id):
806
"""Read the cached basis inventory."""
807
path = self._basis_inventory_name(revision_id)
808
return self.branch.controlfile(path, 'r').read()
502
811
def read_working_inventory(self):
503
812
"""Read the working inventory."""