/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: Robert Collins
  • Date: 2005-10-29 23:48:45 UTC
  • Revision ID: robertc@robertcollins.net-20051029234845-7ae4e7d118bdd3ed
Implement a 'bzr push' command, with saved locations; update diff to return 1.

    * 'bzr diff' now returns 1 when there are changes in the working 
      tree.

    * 'bzr push' now exists and can push changes to a remote location. 
      This uses the transport infrastructure, and can store the remote
      location in the ~/.bazaar/branches.conf configuration file.

    * WorkingTree.pull has been split across Branch and WorkingTree,
      to allow Branch only pulls.

    * commands.display_command now returns the result of the decorated 
      function.

    * LocationConfig now has a set_user_option(key, value) call to save
      a setting in its matching location section (a new one is created
      if needed).

    * Branch has two new methods, get_push_location and set_push_location
      to respectively, get and set the push location.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Canonical Ltd
 
2
 
 
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.
 
7
 
 
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.
 
12
 
 
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
 
16
 
 
17
"""WorkingTree object and friends.
 
18
 
 
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.
 
24
 
 
25
At the moment every WorkingTree has its own branch.  Remote
 
26
WorkingTrees aren't supported.
 
27
 
 
28
To get a WorkingTree, call Branch.working_tree():
 
29
"""
 
30
 
 
31
 
 
32
# TODO: Don't allow WorkingTrees to be constructed for remote branches if 
 
33
# they don't work.
 
34
 
 
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.
 
38
 
 
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.
 
44
 
 
45
import os
 
46
import stat
 
47
import fnmatch
 
48
 
 
49
from bzrlib.branch import Branch, needs_read_lock, needs_write_lock, quotefn
 
50
import bzrlib.tree
 
51
from bzrlib.osutils import appendpath, file_kind, isdir, splitpath, relpath
 
52
from bzrlib.errors import BzrCheckError, DivergedBranches, NotVersionedError
 
53
from bzrlib.trace import mutter
 
54
 
 
55
 
 
56
class TreeEntry(object):
 
57
    """An entry that implements the minium interface used by commands.
 
58
 
 
59
    This needs further inspection, it may be better to have 
 
60
    InventoryEntries without ids - though that seems wrong. For now,
 
61
    this is a parallel hierarchy to InventoryEntry, and needs to become
 
62
    one of several things: decorates to that hierarchy, children of, or
 
63
    parents of it.
 
64
    Another note is that these objects are currently only used when there is
 
65
    no InventoryEntry available - i.e. for unversioned objects.
 
66
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
 
67
    """
 
68
 
 
69
    def __eq__(self, other):
 
70
        # yes, this us ugly, TODO: best practice __eq__ style.
 
71
        return (isinstance(other, TreeEntry)
 
72
                and other.__class__ == self.__class__)
 
73
 
 
74
    def kind_character(self):
 
75
        return "???"
 
76
 
 
77
 
 
78
class TreeDirectory(TreeEntry):
 
79
    """See TreeEntry. This is a directory in a working tree."""
 
80
 
 
81
    def __eq__(self, other):
 
82
        return (isinstance(other, TreeDirectory)
 
83
                and other.__class__ == self.__class__)
 
84
 
 
85
    def kind_character(self):
 
86
        return "/"
 
87
 
 
88
 
 
89
class TreeFile(TreeEntry):
 
90
    """See TreeEntry. This is a regular file in a working tree."""
 
91
 
 
92
    def __eq__(self, other):
 
93
        return (isinstance(other, TreeFile)
 
94
                and other.__class__ == self.__class__)
 
95
 
 
96
    def kind_character(self):
 
97
        return ''
 
98
 
 
99
 
 
100
class TreeLink(TreeEntry):
 
101
    """See TreeEntry. This is a symlink in a working tree."""
 
102
 
 
103
    def __eq__(self, other):
 
104
        return (isinstance(other, TreeLink)
 
105
                and other.__class__ == self.__class__)
 
106
 
 
107
    def kind_character(self):
 
108
        return ''
 
109
 
 
110
 
 
111
class WorkingTree(bzrlib.tree.Tree):
 
112
    """Working copy tree.
 
113
 
 
114
    The inventory is held in the `Branch` working-inventory, and the
 
115
    files are in a directory on disk.
 
116
 
 
117
    It is possible for a `WorkingTree` to have a filename which is
 
118
    not listed in the Inventory and vice versa.
 
119
    """
 
120
 
 
121
    def __init__(self, basedir, branch=None):
 
122
        """Construct a WorkingTree for basedir.
 
123
 
 
124
        If the branch is not supplied, it is opened automatically.
 
125
        If the branch is supplied, it must be the branch for this basedir.
 
126
        (branch.base is not cross checked, because for remote branches that
 
127
        would be meaningless).
 
128
        """
 
