~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-05-27 05:23:57 UTC
  • Revision ID: mbp@sourcefrog.net-20050527052357-240127f785aa3d60
- start to move toward Branch.lock and unlock methods, 
  rather than setting it in the constructor

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
from sets import Set
19
 
 
20
18
import sys, os, os.path, random, time, sha, sets, types, re, shutil, tempfile
21
19
import traceback, socket, fnmatch, difflib, time
22
20
from binascii import hexlify
24
22
import bzrlib
25
23
from inventory import Inventory
26
24
from trace import mutter, note
27
 
from tree import Tree, EmptyTree, RevisionTree, WorkingTree
 
25
from tree import Tree, EmptyTree, RevisionTree
28
26
from inventory import InventoryEntry, Inventory
29
27
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
30
28
     format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
31
29
     joinpath, sha_string, file_kind, local_time_offset, appendpath
32
30
from store import ImmutableStore
33
31
from revision import Revision
34
 
from errors import bailout, BzrError
 
32
from errors import BzrError
35
33
from textui import show_status
36
 
from diff import diff_trees
37
34
 
38
35
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
39
36
## TODO: Maybe include checks for common corruption of newlines, etc?
40
37
 
41
38
 
42
39
 
 
40
def find_branch(f, **args):
 
41
    if f and (f.startswith('http://') or f.startswith('https://')):
 
42
        import remotebranch 
 
43
        return remotebranch.RemoteBranch(f, **args)
 
44
    else:
 
45
        return Branch(f, **args)
 
46
        
 
47
 
43
48
def find_branch_root(f=None):
44
49
    """Find the branch root enclosing f, or pwd.
45
50
 
 
51
    f may be a filename or a URL.
 
52
 
46
53
    It is not necessary that f exists.
47
54
 
48
55
    Basically we keep looking up until we find the control directory or
53
60
        f = os.path.realpath(f)
54
61
    else:
55
62
        f = os.path.abspath(f)
 
63
    if not os.path.exists(f):
 
64
        raise BzrError('%r does not exist' % f)
 
65
        
56
66
 
57
67
    orig_f = f
58
68
 
70
80
######################################################################
71
81
# branch objects
72
82
 
73
 
class Branch:
 
83
class Branch(object):
74
84
    """Branch holding a history of revisions.
75
85
 
76
86
    base
77
87
        Base directory of the branch.
 
88
 
 
89
    _lock_mode
 
90
        None, or a duple with 'r' or 'w' for the first element and a positive
 
91
        count for the second.
 
92
 
 
93
    _lockfile
 
94
        Open file used for locking.
78
95
    """
79
 
    _lockmode = None
 
96
    base = None
 
97
    _lock_mode = None
80
98
    
81
99
    def __init__(self, base, init=False, find_root=True, lock_mode='w'):
82
100
        """Create new branch object at a particular location.
101
119
        else:
102
120
            self.base = os.path.realpath(base)
103
121
            if not isdir(self.controlfilename('.')):
104
 
                bailout("not a bzr branch: %s" % quotefn(base),
105
 
                        ['use "bzr init" to initialize a new working tree',
106
 
                         'current bzr can only operate from top-of-tree'])
 
122
                from errors import NotBranchError
 
123
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
 
124
                                     ['use "bzr init" to initialize a new working tree',
 
125
                                      'current bzr can only operate from top-of-tree'])
107
126
        self._check_format()
 
127
        self._lockfile = self.controlfile('branch-lock', 'wb')
108
128
        self.lock(lock_mode)
109
129
 
110
130
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
119
139
    __repr__ = __str__
120
140
 
121
141
 
122
 
 
123
 
    def lock(self, mode='w'):
124
 
        """Lock the on-disk branch, excluding other processes."""
125
 
        try:
126
 
            import fcntl, errno
127
 
 
128
 
            if mode == 'w':
129
 
                lm = fcntl.LOCK_EX
130
 
                om = os.O_WRONLY | os.O_CREAT
