~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-05-03 07:48:54 UTC
  • Revision ID: mbp@sourcefrog.net-20050503074854-adb6f9d6382e27a9
- sketchy experiments in bash and zsh completion

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
 
    base
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.
 
76
    TODO: Perhaps use different stores for different classes of object,
 
77
           so that we can keep track of how much space each one uses,
 
78
           or garbage-collect them.
 
79
 
 
80
    TODO: Add a RemoteBranch subclass.  For the basic case of read-only
 
81
           HTTP access this should be very easy by, 
 
82
           just redirecting controlfile access into HTTP requests.
 
83
           We would need a RemoteStore working similarly.
 
84
 
 
85
    TODO: Keep the on-disk branch locked while the object exists.
 
86
 
 
87
    TODO: mkdir() method.
121
88
    """
122
 
    base = None
123
 
    _lock_mode = None
124
 
    _lock_count = None
125
 
    
126
89
    def __init__(self, base, init=False, find_root=True):
127
90
        """Create new branch object at a particular location.
128
91
 
146
109
        else:
147
110
            self.base = os.path.realpath(base)
148
111
            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'])
 
112
                bailout("not a bzr branch: %s" % quotefn(base),
 
113
                        ['use "bzr init" to initialize a new working tree',
 
114
                         'current bzr can only operate from top-of-tree'])
153
115
        self._check_format()
154
 
        self._lockfile = self.controlfile('branch-lock', 'wb')
155
116
 
156
117
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
157
118
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
165
126
    __repr__ = __str__
166
127
 
167
128
 
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
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
207
 
 
208
 
 
209
129
    def abspath(self, name):
210
130
        """Return absolute filename for something in the branch"""
211
131
        return os.path.join(self.base, name)
218
138
        rp = os.path.realpath(path)
219
139
        # FIXME: windows
220
140
        if not rp.startswith(self.base):
221
 
            from errors import NotBranchError
222
 
            raise NotBranchError("path %r is not within branch %r" % (rp, self.base))
 
141
            bailout("path %r is not within branch %r" % (rp, self.base))
223
142
        rp = rp[len(self.base):]
224
143
        rp = rp.lstrip(os.sep)
225
144
        return rp
239
158
        and binary.  binary files are untranslated byte streams.  Text
240
159
        control files are stored with Unix newlines and in UTF-8, even
241
160
        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
161
        """
246
162
 
247
163
        fn = self.controlfilename(file_or_path)
268
184
        for d in ('text-store', 'inventory-store', 'revision-store'):
269
185
            os.mkdir(self.controlfilename(d))
270
186
        for f in ('revision-history', 'merged-patches',
271
 
                  'pending-merged-patches', 'branch-name',
272
 
                  'branch-lock'):
 
187
                  'pending-merged-patches', 'branch-name'):
273
188
            self.controlfile(f, 'w').write('')
274
189
        mutter('created control directory in ' + self.base)
275
190
        Inventory().write_xml(self.controlfile('inventory','w'))
289
204
        fmt = self.controlfile('branch-format', 'r').read()
290
205
        fmt.replace('\r\n', '')
291
206
        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
 
207
            bailout('sorry, branch format %r not supported' % fmt,
 
208
                    ['use a different bzr version',
 
209
                     'or remove the .bzr directory and "bzr init" again'])
 
210
 
 
211
 
299
212
    def read_working_inventory(self):
300
213
        """Read the working inventory."""
301
214
        before = time.time()
305
218
        mutter("loaded inventory of %d items in %f"
306
219
               % (len(inv), time.time() - before))
307
220
        return inv
308
 
            
 
221
 
309
222
 
310
223
    def _write_inventory(self, inv):
311
224
        """Update the working inventory.
324
237
            os.remove(inv_fname)
325
238
        os.rename(tmpfname, inv_fname)
326
239
        mutter('wrote working inventory')
327
 
            
 
240
 
328
241
 
329
242
    inventory = property(read_working_inventory, _write_inventory, None,
330
243
                         """Inventory for the working copy.""")
