~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

[merge] bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
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.
44
44
 
 
45
from copy import deepcopy
45
46
import os
46
47
import stat
47
48
import fnmatch
48
49
 
49
 
from bzrlib.branch import Branch, needs_read_lock, needs_write_lock, quotefn
50
 
import bzrlib.tree
 
50
from bzrlib.branch import (Branch,
 
51
                           is_control_file,
 
52
                           needs_read_lock,
 
53
                           needs_write_lock,
 
54
                           quotefn)
 
55
from bzrlib.errors import (BzrCheckError,
 
56
                           BzrError,
 
57
                           DivergedBranches,
 
58
                           WeaveRevisionNotPresent,
 
59
                           NotBranchError,
 
60
                           NotVersionedError)
 
61
from bzrlib.inventory import InventoryEntry
51
62
from bzrlib.osutils import (appendpath,
 
63
                            compact_date,
52
64
                            file_kind,
53
65
                            isdir,
54
66
                            pumpfile,
55
67
                            splitpath,
56
 
                            relpath)
57
 
from bzrlib.errors import BzrCheckError, DivergedBranches, NotVersionedError
 
68
                            rand_bytes,
 
69
                            realpath,
 
70
                            relpath,
 
71
                            rename)
 
72
import bzrlib.tree
58
73
from bzrlib.trace import mutter
59
74
import bzrlib.xml5
60
75
 
61
76
 
 
77
def gen_file_id(name):
 
78
    """Return new file id.
 
79
 
 
80
    This should probably generate proper UUIDs, but for the moment we
 
81
    cope with just randomness because running uuidgen every time is
 
82
    slow."""
 
83
    import re
 
84
    from binascii import hexlify
 
85
    from time import time
 
86
 
 
87
    # get last component
 
88
    idx = name.rfind('/')
 
89
    if idx != -1:
 
90
        name = name[idx+1 : ]
 
91
    idx = name.rfind('\\')
 
92
    if idx != -1:
 
93
        name = name[idx+1 : ]
 
94
 
 
95
    # make it not a hidden file
 
96
    name = name.lstrip('.')
 
97
 
 
98
    # remove any wierd characters; we don't escape them but rather
 
99
    # just pull them out
 
100
    name = re.sub(r'[^\w.]', '', name)
 
101
 
 
102
    s = hexlify(rand_bytes(8))
 
103
    return '-'.join((name, compact_date(time()), s))
 
104
 
 
105
 
 
106
def gen_root_id():
 
107
    """Return a new tree-root file id."""
 
108
    return gen_file_id('TREE_ROOT')
 
109
 
 
110
 
62
111
class TreeEntry(object):
63
112
    """An entry that implements the minium interface used by commands.
64
113
 
124
173
    not listed in the Inventory and vice versa.
125
174
    """
126
175
 
127
 
    def __init__(self, basedir, branch=None):
 
176
    def __init__(self, basedir=u'.', branch=None):
128
177
        """Construct a WorkingTree for basedir.
129
178
 
130
179
        If the branch is not supplied, it is opened automatically.
141
190
        assert isinstance(branch, Branch), \
142
191
            "branch %r is not a Branch" % branch
143
192
        self.branch = branch
144
 
        self.basedir = basedir
145
 
        self._inventory = self.read_working_inventory()
146
 
        self.path2id = self._inventory.path2id
 
193
        self.basedir = realpath(basedir)
 
194
 
 
195
        self._set_inventory(self.read_working_inventory())
147
196
 
148
197
        # update the whole cache up front and write to disk if anything changed;
149
198
        # in the future we might want to do this more selectively
159
208
            mutter("write hc")
160
209
            hc.write()
161
210
 
 
211
    def _set_inventory(self, inv):
 
212
        self._inventory = inv
 
213
        self.path2id = self._inventory.path2id
 
214
 
 
215
    @staticmethod
 
216
    def open_containing(path=None):
 
217
        """Open an existing working tree which has its root about path.
 
218
        
 
219
        This probes for a working tree at path and searches upwards from there.
 
220
 
 
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.
 
225
        """
 
226
        if path is None:
 
227
            path = os.getcwdu()
 
228
        else:
 
229
            # sanity check.
 
230
            if path.find('://') != -1:
 
231
                raise NotBranchError(path=path)
 
232
        path = os.path.abspath(path)
 
233
        tail = u''
 
234
        while True:
 
235
            try:
 
236
                return WorkingTree(path), tail
 
237
            except NotBranchError:
 
238
                pass
 
239
            if tail:
 
240
                tail = os.path.join(os.path.basename(path), tail)
 
241
            else:
 
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)
 
248
 
162
249
    def __iter__(self):
163
250
        """Iterate through file_ids for this tree.
