~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-05-13 00:57:32 UTC
  • Revision ID: mbp@sourcefrog.net-20050513005732-26b0a3042cbb57d1
- more notes on tagging

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
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
34
36
 
35
37
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
43
45
        return remotebranch.RemoteBranch(f, **args)
44
46
    else:
45
47
        return Branch(f, **args)
46
 
 
47
 
 
48
 
 
49
 
def _relpath(base, path):
50
 
    """Return path relative to base, or raise exception.
51
 
 
52
 
    The path may be either an absolute path or a path relative to the
53
 
    current working directory.
54
 
 
55
 
    Lifted out of Branch.relpath for ease of testing.
56
 
 
57
 
    os.path.commonprefix (python2.4) has a bad bug that it works just
58
 
    on string prefixes, assuming that '/u' is a prefix of '/u2'.  This
59
 
    avoids that problem."""
60
 
    rp = os.path.abspath(path)
61
 
 
62
 
    s = []
63
 
    head = rp
64
 
    while len(head) >= len(base):
65
 
        if head == base:
66
 
            break
67
 
        head, tail = os.path.split(head)
68
 
        if tail:
69
 
            s.insert(0, tail)
70
 
    else:
71
 
        from errors import NotBranchError
72
 
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
73
 
 
74
 
    return os.sep.join(s)
75
48
        
76
49
 
77
50
def find_branch_root(f=None):
104
77
            raise BzrError('%r is not in a branch' % orig_f)
105
78
        f = head
106
79
    
107
 
class DivergedBranches(Exception):
108
 
    def __init__(self, branch1, branch2):
109
 
        self.branch1 = branch1
110
 
        self.branch2 = branch2
111
 
        Exception.__init__(self, "These branches have diverged.")
 
80
 
112
81
 
113
82
######################################################################
114
83
# branch objects
115
84
 
116
 
class Branch(object):
 
85
class Branch:
117
86
    """Branch holding a history of revisions.
118
87
 
119
88
    base
120
89
        Base directory of the branch.
121
 
 
122
 
    _lock_mode
123
 
        None, or 'r' or 'w'
124
 
 
125
 
    _lock_count
126
 
        If _lock_mode is true, a positive count of the number of times the
127
 
        lock has been taken.
128
 
 
129
 
    _lock
130
 
        Lock object from bzrlib.lock.
131
90
    """
132
 
    base = None
133
 
    _lock_mode = None
134
 
    _lock_count = None
135
 
    _lock = None
 
91
    _lockmode = None
136
92
    
137
 
    def __init__(self, base, init=False, find_root=True):
 
93
    def __init__(self, base, init=False, find_root=True, lock_mode='w'):
