~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-05-30 03:14:07 UTC
  • Revision ID: mbp@sourcefrog.net-20050530031407-d37f43ff76a5e0d9
- tests for add --no-recurse

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
 
 
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
 
43
71
def find_branch_root(f=None):
44
72
    """Find the branch root enclosing f, or pwd.
45
73
 
 
74
    f may be a filename or a URL.
 
75
 
46
76
    It is not necessary that f exists.
47
77
 
48
78
    Basically we keep looking up until we find the control directory or
53
83
        f = os.path.realpath(f)
54
84
    else:
55
85
        f = os.path.abspath(f)
 
86
    if not os.path.exists(f):
 
87
        raise BzrError('%r does not exist' % f)
 
88
        
56
89
 
57
90
    orig_f = f
58
91
 
70
103
######################################################################
71
104
# branch objects
72
105
 
73
 
class Branch:
 
106
class Branch(object):
74
107
    """Branch holding a history of revisions.
75
108
 
76
109
    base
77
110
        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.
78
121
    """
79
 
    _lockmode = None
 
122
    base = None
 
123
    _lock_mode = None
 
124
    _lock_count = None
80
125
    
81
 
    def __init__(self, base, init=False, find_root=True, lock_mode='w'):
 
126
    def __init__(self, base, init=False, find_root=True):
82
127
        """Create new branch object at a particular location.
83
128
 
84
129
        base -- Base directory for the branch.
101
146
        else:
102
147
            self.base = os.path.realpath(base)
103
148
            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'])
 
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'])
107
153
        self._check_format()
108
 
        self.lock(lock_mode)
 
154
        self._lockfile = self.controlfile('branch-lock', 'wb')
109
155
 
110
156
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
111
157
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
119
165
    __repr__ = __str__
120
166
 
121
167
 
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
 
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")
 
179
            
 
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
134
188
            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
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)
 
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
169
207
 
170
208
 
171
209
    def abspath(self, name):
180
218
        rp = os.path.realpath(path)
181
219
        # FIXME: windows
182
220
        if not rp.startswith(self.base):
183
 
            bailout("path %r is not within branch %r" % (rp, self.base))
 
221
            from errors import NotBranchError
 
222
            raise NotBranchError("path %r is not within branch %r" % (rp, self.base))
184
223
        rp = rp[len(self.base):]
185
224
        rp = rp.lstrip(os.sep)
186
225
        return rp
200
239
        and binary.  binary files are untranslated byte streams.  Text
201
240
        control files are stored with Unix newlines and in UTF-8, even
202
241
        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.
203
245
        """
204
246
 
205
247
        fn = self.controlfilename(file_or_path)
247
289
        fmt = self.controlfile('branch-format', 'r').read()
248
290
        fmt.replace('\r\n', '')
249
291
        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'])
253
 
 
254
 
 
 
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
255
299
    def read_working_inventory(self):
256
300
        """Read the working inventory."""
257
 
        self._need_readlock()
258
301
        before = time.time()
259
302
        # ElementTree does its own conversion from UTF-8, so open in
260
303
        # binary.
262
305
        mutter("loaded inventory of %d items in %f"
263
306
               % (len(inv), time.time() - before))
264
307
        return inv
265
 
 
 
308
            
266
309
 
267
310
    def _write_inventory(self, inv):
268
311
        """Update the working inventory.
270
313
        That is to say, the inventory describing changes underway, that
271
314
        will be committed to the next revision.
272
315
        """
273
 
        self._need_writelock()
274
316
        ## TODO: factor out to atomicfile?  is rename safe on windows?
275
317
        ## TODO: Maybe some kind of clean/dirty marker on inventory?
276
318
        tmpfname = self.controlfilename('inventory.tmp')
282
324
            os.remove(inv_fname)
283
325
        os.rename(tmpfname, inv_fname)
284
326
        mutter('wrote working inventory')
285
 
 
 
327
            
286
328
 
287
329
    inventory = property(read_working_inventory, _write_inventory, None,
288
330
                         """Inventory for the working copy.""")
289
331
 
290
332
 
291
 
    def add(self, files, verbose=False):
 
333
    @with_writelock
 
334
    def add(self, files, verbose=False, ids=None):
292
335
        """Make files versioned.
