~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-04-29 00:43:34 UTC
  • Revision ID: mbp@sourcefrog.net-20050429004334-bbb9dc81ce0d9de3
- update install instructions

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
 
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
 
29
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, chomp, \
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
 
def _relpath(base, path):
72
 
    """Return path relative to base, or raise exception.
73
 
 
74
 
    The path may be either an absolute path or a path relative to the
75
 
    current working directory.
76
 
 
77
 
    Lifted out of Branch.relpath for ease of testing.
78
 
 
79
 
    os.path.commonprefix (python2.4) has a bad bug that it works just
80
 
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
81
 
    avoids that problem."""
82
 
    rp = os.path.abspath(path)
83
 
 
84
 
    s = []
85
 
    head = rp
86
 
    while len(head) >= len(base):
87
 
        if head == base:
88
 
            break
89
 
        head, tail = os.path.split(head)
90
 
        if tail:
91
 
            s.insert(0, tail)
92
 
    else:
93
 
        from errors import NotBranchError
94
 
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
95
 
 
96
 
    return os.sep.join(s)
97
 
        
98
 
 
99
43
def find_branch_root(f=None):
100
44
    """Find the branch root enclosing f, or pwd.
101
45
 
102
 
    f may be a filename or a URL.
103
 
 
104
46
    It is not necessary that f exists.
105
47
 
106
48
    Basically we keep looking up until we find the control directory or
111
53
        f = os.path.realpath(f)
112
54
    else:
113
55
        f = os.path.abspath(f)
114
 
    if not os.path.exists(f):
115
 
        raise BzrError('%r does not exist' % f)
116
 
        
117
56
 
118
57
    orig_f = f
119
58
 
131
70
######################################################################
132
71
# branch objects
133
72
 
134
 
class Branch(object):
 
73
class Branch:
135
74
    """Branch holding a history of revisions.
136
75
 
137
 
    base
138
 
        Base directory of the branch.
139
 
 
140
 
    _lock_mode
141
 
        None, or 'r' or 'w'
142
 
 
143
 
    _lock_count
144
 
        If _lock_mode is true, a positive count of the number of times the
145
 
        lock has been taken.
146
 
 
147
 
    _lockfile
148
 
        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.
149
88
    """
150
 
    base = None
151
 
    _lock_mode = None
152
 
    _lock_count = None
153
 
    
154
89
    def __init__(self, base, init=False, find_root=True):
155
90
        """Create new branch object at a particular location.
156
91
 
174
109
        else:
175
110
            self.base = os.path.realpath(base)
176
111
            if not isdir(self.controlfilename('.')):
177
 
                from errors import NotBranchError
178
 
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
179
 
                                     ['use "bzr init" to initialize a new working tree',
180
 
                                      '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'])
181
115
        self._check_format()
182
 
        self._lockfile = self.controlfile('branch-lock', 'wb')
183
116
 
184
117
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
185
118
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
193
126
    __repr__ = __str__
194
127
 
195
128
 
196
 
    def __del__(self):
197
 
        if self._lock_mode:
198
 
            from warnings import warn
199
 
            warn("branch %r was not explicitly unlocked" % self)
200
 
            self.unlock()
201
 
 
202
 
 
203
 
    def lock(self, mode):
204
 
        if self._lock_mode:
205
 
            if mode == 'w' and cur_lm == 'r':
206
 
                raise BzrError("can't upgrade to a write lock")
207
 
            
208
 
            assert self._lock_count >= 1
209
 
            self._lock_count += 1
210
 
        else:
211
 
            from bzrlib.lock import lock, LOCK_SH, LOCK_EX
212
 
            if mode == 'r':
213
 
                m = LOCK_SH
214
 
            elif mode == 'w':
215
 
                m = LOCK_EX
216
 
            else:
217
 
                raise ValueError('invalid lock mode %r' % mode)
218
 
 
219
 
            lock(self._lockfile, m)
220
 
            self._lock_mode = mode
221
 
            self._lock_count = 1
222
 
 
223
 
 
224
 
    def unlock(self):
225
 
        if not self._lock_mode:
226
 
            raise BzrError('branch %r is not locked' % (self))
227
 
 
228
 
        if self._lock_count > 1:
229
 
            self._lock_count -= 1
230
 
        else:
231
 
            assert self._lock_count == 1
232
 
            from bzrlib.lock import unlock
233
 
            unlock(self._lockfile)
234
 
            self._lock_mode = self._lock_count = None
235
 
 
236
 
 
237
129
    def abspath(self, name):
238
130
        """Return absolute filename for something in the branch"""
239
131
        return os.path.join(self.base, name)