331
244
 
332
245
 
333
 
    @with_writelock
334
 
    def add(self, files, verbose=False, ids=None):
 
246
    def add(self, files, verbose=False):
335
247
        """Make files versioned.
336
248
 
337
249
        Note that the command line normally calls smart_add instead.
350
262
        TODO: Adding a directory should optionally recurse down and
351
263
               add all non-ignored children.  Perhaps do that in a
352
264
               higher-level method.
 
265
 
 
266
        >>> b = ScratchBranch(files=['foo'])
 
267
        >>> 'foo' in b.unknowns()
 
268
        True
 
269
        >>> b.show_status()
 
270
        ?       foo
 
271
        >>> b.add('foo')
 
272
        >>> 'foo' in b.unknowns()
 
273
        False
 
274
        >>> bool(b.inventory.path2id('foo'))
 
275
        True
 
276
        >>> b.show_status()
 
277
        A       foo
 
278
 
 
279
        >>> b.add('foo')
 
280
        Traceback (most recent call last):
 
281
        ...
 
282
        BzrError: ('foo is already versioned', [])
 
283
 
 
284
        >>> b.add(['nothere'])
 
285
        Traceback (most recent call last):
 
286
        BzrError: ('cannot add: not a regular file or directory: nothere', [])
353
287
        """
 
288
 
354
289
        # TODO: Re-adding a file that is removed in the working copy
355
290
        # should probably put it back with the previous ID.
356
291
        if isinstance(files, types.StringTypes):
357
 
            assert(ids is None or isinstance(ids, types.StringTypes))
358
292
            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
 
 
 
293
        
367
294
        inv = self.read_working_inventory()
368
 
        for f,file_id in zip(files, ids):
 
295
        for f in files:
369
296
            if is_control_file(f):
370
 
                raise BzrError("cannot add control file %s" % quotefn(f))
 
297
                bailout("cannot add control file %s" % quotefn(f))
371
298
 
372
299
            fp = splitpath(f)
373
300
 
374
301
            if len(fp) == 0:
375
 
                raise BzrError("cannot add top-level %r" % f)
376
 
 
 
302
                bailout("cannot add top-level %r" % f)
 
303
                
377
304
            fullpath = os.path.normpath(self.abspath(f))
378
305
 
379
306
            try:
380
307
                kind = file_kind(fullpath)
381
308
            except OSError:
382
309
                # maybe something better?
383
 
                raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
384
 
 
 
310
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
311
            
385
312
            if kind != 'file' and kind != 'directory':
386
 
                raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
 
313
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
387
314
 
388
 
            if file_id is None:
389
 
                file_id = gen_file_id(f)
 
315
            file_id = gen_file_id(f)
390
316
            inv.add_path(f, kind=kind, file_id=file_id)
391
317
 
392
318
            if verbose:
393
319
                show_status('A', kind, quotefn(f))
394
 
 
 
320
                
395
321
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
396
 
 
 
322
            
397
323
        self._write_inventory(inv)
398
 
            
 
324
 
399
325
 
400
326
    def print_file(self, file, revno):
401
327
        """Print `file` to stdout."""
403
329
        # use inventory as it was in that revision
404
330
        file_id = tree.inventory.path2id(file)
405
331
        if not file_id:
406
 
            raise BzrError("%r is not present in revision %d" % (file, revno))
 
332
            bailout("%r is not present in revision %d" % (file, revno))
407
333
        tree.print_file(file_id)
408
 
 
409
 
 
410
 
    @with_writelock
 
334
        
 
335
 
411
336
    def remove(self, files, verbose=False):