293
336
 
294
337
        Note that the command line normally calls smart_add instead.
307
350
        TODO: Adding a directory should optionally recurse down and
308
351
               add all non-ignored children.  Perhaps do that in a
309
352
               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
353
        """
333
 
        self._need_writelock()
334
 
 
335
354
        # TODO: Re-adding a file that is removed in the working copy
336
355
        # should probably put it back with the previous ID.
337
356
        if isinstance(files, types.StringTypes):
 
357
            assert(ids is None or isinstance(ids, types.StringTypes))
338
358
            files = [files]
339
 
        
 
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
 
340
367
        inv = self.read_working_inventory()
341
 
        for f in files:
 
368
        for f,file_id in zip(files, ids):
342
369
            if is_control_file(f):
343
 
                bailout("cannot add control file %s" % quotefn(f))
 
370
                raise BzrError("cannot add control file %s" % quotefn(f))
344
371
 
345
372
            fp = splitpath(f)
346
373
 
347
374
            if len(fp) == 0:
348
 
                bailout("cannot add top-level %r" % f)
349
 
                
 
375
                raise BzrError("cannot add top-level %r" % f)
 
376
 
350
377
            fullpath = os.path.normpath(self.abspath(f))
351
378
 
352
379
            try:
353
380
                kind = file_kind(fullpath)
354
381
            except OSError:
355
382
                # maybe something better?
356
 
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
357
 
            
 
383
                raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
 
384
 
358
385
            if kind != 'file' and kind != 'directory':
359
 
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
386
                raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
360
387
 
361
 
            file_id = gen_file_id(f)
 
388
            if file_id is None:
 
389
                file_id = gen_file_id(f)
362
390
            inv.add_path(f, kind=kind, file_id=file_id)
363
391
 
364
392
            if verbose:
365
393
                show_status('A', kind, quotefn(f))
366
 
                
 
394
 
367
395
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
 
396
 
 
397
        self._write_inventory(inv)
368
398
            
369
 
        self._write_inventory(inv)
370
 
 
371
399
 
372
400
    def print_file(self, file, revno):
373
401
        """Print `file` to stdout."""
374
 
        self._need_readlock()
375
402
        tree = self.revision_tree(self.lookup_revision(revno))
376
403
        # use inventory as it was in that revision
377
404
        file_id = tree.inventory.path2id(file)
378
405
        if not file_id:
379
 
            bailout("%r is not present in revision %d" % (file, revno))
 
406
            raise BzrError("%r is not present in revision %d" % (file, revno))
380
407
        tree.print_file(file_id)
381
 
        
382
 
 
 
408
 
 
409
 
 
410
    @with_writelock
383
411
    def remove(self, files, verbose=False):
384
412
        """Mark nominated files for removal from the inventory.
385
413
 
387
415
 
388
416
        TODO: Refuse to remove modified files unless --force is given?
389
417
 
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
418
        TODO: Do something useful with directories.
413
419
 
414
420
        TODO: Should this remove the text or not?  Tough call; not
418
424
        """
419
425
        ## TODO: Normalize names
420
426
        ## TODO: Remove nested loops; better scalability
421
 
        self._need_writelock()
422
 
 
423
427
        if isinstance(files, types.StringTypes):
424
428
            files = [files]
425
 
        
 
429
 
426
430
        tree = self.working_tree()
427
431
        inv = tree.inventory
428
432
 
430
434
        for f in files:
431
435
            fid = inv.path2id(f)
432
436
            if not fid:
433
 
                bailout("cannot remove unversioned file %s" % quotefn(f))
 
437
                raise BzrError("cannot remove unversioned file %s" % quotefn(f))
434
438
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
435
439
            if verbose:
436
440
                # having remove it, it must be either ignored or unknown
444
448
        self._write_inventory(inv)
445
449
 
446
450
 
 
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
 
447
461
    def unknowns(self):
448
462
        """Return all unknown files.
