~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-05-09 01:23:17 UTC
  • Revision ID: mbp@sourcefrog.net-20050509012317-a503ae2eed842146
- doc: please run tests after installation

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
 
18
20
import sys, os, os.path, random, time, sha, sets, types, re, shutil, tempfile
19
21
import traceback, socket, fnmatch, difflib, time
20
22
from binascii import hexlify
22
24
import bzrlib
23
25
from inventory import Inventory
24
26
from trace import mutter, note
25
 
from tree import Tree, EmptyTree, RevisionTree
 
27
from tree import Tree, EmptyTree, RevisionTree, WorkingTree
26
28
from inventory import InventoryEntry, Inventory
27
29
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
28
30
     format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
29
31
     joinpath, sha_string, file_kind, local_time_offset, appendpath
30
32
from store import ImmutableStore
31
33
from revision import Revision
32
 
from errors import BzrError
 
34
from errors import bailout, BzrError
33
35
from textui import show_status
 
36
from diff import diff_trees
34
37
 
35
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
36
39
## TODO: Maybe include checks for common corruption of newlines, etc?
37
40
 
38
41
 
39
42
 
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
 
 
48
 
 
49
 
def with_writelock(method):
50
 
    """Method decorator for functions run with the branch locked."""
51
 
    def d(self, *a, **k):
52
 
        # called with self set to the branch
53
 
        self.lock('w')
54
 
        try:
55
 
            return method(self, *a, **k)
56
 
        finally:
57
 
            self.unlock()
58
 
    return d
59
 
 
60
 
 
61
 
def with_readlock(method):
62
 
    def d(self, *a, **k):
63
 
        self.lock('r')
64
 
        try:
65
 
            return method(self, *a, **k)
66
 
        finally:
67
 
            self.unlock()
68
 
    return d
69
 
        
70
 
 
71
43
def find_branch_root(f=None):
72
44
    """Find the branch root enclosing f, or pwd.
73
45
 
74
 
    f may be a filename or a URL.
75
 
 
76
46
    It is not necessary that f exists.
77
47
 
78
48
    Basically we keep looking up until we find the control directory or
83
53
        f = os.path.realpath(f)
84
54
    else:
85
55
        f = os.path.abspath(f)
86
 
    if not os.path.exists(f):
87
 
        raise BzrError('%r does not exist' % f)
88
 
        
89
56
 
90
57
    orig_f = f
91
58
 
103
70
######################################################################
104
71
# branch objects
105
72
 
106
 
class Branch(object):
 
73
class Branch:
107
74
    """Branch holding a history of revisions.
108
75
 
109
76
    base
110
77
        Base directory of the branch.
111
 
 
112
 
    _lock_mode
113
 
        None, or 'r' or 'w'
114
 
 
115
 
    _lock_count
116
 
        If _lock_mode is true, a positive count of the number of times the
117
 
        lock has been taken.
118
 
 
119
 
    _lockfile
120
 
        Open file used for locking.
121
78
    """
122
 
    base = None
123
 
    _lock_mode = None
124
 
    _lock_count = None
 
79
    _lockmode = None
125
80
    
126
 
    def __init__(self, base, init=False, find_root=True):
 
81
    def __init__(self, base, init=False, find_root=True, lock_mode='w'):
127
82
        """Create new branch object at a particular location.
128
83
 
129
84
        base -- Base directory for the branch.
146
101
        else:
147
102
            self.base = os.path.realpath(base)
148
103
            if not isdir(self.controlfilename('.')):
149
 
                from errors import NotBranchError
150
 
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
151
 
                                     ['use "bzr init" to initialize a new working tree',
152
 
                                      'current bzr can only operate from top-of-tree'])
 
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'])
153
107
        self._check_format()
154
 
        self._lockfile = self.controlfile('branch-lock', 'wb')
 
108
        self.lock(lock_mode)
155
109
 
156
110
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
157
111
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
165
119
    __repr__ = __str__
166
120
 
167
121
 
168
 
    def __del__(self):
169
 
        if self._lock_mode:
170
 
            from warnings import warn
171
 
            warn("branch %r was not explicitly unlocked" % self)
172
 
            self.unlock()