412
337
        """Mark nominated files for removal from the inventory.
413
338
 
415
340
 
416
341
        TODO: Refuse to remove modified files unless --force is given?
417
342
 
 
343
        >>> b = ScratchBranch(files=['foo'])
 
344
        >>> b.add('foo')
 
345
        >>> b.inventory.has_filename('foo')
 
346
        True
 
347
        >>> b.remove('foo')
 
348
        >>> b.working_tree().has_filename('foo')
 
349
        True
 
350
        >>> b.inventory.has_filename('foo')
 
351
        False
 
352
        
 
353
        >>> b = ScratchBranch(files=['foo'])
 
354
        >>> b.add('foo')
 
355
        >>> b.commit('one')
 
356
        >>> b.remove('foo')
 
357
        >>> b.commit('two')
 
358
        >>> b.inventory.has_filename('foo') 
 
359
        False
 
360
        >>> b.basis_tree().has_filename('foo') 
 
361
        False
 
362
        >>> b.working_tree().has_filename('foo') 
 
363
        True
 
364
 
418
365
        TODO: Do something useful with directories.
419
366
 
420
367
        TODO: Should this remove the text or not?  Tough call; not
424
371
        """
425
372
        ## TODO: Normalize names
426
373
        ## TODO: Remove nested loops; better scalability
 
374
 
427
375
        if isinstance(files, types.StringTypes):
428
376
            files = [files]
429
 
 
 
377
        
430
378
        tree = self.working_tree()
431
379
        inv = tree.inventory
432
380
 
434
382
        for f in files:
435
383
            fid = inv.path2id(f)
436
384
            if not fid:
437
 
                raise BzrError("cannot remove unversioned file %s" % quotefn(f))
 
385
                bailout("cannot remove unversioned file %s" % quotefn(f))
438
386
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
439
387
            if verbose:
440
388
                # having remove it, it must be either ignored or unknown
448
396
        self._write_inventory(inv)
449
397
 
450
398
 
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
399
    def unknowns(self):
462
400
        """Return all unknown files.
463
401
 
477
415
        return self.working_tree().unknowns()
478
416
 
479
417
 
 
418
    def commit(self, message, timestamp=None, timezone=None,
 
419
               committer=None,
 
420
               verbose=False):
 
421
        """Commit working copy as a new revision.
 
422
        
 
423
        The basic approach is to add all the file texts into the
 
424
        store, then the inventory, then make a new revision pointing
 
425
        to that inventory and store that.
 
426
        
 
427
        This is not quite safe if the working copy changes during the
 
428
        commit; for the moment that is simply not allowed.  A better
 
429
        approach is to make a temporary copy of the files before
 
430
        computing their hashes, and then add those hashes in turn to
 
431
        the inventory.  This should mean at least that there are no
 
432
        broken hash pointers.  There is no way we can get a snapshot
 
433
        of the whole directory at an instant.  This would also have to
 
434
        be robust against files disappearing, moving, etc.  So the
 
435
        whole thing is a bit hard.
 
436
 
 
437
        timestamp -- if not None, seconds-since-epoch for a
 
438
             postdated/predated commit.
 