243
135
        """Return path relative to this branch of something inside it.
244
136
 
245
137
        Raises an error if path is not in this branch."""
246
 
        return _relpath(self.base, path)
 
138
        rp = os.path.realpath(path)
 
139
        # FIXME: windows
 
140
        if not rp.startswith(self.base):
 
141
            bailout("path %r is not within branch %r" % (rp, self.base))
 
142
        rp = rp[len(self.base):]
 
143
        rp = rp.lstrip(os.sep)
 
144
        return rp
247
145
 
248
146
 
249
147
    def controlfilename(self, file_or_path):
260
158
        and binary.  binary files are untranslated byte streams.  Text
261
159
        control files are stored with Unix newlines and in UTF-8, even
262
160
        if the platform or locale defaults are different.
263
 
 
264
 
        Controlfiles should almost never be opened in write mode but
265
 
        rather should be atomically copied and replaced using atomicfile.
266
161
        """
267
162
 
268
163
        fn = self.controlfilename(file_or_path)
289
184
        for d in ('text-store', 'inventory-store', 'revision-store'):
290
185
            os.mkdir(self.controlfilename(d))
291
186
        for f in ('revision-history', 'merged-patches',
292
 
                  'pending-merged-patches', 'branch-name',
293
 
                  'branch-lock'):
 
187
                  'pending-merged-patches', 'branch-name'):
294
188
            self.controlfile(f, 'w').write('')
295
189
        mutter('created control directory in ' + self.base)
296
190
        Inventory().write_xml(self.controlfile('inventory','w'))
310
204
        fmt = self.controlfile('branch-format', 'r').read()
311
205
        fmt.replace('\r\n', '')
312
206
        if fmt != BZR_BRANCH_FORMAT:
313
 
            raise BzrError('sorry, branch format %r not supported' % fmt,
314
 
                           ['use a different bzr version',
315
 
                            'or remove the .bzr directory and "bzr init" again'])
316
 
 
317
 
 
318
 
 
319
 
    @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
 
320
212
    def read_working_inventory(self):
321
213
        """Read the working inventory."""
322
214
        before = time.time()
326
218
        mutter("loaded inventory of %d items in %f"
327
219
               % (len(inv), time.time() - before))
328
220
        return inv
329
 
            
 
221
 
330
222
 
331
223
    def _write_inventory(self, inv):
332
224
        """Update the working inventory.
345
237
            os.remove(inv_fname)
346
238
        os.rename(tmpfname, inv_fname)
347
239
        mutter('wrote working inventory')
348
 
            
 
240
 
349
241
 
350
242
    inventory = property(read_working_inventory, _write_inventory, None,
351
243
                         """Inventory for the working copy.""")
352
244
 
353
245
 
354
 
    @with_writelock
355
 
    def add(self, files, verbose=False, ids=None):
 
246
    def add(self, files, verbose=False):
356
247
        """Make files versioned.
357
248
 
358
249
        Note that the command line normally calls smart_add instead.
360
251
        This puts the files in the Added state, so that they will be
361
252
        recorded by the next commit.
362
253
 
363
 
        files
364
 
            List of paths to add, relative to the base of the tree.
365
 
 
366
 
        ids
367
 
            If set, use these instead of automatically generated ids.
368
 
            Must be the same length as the list of files, but may
369
 
            contain None for ids that are to be autogenerated.
370
 
 
371
254
        TODO: Perhaps have an option to add the ids even if the files do
372
 
              not (yet) exist.
 
255
               not (yet) exist.
373
256
 
374
257
        TODO: Perhaps return the ids of the files?  But then again it
375
 
              is easy to retrieve them if they're needed.
 
258
               is easy to retrieve them if they're needed.
 
259
 
 
260
        TODO: Option to specify file id.
376
261
 
377
262
        TODO: Adding a directory should optionally recurse down and
378
 
              add all non-ignored children.  Perhaps do that in a
379
 
              higher-level method.
 
263
               add all non-ignored children.  Perhaps do that in a
 
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', [])
380
287
        """
 
288
 
381
289
        # TODO: Re-adding a file that is removed in the working copy
382
290
        # should probably put it back with the previous ID.
383
291
        if isinstance(files, types.StringTypes):
384
 
            assert(ids is None or isinstance(ids, types.StringTypes))
385
292
            files = [files]
386
 
            if ids is not None:
387
 
                ids = [ids]
388
 
 
389
 
        if ids is None:
390
 
            ids = [None] * len(files)
391
 
        else:
392
 
            assert(len(ids) == len(files))
393
 
 
 
293
        
394
294
        inv = self.read_working_inventory()