173
 
 
174
 
 
175
 
    def lock(self, mode):
176
 
        if self._lock_mode:
177
 
            if mode == 'w' and cur_lm == 'r':
178
 
                raise BzrError("can't upgrade to a write lock")
 
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
179
146
            
180
 
            assert self._lock_count >= 1
181
 
            self._lock_count += 1
182
 
        else:
183
 
            from bzrlib.lock import lock, LOCK_SH, LOCK_EX
184
 
            if mode == 'r':
185
 
                m = LOCK_SH
186
 
            elif mode == 'w':
187
 
                m = LOCK_EX
188
 
            else:
189
 
                raise ValueError('invalid lock mode %r' % mode)
190
 
 
191
 
            lock(self._lockfile, m)
192
 
            self._lock_mode = mode
193
 
            self._lock_count = 1
194
 
 
195
 
 
196
 
    def unlock(self):
197
 
        if not self._lock_mode:
198
 
            raise BzrError('branch %r is not locked' % (self))
199
 
 
200
 
        if self._lock_count > 1:
201
 
            self._lock_count -= 1
202
 
        else:
203
 
            assert self._lock_count == 1
204
 
            from bzrlib.lock import unlock
205
 
            unlock(self._lockfile)
206
 
            self._lock_mode = self._lock_count = None
 
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
 
160
 
 
161
 
 
162
    def _need_readlock(self):
 
163
        if self._lockmode not in ['r', 'w']:
 
164
            raise BzrError('need read lock on branch, only have %r' % self._lockmode)
 
165
 
 
166
    def _need_writelock(self):
 
167
        if self._lockmode not in ['w']:
 
168
            raise BzrError('need write lock on branch, only have %r' % self._lockmode)
207
169
 
208
170
 
209
171
    def abspath(self, name):
218
180
        rp = os.path.realpath(path)
219
181
        # FIXME: windows
220
182
        if not rp.startswith(self.base):
221
 
            from errors import NotBranchError
222
 
            raise NotBranchError("path %r is not within branch %r" % (rp, self.base))
 
183
            bailout("path %r is not within branch %r" % (rp, self.base))
223
184
        rp = rp[len(self.base):]
224
185
        rp = rp.lstrip(os.sep)
225
186
        return rp
239
200
        and binary.  binary files are untranslated byte streams.  Text
240
201
        control files are stored with Unix newlines and in UTF-8, even
241
202
        if the platform or locale defaults are different.
242
 
 
243
 
        Controlfiles should almost never be opened in write mode but
244
 
        rather should be atomically copied and replaced using atomicfile.
245
203
        """
246
204
 
247
205
        fn = self.controlfilename(file_or_path)
289
247
        fmt = self.controlfile('branch-format', 'r').read()
290
248
        fmt.replace('\r\n', '')
291
249
        if fmt != BZR_BRANCH_FORMAT:
292
 
            raise BzrError('sorry, branch format %r not supported' % fmt,
293
 
                           ['use a different bzr version',
294
 
                            'or remove the .bzr directory and "bzr init" again'])
295
 
 
296
 
 
297
 
 
298
 
    @with_readlock
 
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'])
 
253
 
 
254
 
299
255
    def read_working_inventory(self):
300
256
        """Read the working inventory."""
 
257
        self._need_readlock()
301
258
        before = time.time()
302
259
        # ElementTree does its own conversion from UTF-8, so open in
303
260
        # binary.
305
262
        mutter("loaded inventory of %d items in %f"
306
263
               % (len(inv), time.time() - before))
307
264
        return inv
308
 
            
 
265
 
309
266
 
310
267
    def _write_inventory(self, inv):
311
268
        """Update the working inventory.
313
270
        That is to say, the inventory describing changes underway, that
314
271
        will be committed to the next revision.
315
272
        """
 
273
        self._need_writelock()
316
274
        ## TODO: factor out to atomicfile?  is rename safe on windows?
317
275
        ## TODO: Maybe some kind of clean/dirty marker on inventory?
318
276
        tmpfname = self.controlfilename('inventory.tmp')
324
282
            os.remove(inv_fname)
325
283
        os.rename(tmpfname, inv_fname)
326
284
        mutter('wrote working inventory')
327
 
            
 
285
 
328
286
 
329
287
    inventory = property(read_working_inventory, _write_inventory, None,
330
288
                         """Inventory for the working copy.""")
331
289
 
332
290
 
333
 
    @with_writelock
334
 
    def add(self, files, verbose=False, ids=None):
 
291
    def add(self, files, verbose=False):
335
292
        """Make files versioned.