131
 
            elif mode == 'r':
132
 
                lm = fcntl.LOCK_SH
133
 
                om = os.O_RDONLY
134
 
            else:
135
 
                raise BzrError("invalid locking mode %r" % mode)
136
 
 
137
 
            try:
138
 
                lockfile = os.open(self.controlfilename('branch-lock'), om)
139
 
            except OSError, e:
140
 
                if e.errno == errno.ENOENT:
141
 
                    # might not exist on branches from <0.0.4
142
 
                    self.controlfile('branch-lock', 'w').close()
143
 
                    lockfile = os.open(self.controlfilename('branch-lock'), om)
144
 
                else:
145
 
                    raise e
146
 
            
147
 
            fcntl.lockf(lockfile, lm)
148
 
            def unlock():
149
 
                fcntl.lockf(lockfile, fcntl.LOCK_UN)
150
 
                os.close(lockfile)
151
 
                self._lockmode = None
152
 
            self.unlock = unlock
153
 
            self._lockmode = mode
154
 
        except ImportError:
155
 
            warning("please write a locking method for platform %r" % sys.platform)
156
 
            def unlock():
157
 
                self._lockmode = None
158
 
            self.unlock = unlock
159
 
            self._lockmode = mode
 
142
    def __del__(self):
 
143
        if self._lock_mode:
 
144
            from warnings import warn
 
145
            warn("branch %r was not explicitly unlocked" % self)
 
146
            self.unlock()
 
147
 
 
148
 
 
149
    def lock(self, mode):
 
150
        if self._lock_mode:
 
151
            raise BzrError('branch %r is already locked: %r' % (self, self._lock_mode))
 
152
 
 
153
        from bzrlib.lock import lock, LOCK_SH, LOCK_EX
 
154
        if mode == 'r':
 
155
            m = LOCK_SH
 
156
        elif mode == 'w':
 
157
            m = LOCK_EX
 
158
        else:
 
159
            raise ValueError('invalid lock mode %r' % mode)
 
160
        
 
161
        lock(self._lockfile, m)
 
162
        self._lock_mode = (mode, 1)
 
163
 
 
164
 
 
165
    def unlock(self):
 
166
        if not self._lock_mode:
 
167
            raise BzrError('branch %r is not locked' % (self))
 
168
        from bzrlib.lock import unlock
 
169
        unlock(self._lockfile)
 
170
        self._lock_mode = None
160
171
 
161
172
 
162
173
    def _need_readlock(self):
163
 
        if self._lockmode not in ['r', 'w']:
 
174
        if not self._lock_mode:
164
175
            raise BzrError('need read lock on branch, only have %r' % self._lockmode)
165
176
 
 
177
 
166
178
    def _need_writelock(self):
167
 
        if self._lockmode not in ['w']:
 
179
        if (self._lock_mode == None) or (self._lock_mode[0] != 'w'):
168
180
            raise BzrError('need write lock on branch, only have %r' % self._lockmode)
169
181
 
170
182
 
180
192
        rp = os.path.realpath(path)
181
193
        # FIXME: windows
182
194
        if not rp.startswith(self.base):
183
 
            bailout("path %r is not within branch %r" % (rp, self.base))
 
195
            from errors import NotBranchError
 
196
            raise NotBranchError("path %r is not within branch %r" % (rp, self.base))
184
197
        rp = rp[len(self.base):]
185
198
        rp = rp.lstrip(os.sep)
186
199
        return rp
200
213
        and binary.  binary files are untranslated byte streams.  Text
201
214
        control files are stored with Unix newlines and in UTF-8, even
202
215
        if the platform or locale defaults are different.
 
216
 
 
217
        Controlfiles should almost never be opened in write mode but
 
218
        rather should be atomically copied and replaced using atomicfile.