138
94
        """Create new branch object at a particular location.
139
95
 
140
96
        base -- Base directory for the branch.
157
113
        else:
158
114
            self.base = os.path.realpath(base)
159
115
            if not isdir(self.controlfilename('.')):
160
 
                from errors import NotBranchError
161
 
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
162
 
                                     ['use "bzr init" to initialize a new working tree',
163
 
                                      'current bzr can only operate from top-of-tree'])
 
116
                bailout("not a bzr branch: %s" % quotefn(base),
 
117
                        ['use "bzr init" to initialize a new working tree',
 
118
                         'current bzr can only operate from top-of-tree'])
164
119
        self._check_format()
 
120
        self.lock(lock_mode)
165
121
 
166
122
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
167
123
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
175
131
    __repr__ = __str__
176
132
 
177
133
 
178
 
    def __del__(self):
179
 
        if self._lock_mode or self._lock:
180
 
            from warnings import warn
181
 
            warn("branch %r was not explicitly unlocked" % self)
182
 
            self._lock.unlock()
183
 
 
184
 
 
185
 
 
186
 
    def lock_write(self):
187
 
        if self._lock_mode:
188
 
            if self._lock_mode != 'w':
189
 
                from errors import LockError
190
 
                raise LockError("can't upgrade to a write lock from %r" %
191
 
                                self._lock_mode)
192
 
            self._lock_count += 1
193
 
        else:
194
 
            from bzrlib.lock import WriteLock
195
 
 
196
 
            self._lock = WriteLock(self.controlfilename('branch-lock'))
197
 
            self._lock_mode = 'w'
198
 
            self._lock_count = 1
199
 
 
200
 
 
201
 
 
202
 
    def lock_read(self):
203
 
        if self._lock_mode:
204
 
            assert self._lock_mode in ('r', 'w'), \
205
 
                   "invalid lock mode %r" % self._lock_mode
206
 
            self._lock_count += 1
207
 
        else:
208
 
            from bzrlib.lock import ReadLock
209
 
 
210
 
            self._lock = ReadLock(self.controlfilename('branch-lock'))
211
 
            self._lock_mode = 'r'
212
 
            self._lock_count = 1
213
 
                        
214
 
 
 
134
 
 
135
    def lock(self, mode='w'):
 
136
        """Lock the on-disk branch, excluding other processes."""
 
137
        try:
 
138
            import fcntl, errno
 
139
 
 
140
            if mode == 'w':
 
141
                lm = fcntl.LOCK_EX
 
142
                om = os.O_WRONLY | os.O_CREAT
 
143
            elif mode == 'r':
 
144
                lm = fcntl.LOCK_SH
 
145
                om = os.O_RDONLY
 
146
            else:
 
147
                raise BzrError("invalid locking mode %r" % mode)
 
148
 
 
149
            try:
 
150
                lockfile = os.open(self.controlfilename('branch-lock'), om)
 
151
            except OSError, e:
 
152
                if e.errno == errno.ENOENT:
 
153
                    # might not exist on branches from <0.0.4
 
154
                    self.controlfile('branch-lock', 'w').close()
 
155
                    lockfile = os.open(self.controlfilename('branch-lock'), om)
 
156
                else:
 
157
                    raise e
215
158
            
216
 
    def unlock(self):
217
 
        if not self._lock_mode:
218
 
            from errors import LockError
219
 
            raise LockError('branch %r is not locked' % (self))
220
 
 
221
 
        if self._lock_count > 1:
222
 
            self._lock_count -= 1
223
 
        else:
224
 
            self._lock.unlock()
225
 
            self._lock = None
226
 
            self._lock_mode = self._lock_count = None
 
159
            fcntl.lockf(lockfile, lm)
 
160
            def unlock():
 
161
                fcntl.lockf(lockfile, fcntl.LOCK_UN)
 
162
                os.close(lockfile)
 
163
                self._lockmode = None
 
164
            self.unlock = unlock
 
165
            self._lockmode = mode
 
166
        except ImportError:
 
167
            warning("please write a locking method for platform %r" % sys.platform)
 
168
            def unlock():
 
169
                self._lockmode = None
 
170
            self.unlock = unlock
 
171
            self._lockmode = mode
 
172
 
 
173
 
 
174
    def _need_readlock(self):
 
175
        if self._lockmode not in ['r', 'w']:
 
176
            raise BzrError('need read lock on branch, only have %r' % self._lockmode)
 
177
 
 
178
    def _need_writelock(self):
 
179
        if self._lockmode not in ['w']:
 
180
            raise BzrError('need write lock on branch, only have %r' % self._lockmode)
227
181
 
228
182
 
229
183
    def abspath(self, name):
235
189
        """Return path relative to this branch of something inside it.
236
190
 
237
191
        Raises an error if path is not in this branch."""
238
 
        return _relpath(self.base, path)
 
192
        rp = os.path.realpath(path)
 
193
        # FIXME: windows
 
194
        if not rp.startswith(self.base):
 
195
            bailout("path %r is not within branch %r" % (rp, self.base))
 
196
        rp = rp[len(self.base):]
 
197
        rp = rp.lstrip(os.sep)
 
198
        return rp
239
199
 
240
200
 
241
201
    def controlfilename(self, file_or_path):
302
262
        fmt = self.controlfile('branch-format', 'r').read()
303
263
        fmt.replace('\r\n', '')
304
264
        if fmt != BZR_BRANCH_FORMAT:
305
 
            raise BzrError('sorry, branch format %r not supported' % fmt,
306
 
                           ['use a different bzr version',
307
 
                            'or remove the .bzr directory and "bzr init" again'])
308
 
 
 
265
            bailout('sorry, branch format %r not supported' % fmt,
 
266
                    ['use a different bzr version',
 
267
                     'or remove the .bzr directory and "bzr init" again'])
309
268
 
310
269
 
311
270
    def read_working_inventory(self):
312
271
        """Read the working inventory."""
 
272
        self._need_readlock()
313
273
        before = time.time()
314
274
        # ElementTree does its own conversion from UTF-8, so open in
315
275
        # binary.
316
 
        self.lock_read()
317
 
        try:
318
 
            inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
319
 
            mutter("loaded inventory of %d items in %f"
320
 
                   % (len(inv), time.time() - before))
321
 
            return inv
322
 
        finally:
323
 
            self.unlock()
324
 
            
 
276
        inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
 
277
        mutter("loaded inventory of %d items in %f"
 
278
               % (len(inv), time.time() - before))
 
279
        return inv
 
280
 
325
281
 
326
282
    def _write_inventory(self, inv):
327
283
        """Update the working inventory.