395
 
        for f,file_id in zip(files, ids):
 
295
        for f in files:
396
296
            if is_control_file(f):
397
 
                raise BzrError("cannot add control file %s" % quotefn(f))
 
297
                bailout("cannot add control file %s" % quotefn(f))
398
298
 
399
299
            fp = splitpath(f)
400
300
 
401
301
            if len(fp) == 0:
402
 
                raise BzrError("cannot add top-level %r" % f)
403
 
 
 
302
                bailout("cannot add top-level %r" % f)
 
303
                
404
304
            fullpath = os.path.normpath(self.abspath(f))
405
305
 
406
306
            try:
407
307
                kind = file_kind(fullpath)
408
308
            except OSError:
409
309
                # maybe something better?
410
 
                raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
411
 
 
 
310
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
311
            
412
312
            if kind != 'file' and kind != 'directory':
413
 
                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))
414
314
 
415
 
            if file_id is None:
416
 
                file_id = gen_file_id(f)
 
315
            file_id = gen_file_id(f)
417
316
            inv.add_path(f, kind=kind, file_id=file_id)
418
317
 
419
318
            if verbose:
420
319
                show_status('A', kind, quotefn(f))
421
 
 
 
320
                
422
321
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
423
 
 
 
322
            
424
323
        self._write_inventory(inv)
425
 
            
 
324
 
426
325
 
427
326
    def print_file(self, file, revno):
428
327
        """Print `file` to stdout."""
430
329
        # use inventory as it was in that revision
431
330
        file_id = tree.inventory.path2id(file)
432
331
        if not file_id:
433
 
            raise BzrError("%r is not present in revision %d" % (file, revno))
 
332
            bailout("%r is not present in revision %d" % (file, revno))
434
333
        tree.print_file(file_id)
435
 
 
436
 
 
437
 
    @with_writelock
 
334
        
 
335
 
438
336
    def remove(self, files, verbose=False):
439
337
        """Mark nominated files for removal from the inventory.
440
338
 
442
340
 
443
341
        TODO: Refuse to remove modified files unless --force is given?
444
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
 
445
365
        TODO: Do something useful with directories.
446
366
 
447
367
        TODO: Should this remove the text or not?  Tough call; not
451
371
        """
452
372
        ## TODO: Normalize names
453
373
        ## TODO: Remove nested loops; better scalability
 
374
 
454
375
        if isinstance(files, types.StringTypes):
455
376
            files = [files]
456
 
 
 
377
        
457
378
        tree = self.working_tree()
458
379
        inv = tree.inventory
459
380
 
461
382
        for f in files:
462
383
            fid = inv.path2id(f)
463
384
            if not fid:
464
 
                raise BzrError("cannot remove unversioned file %s" % quotefn(f))
 
385
                bailout("cannot remove unversioned file %s" % quotefn(f))
465
386
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
466
387
            if verbose:
467
388
                # having remove it, it must be either ignored or unknown
475
396
        self._write_inventory(inv)
476
397
 
477
398
 
478
 
    def set_inventory(self, new_inventory_list):
479
 
        inv = Inventory()
480
 
        for path, file_id, parent, kind in new_inventory_list:
481
 
            name = os.path.basename(path)
482
 
            if name == "":
483
 
                continue
484
 
            inv.add(InventoryEntry(file_id, name, kind, parent))
485
 
        self._write_inventory(inv)
486
 
 
487
 
 
488
399
    def unknowns(self):
489
400
        """Return all unknown files.
490
401
 
504
415
        return self.working_tree().unknowns()
505
416
 
506
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
 
507
588
    def append_revision(self, revision_id):
508
589
        mutter("add {%s} to revision-history" % revision_id)
509
590
        rev_history = self.revision_history()
548
629
            return self.get_inventory(self.get_revision(revision_id).inventory_id)
549
630
 
550
631
 
551
 
    @with_readlock
552
632
    def revision_history(self):
553
633
        """Return sequence of revision hashes on to this branch.
554
634
 
555
635
        >>> ScratchBranch().revision_history()
556
636
        []
557
637
        """
558
 
        return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
559
 
 
560
 
 
561
 
    def enum_history(self, direction):
562
 
        """Return (revno, revision_id) for history of branch.
563
 
 
564
 
        direction
565
 
            'forward' is from earliest to latest
566
 
            'reverse' is from latest to earliest