203
219
        """
204
220
 
205
221
        fn = self.controlfilename(file_or_path)
247
263
        fmt = self.controlfile('branch-format', 'r').read()
248
264
        fmt.replace('\r\n', '')
249
265
        if fmt != BZR_BRANCH_FORMAT:
250
 
            bailout('sorry, branch format %r not supported' % fmt,
251
 
                    ['use a different bzr version',
252
 
                     'or remove the .bzr directory and "bzr init" again'])
 
266
            raise BzrError('sorry, branch format %r not supported' % fmt,
 
267
                           ['use a different bzr version',
 
268
                            'or remove the .bzr directory and "bzr init" again'])
253
269
 
254
270
 
255
271
    def read_working_inventory(self):
288
304
                         """Inventory for the working copy.""")
289
305
 
290
306
 
291
 
    def add(self, files, verbose=False):
 
307
    def add(self, files, verbose=False, ids=None):
292
308
        """Make files versioned.
293
309
 
294
310
        Note that the command line normally calls smart_add instead.
307
323
        TODO: Adding a directory should optionally recurse down and
308
324
               add all non-ignored children.  Perhaps do that in a
309
325
               higher-level method.
310
 
 
311
 
        >>> b = ScratchBranch(files=['foo'])
312
 
        >>> 'foo' in b.unknowns()
313
 
        True
314
 
        >>> b.show_status()
315
 
        ?       foo
316
 
        >>> b.add('foo')
317
 
        >>> 'foo' in b.unknowns()
318
 
        False
319
 
        >>> bool(b.inventory.path2id('foo'))
320
 
        True
321
 
        >>> b.show_status()
322
 
        A       foo
323
 
 
324
 
        >>> b.add('foo')
325
 
        Traceback (most recent call last):
326
 
        ...
327
 
        BzrError: ('foo is already versioned', [])
328
 
 
329
 
        >>> b.add(['nothere'])
330
 
        Traceback (most recent call last):
331
 
        BzrError: ('cannot add: not a regular file or directory: nothere', [])
332
326
        """
333
327
        self._need_writelock()
334
328
 
335
329
        # TODO: Re-adding a file that is removed in the working copy
336
330
        # should probably put it back with the previous ID.
337
331
        if isinstance(files, types.StringTypes):
 
332
            assert(ids is None or isinstance(ids, types.StringTypes))
338
333
            files = [files]
 
334
            if ids is not None:
 
335
                ids = [ids]
 
336
 
 
337
        if ids is None:
 
338
            ids = [None] * len(files)
 
339
        else:
 
340
            assert(len(ids) == len(files))
339
341
        
340
342
        inv = self.read_working_inventory()
341
 
        for f in files:
 
343
        for f,file_id in zip(files, ids):
342
344
            if is_control_file(f):
343
 
                bailout("cannot add control file %s" % quotefn(f))
 
345
                raise BzrError("cannot add control file %s" % quotefn(f))
344
346
 
345
347
            fp = splitpath(f)
346
348
 
347
349
            if len(fp) == 0:
348
 
                bailout("cannot add top-level %r" % f)
 
350
                raise BzrError("cannot add top-level %r" % f)
349
351
                
350
352
            fullpath = os.path.normpath(self.abspath(f))
351
353
 
353
355
                kind = file_kind(fullpath)
354
356
            except OSError:
355
357
                # maybe something better?
356
 
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
358
                raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
357
359
            
358
360
            if kind != 'file' and kind != 'directory':
359
 
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
361
                raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
360
362
 
361
 
            file_id = gen_file_id(f)
 
363
            if file_id is None:
 
364
                file_id = gen_file_id(f)
362
365
            inv.add_path(f, kind=kind, file_id=file_id)
363
366
 
364
367
            if verbose:
376
379
        # use inventory as it was in that revision
377
380
        file_id = tree.inventory.path2id(file)
378
381
        if not file_id:
379
 
            bailout("%r is not present in revision %d" % (file, revno))
 
382
            raise BzrError("%r is not present in revision %d" % (file, revno))
380
383
        tree.print_file(file_id)
381
384
        
382
385
 
387
390
 
388
391
        TODO: Refuse to remove modified files unless --force is given?
389
392
 
390
 
        >>> b = ScratchBranch(files=['foo'])
391
 
        >>> b.add('foo')
392
 
        >>> b.inventory.has_filename('foo')
393
 
        True
394
 
        >>> b.remove('foo')
395
 
        >>> b.working_tree().has_filename('foo')
396
 
        True
397
 
        >>> b.inventory.has_filename('foo')
398
 
        False
399
 
        
400
 
        >>> b = ScratchBranch(files=['foo'])
401
 
        >>> b.add('foo')
402
 
        >>> b.commit('one')
403
 
        >>> b.remove('foo')
404
 
        >>> b.commit('two')
405
 
        >>> b.inventory.has_filename('foo') 
406
 
        False
407
 
        >>> b.basis_tree().has_filename('foo') 
408
 
        False
409
 
        >>> b.working_tree().has_filename('foo') 
410
 
        True
411
 
 
412
393
        TODO: Do something useful with directories.
413
394
 
414
395
        TODO: Should this remove the text or not?  Tough call; not
430
411
        for f in files:
431
412
            fid = inv.path2id(f)
432
413
            if not fid:
433
 
                bailout("cannot remove unversioned file %s" % quotefn(f))
 
414
                raise BzrError("cannot remove unversioned file %s" % quotefn(f))
434
415
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
435
416
            if verbose:
436
417
                # having remove it, it must be either ignored or unknown
443
424
 
444
425
        self._write_inventory(inv)
445
426
 
 
427
    def set_inventory(self, new_inventory_list):
 
428
        inv = Inventory()
 
429
        for path, file_id, parent, kind in new_inventory_list:
 
430
            name = os.path.basename(path)
 
431
            if name == "":
 
432
                continue
 
433
            inv.add(InventoryEntry(file_id, name, kind, parent))
 
434
        self._write_inventory(inv)
 
435
 
446
436
 
447
437
    def unknowns(self):
448
438
        """Return all unknown files.