336
293
 
337
294
        Note that the command line normally calls smart_add instead.
350
307
        TODO: Adding a directory should optionally recurse down and
351
308
               add all non-ignored children.  Perhaps do that in a
352
309
               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', [])
353
332
        """
 
333
        self._need_writelock()
 
334
 
354
335
        # TODO: Re-adding a file that is removed in the working copy
355
336
        # should probably put it back with the previous ID.
356
337
        if isinstance(files, types.StringTypes):
357
 
            assert(ids is None or isinstance(ids, types.StringTypes))
358
338
            files = [files]
359
 
            if ids is not None:
360
 
                ids = [ids]
361
 
 
362
 
        if ids is None:
363
 
            ids = [None] * len(files)
364
 
        else:
365
 
            assert(len(ids) == len(files))
366
 
 
 
339
        
367
340
        inv = self.read_working_inventory()
368
 
        for f,file_id in zip(files, ids):
 
341
        for f in files:
369
342
            if is_control_file(f):
370
 
                raise BzrError("cannot add control file %s" % quotefn(f))
 
343
                bailout("cannot add control file %s" % quotefn(f))
371
344
 
372
345
            fp = splitpath(f)
373
346
 
374
347
            if len(fp) == 0:
375
 
                raise BzrError("cannot add top-level %r" % f)
376
 
 
 
348
                bailout("cannot add top-level %r" % f)
 
349
                
377
350
            fullpath = os.path.normpath(self.abspath(f))
378
351
 
379
352
            try:
380
353
                kind = file_kind(fullpath)
381
354
            except OSError:
382
355
                # maybe something better?
383
 
                raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
384
 
 
 
356
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
357
            
385
358
            if kind != 'file' and kind != 'directory':
386
 
                raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
 
359
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
387
360
 
388
 
            if file_id is None:
389
 
                file_id = gen_file_id(f)
 
361
            file_id = gen_file_id(f)
390
362
            inv.add_path(f, kind=kind, file_id=file_id)
391
363
 
392
364
            if verbose:
393
365
                show_status('A', kind, quotefn(f))
394
 
 
 
366
                
395
367
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
396
 
 
 
368
            
397
369
        self._write_inventory(inv)
398
 
            
 
370
 
399
371
 
400
372
    def print_file(self, file, revno):
401
373
        """Print `file` to stdout."""
 
374
        self._need_readlock()
402
375
        tree = self.revision_tree(self.lookup_revision(revno))
403
376
        # use inventory as it was in that revision
404
377
        file_id = tree.inventory.path2id(file)
405
378
        if not file_id:
406
 
            raise BzrError("%r is not present in revision %d" % (file, revno))
 
379
            bailout("%r is not present in revision %d" % (file, revno))
407
380
        tree.print_file(file_id)
408
 
 
409
 
 
410
 
    @with_writelock
 
381
        
 
382
 
411
383
    def remove(self, files, verbose=False):
412
384
        """Mark nominated files for removal from the inventory.
413
385
 
415
387
 
416
388
        TODO: Refuse to remove modified files unless --force is given?
417
389
 
 
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
 
418
412
        TODO: Do something useful with directories.
419
413
 
420
414
        TODO: Should this remove the text or not?  Tough call; not
