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
58
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')
62
111
class TreeEntry(object):
63
112
"""An entry that implements the minium interface used by commands.
159
208
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)
162
249
def __iter__(self):
163
250
"""Iterate through file_ids for this tree.
199
283
return inv.root.file_id
201
285
def _get_store_filename(self, file_id):
202
## XXX: badly named; this isn't in the store at all
286
## XXX: badly named; this is not in the store at all
203
287
return self.abspath(self.id2path(file_id))
205
289
@needs_write_lock
206
290
def commit(self, *args, **kw):
207
291
from bzrlib.commit import Commit
208
292
Commit().commit(self.branch, *args, **kw)
209
self._inventory = self.read_working_inventory()
293
self._set_inventory(self.read_working_inventory())
211
295
def id2abspath(self, file_id):
212
296
return self.abspath(self.id2path(file_id))
215
298
def has_id(self, file_id):
216
299
# files that have been deleted are excluded
217
300
inv = self._inventory
245
326
return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
247
328
@needs_write_lock
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)
248
394
def add_pending_merge(self, *revision_ids):
249
395
# TODO: Perhaps should check at this point that the
250
396
# history of the revision is actually present?
357
503
for ff in descend(fp, f_ie.file_id, fap):
360
for f in descend('', inv.root.file_id, self.basedir):
506
for f in descend(u'', 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)
365
627
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())
366
645
for subp in self.extras():
367
646
if not self.is_ignored(subp):
499
778
"""See Branch.lock_write, and WorkingTree.unlock."""
500
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()
503
805
def read_working_inventory(self):
504
806
"""Read the working inventory."""