463
453
        return self.working_tree().unknowns()
464
454
 
465
455
 
466
 
    def commit(self, message, timestamp=None, timezone=None,
467
 
               committer=None,
468
 
               verbose=False):
469
 
        """Commit working copy as a new revision.
470
 
        
471
 
        The basic approach is to add all the file texts into the
472
 
        store, then the inventory, then make a new revision pointing
473
 
        to that inventory and store that.
474
 
        
475
 
        This is not quite safe if the working copy changes during the
476
 
        commit; for the moment that is simply not allowed.  A better
477
 
        approach is to make a temporary copy of the files before
478
 
        computing their hashes, and then add those hashes in turn to
479
 
        the inventory.  This should mean at least that there are no
480
 
        broken hash pointers.  There is no way we can get a snapshot
481
 
        of the whole directory at an instant.  This would also have to
482
 
        be robust against files disappearing, moving, etc.  So the
483
 
        whole thing is a bit hard.
484
 
 
485
 
        timestamp -- if not None, seconds-since-epoch for a
486
 
             postdated/predated commit.
487
 
        """
488
 
        self._need_writelock()
489
 
 
490
 
        ## TODO: Show branch names
491
 
 
492
 
        # TODO: Don't commit if there are no changes, unless forced?
493
 
 
494
 
        # First walk over the working inventory; and both update that
495
 
        # and also build a new revision inventory.  The revision
496
 
        # inventory needs to hold the text-id, sha1 and size of the
497
 
        # actual file versions committed in the revision.  (These are
498
 
        # not present in the working inventory.)  We also need to
499
 
        # detect missing/deleted files, and remove them from the
500
 
        # working inventory.
501
 
 
502
 
        work_inv = self.read_working_inventory()
503
 
        inv = Inventory()
504
 
        basis = self.basis_tree()
505
 
        basis_inv = basis.inventory
506
 
        missing_ids = []
507
 
        for path, entry in work_inv.iter_entries():