329
285
        That is to say, the inventory describing changes underway, that
330
286
        will be committed to the next revision.
331
287
        """
 
288
        self._need_writelock()
332
289
        ## TODO: factor out to atomicfile?  is rename safe on windows?
333
290
        ## TODO: Maybe some kind of clean/dirty marker on inventory?
334
291
        tmpfname = self.controlfilename('inventory.tmp')
340
297
            os.remove(inv_fname)
341
298
        os.rename(tmpfname, inv_fname)
342
299
        mutter('wrote working inventory')
343
 
            
 
300
 
344
301
 
345
302
    inventory = property(read_working_inventory, _write_inventory, None,
346
303
                         """Inventory for the working copy.""")
347
304
 
348
305
 
349
 
    def add(self, files, verbose=False, ids=None):
 
306
    def add(self, files, verbose=False):
350
307
        """Make files versioned.
351
308
 
352
309
        Note that the command line normally calls smart_add instead.
354
311
        This puts the files in the Added state, so that they will be
355
312
        recorded by the next commit.
356
313
 
357
 
        files
358
 
            List of paths to add, relative to the base of the tree.
359
 
 
360
 
        ids
361
 
            If set, use these instead of automatically generated ids.
362
 
            Must be the same length as the list of files, but may
363
 
            contain None for ids that are to be autogenerated.
364
 
 
365
314
        TODO: Perhaps have an option to add the ids even if the files do
366
 
              not (yet) exist.
 
315
               not (yet) exist.
367
316
 
368
317
        TODO: Perhaps return the ids of the files?  But then again it
369
 
              is easy to retrieve them if they're needed.
 
318
               is easy to retrieve them if they're needed.
 
319
 
 
320
        TODO: Option to specify file id.
370
321
 
371
322
        TODO: Adding a directory should optionally recurse down and
372
 
              add all non-ignored children.  Perhaps do that in a
373
 
              higher-level method.
 
323
               add all non-ignored children.  Perhaps do that in a
 
324
               higher-level method.
374
325
        """
 
326
        self._need_writelock()
 
327
 
375
328
        # TODO: Re-adding a file that is removed in the working copy
376
329
        # should probably put it back with the previous ID.
377
330
        if isinstance(files, types.StringTypes):
378
 
            assert(ids is None or isinstance(ids, types.StringTypes))
379
331
            files = [files]
380
 
            if ids is not None:
381
 
                ids = [ids]
382
 
 
383
 
        if ids is None:
384
 
            ids = [None] * len(files)
385
 
        else:
386
 
            assert(len(ids) == len(files))
387
 
 
388
 
        self.lock_write()
389
 
        try:
390
 
            inv = self.read_working_inventory()
391
 
            for f,file_id in zip(files, ids):
392
 
                if is_control_file(f):
393
 
                    raise BzrError("cannot add control file %s" % quotefn(f))
394
 
 
395
 
                fp = splitpath(f)
396
 
 
397
 
                if len(fp) == 0:
398
 
                    raise BzrError("cannot add top-level %r" % f)
399
 
 
400
 
                fullpath = os.path.normpath(self.abspath(f))
401
 
 
402
 
                try:
403
 
                    kind = file_kind(fullpath)
404
 
                except OSError:
405
 
                    # maybe something better?
406
 
                    raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
407
 
 
408
 
                if kind != 'file' and kind != 'directory':
409
 
                    raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
410
 
 
411
 
                if file_id is None:
412
 
                    file_id = gen_file_id(f)
413
 
                inv.add_path(f, kind=kind, file_id=file_id)
414
 
 
415
 
                if verbose:
416
 
                    show_status('A', kind, quotefn(f))
417
 
 
418
 
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
419
 
 
420
 
            self._write_inventory(inv)
421
 
        finally:
422
 
            self.unlock()
423
 
            
 
332
        
 
333
        inv = self.read_working_inventory()
 
334
        for f in files:
 
335
            if is_control_file(f):
 
336
                bailout("cannot add control file %s" % quotefn(f))
 
337
 
 
338
            fp = splitpath(f)
 
339
 
 
340
            if len(fp) == 0:
 
341
                bailout("cannot add top-level %r" % f)
 
342
                
 
343
            fullpath = os.path.normpath(self.abspath(f))
 
344
 
 
345
            try:
 
346
                kind = file_kind(fullpath)
 
347
            except OSError:
 
348
                # maybe something better?
 
349
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
350
            
 
351
            if kind != 'file' and kind != 'directory':
 
352
                bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
 
353
 
 
354
            file_id = gen_file_id(f)
 
355
            inv.add_path(f, kind=kind, file_id=file_id)
 
356
 
 
357
            if verbose:
 
358
                show_status('A', kind, quotefn(f))
 
359
                
 
360
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
 
361
            
 
362
        self._write_inventory(inv)
 
363
 
424
364
 
425
365
    def print_file(self, file, revno):
426
366
        """Print `file` to stdout."""
427
 
        self.lock_read()
428
 
        try:
429
 
            tree = self.revision_tree(self.lookup_revision(revno))
430
 
            # use inventory as it was in that revision
431
 
            file_id = tree.inventory.path2id(file)
432
 
            if not file_id:
433
 
                raise BzrError("%r is not present in revision %d" % (file, revno))
434
 
            tree.print_file(file_id)
435
 
        finally:
436
 
            self.unlock()
437
 
 
 
367
        self._need_readlock()
 
368
        tree = self.revision_tree(self.lookup_revision(revno))
 
369
        # use inventory as it was in that revision
 
370
        file_id = tree.inventory.path2id(file)
 
371
        if not file_id:
 
372
            bailout("%r is not present in revision %d" % (file, revno))
 
373
        tree.print_file(file_id)
 
374
        
438
375
 
439
376
    def remove(self, files, verbose=False):
440
377
        """Mark nominated files for removal from the inventory.