449
463
 
463
477
        return self.working_tree().unknowns()
464
478
 
465
479
 
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
480
    def append_revision(self, revision_id):
638
481
        mutter("add {%s} to revision-history" % revision_id)
639
482
        rev_history = self.revision_history()
655
498
 
656
499
    def get_revision(self, revision_id):
657
500
        """Return the Revision object for a named revision"""
658
 
        self._need_readlock()
659
501
        r = Revision.read_xml(self.revision_store[revision_id])
660
502
        assert r.revision_id == revision_id
661
503
        return r
667
509
        TODO: Perhaps for this and similar methods, take a revision
668
510
               parameter which can be either an integer revno or a
669
511
               string hash."""
670
 
        self._need_readlock()
671
512
        i = Inventory.read_xml(self.inventory_store[inventory_id])
672
513
        return i
673
514
 
674
515
 
675
516
    def get_revision_inventory(self, revision_id):
676
517
        """Return inventory of a past revision."""
677
 
        self._need_readlock()
678
518
        if revision_id == None:
679
519
            return Inventory()
680
520
        else:
681
521
            return self.get_inventory(self.get_revision(revision_id).inventory_id)
682
522
 
683
523
 
 
524
    @with_readlock
684
525
    def revision_history(self):
685
526
        """Return sequence of revision hashes on to this branch.
686
527
 
687
528
        >>> ScratchBranch().revision_history()
688
529
        []
689
530
        """
690
 
        self._need_readlock()
691
531
        return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
692
532
 
693
533
 
710
550
                yield i, rh[i-1]
711
551
                i -= 1
712
552
        else:
713
 
            raise BzrError('invalid history direction %r' % direction)
 
553
            raise ValueError('invalid history direction', direction)
714
554
 
715
555
 
716
556
    def revno(self):
718
558
 
719
559
        That is equivalent to the number of revisions committed to
720
560
        this branch.
721
 
 
722
 
        >>> b = ScratchBranch()
723
 
        >>> b.revno()
724
 
        0
725
 
        >>> b.commit('no foo')
726
 
        >>> b.revno()
727
 
        1
728
561
        """
729
562
        return len(self.revision_history())
730
563
 
731
564
 
732
565
    def last_patch(self):
733
566
        """Return last patch hash, or None if no history.
734
 
 
735
 
        >>> ScratchBranch().last_patch() == None
736
 
        True
737
567
        """
738
568
        ph = self.revision_history()
739
569
        if ph:
740
570
            return ph[-1]
741
571
        else:
742
572
            return None
 
573
 
 
574
 
 
575
    def commit(self, *args, **kw):
 
576
        """Deprecated"""
 
577
        from bzrlib.commit import commit
 
578
        commit(self, *args, **kw)
743
579
        
744
580
 
745
581
    def lookup_revision(self, revno):
759
595
 
760
596
        `revision_id` may be None for the null revision, in which case
761
597
        an `EmptyTree` is returned."""
762
 
        self._need_readlock()
 
598
        # TODO: refactor this to use an existing revision object
 
599
        # so we don't need to read it in twice.
763
600
        if revision_id == None:
764
601
            return EmptyTree()
765
602
        else:
769
606
 
770
607
    def working_tree(self):
771
608
        """Return a `Tree` for the working copy."""
 
609
        from workingtree import WorkingTree
772
610
        return WorkingTree(self.base, self.read_working_inventory())
773
611
 
774
612
 
776
614
        """Return `Tree` object for last revision.
777
615
 
778
616
        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
