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 Branch.working_tree():
32
# TODO: Don't allow WorkingTrees to be constructed for remote branches if
35
# 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.
49
from bzrlib.branch import Branch, needs_read_lock, needs_write_lock, quotefn
51
from bzrlib.osutils import (appendpath,
57
from bzrlib.errors import BzrCheckError, DivergedBranches, NotVersionedError
58
from bzrlib.trace import mutter
62
class TreeEntry(object):
63
"""An entry that implements the minium interface used by commands.
65
This needs further inspection, it may be better to have
66
InventoryEntries without ids - though that seems wrong. For now,
67
this is a parallel hierarchy to InventoryEntry, and needs to become
68
one of several things: decorates to that hierarchy, children of, or
70
Another note is that these objects are currently only used when there is
71
no InventoryEntry available - i.e. for unversioned objects.
72
Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
75
def __eq__(self, other):
76
# yes, this us ugly, TODO: best practice __eq__ style.
77
return (isinstance(other, TreeEntry)
78
and other.__class__ == self.__class__)
80
def kind_character(self):
84
class TreeDirectory(TreeEntry):
85
"""See TreeEntry. This is a directory in a working tree."""
87
def __eq__(self, other):
88
return (isinstance(other, TreeDirectory)
89
and other.__class__ == self.__class__)
91
def kind_character(self):
95
class TreeFile(TreeEntry):
96
"""See TreeEntry. This is a regular file in a working tree."""
98
def __eq__(self, other):
99
return (isinstance(other, TreeFile)
100
and other.__class__ == self.__class__)
102
def kind_character(self):
106
class TreeLink(TreeEntry):
107
"""See TreeEntry. This is a symlink in a working tree."""
109
def __eq__(self, other):
110
return (isinstance(other, TreeLink)
111
and other.__class__ == self.__class__)
113
def kind_character(self):
117
class WorkingTree(bzrlib.tree.Tree):
118
"""Working copy tree.
120
The inventory is held in the `Branch` working-inventory, and the
121
files are in a directory on disk.
123
It is possible for a `WorkingTree` to have a filename which is
124
not listed in the Inventory and vice versa.
127
def __init__(self, basedir, branch=None):
128
"""Construct a WorkingTree for basedir.
130
If the branch is not supplied, it is opened automatically.
131
If the branch is supplied, it must be the branch for this basedir.
132
(branch.base is not cross checked, because for remote branches that
133
would be meaningless).
135
from bzrlib.hashcache import HashCache
136
from bzrlib.trace import note, mutter
137
assert isinstance(basedir, basestring), \
138
"base directory %r is not a string" % basedir
140
branch = Branch.open(basedir)
141
assert isinstance(branch, Branch), \
142
"branch %r is not a Branch" % branch
144
self.basedir = basedir
145
self._inventory = self.read_working_inventory()
146
self.path2id = self._inventory.path2id
148
# update the whole cache up front and write to disk if anything changed;
149
# in the future we might want to do this more selectively
150
# two possible ways offer themselves : in self._unlock, write the cache
151
# if needed, or, when the cache sees a change, append it to the hash
152
# cache file, and have the parser take the most recent entry for a
154
hc = self._hashcache = HashCache(basedir)
163
"""Iterate through file_ids for this tree.
165
file_ids are in a WorkingTree if they are in the working inventory
166
and the working file exists.
168
inv = self._inventory
169
for path, ie in inv.iter_entries():
170
if bzrlib.osutils.lexists(self.abspath(path)):
175
return "<%s of %s>" % (self.__class__.__name__,
176
getattr(self, 'basedir', None))
180
def abspath(self, filename):
181
return os.path.join(self.basedir, filename)
183
def relpath(self, abspath):
184
"""Return the local path portion from a given absolute path."""
185
return relpath(self.basedir, abspath)
187
def has_filename(self, filename):
188
return bzrlib.osutils.lexists(self.abspath(filename))
190
def get_file(self, file_id):
191
return self.get_file_byname(self.id2path(file_id))
193
def get_file_byname(self, filename):
194
return file(self.abspath(filename), 'rb')
196
def get_root_id(self):
197
"""Return the id of this trees root"""
198
inv = self.read_working_inventory()
199
return inv.root.file_id
201
def _get_store_filename(self, file_id):
202
## XXX: badly named; this isn't in the store at all
203
return self.abspath(self.id2path(file_id))
206
def id2abspath(self, file_id):
207
return self.abspath(self.id2path(file_id))
210
def has_id(self, file_id):
211
# files that have been deleted are excluded
212
inv = self._inventory
213
if not inv.has_id(file_id):
215
path = inv.id2path(file_id)
216
return bzrlib.osutils.lexists(self.abspath(path))
218
def has_or_had_id(self, file_id):
219
if file_id == self.inventory.root.file_id:
221
return self.inventory.has_id(file_id)
223
__contains__ = has_id
226
def get_file_size(self, file_id):
227
return os.path.getsize(self.id2abspath(file_id))
229
def get_file_sha1(self, file_id):
230
path = self._inventory.id2path(file_id)
231
return self._hashcache.get_sha1(path)
234
def is_executable(self, file_id):
236
return self._inventory[file_id].executable
238
path = self._inventory.id2path(file_id)
239
mode = os.lstat(self.abspath(path)).st_mode
240
return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
242
def pending_merges(self):
243
"""Return a list of pending merges.
245
These are revisions that have been merged into the working
246
directory but not yet committed.
248
cfn = self.branch._rel_controlfilename('pending-merges')
249
if not self.branch._transport.has(cfn):
252
for l in self.branch.controlfile('pending-merges', 'r').readlines():
253
p.append(l.rstrip('\n'))
256
def get_symlink_target(self, file_id):
257
return os.readlink(self.id2abspath(file_id))
259
def file_class(self, filename):
260
if self.path2id(filename):
262
elif self.is_ignored(filename):
268
def list_files(self):
269
"""Recursively list all files as (path, class, kind, id).
271
Lists, but does not descend into unversioned directories.
273
This does not include files that have been deleted in this
276
Skips the control directory.
278
inv = self._inventory
280
def descend(from_dir_relpath, from_dir_id, dp):
284
## TODO: If we find a subdirectory with its own .bzr
285
## directory, then that is a separate tree and we
286
## should exclude it.
287
if bzrlib.BZRDIR == f:
291
fp = appendpath(from_dir_relpath, f)
294
fap = appendpath(dp, f)
296
f_ie = inv.get_child(from_dir_id, f)
299
elif self.is_ignored(fp):
308
raise BzrCheckError("file %r entered as kind %r id %r, "
310
% (fap, f_ie.kind, f_ie.file_id, fk))
312
# make a last minute entry
316
if fk == 'directory':
317
entry = TreeDirectory()
320
elif fk == 'symlink':
325
yield fp, c, fk, (f_ie and f_ie.file_id), entry
327
if fk != 'directory':
331
# don't descend unversioned directories
334
for ff in descend(fp, f_ie.file_id, fap):
337
for f in descend('', inv.root.file_id, self.basedir):
343
for subp in self.extras():
344
if not self.is_ignored(subp):
347
def iter_conflicts(self):
349
for path in (s[0] for s in self.list_files()):
350
stem = get_conflicted_stem(path)
353
if stem not in conflicted:
358
def pull(self, source, overwrite=False):
359
from bzrlib.merge import merge_inner
362
old_revision_history = self.branch.revision_history()
363
self.branch.pull(source, overwrite)
364
new_revision_history = self.branch.revision_history()
365
if new_revision_history != old_revision_history:
366
if len(old_revision_history):
367
other_revision = old_revision_history[-1]
369
other_revision = None
370
merge_inner(self.branch,
371
self.branch.basis_tree(),
372
self.branch.revision_tree(other_revision))
377
"""Yield all unknown files in this WorkingTree.
379
If there are any unknown directories then only the directory is
380
returned, not all its children. But if there are unknown files
381
under a versioned subdirectory, they are returned.
383
Currently returned depth-first, sorted by name within directories.
385
## TODO: Work from given directory downwards
386
for path, dir_entry in self.inventory.directories():
387
mutter("search for unknowns in %r" % path)
388
dirabs = self.abspath(path)
389
if not isdir(dirabs):
390
# e.g. directory deleted
394
for subf in os.listdir(dirabs):
396
and (subf not in dir_entry.children)):
401
subp = appendpath(path, subf)
405
def ignored_files(self):
406
"""Yield list of PATH, IGNORE_PATTERN"""
407
for subp in self.extras():
408
pat = self.is_ignored(subp)
413
def get_ignore_list(self):
414
"""Return list of ignore patterns.
416
Cached in the Tree object after the first call.
418
if hasattr(self, '_ignorelist'):
419
return self._ignorelist
421
l = bzrlib.DEFAULT_IGNORE[:]
422
if self.has_filename(bzrlib.IGNORE_FILENAME):
423
f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
424
l.extend([line.rstrip("\n\r") for line in f.readlines()])
429
def is_ignored(self, filename):
430
r"""Check whether the filename matches an ignore pattern.
432
Patterns containing '/' or '\' need to match the whole path;
433
others match against only the last component.
435
If the file is ignored, returns the pattern which caused it to
436
be ignored, otherwise None. So this can simply be used as a
437
boolean if desired."""
439
# TODO: Use '**' to match directories, and other extended
440
# globbing stuff from cvs/rsync.
442
# XXX: fnmatch is actually not quite what we want: it's only
443
# approximately the same as real Unix fnmatch, and doesn't
444
# treat dotfiles correctly and allows * to match /.
445
# Eventually it should be replaced with something more
448
for pat in self.get_ignore_list():
449
if '/' in pat or '\\' in pat:
451
# as a special case, you can put ./ at the start of a
452
# pattern; this is good to match in the top-level
455
if (pat[:2] == './') or (pat[:2] == '.\\'):
459
if fnmatch.fnmatchcase(filename, newpat):
462
if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
467
def kind(self, file_id):
468
return file_kind(self.id2abspath(file_id))
471
"""See Branch.lock_read, and WorkingTree.unlock."""
472
return self.branch.lock_read()
474
def lock_write(self):
475
"""See Branch.lock_write, and WorkingTree.unlock."""
476
return self.branch.lock_write()
479
def read_working_inventory(self):
480
"""Read the working inventory."""
481
# ElementTree does its own conversion from UTF-8, so open in
483
f = self.branch.controlfile('inventory', 'rb')
484
return bzrlib.xml5.serializer_v5.read_inventory(f)
487
def remove(self, files, verbose=False):
488
"""Remove nominated files from the working inventory..
490
This does not remove their text. This does not run on XXX on what? RBC
492
TODO: Refuse to remove modified files unless --force is given?
494
TODO: Do something useful with directories.
496
TODO: Should this remove the text or not? Tough call; not
497
removing may be useful and the user can just use use rm, and
498
is the opposite of add. Removing it is consistent with most
499
other tools. Maybe an option.
501
## TODO: Normalize names
502
## TODO: Remove nested loops; better scalability
503
if isinstance(files, basestring):
508
# do this before any modifications
512
# TODO: Perhaps make this just a warning, and continue?
513
# This tends to happen when
514
raise NotVersionedError(path=f)
515
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
517
# having remove it, it must be either ignored or unknown
518
if self.is_ignored(f):
522
show_status(new_status, inv[fid].kind, quotefn(f))
525
self._write_inventory(inv)
528
def revert(self, filenames, old_tree=None, backups=True):
529
from bzrlib.merge import merge_inner
531
old_tree = self.branch.basis_tree()
532
merge_inner(self.branch, old_tree,
533
self, ignore_zero=True,
534
backup_files=backups,
535
interesting_files=filenames)
536
if not len(filenames):
537
self.branch.set_pending_merges([])
540
def set_inventory(self, new_inventory_list):
541
from bzrlib.inventory import (Inventory,
546
inv = Inventory(self.get_root_id())
547
for path, file_id, parent, kind in new_inventory_list:
548
name = os.path.basename(path)
551
# fixme, there should be a factory function inv,add_??
552
if kind == 'directory':
553
inv.add(InventoryDirectory(file_id, name, parent))
555
inv.add(InventoryFile(file_id, name, parent))
556
elif kind == 'symlink':
557
inv.add(InventoryLink(file_id, name, parent))
559
raise BzrError("unknown kind %r" % kind)
560
self._write_inventory(inv)
563
def set_root_id(self, file_id):
564
"""Set the root id for this tree."""
565
inv = self.read_working_inventory()
566
orig_root_id = inv.root.file_id
567
del inv._byid[inv.root.file_id]
568
inv.root.file_id = file_id
569
inv._byid[inv.root.file_id] = inv.root
572
if entry.parent_id in (None, orig_root_id):
573
entry.parent_id = inv.root.file_id
574
self._write_inventory(inv)
577
"""See Branch.unlock.
579
WorkingTree locking just uses the Branch locking facilities.
580
This is current because all working trees have an embedded branch
581
within them. IF in the future, we were to make branch data shareable
582
between multiple working trees, i.e. via shared storage, then we
583
would probably want to lock both the local tree, and the branch.
585
return self.branch.unlock()
588
def _write_inventory(self, inv):
589
"""Write inventory as the current inventory."""
590
from cStringIO import StringIO
591
from bzrlib.atomicfile import AtomicFile
593
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
595
f = AtomicFile(self.branch.controlfilename('inventory'))
601
mutter('wrote working inventory')
604
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
605
def get_conflicted_stem(path):
606
for suffix in CONFLICT_SUFFIXES:
607
if path.endswith(suffix):
608
return path[:-len(suffix)]