452
389
        """
453
390
        ## TODO: Normalize names
454
391
        ## TODO: Remove nested loops; better scalability
 
392
        self._need_writelock()
 
393
 
455
394
        if isinstance(files, types.StringTypes):
456
395
            files = [files]
457
 
 
458
 
        self.lock_write()
459
 
 
460
 
        try:
461
 
            tree = self.working_tree()
462
 
            inv = tree.inventory
463
 
 
464
 
            # do this before any modifications
465
 
            for f in files:
466
 
                fid = inv.path2id(f)
467
 
                if not fid:
468
 
                    raise BzrError("cannot remove unversioned file %s" % quotefn(f))
469
 
                mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
470
 
                if verbose:
471
 
                    # having remove it, it must be either ignored or unknown
472
 
                    if tree.is_ignored(f):
473
 
                        new_status = 'I'
474
 
                    else:
475
 
                        new_status = '?'
476
 
                    show_status(new_status, inv[fid].kind, quotefn(f))
477
 
                del inv[fid]
478
 
 
479
 
            self._write_inventory(inv)
480
 
        finally:
481
 
            self.unlock()
482
 
 
483
 
 
484
 
    # FIXME: this doesn't need to be a branch method
485
 
    def set_inventory(self, new_inventory_list):
486
 
        inv = Inventory()
487
 
        for path, file_id, parent, kind in new_inventory_list:
488
 
            name = os.path.basename(path)
489
 
            if name == "":
490
 
                continue
491
 
            inv.add(InventoryEntry(file_id, name, kind, parent))
 
396
        
 
397
        tree = self.working_tree()
 
398
        inv = tree.inventory
 
399
 
 
400
        # do this before any modifications
 
401
        for f in files:
 
402
            fid = inv.path2id(f)
 
403
            if not fid:
 
404
                bailout("cannot remove unversioned file %s" % quotefn(f))
 
405
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
 
406
            if verbose:
 
407
                # having remove it, it must be either ignored or unknown
 
408
                if tree.is_ignored(f):
 
409
                    new_status = 'I'
 
410
                else:
 
411
                    new_status = '?'
 
412
                show_status(new_status, inv[fid].kind, quotefn(f))
 
413
            del inv[fid]
 
414
 
492
415
        self._write_inventory(inv)
493
416
 
494
417
 
532
455
 
533
456
    def get_revision(self, revision_id):
534
457
        """Return the Revision object for a named revision"""
 
458
        self._need_readlock()
535
459
        r = Revision.read_xml(self.revision_store[revision_id])
536
460
        assert r.revision_id == revision_id
537
461
        return r
543
467
        TODO: Perhaps for this and similar methods, take a revision
544
468
               parameter which can be either an integer revno or a
545
469
               string hash."""
 
470
        self._need_readlock()
546
471
        i = Inventory.read_xml(self.inventory_store[inventory_id])
547
472
        return i
548
473
 
549
474
 
550
475
    def get_revision_inventory(self, revision_id):
551
476
        """Return inventory of a past revision."""
 
477
        self._need_readlock()
552
478
        if revision_id == None:
553
479
            return Inventory()
554
480
        else:
561
487
        >>> ScratchBranch().revision_history()
562
488
        []