439
        """
 
440
 
 
441
        ## TODO: Show branch names
 
442
 
 
443
        # TODO: Don't commit if there are no changes, unless forced?
 
444
 
 
445
        # First walk over the working inventory; and both update that
 
446
        # and also build a new revision inventory.  The revision
 
447
        # inventory needs to hold the text-id, sha1 and size of the
 
448
        # actual file versions committed in the revision.  (These are
 
449
        # not present in the working inventory.)  We also need to
 
450
        # detect missing/deleted files, and remove them from the
 
451
        # working inventory.
 
452
 
 
453
        work_inv = self.read_working_inventory()
 
454
        inv = Inventory()
 
455
        basis = self.basis_tree()
 
456
        basis_inv = basis.inventory
 
457
        missing_ids = []
 
458
        for path, entry in work_inv.iter_entries():
 
459
            ## TODO: Cope with files that have gone missing.
 
460
 
 
461
            ## TODO: Check that the file kind has not changed from the previous
 
462
            ## revision of this file (if any).
 
463
 
 
464
            entry = entry.copy()
 
465
 
 
466
            p = self.abspath(path)
 
467
            file_id = entry.file_id
 
468
            mutter('commit prep file %s, id %r ' % (p, file_id))
 
469
 
 
470
            if not os.path.exists(p):
 
471
                mutter("    file is missing, removing from inventory")
 
472
                if verbose:
 
473
                    show_status('D', entry.kind, quotefn(path))
 
474
                missing_ids.append(file_id)
 
475
                continue
 
476
 
 
477
            # TODO: Handle files that have been deleted
 
478
 
 
479
            # TODO: Maybe a special case for empty files?  Seems a
 
480
            # waste to store them many times.
 
481
 
 
482
            inv.add(entry)
 
483
 
 
484
            if basis_inv.has_id(file_id):
 
485
                old_kind = basis_inv[file_id].kind
 
486
                if old_kind != entry.kind:
 
487
                    bailout("entry %r changed kind from %r to %r"
 
488
                            % (file_id, old_kind, entry.kind))
 
489
 
 
490
            if entry.kind == 'directory':
 
491
                if not isdir(p):
 
492
                    bailout("%s is entered as directory but not a directory" % quotefn(p))
 
493
            elif entry.kind == 'file':
 
494
                if not isfile(p):
 
495
                    bailout("%s is entered as file but is not a file" % quotefn(p))
 
496
 
 
497
                content = file(p, 'rb').read()
 
498
 
 
499
                entry.text_sha1 = sha_string(content)
 
500
                entry.text_size = len(content)
 
501
 
 
502
                old_ie = basis_inv.has_id(file_id) and basis_inv[file_id]
 
503
                if (old_ie
 
504
                    and (old_ie.text_size == entry.text_size)
 
505
                    and (old_ie.text_sha1 == entry.text_sha1)):
 
506
                    ## assert content == basis.get_file(file_id).read()
 
507
                    entry.text_id = basis_inv[file_id].text_id
 
508
                    mutter('    unchanged from previous text_id {%s}' %
 
509
                           entry.text_id)
 
510
                    
 
511
                else:
 
512
                    entry.text_id = gen_file_id(entry.name)
 
513
                    self.text_store.add(content, entry.text_id)
 
514
                    mutter('    stored with text_id {%s}' % entry.text_id)
 
515
                    if verbose:
 
516
                        if not old_ie:
 
517
                            state = 'A'
 
518
                        elif (old_ie.name == entry.name
 
519
                              and old_ie.parent_id == entry.parent_id):
 
520
                            state = 'M'
 
521
                        else:
 
522
                            state = 'R'
 
523
 
 
524
                        show_status(state, entry.kind, quotefn(path))
 
525
 
 
526
        for file_id in missing_ids:
 
527
            # have to do this later so we don't mess up the iterator.
 
528
            # since parents may be removed before their children we
 
529
            # have to test.
 
530
 
 
531
            # FIXME: There's probably a better way to do this; perhaps
 
532
            # the workingtree should know how to filter itself.
 
533
            if work_inv.has_id(file_id):
 
534
                del work_inv[file_id]
 
535
 
 
536
 
 
537
        inv_id = rev_id = _gen_revision_id(time.time())
 
538
        
 
539
        inv_tmp = tempfile.TemporaryFile()
 
540
        inv.write_xml(inv_tmp)
 
541
        inv_tmp.seek(0)
 
542
        self.inventory_store.add(inv_tmp, inv_id)
 
543
        mutter('new inventory_id is {%s}' % inv_id)
 
544
 
 
545
        self._write_inventory(work_inv)
 
546
 
 
547
        if timestamp == None:
 
548
            timestamp = time.time()
 
549
 
 
550
        if committer == None:
 
551
            committer = username()
 
552
 
 
553
        if timezone == None:
 
554
            timezone = local_time_offset()
 
555
 
 
556
        mutter("building commit log message")
 
557
        rev = Revision(timestamp=timestamp,
 
558
                       timezone=timezone,
 
559
                       committer=committer,
 
560
                       precursor = self.last_patch(),
 
561
                       message = message,
 
562
                       inventory_id=inv_id,
 
563
                       revision_id=rev_id)
 
564
 
 
565
        rev_tmp = tempfile.TemporaryFile()
 
566
        rev.write_xml(rev_tmp)
 
567
        rev_tmp.seek(0)
 
568
        self.revision_store.add(rev_tmp, rev_id)
 
569
        mutter("new revision_id is {%s}" % rev_id)
 
570
        
 
571
        ## XXX: Everything up to here can simply be orphaned if we abort
 
572
        ## the commit; it will leave junk files behind but that doesn't
 
573
        ## matter.
 
574
 
 
575
        ## TODO: Read back the just-generated changeset, and make sure it
 
576
        ## applies and recreates the right state.
 
577
 
 
578
        ## TODO: Also calculate and store the inventory SHA1
 
579
        mutter("committing patch r%d" % (self.revno() + 1))
 
580
 
 
581
 
 
582
        self.append_revision(rev_id)
 
583
        
 
584
        if verbose:
 
585
            note("commited r%d" % self.revno())
 
586
 
 
587
 
480
588
    def append_revision(self, revision_id):
481
589
        mutter("add {%s} to revision-history" % revision_id)
482
590
        rev_history = self.revision_history()
521
629
            return self.get_inventory(self.get_revision(revision_id).inventory_id)
522
630
 
523
631
 
524
 
    @with_readlock
525
632
    def revision_history(self):
526
633
        """Return sequence of revision hashes on to this branch.