567
 
        """
568
 
        rh = self.revision_history()
569
 
        if direction == 'forward':
570
 
            i = 1
571
 
            for rid in rh:
572
 
                yield i, rid
573
 
                i += 1
574
 
        elif direction == 'reverse':
575
 
            i = len(rh)
576
 
            while i > 0:
577
 
                yield i, rh[i-1]
578
 
                i -= 1
579
 
        else:
580
 
            raise ValueError('invalid history direction', direction)
 
638
        return [chomp(l) for l in self.controlfile('revision-history', 'r').readlines()]
581
639
 
582
640
 
583
641
    def revno(self):
585
643
 
586
644
        That is equivalent to the number of revisions committed to
587
645
        this branch.
 
646
 
 
647
        >>> b = ScratchBranch()
 
648
        >>> b.revno()
 
649
        0
 
650
        >>> b.commit('no foo')
 
651
        >>> b.revno()
 
652
        1
588
653
        """
589
654
        return len(self.revision_history())
590
655
 
591
656
 
592
657
    def last_patch(self):
593
658
        """Return last patch hash, or None if no history.
 
659
 
 
660
        >>> ScratchBranch().last_patch() == None
 
661
        True
594
662
        """
595
663
        ph = self.revision_history()
596
664
        if ph:
597
665
            return ph[-1]
598
666
        else:
599
667
            return None
600
 
 
601
 
 
602
 
    def commit(self, *args, **kw):
603
 
        """Deprecated"""
604
 
        from bzrlib.commit import commit
605
 
        commit(self, *args, **kw)
606
668
        
607
669
 
608
670
    def lookup_revision(self, revno):
622
684
 
623
685
        `revision_id` may be None for the null revision, in which case
624
686
        an `EmptyTree` is returned."""
625
 
        # TODO: refactor this to use an existing revision object
626
 
        # so we don't need to read it in twice.
 
687
 
627
688
        if revision_id == None:
628
689
            return EmptyTree()
629
690
        else:
633
694
 
634
695
    def working_tree(self):
635
696
        """Return a `Tree` for the working copy."""
636
 
        from workingtree import WorkingTree
637
697
        return WorkingTree(self.base, self.read_working_inventory())
638
698
 
639
699
 
641
701
        """Return `Tree` object for last revision.
642
702
 
643
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
644
714
        """
645
715
        r = self.last_patch()
646
716
        if r == None:
650
720
 
651
721
 
652
722
 
653
 
    @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
 
654
770
    def rename_one(self, from_rel, to_rel):
655
771
        """Rename one file.
656
772
 
657
773
        This can change the directory or the filename or both.
658
 
        """
 
774
         """
659
775
        tree = self.working_tree()
660
776
        inv = tree.inventory
661
777
        if not tree.has_filename(from_rel):
662
 
            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)
663
779
        if tree.has_filename(to_rel):
664
 
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
665
 
 
 
780
            bailout("can't rename: new working file %r already exists" % to_rel)
 
781
            
666
782
        file_id = inv.path2id(from_rel)
667
783
        if file_id == None:
668
 
            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)
669
785
 
670
786
        if inv.path2id(to_rel):
671
 
            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)
672
788
 
673
789
        to_dir, to_tail = os.path.split(to_rel)
674
790
        to_dir_id = inv.path2id(to_dir)
675
791
        if to_dir_id == None and to_dir != '':
676
 
            raise BzrError("can't determine destination directory id for %r" % to_dir)
 
792
            bailout("can't determine destination directory id for %r" % to_dir)
677
793
 
678
794
        mutter("rename_one:")
679
795
        mutter("  file_id    {%s}" % file_id)
681
797
        mutter("  to_rel     %r" % to_rel)
682
798
        mutter("  to_dir     %r" % to_dir)
683
799
        mutter("  to_dir_id  {%s}" % to_dir_id)
684
 
 
 
800
            
685
801
        inv.rename(file_id, to_dir_id, to_tail)
686
802
 
687
803
        print "%s => %s" % (from_rel, to_rel)
688
 
 
 
804
        
689
805
        from_abs = self.abspath(from_rel)
690
806
        to_abs = self.abspath(to_rel)
691
807
        try:
692
808
            os.rename(from_abs, to_abs)
693
809
        except OSError, e:
694
 
            raise BzrError("failed to rename %r to %r: %s"
 
810
            bailout("failed to rename %r to %r: %s"
695
811
                    % (from_abs, to_abs, e[1]),
696
812
                    ["rename rolled back"])
697
813
 
698
814
        self._write_inventory(inv)
699
 
 
700
 
 
701
 
 
702
 
    @with_writelock
 
815
            
 
816
 
 
817
 
703
818
    def move(self, from_paths, to_name):
704
819
        """Rename files.
705
820
 
717
832
        inv = tree.inventory
718
833
        to_abs = self.abspath(to_name)
719
834
        if not isdir(to_abs):
720
 
            raise BzrError("destination %r is not a directory" % to_abs)
 
835
            bailout("destination %r is not a directory" % to_abs)
721
836
        if not tree.has_filename(to_name):
722
 
            raise BzrError("destination %r not in working directory" % to_abs)
 
837
            bailout("destination %r not in working directory" % to_abs)
723
838
        to_dir_id = inv.path2id(to_name)
724
839
        if to_dir_id == None and to_name != '':
725
 
            raise BzrError("destination %r is not a versioned directory" % to_name)
 
840
            bailout("destination %r is not a versioned directory" % to_name)
726
841
        to_dir_ie = inv[to_dir_id]
727
842
        if to_dir_ie.kind not in ('directory', 'root_directory'):
728
 
            raise BzrError("destination %r is not a directory" % to_abs)
 
843
            bailout("destination %r is not a directory" % to_abs)
729
844
 
730
 
        to_idpath = inv.get_idpath(to_dir_id)
 
845
        to_idpath = Set(inv.get_idpath(to_dir_id))
731
846
 
732
847
        for f in from_paths:
733
848
            if not tree.has_filename(f):
734
 
                raise BzrError("%r does not exist in working tree" % f)
 
849
                bailout("%r does not exist in working tree" % f)
735
850
            f_id = inv.path2id(f)
736
851
            if f_id == None:
737
 
                raise BzrError("%r is not versioned" % f)
 
852
                bailout("%r is not versioned" % f)
738
853
            name_tail = splitpath(f)[-1]
739
854
            dest_path = appendpath(to_name, name_tail)
740
855
            if tree.has_filename(dest_path):
741
 
                raise BzrError("destination %r already exists" % dest_path)
 
856
                bailout("destination %r already exists" % dest_path)
742
857
            if f_id in to_idpath:
743
 
                raise BzrError("can't move %r to a subdirectory of itself" % f)
 
858
                bailout("can't move %r to a subdirectory of itself" % f)
744
859
 
745
860
        # OK, so there's a race here, it's possible that someone will
746
861
        # create a file in this interval and then the rename might be
754
869
            try:
755
870
                os.rename(self.abspath(f), self.abspath(dest_path))
756
871
            except OSError, e:
757
 
                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]),
758
873
                        ["rename rolled back"])
759
874
 
760
875
        self._write_inventory(inv)
761
876
 
762
877
 
763
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
 
764
931
 
765
932
class ScratchBranch(Branch):
766
933
    """Special test class: a branch that cleans up after itself.
769
936
    >>> isdir(b.base)
770
937
    True
771
938
    >>> bd = b.base
772
 
    >>> b.destroy()
 
939
    >>> del b
773
940
    >>> isdir(bd)
774
941
    False
775
942
    """
789
956
 
790
957
 
791
958
    def __del__(self):
792
 
        self.destroy()
793
 
 
794
 
    def destroy(self):
795
959
        """Destroy the test branch, removing the scratch directory."""
796
960
        try:
797
 
            mutter("delete ScratchBranch %s" % self.base)
798
961
            shutil.rmtree(self.base)
799
 
        except OSError, e:
 
962
        except OSError:
800
963
            # Work around for shutil.rmtree failing on Windows when
801
964
            # readonly files are encountered
802
 
            mutter("hit exception in destroying ScratchBranch: %s" % e)
803
965
            for root, dirs, files in os.walk(self.base, topdown=False):
804
966
                for name in files:
805
967
                    os.chmod(os.path.join(root, name), 0700)
806
968
            shutil.rmtree(self.base)
807
 
        self.base = None
808
969
 
809
970
    
810
971
 
827
988
 
828
989
 
829
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
 
830
998
def gen_file_id(name):
831
999
    """Return new file id.
832
1000
 
833
1001
    This should probably generate proper UUIDs, but for the moment we
834
1002
    cope with just randomness because running uuidgen every time is
835
1003
    slow."""
836
 
    import re
837
 
 
838
 
    # get last component
839
1004
    idx = name.rfind('/')
840
1005
    if idx != -1:
841
1006
        name = name[idx+1 : ]
843
1008
    if idx != -1:
844
1009
        name = name[idx+1 : ]
845
1010
 
846
 
    # make it not a hidden file
847
1011
    name = name.lstrip('.')
848
1012
 
849
 
    # remove any wierd characters; we don't escape them but rather
850
 
    # just pull them out
851
 
    name = re.sub(r'[^\w.]', '', name)
852
 
 
853
1013
    s = hexlify(rand_bytes(8))
854
1014
    return '-'.join((name, compact_date(time.time()), s))