617
        """
790
618
        r = self.last_patch()
791
619
        if r == None:
795
623
 
796
624
 
797
625
 
 
626
    @with_writelock
798
627
    def rename_one(self, from_rel, to_rel):
799
628
        """Rename one file.
800
629
 
801
630
        This can change the directory or the filename or both.
802
631
        """
803
 
        self._need_writelock()
804
632
        tree = self.working_tree()
805
633
        inv = tree.inventory
806
634
        if not tree.has_filename(from_rel):
807
 
            bailout("can't rename: old working file %r does not exist" % from_rel)
 
635
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
808
636
        if tree.has_filename(to_rel):
809
 
            bailout("can't rename: new working file %r already exists" % to_rel)
810
 
            
 
637
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
 
638
 
811
639
        file_id = inv.path2id(from_rel)
812
640
        if file_id == None:
813
 
            bailout("can't rename: old name %r is not versioned" % from_rel)
 
641
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
814
642
 
815
643
        if inv.path2id(to_rel):
816
 
            bailout("can't rename: new name %r is already versioned" % to_rel)
 
644
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
817
645
 
818
646
        to_dir, to_tail = os.path.split(to_rel)
819
647
        to_dir_id = inv.path2id(to_dir)
820
648
        if to_dir_id == None and to_dir != '':
821
 
            bailout("can't determine destination directory id for %r" % to_dir)
 
649
            raise BzrError("can't determine destination directory id for %r" % to_dir)
822
650
 
823
651
        mutter("rename_one:")
824
652
        mutter("  file_id    {%s}" % file_id)
826
654
        mutter("  to_rel     %r" % to_rel)
827
655
        mutter("  to_dir     %r" % to_dir)
828
656
        mutter("  to_dir_id  {%s}" % to_dir_id)
829
 
            
 
657
 
830
658
        inv.rename(file_id, to_dir_id, to_tail)
831
659
 
832
660
        print "%s => %s" % (from_rel, to_rel)
833
 
        
 
661
 
834
662
        from_abs = self.abspath(from_rel)
835
663
        to_abs = self.abspath(to_rel)
836
664
        try:
837
665
            os.rename(from_abs, to_abs)
838
666
        except OSError, e:
839
 
            bailout("failed to rename %r to %r: %s"
 
667
            raise BzrError("failed to rename %r to %r: %s"
840
668
                    % (from_abs, to_abs, e[1]),
841
669
                    ["rename rolled back"])
842
670
 
843
671
        self._write_inventory(inv)
844
 
            
845
 
 
846
 
 
 
672
 
 
673
 
 
674
 
 
675
    @with_writelock
847
676
    def move(self, from_paths, to_name):
848
677
        """Rename files.
849
678
 
855
684
        Note that to_name is only the last component of the new name;
856
685
        this doesn't change the directory.