527
634
 
531
638
        return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
532
639
 
533
640
 
534
 
    def enum_history(self, direction):
535
 
        """Return (revno, revision_id) for history of branch.
536
 
 
537
 
        direction
538
 
            'forward' is from earliest to latest
539
 
            'reverse' is from latest to earliest
540
 
        """
541
 
        rh = self.revision_history()
542
 
        if direction == 'forward':
543
 
            i = 1
544
 
            for rid in rh:
545
 
                yield i, rid
546
 
                i += 1
547
 
        elif direction == 'reverse':
548
 
            i = len(rh)
549
 
            while i > 0:
550
 
                yield i, rh[i-1]
551
 
                i -= 1
552
 
        else:
553
 
            raise ValueError('invalid history direction', direction)
554
 
 
555
 
 
556
641
    def revno(self):
557
642
        """Return current revision number for this branch.
558
643
 
559
644
        That is equivalent to the number of revisions committed to
560
645
        this branch.
 
646
 
 
647
        >>> b = ScratchBranch()
 
648
        >>> b.revno()
 
649
        0
 
650
        >>> b.commit('no foo')
 
651
        >>> b.revno()
 
652
        1
561
653
        """
562
654
        return len(self.revision_history())
563
655
 
564
656
 
565
657
    def last_patch(self):
566
658
        """Return last patch hash, or None if no history.
 
659
 
 
660
        >>> ScratchBranch().last_patch() == None
 
661
        True
567
662
        """
568
663
        ph = self.revision_history()
569
664
        if ph:
570
665
            return ph[-1]
571
666
        else:
572
667
            return None
573
 
 
574
 
 
575
 
    def commit(self, *args, **kw):
576
 
        """Deprecated"""
577
 
        from bzrlib.commit import commit
578
 
        commit(self, *args, **kw)
579
668
        
580
669
 
581
670
    def lookup_revision(self, revno):
595
684
 
596
685
        `revision_id` may be None for the null revision, in which case
597
686
        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.
 
687
 
600
688
        if revision_id == None:
601
689
            return EmptyTree()
602
690
        else:
606
694
 
607
695
    def working_tree(self):
608
696
        """Return a `Tree` for the working copy."""
609
 
        from workingtree import WorkingTree
610
697
        return WorkingTree(self.base, self.read_working_inventory())
611
698
 
612
699
 