424
418
        """
425
419
        ## TODO: Normalize names
426
420
        ## TODO: Remove nested loops; better scalability
 
421
        self._need_writelock()
 
422
 
427
423
        if isinstance(files, types.StringTypes):
428
424
            files = [files]
429
 
 
 
425
        
430
426
        tree = self.working_tree()
431
427
        inv = tree.inventory
432
428
 
434
430
        for f in files:
435
431
            fid = inv.path2id(f)
436
432
            if not fid:
437
 
                raise BzrError("cannot remove unversioned file %s" % quotefn(f))
 
433
                bailout("cannot remove unversioned file %s" % quotefn(f))
438
434
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
439
435
            if verbose:
440
436
                # having remove it, it must be either ignored or unknown
448
444
        self._write_inventory(inv)
449
445
 
450
446
 
451
 
    def set_inventory(self, new_inventory_list):
452
 
        inv = Inventory()
453
 
        for path, file_id, parent, kind in new_inventory_list:
454
 
            name = os.path.basename(path)
455
 
            if name == "":
456
 
                continue
457
 
            inv.add(InventoryEntry(file_id, name, kind, parent))
458
 
        self._write_inventory(inv)
459
 
 
460
 
 
461
447
    def unknowns(self):
462
448
        """Return all unknown files.
463
449
 
477
463
        return self.working_tree().unknowns()
478
464
 
479
465
 
 
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
 
480
637
    def append_revision(self, revision_id):
481
638
        mutter("add {%s} to revision-history" % revision_id)
482
639
        rev_history = self.revision_history()
498
655
 
499
656
    def get_revision(self, revision_id):
500
657
        """Return the Revision object for a named revision"""
 
658
        self._need_readlock()
501
659
        r = Revision.read_xml(self.revision_store[revision_id])
502
660
        assert r.revision_id == revision_id
503
661
        return r
509
667
        TODO: Perhaps for this and similar methods, take a revision
510
668
               parameter which can be either an integer revno or a
511
669
               string hash."""
 
670
        self._need_readlock()
512
671
        i = Inventory.read_xml(self.inventory_store[inventory_id])
513
672
        return i
514
673
 
515
674
 
516
675
    def get_revision_inventory(self, revision_id):
517
676
        """Return inventory of a past revision."""
 
677
        self._need_readlock()
518
678
        if revision_id == None:
519
679
            return Inventory()
520
680
        else:
521
681
            return self.get_inventory(self.get_revision(revision_id).inventory_id)
522
682
 
523
683
 
524
 
    @with_readlock
525
684
    def revision_history(self):
526
685
        """Return sequence of revision hashes on to this branch.
527
686
 
528
687
        >>> ScratchBranch().revision_history()
529
688
        []
530
689
        """
 
690
        self._need_readlock()
531
691
        return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
532
692
 
533
693
 
550
710
                yield i, rh[i-1]
551
711
                i -= 1
552
712
        else:
553
 
            raise ValueError('invalid history direction', direction)
 
713
            raise BzrError('invalid history direction %r' % direction)
554
714
 
555
715
 
556
716
    def revno(self):
558
718
 
559
719
        That is equivalent to the number of revisions committed to
560
720
        this branch.
 
721
 
 
722
        >>> b = ScratchBranch()
 
723
        >>> b.revno()
 
724
        0
 
725
        >>> b.commit('no foo')
 
726
        >>> b.revno()
 
727
        1
561
728
        """
562
729
        return len(self.revision_history())
563
730
 
564
731
 
565
732
    def last_patch(self):
566
733
        """Return last patch hash, or None if no history.
 
734
 
 
735
        >>> ScratchBranch().last_patch() == None
 
736
        True
567
737
        """
568
738
        ph = self.revision_history()
569
739
        if ph:
570
740
            return ph[-1]
571
741
        else:
572
742
            return None
573
 
 
574
 
 
575
 
    def commit(self, *args, **kw):
576
 
        """Deprecated"""
577
 
        from bzrlib.commit import commit
578
 
        commit(self, *args, **kw)
579
743
        
580
744
 
581
745
    def lookup_revision(self, revno):
595
759
 
596
760
        `revision_id` may be None for the null revision, in which case
597
761
        an `EmptyTree` is returned."""
598
 
        # TODO: refactor this to use an existing revision object
599
 
        # so we don't need to read it in twice.
 
762
        self._need_readlock()
600
763
        if revision_id == None:
601
764
            return EmptyTree()
602
765
        else:
606
769
 
607
770
    def working_tree(self):
608
771
        """Return a `Tree` for the working copy."""
609
 
        from workingtree import WorkingTree
610
772
        return WorkingTree(self.base, self.read_working_inventory())
611
773
 
612
774
 
614
776
        """Return `Tree` object for last revision.
615
777
 
616
778
        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