857
686
        """
858
 
        self._need_writelock()
859
687
        ## TODO: Option to move IDs only
860
688
        assert not isinstance(from_paths, basestring)
861
689
        tree = self.working_tree()
862
690
        inv = tree.inventory
863
691
        to_abs = self.abspath(to_name)
864
692
        if not isdir(to_abs):
865
 
            bailout("destination %r is not a directory" % to_abs)
 
693
            raise BzrError("destination %r is not a directory" % to_abs)
866
694
        if not tree.has_filename(to_name):
867
 
            bailout("destination %r not in working directory" % to_abs)
 
695
            raise BzrError("destination %r not in working directory" % to_abs)
868
696
        to_dir_id = inv.path2id(to_name)
869
697
        if to_dir_id == None and to_name != '':
870
 
            bailout("destination %r is not a versioned directory" % to_name)
 
698
            raise BzrError("destination %r is not a versioned directory" % to_name)
871
699
        to_dir_ie = inv[to_dir_id]
872
700
        if to_dir_ie.kind not in ('directory', 'root_directory'):
873
 
            bailout("destination %r is not a directory" % to_abs)
 
701
            raise BzrError("destination %r is not a directory" % to_abs)
874
702
 
875
 
        to_idpath = Set(inv.get_idpath(to_dir_id))
 
703
        to_idpath = inv.get_idpath(to_dir_id)
876
704
 
877
705
        for f in from_paths:
878
706
            if not tree.has_filename(f):
879
 
                bailout("%r does not exist in working tree" % f)
 
707
                raise BzrError("%r does not exist in working tree" % f)
880
708
            f_id = inv.path2id(f)
881
709
            if f_id == None:
882
 
                bailout("%r is not versioned" % f)
 
710
                raise BzrError("%r is not versioned" % f)
883
711
            name_tail = splitpath(f)[-1]
884
712
            dest_path = appendpath(to_name, name_tail)
885
713
            if tree.has_filename(dest_path):
886
 
                bailout("destination %r already exists" % dest_path)
 
714
                raise BzrError("destination %r already exists" % dest_path)
887
715
            if f_id in to_idpath:
888
 
                bailout("can't move %r to a subdirectory of itself" % f)
 
716
                raise BzrError("can't move %r to a subdirectory of itself" % f)
889
717
 
890
718
        # OK, so there's a race here, it's possible that someone will
891
719
        # create a file in this interval and then the rename might be
899
727
            try:
900
728
                os.rename(self.abspath(f), self.abspath(dest_path))
901
729
            except OSError, e:
902
 
                bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
 
730
                raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
903
731
                        ["rename rolled back"])
904
732
 
905
733
        self._write_inventory(inv)
906
734
 
907
735
 
908
736
 
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
 
 
962
737
 
963
738
class ScratchBranch(Branch):
964
739
    """Special test class: a branch that cleans up after itself.
967
742
    >>> isdir(b.base)
968
743
    True
969
744
    >>> bd = b.base
970
 
    >>> del b
 
745
    >>> b.destroy()
971
746
    >>> isdir(bd)
972
747
    False
973
748
    """
987
762
 
988
763
 
989
764
    def __del__(self):
 
765
        self.destroy()
 
766
 
 
767
    def destroy(self):
990
768
        """Destroy the test branch, removing the scratch directory."""
991
769
        try:
 
770
            mutter("delete ScratchBranch %s" % self.base)
992
771
            shutil.rmtree(self.base)
993
 
        except OSError:
 
772
        except OSError, e:
994
773
            # Work around for shutil.rmtree failing on Windows when
995
774
            # readonly files are encountered
 
775
            mutter("hit exception in destroying ScratchBranch: %s" % e)
996
776
            for root, dirs, files in os.walk(self.base, topdown=False):
997
777
                for name in files:
998
778
                    os.chmod(os.path.join(root, name), 0700)
999
779
            shutil.rmtree(self.base)
 
780
        self.base = None
1000
781
 
1001
782
    
1002
783
 
1019
800
 
1020
801
 
1021
802
 
1022
 
def _gen_revision_id(when):
1023
 
    """Return new revision-id."""
1024
 
    s = '%s-%s-' % (user_email(), compact_date(when))
1025
 
    s += hexlify(rand_bytes(8))
1026
 
    return s
1027
 
 
1028
 
 
1029
803
def gen_file_id(name):
1030
804
    """Return new file id.
1031
805
 
1032
806
    This should probably generate proper UUIDs, but for the moment we
1033
807
    cope with just randomness because running uuidgen every time is
1034
808
    slow."""
 
809
    import re
 
810
 
 
811
    # get last component
1035
812
    idx = name.rfind('/')
1036
813
    if idx != -1:
1037
814
        name = name[idx+1 : ]
1039
816
    if idx != -1:
1040
817
        name = name[idx+1 : ]
1041
818
 
 
819
    # make it not a hidden file
1042
820
    name = name.lstrip('.')
1043
821
 
 
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
 
1044
826
    s = hexlify(rand_bytes(8))
1045
827
    return '-'.join((name, compact_date(time.time()), s))