614
701
        """Return `Tree` object for last revision.
615
702
 
616
703
        If there are no revisions yet, return an `EmptyTree`.
 
704
 
 
705
        >>> b = ScratchBranch(files=['foo'])
 
706
        >>> b.basis_tree().has_filename('foo')
 
707
        False
 
708
        >>> b.working_tree().has_filename('foo')
 
709
        True
 
710
        >>> b.add('foo')
 
711
        >>> b.commit('add foo')
 
712
        >>> b.basis_tree().has_filename('foo')
 
713
        True
617
714
        """
618
715
        r = self.last_patch()
619
716
        if r == None:
623
720
 
624
721
 
625
722
 
626
 
    @with_writelock
 
723
    def write_log(self, show_timezone='original', verbose=False):
 
724
        """Write out human-readable log of commits to this branch
 
725
 
 
726
        utc -- If true, show dates in universal time, not local time."""
 
727
        ## TODO: Option to choose either original, utc or local timezone
 
728
        revno = 1
 
729
        precursor = None
 
730
        for p in self.revision_history():
 
731
            print '-' * 40
 
732
            print 'revno:', revno
 
733
            ## TODO: Show hash if --id is given.
 
734
            ##print 'revision-hash:', p
 
735
            rev = self.get_revision(p)
 
736
            print 'committer:', rev.committer
 
737
            print 'timestamp: %s' % (format_date(rev.timestamp, rev.timezone or 0,
 
738
                                                 show_timezone))
 
739
 
 
740
            ## opportunistic consistency check, same as check_patch_chaining
 
741
            if rev.precursor != precursor:
 
742
                bailout("mismatched precursor!")
 
743
 
 
744
            print 'message:'
 
745
            if not rev.message:
 
746
                print '  (no message)'
 
747
            else:
 
748
                for l in rev.message.split('\n'):
 
749
                    print '  ' + l
 
750
 
 
751
            if verbose == True and precursor != None:
 
752
                print 'changed files:'
 
753
                tree = self.revision_tree(p)
 
754
                prevtree = self.revision_tree(precursor)
 
755
                
 
756
                for file_state, fid, old_name, new_name, kind in \
 
757
                                        diff_trees(prevtree, tree, ):
 
758
                    if file_state == 'A' or file_state == 'M':
 
759
                        show_status(file_state, kind, new_name)
 
760
                    elif file_state == 'D':
 
761
                        show_status(file_state, kind, old_name)
 
762
                    elif file_state == 'R':
 
763
                        show_status(file_state, kind,
 
764
                            old_name + ' => ' + new_name)
 
765
                
 
766
            revno += 1
 
767
            precursor = p
 
768
 
 
769
 
627
770
    def rename_one(self, from_rel, to_rel):
628
771
        """Rename one file.
629
772
 
630
773
        This can change the directory or the filename or both.
631
 
        """
 
774
         """
632
775
        tree = self.working_tree()
633
776
        inv = tree.inventory
634
777
        if not tree.has_filename(from_rel):
635
 
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
 
778
            bailout("can't rename: old working file %r does not exist" % from_rel)
636
779
        if tree.has_filename(to_rel):
637
 
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
638
 
 
 
780
            bailout("can't rename: new working file %r already exists" % to_rel)
 
781
            
639
782
        file_id = inv.path2id(from_rel)
640
783
        if file_id == None:
641
 
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
 
784
            bailout("can't rename: old name %r is not versioned" % from_rel)
642
785
 
643
786
        if inv.path2id(to_rel):
644
 
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
 
787
            bailout("can't rename: new name %r is already versioned" % to_rel)
645
788
 
646
789
        to_dir, to_tail = os.path.split(to_rel)
647
790
        to_dir_id = inv.path2id(to_dir)
648
791
        if to_dir_id == None and to_dir != '':
649
 
            raise BzrError("can't determine destination directory id for %r" % to_dir)
 
792
            bailout("can't determine destination directory id for %r" % to_dir)
650
793
 
651
794
        mutter("rename_one:")
652
795
        mutter("  file_id    {%s}" % file_id)
654
797
        mutter("  to_rel     %r" % to_rel)
655
798
        mutter("  to_dir     %r" % to_dir)
656
799
        mutter("  to_dir_id  {%s}" % to_dir_id)
657
 
 
 
800
            
658
801
        inv.rename(file_id, to_dir_id, to_tail)
659
802
 
660
803
        print "%s => %s" % (from_rel, to_rel)
661
 
 
 
804
        
662
805
        from_abs = self.abspath(from_rel)
663
806
        to_abs = self.abspath(to_rel)
664
807
        try:
665
808
            os.rename(from_abs, to_abs)
666
809
        except OSError, e:
667
 
            raise BzrError("failed to rename %r to %r: %s"
 
810
            bailout("failed to rename %r to %r: %s"
668
811
                    % (from_abs, to_abs, e[1]),
669
812
                    ["rename rolled back"])
670
813
 
671
814
        self._write_inventory(inv)
672
 
 
673
 
 
674
 
 
675
 
    @with_writelock
 
815
            
 
816
 
 
817
 
676
818
    def move(self, from_paths, to_name):
677
819
        """Rename files.