563
489
        """
564
 
        self.lock_read()
565
 
        try:
566
 
            return [l.rstrip('\r\n') for l in
567
 
                    self.controlfile('revision-history', 'r').readlines()]
568
 
        finally:
569
 
            self.unlock()
570
 
 
571
 
 
572
 
    def common_ancestor(self, other, self_revno=None, other_revno=None):
573
 
        """
574
 
        >>> import commit
575
 
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
576
 
        >>> sb.common_ancestor(sb) == (None, None)
577
 
        True
578
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
579
 
        >>> sb.common_ancestor(sb)[0]
580
 
        1
581
 
        >>> clone = sb.clone()
582
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
583
 
        >>> sb.common_ancestor(sb)[0]
584
 
        2
585
 
        >>> sb.common_ancestor(clone)[0]
586
 
        1
587
 
        >>> commit.commit(clone, "Committing divergent second revision", 
588
 
        ...               verbose=False)
589
 
        >>> sb.common_ancestor(clone)[0]
590
 
        1
591
 
        >>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
592
 
        True
593
 
        >>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
594
 
        True
595
 
        >>> clone2 = sb.clone()
596
 
        >>> sb.common_ancestor(clone2)[0]
597
 
        2
598
 
        >>> sb.common_ancestor(clone2, self_revno=1)[0]
599
 
        1
600
 
        >>> sb.common_ancestor(clone2, other_revno=1)[0]
601
 
        1
602
 
        """
603
 
        my_history = self.revision_history()
604
 
        other_history = other.revision_history()
605
 
        if self_revno is None:
606
 
            self_revno = len(my_history)
607
 
        if other_revno is None:
608
 
            other_revno = len(other_history)
609
 
        indices = range(min((self_revno, other_revno)))
610
 
        indices.reverse()
611
 
        for r in indices:
612
 
            if my_history[r] == other_history[r]:
613
 
                return r+1, my_history[r]
614
 
        return None, None
 
490
        self._need_readlock()
 
491
        return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
 
492
 
615
493
 
616
494
    def enum_history(self, direction):
617
495
        """Return (revno, revision_id) for history of branch.
632
510
                yield i, rh[i-1]
633
511
                i -= 1
634
512
        else:
635
 
            raise ValueError('invalid history direction', direction)
 
513
            raise BzrError('invalid history direction %r' % direction)
636
514
 
637
515
 
638
516
    def revno(self):
654
532
            return None
655
533
 
656
534
 
657
 
    def missing_revisions(self, other):
658
 
        """
659
 
        If self and other have not diverged, return a list of the revisions
660
 
        present in other, but missing from self.
661
 
 
662
 
        >>> from bzrlib.commit import commit
663
 
        >>> bzrlib.trace.silent = True
664
 
        >>> br1 = ScratchBranch()
665
 
        >>> br2 = ScratchBranch()
666
 
        >>> br1.missing_revisions(br2)
667
 
        []
668
 
        >>> commit(br2, "lala!", rev_id="REVISION-ID-1")
669
 
        >>> br1.missing_revisions(br2)
670
 
        [u'REVISION-ID-1']
671
 
        >>> br2.missing_revisions(br1)
672
 
        []
673
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1")
674
 
        >>> br1.missing_revisions(br2)
675
 
        []
676
 
        >>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
677
 
        >>> br1.missing_revisions(br2)
678
 
        [u'REVISION-ID-2A']
679
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
680
 
        >>> br1.missing_revisions(br2)
681
 
        Traceback (most recent call last):
682
 
        DivergedBranches: These branches have diverged.
683
 
        """
684
 
        self_history = self.revision_history()
685
 
        self_len = len(self_history)
686
 
        other_history = other.revision_history()
687
 
        other_len = len(other_history)
688
 
        common_index = min(self_len, other_len) -1
689
 
        if common_index >= 0 and \
690
 
            self_history[common_index] != other_history[common_index]:
691
 
            raise DivergedBranches(self, other)
692
 
        if self_len < other_len:
693
 
            return other_history[self_len:]
694
 
        return []
695
 
 
696
 
 
697
 
    def update_revisions(self, other):
698
 
        """If self and other have not diverged, ensure self has all the
699
 
        revisions in other
700
 
 
701
 
        >>> from bzrlib.commit import commit
702
 
        >>> bzrlib.trace.silent = True
703
 
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
704
 
        >>> br1.add('foo')
705
 
        >>> br1.add('bar')
706
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
707
 
        >>> br2 = ScratchBranch()
708
 
        >>> br2.update_revisions(br1)
709
 
        Added 2 texts.
710
 
        Added 1 inventories.
711
 
        Added 1 revisions.
712
 
        >>> br2.revision_history()
713
 
        [u'REVISION-ID-1']
714
 
        >>> br2.update_revisions(br1)
715
 
        Added 0 texts.
716
 
        Added 0 inventories.
717
 
        Added 0 revisions.
718
 
        >>> br1.text_store.total_size() == br2.text_store.total_size()
719
 
        True
720
 
        """