129
        from bzrlib.hashcache import HashCache
 
130
        from bzrlib.trace import note, mutter
 
131
        assert isinstance(basedir, basestring), \
 
132
            "base directory %r is not a string" % basedir
 
133
        if branch is None:
 
134
            branch = Branch.open(basedir)
 
135
        assert isinstance(branch, Branch), \
 
136
            "branch %r is not a Branch" % branch
 
137
        self._inventory = branch.inventory
 
138
        self.path2id = self._inventory.path2id
 
139
        self.branch = branch
 
140
        self.basedir = basedir
 
141
 
 
142
        # update the whole cache up front and write to disk if anything changed;
 
143
        # in the future we might want to do this more selectively
 
144
        # two possible ways offer themselves : in self._unlock, write the cache
 
145
        # if needed, or, when the cache sees a change, append it to the hash
 
146
        # cache file, and have the parser take the most recent entry for a
 
147
        # given path only.
 
148
        hc = self._hashcache = HashCache(basedir)
 
149
        hc.read()
 
150
        hc.scan()
 
151
 
 
152
        if hc.needs_write:
 
153
            mutter("write hc")
 
154
            hc.write()
 
155
 
 
156
    def __iter__(self):
 
157
        """Iterate through file_ids for this tree.
 
158
 
 
159
        file_ids are in a WorkingTree if they are in the working inventory
 
160
        and the working file exists.
 
161
        """
 
162
        inv = self._inventory
 
163
        for path, ie in inv.iter_entries():
 
164
            if bzrlib.osutils.lexists(self.abspath(path)):
 
165
                yield ie.file_id
 
166
 
 
167
 
 
168
    def __repr__(self):
 
169
        return "<%s of %s>" % (self.__class__.__name__,
 
170
                               getattr(self, 'basedir', None))
 
171
 
 
172
 
 
173
 
 
174
    def abspath(self, filename):
 
175
        return os.path.join(self.basedir, filename)
 
176
 
 
177
    def relpath(self, abspath):
 
178
        """Return the local path portion from a given absolute path."""
 
179
        return relpath(self.basedir, abspath)
 
180
 
 
181
    def has_filename(self, filename):
 
182
        return bzrlib.osutils.lexists(self.abspath(filename))
 
183
 
 
184
    def get_file(self, file_id):
 
185
        return self.get_file_byname(self.id2path(file_id))
 
186
 
 
187
    def get_file_byname(self, filename):
 
188
        return file(self.abspath(filename), 'rb')
 
189
 
 
190
    def _get_store_filename(self, file_id):
 
191
        ## XXX: badly named; this isn't in the store at all
 
192
        return self.abspath(self.id2path(file_id))
 
193
 
 
194
 
 
195
    def id2abspath(self, file_id):
 
196
        return self.abspath(self.id2path(file_id))
 
197
 
 
198
                
 
199
    def has_id(self, file_id):
 
200
        # files that have been deleted are excluded
 
201
        inv = self._inventory
 
202
        if not inv.has_id(file_id):
 
203
            return False
 
204
        path = inv.id2path(file_id)
 
205
        return bzrlib.osutils.lexists(self.abspath(path))
 
206
 
 
207
    def has_or_had_id(self, file_id):
 
208
        if file_id == self.inventory.root.file_id:
 
209
            return True
 
210
        return self.inventory.has_id(file_id)
 
211
 
 
212
    __contains__ = has_id
 
213
    
 
214
 
 
215
    def get_file_size(self, file_id):
 
216
        return os.path.getsize(self.id2abspath(file_id))
 
217
 
 
218
    def get_file_sha1(self, file_id):
 
219
        path = self._inventory.id2path(file_id)
 
220
        return self._hashcache.get_sha1(path)
 
221
 
 
222
 
 
223
    def is_executable(self, file_id):
 
224
        if os.name == "nt":
 
225
            return self._inventory[file_id].executable
 
226
        else:
 
227
            path = self._inventory.id2path(file_id)
 
228
            mode = os.lstat(self.abspath(path)).st_mode
 
229
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
 
230
 
 
231
    def get_symlink_target(self, file_id):
 
232
        return os.readlink(self.id2abspath(file_id))
 
233
 
 
234
    def file_class(self, filename):
 
235
        if self.path2id(filename):
 
236
            return 'V'
 
237
        elif self.is_ignored(filename):
 
238
            return 'I'
 
239
        else:
 
240
            return '?'
 
241
 
 
242
 
 
243
    def list_files(self):
 
244
        """Recursively list all files as (path, class, kind, id).
 
245
 
 
246
        Lists, but does not descend into unversioned directories.
 
247
 
 
248
        This does not include files that have been deleted in this
 
249
        tree.
 
250
 
 
251
        Skips the control directory.
 
252
        """
 
253
        inv = self._inventory
 