164
251
 
170
257
            if bzrlib.osutils.lexists(self.abspath(path)):
171
258
                yield ie.file_id
172
259
 
173
 
 
174
260
    def __repr__(self):
175
261
        return "<%s of %s>" % (self.__class__.__name__,
176
262
                               getattr(self, 'basedir', None))
177
263
 
178
 
 
179
 
 
180
264
    def abspath(self, filename):
181
265
        return os.path.join(self.basedir, filename)
182
266
 
199
283
        return inv.root.file_id
200
284
        
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))
204
288
 
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())
210
294
 
211
295
    def id2abspath(self, file_id):
212
296
        return self.abspath(self.id2path(file_id))
213
297
 
214
 
                
215
298
    def has_id(self, file_id):
216
299
        # files that have been deleted are excluded
217
300
        inv = self._inventory
226
309
        return self.inventory.has_id(file_id)
227
310
 
228
311
    __contains__ = has_id
229
 
    
230
312
 
231
313
    def get_file_size(self, file_id):
232
314
        return os.path.getsize(self.id2abspath(file_id))
235
317
        path = self._inventory.id2path(file_id)
236
318
        return self._hashcache.get_sha1(path)
237
319
 
238
 
 
239
320
    def is_executable(self, file_id):
240
321
        if os.name == "nt":
241
322
            return self._inventory[file_id].executable
245
326
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
246
327
 
247
328
    @needs_write_lock
 
329
    def add(self, files, ids=None):
 
330
        """Make files versioned.
 
331
 
 
332
        Note that the command line normally calls smart_add instead,
 
333
        which can automatically recurse.
 
334
 
 
335
        This adds the files to the inventory, so that they will be
 
336
        recorded by the next commit.
 
337
 
 
338
        files
 
339
            List of paths to add, relative to the base of the tree.
 
340
 
 
341
        ids
 
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.
 
345
 
 
346
        TODO: Perhaps have an option to add the ids even if the files do
 
347
              not (yet) exist.
 
348
 
 
349
        TODO: Perhaps callback with the ids and paths as they're added.
 
350
        """
 
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))
 
355
            files = [files]
 
356
            if ids is not None:
 
357
                ids = [ids]
 
358
 
 
359
        if ids is None:
 
360
            ids = [None] * len(files)
 
361
        else:
 
362
            assert(len(ids) == len(files))
 
363
 
 
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))
 
368
 
 
369
            fp = splitpath(f)
 
370
 
 
371
            if len(fp) == 0:
 
372
                raise BzrError("cannot add top-level %r" % f)
 
373
 
 
374
            fullpath = os.path.normpath(self.abspath(f))
 
375
 
 
376
            try:
 
377
                kind = file_kind(fullpath)
 
378
            except OSError:
 
379
                # maybe something better?
 
380
                raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
 
381
 
 
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))
 
385
 
 
386
            if file_id is None:
 
387
                file_id = gen_file_id(f)
 
388
            inv.add_path(f, kind=kind, file_id=file_id)
 
389
 
 
390
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
 
391
        self._write_inventory(inv)
 
392
 
 
393
    @needs_write_lock
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):
358
504
                    yield ff
359
505
 
360
 
        for f in descend('', inv.root.file_id, self.basedir):
 
506
        for f in descend(u'', inv.root.file_id, self.basedir):
361
507
            yield f
362
 
            
363
 
 
364
 
 
 
508
 
 
509
    @needs_write_lock
 
510
    def move(self, from_paths, to_name):
 
511
        """Rename files.
 
512
 
 
513
        to_name must exist in the inventory.
 
514
 
 
515
        If to_name exists and is a directory, the files are moved into
 
516
        it, keeping their old names.  
 
517
 
 
518
        Note that to_name is only the last component of the new name;
 
519
        this doesn't change the directory.
 
520
 
 
521
        This returns a list of (from_path, to_path) pairs for each
 
522
        entry that is moved.
 
523
        """
 
524
        result = []
 
525
        ## TODO: Option to move IDs only
 
526
        assert not isinstance(from_paths, basestring)
 
527
        inv = self.inventory
 
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)
 