678
820
 
690
832
        inv = tree.inventory
691
833
        to_abs = self.abspath(to_name)
692
834
        if not isdir(to_abs):
693
 
            raise BzrError("destination %r is not a directory" % to_abs)
 
835
            bailout("destination %r is not a directory" % to_abs)
694
836
        if not tree.has_filename(to_name):
695
 
            raise BzrError("destination %r not in working directory" % to_abs)
 
837
            bailout("destination %r not in working directory" % to_abs)
696
838
        to_dir_id = inv.path2id(to_name)
697
839
        if to_dir_id == None and to_name != '':
698
 
            raise BzrError("destination %r is not a versioned directory" % to_name)
 
840
            bailout("destination %r is not a versioned directory" % to_name)
699
841
        to_dir_ie = inv[to_dir_id]
700
842
        if to_dir_ie.kind not in ('directory', 'root_directory'):
701
 
            raise BzrError("destination %r is not a directory" % to_abs)
 
843
            bailout("destination %r is not a directory" % to_abs)
702
844
 
703
 
        to_idpath = inv.get_idpath(to_dir_id)
 
845
        to_idpath = Set(inv.get_idpath(to_dir_id))
704
846
 
705
847
        for f in from_paths:
706
848
            if not tree.has_filename(f):
707
 
                raise BzrError("%r does not exist in working tree" % f)
 
849
                bailout("%r does not exist in working tree" % f)
708
850
            f_id = inv.path2id(f)
709
851
            if f_id == None:
710
 
                raise BzrError("%r is not versioned" % f)
 
852
                bailout("%r is not versioned" % f)
711
853
            name_tail = splitpath(f)[-1]
712
854
            dest_path = appendpath(to_name, name_tail)
713
855
            if tree.has_filename(dest_path):
714
 
                raise BzrError("destination %r already exists" % dest_path)
 
856
                bailout("destination %r already exists" % dest_path)
715
857
            if f_id in to_idpath:
716
 
                raise BzrError("can't move %r to a subdirectory of itself" % f)
 
858
                bailout("can't move %r to a subdirectory of itself" % f)
717
859
 
718
860
        # OK, so there's a race here, it's possible that someone will
719
861
        # create a file in this interval and then the rename might be
727
869
            try:
728
870
                os.rename(self.abspath(f), self.abspath(dest_path))
729
871
            except OSError, e:
730
 
                raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
 
872
                bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
731
873
                        ["rename rolled back"])
732
874
 
733
875
        self._write_inventory(inv)
734
876
 
735
877
 
736
878
 
 
879
    def show_status(self, show_all=False):
 