721
 
        revision_ids = self.missing_revisions(other)
722
 
        revisions = [other.get_revision(f) for f in revision_ids]
723
 
        needed_texts = sets.Set()
724
 
        for rev in revisions:
725
 
            inv = other.get_inventory(str(rev.inventory_id))
726
 
            for key, entry in inv.iter_entries():
727
 
                if entry.text_id is None:
728
 
                    continue
729
 
                if entry.text_id not in self.text_store:
730
 
                    needed_texts.add(entry.text_id)
731
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
732
 
        print "Added %d texts." % count 
733
 
        inventory_ids = [ f.inventory_id for f in revisions ]
734
 
        count = self.inventory_store.copy_multi(other.inventory_store, 
735
 
                                                inventory_ids)
736
 
        print "Added %d inventories." % count 
737
 
        revision_ids = [ f.revision_id for f in revisions]
738
 
        count = self.revision_store.copy_multi(other.revision_store, 
739
 
                                               revision_ids)
740
 
        for revision_id in revision_ids:
741
 
            self.append_revision(revision_id)
742
 
        print "Added %d revisions." % count
743
 
                    
744
 
        
745
535
    def commit(self, *args, **kw):
746
536
        """Deprecated"""
747
537
        from bzrlib.commit import commit
765
555
 
766
556
        `revision_id` may be None for the null revision, in which case
767
557
        an `EmptyTree` is returned."""
768
 
        # TODO: refactor this to use an existing revision object
769
 
        # so we don't need to read it in twice.
 
558
        self._need_readlock()
770
559
        if revision_id == None:
771
560
            return EmptyTree()
772
561
        else:
798
587
 
799
588
        This can change the directory or the filename or both.
800
589
        """
801
 
        self.lock_write()
 
590
        self._need_writelock()
 
591
        tree = self.working_tree()
 
592
        inv = tree.inventory
 
593
        if not tree.has_filename(from_rel):
 
594
            bailout("can't rename: old working file %r does not exist" % from_rel)
 
595
        if tree.has_filename(to_rel):
 
596
            bailout("can't rename: new working file %r already exists" % to_rel)
 
597
            
 
598
        file_id = inv.path2id(from_rel)
 
599
        if file_id == None:
 
600
            bailout("can't rename: old name %r is not versioned" % from_rel)
 
601
 
 
602
        if inv.path2id(to_rel):
 
603
            bailout("can't rename: new name %r is already versioned" % to_rel)
 
604
 
 
605
        to_dir, to_tail = os.path.split(to_rel)
 
606
        to_dir_id = inv.path2id(to_dir)
 
607
        if to_dir_id == None and to_dir != '':
 
608
            bailout("can't determine destination directory id for %r" % to_dir)
 
609
 
 
610
        mutter("rename_one:")
 
611
        mutter("  file_id    {%s}" % file_id)
 
612
        mutter("  from_rel   %r" % from_rel)
 
613
        mutter("  to_rel     %r" % to_rel)
 
614
        mutter("  to_dir     %r" % to_dir)
 
615
        mutter("  to_dir_id  {%s}" % to_dir_id)
 
616
            
 
617
        inv.rename(file_id, to_dir_id, to_tail)
 
618
 
 
619
        print "%s => %s" % (from_rel, to_rel)
 
620
        
 
621
        from_abs = self.abspath(from_rel)
 
622
        to_abs = self.abspath(to_rel)
802
623
        try:
803
 
            tree = self.working_tree()
804
 
            inv = tree.inventory
805
 
            if not tree.has_filename(from_rel):
806
 
                raise BzrError("can't rename: old working file %r does not exist" % from_rel)
807
 
            if tree.has_filename(to_rel):
808
 
                raise BzrError("can't rename: new working file %r already exists" % to_rel)
809
 
 
810
 
            file_id = inv.path2id(from_rel)
811
 
            if file_id == None:
812
 
                raise BzrError("can't rename: old name %r is not versioned" % from_rel)
813
 
 
814
 
            if inv.path2id(to_rel):
815
 
                raise BzrError("can't rename: new name %r is already versioned" % to_rel)
816
 
 
817
 
            to_dir, to_tail = os.path.split(to_rel)
818
 
            to_dir_id = inv.path2id(to_dir)
819
 
            if to_dir_id == None and to_dir != '':
820
 
                raise BzrError("can't determine destination directory id for %r" % to_dir)