539
 
 
540
        to_idpath = inv.get_idpath(to_dir_id)
 
541
 
 
542
        for f in from_paths:
 
543
            if not self.has_filename(f):
 
544
                raise BzrError("%r does not exist in working tree" % f)
 
545
            f_id = inv.path2id(f)
 
546
            if f_id == None:
 
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)
 
554
 
 
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)
 
559
        try:
 
560
            for f in from_paths:
 
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)
 
565
                try:
 
566
                    rename(self.abspath(f), self.abspath(dest_path))
 
567
                except OSError, e:
 
568
                    raise BzrError("failed to rename %r to %r: %s" %
 
569
                                   (f, dest_path, e[1]),
 
570
                            ["rename rolled back"])
 
571
        except:
 
572
            # restore the inventory on error
 
573
            self._set_inventory(orig_inv)
 
574
            raise
 
575
        self._write_inventory(inv)
 
576
        return result
 
577
 
 
578
    @needs_write_lock
 
579
    def rename_one(self, from_rel, to_rel):
 
580
        """Rename one file.
 
581
 
 
582
        This can change the directory or the filename or both.
 
583
        """
 
584
        inv = self.inventory
 
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)
 
589
 
 
590
        file_id = inv.path2id(from_rel)
 
591
        if file_id == None:
 
592
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
 
593
 
 
594
        entry = inv[file_id]
 
595
        from_parent = entry.parent_id
 
596
        from_name = entry.name
 
597
        
 
598
        if inv.path2id(to_rel):
 
599
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
 
600
 
 
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)
 
605
 
 
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)
 
612
 
 
613
        inv.rename(file_id, to_dir_id, to_tail)
 
614
 
 
615
        from_abs = self.abspath(from_rel)
 
616
        to_abs = self.abspath(to_rel)
 
617
        try:
 
618
            rename(from_abs, to_abs)
 
619
        except OSError, e:
 
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)
 
625
 
 
626
    @needs_read_lock
365
627
    def unknowns(self):
 
628
        """Return all unknown files.
 
629
 
 
630
        These are files in the working directory that are not versioned or
 
631
        control files or ignored.
 
632
        
 
633
        >>> from bzrlib.branch import ScratchBranch
 
634
        >>> b = ScratchBranch(files=['foo', 'foo~'])
 
635
        >>> tree = WorkingTree(b.base, b)
 
636
        >>> map(str, tree.unknowns())
 
637
        ['foo']
 
638
        >>> tree.add('foo')
 
639
        >>> list(b.unknowns())
 
640
        []
 
641
        >>> tree.remove('foo')
 
642
        >>> list(b.unknowns())
 
643
        [u'foo']
 
644
        """
366
645
        for subp in self.extras():
367
646
            if not self.is_ignored(subp):
368
647
                yield subp
383
662
        source.lock_read()
384
663
        try:
385
664
            old_revision_history = self.branch.revision_history()
386
 
            self.branch.pull(source, overwrite)
 
665
            count = self.branch.pull(source, overwrite)
387
666
            new_revision_history = self.branch.revision_history()
388
667
            if new_revision_history != old_revision_history:
389
668
                if len(old_revision_history):
393
672
                merge_inner(self.branch,
394
673
                            self.branch.basis_tree(), 
395
674
                            self.branch.revision_tree(other_revision))
396
 
            return len(new_revision_history) - len(old_revision_history)
 
675
            return count
397
676
        finally:
398
677
            source.unlock()
399
678
 
499
778
        """See Branch.lock_write, and WorkingTree.unlock."""
500
779
        return self.branch.lock_write()
501
780
 
 
781
    def _basis_inventory_name(self, revision_id):
 
782
        return 'basis-inventory.%s' % revision_id
 
783
 
 
784
    def set_last_revision(self, new_revision, old_revision=None):
 
785
        if old_revision:
 
786
            try:
 
787
                path = self._basis_inventory_name(old_revision)
 
788
                path = self.branch._rel_controlfilename(path)
 
789
                self.branch._transport.delete(path)
 
790
            except:
 
791
                pass
 
792
        try:
 
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:
 
797
            pass
 
798
 
 
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()
 
803
        
502
804
    @needs_read_lock
503
805
    def read_working_inventory(self):
504
806
        """Read the working inventory."""
622
924
            f.commit()
623
925
        finally:
624
926
            f.close()
 
927
        self._set_inventory(inv)
625
928
        mutter('wrote working inventory')
626
929
            
627
930