880
        """Display single-line status for non-ignored working files.
 
881
 
 
882
        The list is show sorted in order by file name.
 
883
 
 
884
        >>> b = ScratchBranch(files=['foo', 'foo~'])
 
885
        >>> b.show_status()
 
886
        ?       foo
 
887
        >>> b.add('foo')
 
888
        >>> b.show_status()
 
889
        A       foo
 
890
        >>> b.commit("add foo")
 
891
        >>> b.show_status()
 
892
        >>> os.unlink(b.abspath('foo'))
 
893
        >>> b.show_status()
 
894
        D       foo
 
895
        
 
896
        TODO: Get state for single files.
 
897
        """
 
898
 
 
899
        # We have to build everything into a list first so that it can
 
900
        # sorted by name, incorporating all the different sources.
 
901
 
 
902
        # FIXME: Rather than getting things in random order and then sorting,
 
903
        # just step through in order.
 
904
 
 
905
        # Interesting case: the old ID for a file has been removed,
 
906
        # but a new file has been created under that name.
 
907
 
 
908
        old = self.basis_tree()
 
909
        new = self.working_tree()
 
910
 
 
911
        for fs, fid, oldname, newname, kind in diff_trees(old, new):
 
912
            if fs == 'R':
 
913
                show_status(fs, kind,
 
914
                            oldname + ' => ' + newname)
 
915
            elif fs == 'A' or fs == 'M':
 
916
                show_status(fs, kind, newname)
 
917
            elif fs == 'D':
 
918
                show_status(fs, kind, oldname)
 
919
            elif fs == '.':
 
920
                if show_all:
 
921
                    show_status(fs, kind, newname)
 
922
            elif fs == 'I':
 
923
                if show_all:
 
924
                    show_status(fs, kind, newname)
 
925
            elif fs == '?':
 
926
                show_status(fs, kind, newname)
 
927
            else:
 
928
                bailout("weird file state %r" % ((fs, fid),))
 
929
                
 
930
 
737
931
 
738
932
class ScratchBranch(Branch):
739
933
    """Special test class: a branch that cleans up after itself.
742
936
    >>> isdir(b.base)
743
937
    True
744
938
    >>> bd = b.base
745
 
    >>> b.destroy()
 
939
    >>> del b
746
940
    >>> isdir(bd)
747
941
    False
748
942
    """
762
956
 
763
957
 
764
958
    def __del__(self):
765
 
        self.destroy()
766
 
 
767
 
    def destroy(self):
768
959
        """Destroy the test branch, removing the scratch directory."""
769
960
        try:
770
 
            mutter("delete ScratchBranch %s" % self.base)
771
961
            shutil.rmtree(self.base)
772
 
        except OSError, e:
 
962
        except OSError:
773
963
            # Work around for shutil.rmtree failing on Windows when
774
964
            # readonly files are encountered
775
 
            mutter("hit exception in destroying ScratchBranch: %s" % e)
776
965
            for root, dirs, files in os.walk(self.base, topdown=False):
777
966
                for name in files:
778
967
                    os.chmod(os.path.join(root, name), 0700)
779
968
            shutil.rmtree(self.base)
780
 
        self.base = None
781
969
 
782
970
    
783
971
 
800
988
 
801
989
 
802
990
 
 
991
def _gen_revision_id(when):
 
992
    """Return new revision-id."""
 
993
    s = '%s-%s-' % (user_email(), compact_date(when))
 
994
    s += hexlify(rand_bytes(8))
 
995
    return s
 
996
 
 
997
 
803
998
def gen_file_id(name):
804
999
    """Return new file id.
805
1000
 
806
1001
    This should probably generate proper UUIDs, but for the moment we
807
1002
    cope with just randomness because running uuidgen every time is
808
1003
    slow."""
809
 
    import re
810
 
 
811
 
    # get last component
812
1004
    idx = name.rfind('/')
813
1005
    if idx != -1:
814
1006
        name = name[idx+1 : ]
816
1008
    if idx != -1:
817
1009
        name = name[idx+1 : ]
818
1010
 
819
 
    # make it not a hidden file
820
1011
    name = name.lstrip('.')
821
1012
 
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
1013
    s = hexlify(rand_bytes(8))
827
1014
    return '-'.join((name, compact_date(time.time()), s))