254
 
 
255
        def descend(from_dir_relpath, from_dir_id, dp):
 
256
            ls = os.listdir(dp)
 
257
            ls.sort()
 
258
            for f in ls:
 
259
                ## TODO: If we find a subdirectory with its own .bzr
 
260
                ## directory, then that is a separate tree and we
 
261
                ## should exclude it.
 
262
                if bzrlib.BZRDIR == f:
 
263
                    continue
 
264
 
 
265
                # path within tree
 
266
                fp = appendpath(from_dir_relpath, f)
 
267
 
 
268
                # absolute path
 
269
                fap = appendpath(dp, f)
 
270
                
 
271
                f_ie = inv.get_child(from_dir_id, f)
 
272
                if f_ie:
 
273
                    c = 'V'
 
274
                elif self.is_ignored(fp):
 
275
                    c = 'I'
 
276
                else:
 
277
                    c = '?'
 
278
 
 
279
                fk = file_kind(fap)
 
280
 
 
281
                if f_ie:
 
282
                    if f_ie.kind != fk:
 
283
                        raise BzrCheckError("file %r entered as kind %r id %r, "
 
284
                                            "now of kind %r"
 
285
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
 
286
 
 
287
                # make a last minute entry
 
288
                if f_ie:
 
289
                    entry = f_ie
 
290
                else:
 
291
                    if fk == 'directory':
 
292
                        entry = TreeDirectory()
 
293
                    elif fk == 'file':
 
294
                        entry = TreeFile()
 
295
                    elif fk == 'symlink':
 
296
                        entry = TreeLink()
 
297
                    else:
 
298
                        entry = TreeEntry()
 
299
                
 
300
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
 
301
 
 
302
                if fk != 'directory':
 
303
                    continue
 
304
 
 
305
                if c != 'V':
 
306
                    # don't descend unversioned directories
 
307
                    continue
 
308
                
 
309
                for ff in descend(fp, f_ie.file_id, fap):
 
310
                    yield ff
 
311
 
 
312
        for f in descend('', inv.root.file_id, self.basedir):
 
313
            yield f
 
314
            
 
315
 
 
316
 
 
317
    def unknowns(self):
 
318
        for subp in self.extras():
 
319
            if not self.is_ignored(subp):
 
320
                yield subp
 
321
 
 
322
    def iter_conflicts(self):
 
323
        conflicted = set()
 
324
        for path in (s[0] for s in self.list_files()):
 
325
            stem = get_conflicted_stem(path)
 
326
            if stem is None:
 
327
                continue
 
328
            if stem not in conflicted:
 
329
                conflicted.add(stem)
 
330
                yield stem
 
331
 
 
332
    @needs_write_lock
 
333
    def pull(self, source, overwrite=False):
 
334
        from bzrlib.merge import merge_inner
 
335
        source.lock_read()
 
336
        try:
 
337
            old_revision_history = self.branch.revision_history()
 
338
            self.branch.pull(source, overwrite)
 
339
            new_revision_history = self.branch.revision_history()
 
340
            if new_revision_history != old_revision_history:
 
341
                if len(old_revision_history):
 
342
                    other_revision = old_revision_history[-1]
 
343
                else:
 
344
                    other_revision = None
 
345
                merge_inner(self.branch,
 
346
                            self.branch.basis_tree(), 
 
347
                            self.branch.revision_tree(other_revision))
 
348
        finally:
 
349
            source.unlock()
 
350
 
 
351
    def extras(self):
 
352
        """Yield all unknown files in this WorkingTree.
 
353
 
 
354
        If there are any unknown directories then only the directory is
 
355
        returned, not all its children.  But if there are unknown files
 
356
        under a versioned subdirectory, they are returned.
 
357
 
 
358
        Currently returned depth-first, sorted by name within directories.
 
359
        """
 
360
        ## TODO: Work from given directory downwards
 
361
        for path, dir_entry in self.inventory.directories():
 
362
            mutter("search for unknowns in %r" % path)
 
363
            dirabs = self.abspath(path)
 
364
            if not isdir(dirabs):
 
365
                # e.g. directory deleted
 
366
                continue
 
367
 
 
368
            fl = []
 
369
            for subf in os.listdir(dirabs):
 
370
                if (subf != '.bzr'
 
371
                    and (subf not in dir_entry.children)):
 
372
                    fl.append(subf)
 
373
            
 
374
            fl.sort()
 
375
            for subf in fl:
 
376
                subp = appendpath(path, subf)
 
377
                yield subp
 
378
 
 
379
 
 
380
    def ignored_files(self):
 
381
        """Yield list of PATH, IGNORE_PATTERN"""
 
382
        for subp in self.extras():
 
383
            pat = self.is_ignored(subp)
 
384
            if pat != None:
 
385
                yield subp, pat
 
386
 
 
387
 
 
388
    def get_ignore_list(self):
 
389
        """Return list of ignore patterns.
 
390
 
 
391
        Cached in the Tree object after the first call.
 
392
        """
 
393
        if hasattr(self, '_ignorelist'):
 
394
            return self._ignorelist
 
395
 
 
396
        l = bzrlib.DEFAULT_IGNORE[:]
 
397
        if self.has_filename(bzrlib.IGNORE_FILENAME):
 
398
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
 
399
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
 
400
        self._ignorelist = l
 
401
        return l
 
402
 
 
403
 
 
404
    def is_ignored(self, filename):
 
405
        r"""Check whether the filename matches an ignore pattern.
 
406
 
 
407
        Patterns containing '/' or '\' need to match the whole path;
 
408
        others match against only the last component.
 
409
 
 
410
        If the file is ignored, returns the pattern which caused it to
 
411
        be ignored, otherwise None.  So this can simply be used as a
 
412
        boolean if desired."""
 
413
 
 
414
        # TODO: Use '**' to match directories, and other extended
 
415
        # globbing stuff from cvs/rsync.
 
416
 
 
417
        # XXX: fnmatch is actually not quite what we want: it's only
 
418
        # approximately the same as real Unix fnmatch, and doesn't
 
419
        # treat dotfiles correctly and allows * to match /.
 
420
        # Eventually it should be replaced with something more
 
421
        # accurate.
 
422
        
 
423
        for pat in self.get_ignore_list():
 
424
            if '/' in pat or '\\' in pat:
 
425
                
 
426
                # as a special case, you can put ./ at the start of a
 
427
                # pattern; this is good to match in the top-level
 
428
                # only;
 
429
                
 
430
                if (pat[:2] == './') or (pat[:2] == '.\\'):
 
431
                    newpat = pat[2:]
 
432
                else:
 
433
                    newpat = pat
 
434
                if fnmatch.fnmatchcase(filename, newpat):
 
435
                    return pat
 
436
            else:
 
437
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
 
438
                    return pat
 
439
        else:
 
440
            return None
 
441
 
 
442
    def kind(self, file_id):
 
443
        return file_kind(self.id2abspath(file_id))
 
444
 
 
445
    def lock_read(self):
 
446
        """See Branch.lock_read, and WorkingTree.unlock."""
 
447
        return self.branch.lock_read()
 
448
 
 
449
    def lock_write(self):
 
450
        """See Branch.lock_write, and WorkingTree.unlock."""
 
451
        return self.branch.lock_write()
 
452
 
 
453
    @needs_write_lock
 
454
    def remove(self, files, verbose=False):
 
455
        """Remove nominated files from the working inventory..
 
456
 
 
457
        This does not remove their text.  This does not run on XXX on what? RBC
 
458
 
 
459
        TODO: Refuse to remove modified files unless --force is given?
 
460
 
 
461
        TODO: Do something useful with directories.
 
462
 
 
463
        TODO: Should this remove the text or not?  Tough call; not
 
464
        removing may be useful and the user can just use use rm, and
 
465
        is the opposite of add.  Removing it is consistent with most
 
466
        other tools.  Maybe an option.
 
467
        """
 
468
        ## TODO: Normalize names
 
469
        ## TODO: Remove nested loops; better scalability
 
470
        if isinstance(files, basestring):
 
471
            files = [files]
 
472
 
 
473
        inv = self.inventory
 
474
 
 
475
        # do this before any modifications
 
476
        for f in files:
 
477
            fid = inv.path2id(f)
 
478
            if not fid:
 
479
                # TODO: Perhaps make this just a warning, and continue?
 
480
                # This tends to happen when 
 
481
                raise NotVersionedError(path=f)
 
482
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
 
483
            if verbose:
 
484
                # having remove it, it must be either ignored or unknown
 
485
                if self.is_ignored(f):
 
486
                    new_status = 'I'
 
487
                else:
 
488
                    new_status = '?'
 
489
                show_status(new_status, inv[fid].kind, quotefn(f))
 
490
            del inv[fid]
 
491
 
 
492
        self.branch._write_inventory(inv)
 
493
 
 
494
    def unlock(self):
 
495
        """See Branch.unlock.
 
496
        
 
497
        WorkingTree locking just uses the Branch locking facilities.
 
498
        This is current because all working trees have an embedded branch
 
499
        within them. IF in the future, we were to make branch data shareable
 
500
        between multiple working trees, i.e. via shared storage, then we 
 
501
        would probably want to lock both the local tree, and the branch.
 
502
        """
 
503
        return self.branch.unlock()
 
504
 
 
505
 
 
506
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
 
507
def get_conflicted_stem(path):
 
508
    for suffix in CONFLICT_SUFFIXES:
 
509
        if path.endswith(suffix):
 
510
            return path[:-len(suffix)]