821
 
 
822
 
            mutter("rename_one:")
823
 
            mutter("  file_id    {%s}" % file_id)
824
 
            mutter("  from_rel   %r" % from_rel)
825
 
            mutter("  to_rel     %r" % to_rel)
826
 
            mutter("  to_dir     %r" % to_dir)
827
 
            mutter("  to_dir_id  {%s}" % to_dir_id)
828
 
 
829
 
            inv.rename(file_id, to_dir_id, to_tail)
830
 
 
831
 
            print "%s => %s" % (from_rel, to_rel)
832
 
 
833
 
            from_abs = self.abspath(from_rel)
834
 
            to_abs = self.abspath(to_rel)
835
 
            try:
836
 
                os.rename(from_abs, to_abs)
837
 
            except OSError, e:
838
 
                raise BzrError("failed to rename %r to %r: %s"
839
 
                        % (from_abs, to_abs, e[1]),
840
 
                        ["rename rolled back"])
841
 
 
842
 
            self._write_inventory(inv)
843
 
        finally:
844
 
            self.unlock()
 
624
            os.rename(from_abs, to_abs)
 
625
        except OSError, e:
 
626
            bailout("failed to rename %r to %r: %s"
 
627
                    % (from_abs, to_abs, e[1]),
 
628
                    ["rename rolled back"])
 
629
 
 
630
        self._write_inventory(inv)
 
631
            
845
632
 
846
633
 
847
634
    def move(self, from_paths, to_name):
855
642
        Note that to_name is only the last component of the new name;
856
643
        this doesn't change the directory.
857
644
        """
858
 
        self.lock_write()
859
 
        try:
860
 
            ## TODO: Option to move IDs only
861
 
            assert not isinstance(from_paths, basestring)
862
 
            tree = self.working_tree()
863
 
            inv = tree.inventory
864
 
            to_abs = self.abspath(to_name)
865
 
            if not isdir(to_abs):
866
 
                raise BzrError("destination %r is not a directory" % to_abs)
867
 
            if not tree.has_filename(to_name):
868
 
                raise BzrError("destination %r not in working directory" % to_abs)
869
 
            to_dir_id = inv.path2id(to_name)
870
 
            if to_dir_id == None and to_name != '':
871
 
                raise BzrError("destination %r is not a versioned directory" % to_name)
872
 
            to_dir_ie = inv[to_dir_id]
873
 
            if to_dir_ie.kind not in ('directory', 'root_directory'):
874
 
                raise BzrError("destination %r is not a directory" % to_abs)
875
 
 
876
 
            to_idpath = inv.get_idpath(to_dir_id)
877
 
 
878
 
            for f in from_paths:
879
 
                if not tree.has_filename(f):
880
 
                    raise BzrError("%r does not exist in working tree" % f)
881
 
                f_id = inv.path2id(f)
882
 
                if f_id == None:
883
 
                    raise BzrError("%r is not versioned" % f)
884
 
                name_tail = splitpath(f)[-1]
885
 
                dest_path = appendpath(to_name, name_tail)
886
 
                if tree.has_filename(dest_path):
887
 
                    raise BzrError("destination %r already exists" % dest_path)
888
 
                if f_id in to_idpath:
889
 
                    raise BzrError("can't move %r to a subdirectory of itself" % f)
890
 
 
891
 
            # OK, so there's a race here, it's possible that someone will
892
 
            # create a file in this interval and then the rename might be
893
 
            # left half-done.  But we should have caught most problems.
894
 
 
895
 
            for f in from_paths:
896
 
                name_tail = splitpath(f)[-1]
897
 
                dest_path = appendpath(to_name, name_tail)
898
 
                print "%s => %s" % (f, dest_path)
899
 
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
900
 
                try:
901
 
                    os.rename(self.abspath(f), self.abspath(dest_path))
902
 
                except OSError, e:
903
 
                    raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
904
 
                            ["rename rolled back"])
905
 
 
906
 
            self._write_inventory(inv)
907
 
        finally:
908
 
            self.unlock()
 
645
        self._need_writelock()
 
646
        ## TODO: Option to move IDs only
 
647
        assert not isinstance(from_paths, basestring)
 
648
        tree = self.working_tree()
 
649
        inv = tree.inventory
 
650
        to_abs = self.abspath(to_name)
 
651
        if not isdir(to_abs):
 
652
            bailout("destination %r is not a directory" % to_abs)
 
653
        if not tree.has_filename(to_name):
 
654
            bailout("destination %r not in working directory" % to_abs)
 
655
        to_dir_id = inv.path2id(to_name)
 
656
        if to_dir_id == None and to_name != '':
 
657
            bailout("destination %r is not a versioned directory" % to_name)
 
658
        to_dir_ie = inv[to_dir_id]
 
659
        if to_dir_ie.kind not in ('directory', 'root_directory'):
 
660
            bailout("destination %r is not a directory" % to_abs)
 
661
 
 
662
        to_idpath = Set(inv.get_idpath(to_dir_id))
 
663
 
 
664
        for f in from_paths:
 
665
            if not tree.has_filename(f):
 
666
                bailout("%r does not exist in working tree" % f)
 
667
            f_id = inv.path2id(f)
 
668
            if f_id == None:
 
669
                bailout("%r is not versioned" % f)
 
670
            name_tail = splitpath(f)[-1]
 
671
            dest_path = appendpath(to_name, name_tail)
 
672
            if tree.has_filename(dest_path):
 
673
                bailout("destination %r already exists" % dest_path)
 
674
            if f_id in to_idpath:
 
675
                bailout("can't move %r to a subdirectory of itself" % f)
 
676
 
 
677
        # OK, so there's a race here, it's possible that someone will
 
678
        # create a file in this interval and then the rename might be
 
679
        # left half-done.  But we should have caught most problems.
 
680
 
 
681
        for f in from_paths:
 
682
            name_tail = splitpath(f)[-1]
 
683
            dest_path = appendpath(to_name, name_tail)
 
684
            print "%s => %s" % (f, dest_path)
 
685
            inv.rename(inv.path2id(f), to_dir_id, name_tail)
 
686
            try:
 
687
                os.rename(self.abspath(f), self.abspath(dest_path))
 
688
            except OSError, e:
 
689
                bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
 
690
                        ["rename rolled back"])
 
691
 
 
692
        self._write_inventory(inv)
 
693
 
909
694
 
910
695
 
911
696
 
920
705
    >>> isdir(bd)
921
706
    False
922
707
    """