508
 
            ## TODO: Cope with files that have gone missing.
509
 
 
510
 
            ## TODO: Check that the file kind has not changed from the previous
511
 
            ## revision of this file (if any).
512
 
 
513
 
            entry = entry.copy()
514
 
 
515
 
            p = self.abspath(path)
516
 
            file_id = entry.file_id
517
 
            mutter('commit prep file %s, id %r ' % (p, file_id))
518
 
 
519
 
            if not os.path.exists(p):
520
 
                mutter("    file is missing, removing from inventory")
521
 
                if verbose:
522
 
                    show_status('D', entry.kind, quotefn(path))
523
 
                missing_ids.append(file_id)
524
 
                continue
525
 
 
526
 
            # TODO: Handle files that have been deleted
527
 
 
528
 
            # TODO: Maybe a special case for empty files?  Seems a
529
 
            # waste to store them many times.
530
 
 
531
 
            inv.add(entry)
532
 
 
533
 
            if basis_inv.has_id(file_id):
534
 
                old_kind = basis_inv[file_id].kind
535
 
                if old_kind != entry.kind:
536
 
                    bailout("entry %r changed kind from %r to %r"
537
 
                            % (file_id, old_kind, entry.kind))
538
 
 
539
 
            if entry.kind == 'directory':
540
 
                if not isdir(p):
541
 
                    bailout("%s is entered as directory but not a directory" % quotefn(p))
542
 
            elif entry.kind == 'file':
543
 
                if not isfile(p):
544
 
                    bailout("%s is entered as file but is not a file" % quotefn(p))
545
 
 
546
 
                content = file(p, 'rb').read()
547
 
 
548
 
                entry.text_sha1 = sha_string(content)
549
 
                entry.text_size = len(content)
550
 
 
551
 
                old_ie = basis_inv.has_id(file_id) and basis_inv[file_id]
552
 
                if (old_ie
553
 
                    and (old_ie.text_size == entry.text_size)
554
 
                    and (old_ie.text_sha1 == entry.text_sha1)):
555
 
                    ## assert content == basis.get_file(file_id).read()
556
 
                    entry.text_id = basis_inv[file_id].text_id
557
 
                    mutter('    unchanged from previous text_id {%s}' %
558
 
                           entry.text_id)
559
 
                    
560
 
                else:
561
 
                    entry.text_id = gen_file_id(entry.name)
562
 
                    self.text_store.add(content, entry.text_id)
563
 
                    mutter('    stored with text_id {%s}' % entry.text_id)
564
 
                    if verbose:
565
 
                        if not old_ie:
566
 
                            state = 'A'
567
 
                        elif (old_ie.name == entry.name
568
 
                              and old_ie.parent_id == entry.parent_id):
569
 
                            state = 'M'
570
 
                        else:
571
 
                            state = 'R'
572
 
 
573
 
                        show_status(state, entry.kind, quotefn(path))
574
 
 
575
 
        for file_id in missing_ids:
576
 
            # have to do this later so we don't mess up the iterator.
577
 
            # since parents may be removed before their children we
578
 
            # have to test.
579
 
 
580
 
            # FIXME: There's probably a better way to do this; perhaps
581
 
            # the workingtree should know how to filter itself.
582
 
            if work_inv.has_id(file_id):
583
 
                del work_inv[file_id]
584
 
 
585
 
 
586
 
        inv_id = rev_id = _gen_revision_id(time.time())
587
 
        
588
 
        inv_tmp = tempfile.TemporaryFile()
589
 
        inv.write_xml(inv_tmp)
590
 
        inv_tmp.seek(0)
591
 
        self.inventory_store.add(inv_tmp, inv_id)
592
 
        mutter('new inventory_id is {%s}' % inv_id)
593
 
 
594
 
        self._write_inventory(work_inv)
595
 
 
596
 
        if timestamp == None:
597
 
            timestamp = time.time()
598
 
 
599
 
        if committer == None:
600
 
            committer = username()
601
 
 
602
 
        if timezone == None:
603
 
            timezone = local_time_offset()
604
 
 
605
 
        mutter("building commit log message")
606
 
        rev = Revision(timestamp=timestamp,
607
 
                       timezone=timezone,
608
 
                       committer=committer,
609
 
                       precursor = self.last_patch(),
610
 
                       message = message,
611
 
                       inventory_id=inv_id,
612
 
                       revision_id=rev_id)
613
 
 
614
 
        rev_tmp = tempfile.TemporaryFile()
615
 
        rev.write_xml(rev_tmp)
616
 
        rev_tmp.seek(0)
617
 
        self.revision_store.add(rev_tmp, rev_id)
618
 
        mutter("new revision_id is {%s}" % rev_id)
619
 
        
620
 
        ## XXX: Everything up to here can simply be orphaned if we abort
621
 
        ## the commit; it will leave junk files behind but that doesn't
622
 
        ## matter.
623
 
 
624
 
        ## TODO: Read back the just-generated changeset, and make sure it
625
 
        ## applies and recreates the right state.
626
 
 
627
 
        ## TODO: Also calculate and store the inventory SHA1
628
 
        mutter("committing patch r%d" % (self.revno() + 1))
629
 
 
630
 
 
631
 
        self.append_revision(rev_id)
632
 
        
633
 
        if verbose:
634
 
            note("commited r%d" % self.revno())
635
 
 
636
 
 
637
456
    def append_revision(self, revision_id):
638
457
        mutter("add {%s} to revision-history" % revision_id)
639
458
        rev_history = self.revision_history()
710
529
                yield i, rh[i-1]
711
530
                i -= 1
712
531
        else:
713
 
            raise BzrError('invalid history direction %r' % direction)
 
532
            raise ValueError('invalid history direction', direction)
714
533
 
715
534
 
716
535
    def revno(self):
718
537
 
719
538
        That is equivalent to the number of revisions committed to
720
539
        this branch.
721
 
 
722
 
        >>> b = ScratchBranch()
723
 
        >>> b.revno()
724
 
        0
725
 
        >>> b.commit('no foo')
726
 
        >>> b.revno()
727
 
        1
728
540
        """
729
541
        return len(self.revision_history())
730
542
 
731
543
 
732
544
    def last_patch(self):
733
545
        """Return last patch hash, or None if no history.
734
 
 
735
 
        >>> ScratchBranch().last_patch() == None
736
 
        True
737
546
        """
738
547
        ph = self.revision_history()
739
548
        if ph:
740
549
            return ph[-1]
741
550
        else:
742
551
            return None
 
552
 
 
553
 
 
554
    def commit(self, *args, **kw):
 
555
        """Deprecated"""
 
556
        from bzrlib.commit import commit
 
557
        commit(self, *args, **kw)
743
558
        
744
559
 
745
560
    def lookup_revision(self, revno):
759
574
 
760
575
        `revision_id` may be None for the null revision, in which case
761
576
        an `EmptyTree` is returned."""
 
577
        # TODO: refactor this to use an existing revision object
 
578
        # so we don't need to read it in twice.
762
579
        self._need_readlock()
763
580
        if revision_id == None:
764
581
            return EmptyTree()
769
586
 
770
587
    def working_tree(self):
771
588
        """Return a `Tree` for the working copy."""
 
589
        from workingtree import WorkingTree
772
590
        return WorkingTree(self.base, self.read_working_inventory())
773
591
 
774
592
 
776
594
        """Return `Tree` object for last revision.
777
595
 
778
596
        If there are no revisions yet, return an `EmptyTree`.
779
 
 
780
 
        >>> b = ScratchBranch(files=['foo'])
781
 
        >>> b.basis_tree().has_filename('foo')
782
 
        False
783
 
        >>> b.working_tree().has_filename('foo')
784
 
        True
785
 
        >>> b.add('foo')
786
 
        >>> b.commit('add foo')
787
 
        >>> b.basis_tree().has_filename('foo')
788
 
        True
789
597
        """