617
789
        """
618
790
        r = self.last_patch()
619
791
        if r == None:
623
795
 
624
796
 
625
797
 
626
 
    @with_writelock
627
798
    def rename_one(self, from_rel, to_rel):
628
799
        """Rename one file.
629
800
 
630
801
        This can change the directory or the filename or both.
631
802
        """
 
803
        self._need_writelock()
632
804
        tree = self.working_tree()
633
805
        inv = tree.inventory
634
806
        if not tree.has_filename(from_rel):
635
 
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
 
807
            bailout("can't rename: old working file %r does not exist" % from_rel)
636
808
        if tree.has_filename(to_rel):
637
 
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
638
 
 
 
809
            bailout("can't rename: new working file %r already exists" % to_rel)
 
810
            
639
811
        file_id = inv.path2id(from_rel)
640
812
        if file_id == None:
641
 
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
 
813
            bailout("can't rename: old name %r is not versioned" % from_rel)
642
814
 
643
815
        if inv.path2id(to_rel):
644
 
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
 
816
            bailout("can't rename: new name %r is already versioned" % to_rel)
645
817
 
646
818
        to_dir, to_tail = os.path.split(to_rel)
647
819
        to_dir_id = inv.path2id(to_dir)
648
820
        if to_dir_id == None and to_dir != '':
649
 
            raise BzrError("can't determine destination directory id for %r" % to_dir)
 
821
            bailout("can't determine destination directory id for %r" % to_dir)
650
822
 
651
823
        mutter("rename_one:")
652
824
        mutter("  file_id    {%s}" % file_id)
654
826
        mutter("  to_rel     %r" % to_rel)
655
827
        mutter("  to_dir     %r" % to_dir)
656
828
        mutter("  to_dir_id  {%s}" % to_dir_id)
657
 
 
 
829
            
658
830
        inv.rename(file_id, to_dir_id, to_tail)
659
831
 
660
832
        print "%s => %s" % (from_rel, to_rel)
661
 
 
 
833
        
662
834
        from_abs = self.abspath(from_rel)
663
835
        to_abs = self.abspath(to_rel)
664
836
        try:
665
837
            os.rename(from_abs, to_abs)
666
838
        except OSError, e:
667
 
            raise BzrError("failed to rename %r to %r: %s"
 
839
            bailout("failed to rename %r to %r: %s"
668
840
                    % (from_abs, to_abs, e[1]),
669
841
                    ["rename rolled back"])
670
842
 
671
843
        self._write_inventory(inv)
672
 
 
673
 
 
674
 
 
675
 
    @with_writelock
 
844
            
 
845
 
 
846
 
676
847
    def move(self, from_paths, to_name):
677
848
        """Rename files.
678
849
 
684
855
        Note that to_name is only the last component of the new name;
685
856
        this doesn't change the directory.