923
 
    def __init__(self, files=[], dirs=[], base=None):
 
708
    def __init__(self, files=[], dirs=[]):
924
709
        """Make a test branch.
925
710
 
926
711
        This creates a temporary directory and runs init-tree in it.
927
712
 
928
713
        If any files are listed, they are created in the working copy.
929
714
        """
930
 
        init = False
931
 
        if base is None:
932
 
            base = tempfile.mkdtemp()
933
 
            init = True
934
 
        Branch.__init__(self, base, init=init)
 
715
        Branch.__init__(self, tempfile.mkdtemp(), init=True)
935
716
        for d in dirs:
936
717
            os.mkdir(self.abspath(d))
937
718
            
939
720
            file(os.path.join(self.base, f), 'w').write('content of %s' % f)
940
721
 
941
722
 
942
 
    def clone(self):
943
 
        """
944
 
        >>> orig = ScratchBranch(files=["file1", "file2"])
945
 
        >>> clone = orig.clone()
946
 
        >>> os.path.samefile(orig.base, clone.base)
947
 
        False
948
 
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
949
 
        True
950
 
        """
951
 
        base = tempfile.mkdtemp()
952
 
        os.rmdir(base)
953
 
        shutil.copytree(self.base, base, symlinks=True)
954
 
        return ScratchBranch(base=base)
955
 
        
956
723
    def __del__(self):
957
724
        self.destroy()
958
725
 
959
726
    def destroy(self):
960
727
        """Destroy the test branch, removing the scratch directory."""
961
728
        try:
962
 
            if self.base:
963
 
                mutter("delete ScratchBranch %s" % self.base)
964
 
                shutil.rmtree(self.base)
 
729
            mutter("delete ScratchBranch %s" % self.base)
 
730
            shutil.rmtree(self.base)
965
731
        except OSError, e:
966
732
            # Work around for shutil.rmtree failing on Windows when
967
733
            # readonly files are encountered
999
765
    This should probably generate proper UUIDs, but for the moment we
1000
766
    cope with just randomness because running uuidgen every time is
1001
767
    slow."""
1002
 
    import re
1003
 
 
1004
 
    # get last component
1005
768
    idx = name.rfind('/')
1006
769
    if idx != -1:
1007
770
        name = name[idx+1 : ]
1009
772
    if idx != -1:
1010
773
        name = name[idx+1 : ]
1011
774
 
1012
 
    # make it not a hidden file
1013
775
    name = name.lstrip('.')
1014
776
 
1015
 
    # remove any wierd characters; we don't escape them but rather
1016
 
    # just pull them out
1017
 
    name = re.sub(r'[^\w.]', '', name)
1018
 
 
1019
777
    s = hexlify(rand_bytes(8))
1020
778
    return '-'.join((name, compact_date(time.time()), s))