790
598
        r = self.last_patch()
791
599
        if r == None:
804
612
        tree = self.working_tree()
805
613
        inv = tree.inventory
806
614
        if not tree.has_filename(from_rel):
807
 
            bailout("can't rename: old working file %r does not exist" % from_rel)
 
615
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
808
616
        if tree.has_filename(to_rel):
809
 
            bailout("can't rename: new working file %r already exists" % to_rel)
 
617
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
810
618
            
811
619
        file_id = inv.path2id(from_rel)
812
620
        if file_id == None:
813
 
            bailout("can't rename: old name %r is not versioned" % from_rel)
 
621
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
814
622
 
815
623
        if inv.path2id(to_rel):
816
 
            bailout("can't rename: new name %r is already versioned" % to_rel)
 
624
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
817
625
 
818
626
        to_dir, to_tail = os.path.split(to_rel)
819
627
        to_dir_id = inv.path2id(to_dir)
820
628
        if to_dir_id == None and to_dir != '':
821
 
            bailout("can't determine destination directory id for %r" % to_dir)
 
629
            raise BzrError("can't determine destination directory id for %r" % to_dir)
822
630
 
823
631
        mutter("rename_one:")
824
632
        mutter("  file_id    {%s}" % file_id)
836
644
        try:
837
645
            os.rename(from_abs, to_abs)
838
646
        except OSError, e:
839
 
            bailout("failed to rename %r to %r: %s"
 
647
            raise BzrError("failed to rename %r to %r: %s"
840
648
                    % (from_abs, to_abs, e[1]),
841
649
                    ["rename rolled back"])
842
650
 
862
670
        inv = tree.inventory
863
671
        to_abs = self.abspath(to_name)
864
672
        if not isdir(to_abs):
865
 
            bailout("destination %r is not a directory" % to_abs)
 
673
            raise BzrError("destination %r is not a directory" % to_abs)
866
674
        if not tree.has_filename(to_name):
867
 
            bailout("destination %r not in working directory" % to_abs)
 
675
            raise BzrError("destination %r not in working directory" % to_abs)
868
676
        to_dir_id = inv.path2id(to_name)
869
677
        if to_dir_id == None and to_name != '':
870
 
            bailout("destination %r is not a versioned directory" % to_name)
 
678
            raise BzrError("destination %r is not a versioned directory" % to_name)
871
679
        to_dir_ie = inv[to_dir_id]
872
680
        if to_dir_ie.kind not in ('directory', 'root_directory'):
873
 
            bailout("destination %r is not a directory" % to_abs)
 
681
            raise BzrError("destination %r is not a directory" % to_abs)
874
682
 
875
 
        to_idpath = Set(inv.get_idpath(to_dir_id))
 
683
        to_idpath = inv.get_idpath(to_dir_id)
876
684
 
877
685
        for f in from_paths:
878
686
            if not tree.has_filename(f):
879
 
                bailout("%r does not exist in working tree" % f)
 
687
                raise BzrError("%r does not exist in working tree" % f)
880
688
            f_id = inv.path2id(f)
881
689
            if f_id == None:
882
 
                bailout("%r is not versioned" % f)
 
690
                raise BzrError("%r is not versioned" % f)
883
691
            name_tail = splitpath(f)[-1]
884
692
            dest_path = appendpath(to_name, name_tail)
885
693
            if tree.has_filename(dest_path):
886
 
                bailout("destination %r already exists" % dest_path)
 
694
                raise BzrError("destination %r already exists" % dest_path)
887
695
            if f_id in to_idpath:
888
 
                bailout("can't move %r to a subdirectory of itself" % f)
 
696
                raise BzrError("can't move %r to a subdirectory of itself" % f)
889
697
 
890
698
        # OK, so there's a race here, it's possible that someone will
891
699
        # create a file in this interval and then the rename might be
899
707
            try:
900
708
                os.rename(self.abspath(f), self.abspath(dest_path))
901
709
            except OSError, e:
902
 
                bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
 
710
                raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
903
711
                        ["rename rolled back"])