686
857
        """
 
858
        self._need_writelock()
687
859
        ## TODO: Option to move IDs only
688
860
        assert not isinstance(from_paths, basestring)
689
861
        tree = self.working_tree()
690
862
        inv = tree.inventory
691
863
        to_abs = self.abspath(to_name)
692
864
        if not isdir(to_abs):
693
 
            raise BzrError("destination %r is not a directory" % to_abs)
 
865
            bailout("destination %r is not a directory" % to_abs)
694
866
        if not tree.has_filename(to_name):
695
 
            raise BzrError("destination %r not in working directory" % to_abs)
 
867
            bailout("destination %r not in working directory" % to_abs)
696
868
        to_dir_id = inv.path2id(to_name)
697
869
        if to_dir_id == None and to_name != '':
698
 
            raise BzrError("destination %r is not a versioned directory" % to_name)
 
870
            bailout("destination %r is not a versioned directory" % to_name)
699
871
        to_dir_ie = inv[to_dir_id]
700
872
        if to_dir_ie.kind not in ('directory', 'root_directory'):
701
 
            raise BzrError("destination %r is not a directory" % to_abs)
 
873
            bailout("destination %r is not a directory" % to_abs)
702
874
 
703
 
        to_idpath = inv.get_idpath(to_dir_id)
 
875
        to_idpath = Set(inv.get_idpath(to_dir_id))
704
876
 
705
877
        for f in from_paths:
706
878
            if not tree.has_filename(f):
707
 
                raise BzrError("%r does not exist in working tree" % f)
 
879
                bailout("%r does not exist in working tree" % f)
708
880
            f_id = inv.path2id(f)
709
881
            if f_id == None:
710
 
                raise BzrError("%r is not versioned" % f)
 
882
                bailout("%r is not versioned" % f)
711
883
            name_tail = splitpath(f)[-1]
712
884
            dest_path = appendpath(to_name, name_tail)
713
885
            if tree.has_filename(dest_path):
714
 
                raise BzrError("destination %r already exists" % dest_path)
 
886
                bailout("destination %r already exists" % dest_path)
715
887
            if f_id in to_idpath:
716
 
                raise BzrError("can't move %r to a subdirectory of itself" % f)
 
888
                bailout("can't move %r to a subdirectory of itself" % f)
717
889
 
718
890
        # OK, so there's a race here, it's possible that someone will
719
891
        # create a file in this interval and then the rename might be
727
899
            try:
728
900
                os.rename(self.abspath(f), self.abspath(dest_path))
729
901
            except OSError, e:
730
 
                raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
 
902
                bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
731
903
                        ["rename rolled back"])
732
904
 
733
905
        self._write_inventory(inv)
734
906
 
735
907
 
736
908
 
 
909
    def show_status(self, show_all=False):
 
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
        TODO: Get state for single files.
 
927
        """
 
928
        self._need_readlock()
 
929
 
 
930
        # We have to build everything into a list first so that it can
 
931
        # sorted by name, incorporating all the different sources.
 
932
 
 
933
        # FIXME: Rather than getting things in random order and then sorting,
 
934
        # just step through in order.
 
935
 
 
936
        # Interesting case: the old ID for a file has been removed,
 
937
        # but a new file has been created under that name.
 
938
 
 
939
        old = self.basis_tree()
 
940
        new = self.working_tree()
 
941
 
 
942
        for fs, fid, oldname, newname, kind in diff_trees(old, new):
 
943
            if fs == 'R':
 
944
                show_status(fs, kind,
 
945
                            oldname + ' => ' + newname)
 
946
            elif fs == 'A' or fs == 'M':
 
947
                show_status(fs, kind, newname)
 
948
            elif fs == 'D':
 
949
                show_status(fs, kind, oldname)
 
950
            elif fs == '.':
 
951
                if show_all:
 
952
                    show_status(fs, kind, newname)
 
953
            elif fs == 'I':
 
954
                if show_all:
 
955
                    show_status(fs, kind, newname)
 
956
            elif fs == '?':
 
957
                show_status(fs, kind, newname)
 
958
            else:
 
959
                bailout("weird file state %r" % ((fs, fid),))
 
960
                
 
961
 
737
962
 
738
963
class ScratchBranch(Branch):
739
964
    """Special test class: a branch that cleans up after itself.
800
1025
 
801
1026
 
802
1027
 
 
1028
def _gen_revision_id(when):
 
1029
    """Return new revision-id."""
 
1030
    s = '%s-%s-' % (user_email(), compact_date(when))
 
1031
    s += hexlify(rand_bytes(8))
 
1032
    return s
 
1033
 
 
1034
 
803
1035
def gen_file_id(name):
804
1036
    """Return new file id.
805
1037
 
806
1038
    This should probably generate proper UUIDs, but for the moment we
807
1039
    cope with just randomness because running uuidgen every time is
808
1040
    slow."""
809
 
    import re
810
 
 
811
 
    # get last component
812
1041
    idx = name.rfind('/')
813
1042
    if idx != -1:
814
1043
        name = name[idx+1 : ]
816
1045
    if idx != -1:
817
1046
        name = name[idx+1 : ]
818
1047
 
819
 
    # make it not a hidden file
820
1048
    name = name.lstrip('.')
821
1049
 
822
 
    # remove any wierd characters; we don't escape them but rather
823
 
    # just pull them out
824
 
    name = re.sub(r'[^\w.]', '', name)
825
 
 
826
1050
    s = hexlify(rand_bytes(8))
827
1051
    return '-'.join((name, compact_date(time.time()), s))