904
712
 
905
713
        self._write_inventory(inv)
906
714
 
907
715
 
908
716
 
909
 
    def show_status(self, show_all=False, file_list=None):
910
 
        """Display single-line status for non-ignored working files.
911
 
 
912
 
        The list is show sorted in order by file name.
913
 
 
914
 
        >>> b = ScratchBranch(files=['foo', 'foo~'])
915
 
        >>> b.show_status()
916
 
        ?       foo
917
 
        >>> b.add('foo')
918
 
        >>> b.show_status()
919
 
        A       foo
920
 
        >>> b.commit("add foo")
921
 
        >>> b.show_status()
922
 
        >>> os.unlink(b.abspath('foo'))
923
 
        >>> b.show_status()
924
 
        D       foo
925
 
        """
926
 
        self._need_readlock()
927
 
 
928
 
        # We have to build everything into a list first so that it can
929
 
        # sorted by name, incorporating all the different sources.
930
 
 
931
 
        # FIXME: Rather than getting things in random order and then sorting,
932
 
        # just step through in order.
933
 
 
934
 
        # Interesting case: the old ID for a file has been removed,
935
 
        # but a new file has been created under that name.
936
 
 
937
 
        old = self.basis_tree()
938
 
        new = self.working_tree()
939
 
 
940
 
        items = diff_trees(old, new)
941
 
        # We want to filter out only if any file was provided in the file_list.
942
 
        if isinstance(file_list, list) and len(file_list):
943
 
            items = [item for item in items if item[3] in file_list]
944
 
 
945
 
        for fs, fid, oldname, newname, kind in items:
946
 
            if fs == 'R':
947
 
                show_status(fs, kind,
948
 
                            oldname + ' => ' + newname)
949
 
            elif fs == 'A' or fs == 'M':
950
 
                show_status(fs, kind, newname)
951
 
            elif fs == 'D':
952
 
                show_status(fs, kind, oldname)
953
 
            elif fs == '.':
954
 
                if show_all:
955
 
                    show_status(fs, kind, newname)
956
 
            elif fs == 'I':
957
 
                if show_all:
958
 
                    show_status(fs, kind, newname)
959
 
            elif fs == '?':
960
 
                show_status(fs, kind, newname)
961
 
            else:
962
 
                bailout("weird file state %r" % ((fs, fid),))
963
 
                
964
 
 
965
717
 
966
718
class ScratchBranch(Branch):
967
719
    """Special test class: a branch that cleans up after itself.
1028
780
 
1029
781
 
1030
782
 
1031
 
def _gen_revision_id(when):
1032
 
    """Return new revision-id."""
1033
 
    s = '%s-%s-' % (user_email(), compact_date(when))
1034
 
    s += hexlify(rand_bytes(8))
1035
 
    return s
1036
 
 
1037
 
 
1038
783
def gen_file_id(name):
1039
784
    """Return new file id.
1040
785
 
1041
786
    This should probably generate proper UUIDs, but for the moment we
1042
787
    cope with just randomness because running uuidgen every time is
1043
788
    slow."""
 
789
    import re
 
790
 
 
791
    # get last component
1044
792
    idx = name.rfind('/')
1045
793
    if idx != -1:
1046
794
        name = name[idx+1 : ]
1048
796
    if idx != -1:
1049
797
        name = name[idx+1 : ]
1050
798
 
 
799
    # make it not a hidden file
1051
800
    name = name.lstrip('.')
1052
801
 
 
802
    # remove any wierd characters; we don't escape them but rather
 
803
    # just pull them out
 
804
    name = re.sub(r'[^\w.]', '', name)
 
805
 
1053
806
    s = hexlify(rand_bytes(8))
1054
807
    return '-'.join((name, compact_date(time.time()), s))