~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2005-09-23 09:25:16 UTC
  • mto: (1092.3.4)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: robertc@robertcollins.net-20050923092516-e2c3c0f31288669d
Merge what applied of Alexander Belchenko's win32 patch.

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
 
import sys, os, os.path, random, time, sha, sets, types, re, shutil, tempfile
19
 
import traceback, socket, fnmatch, difflib, time
20
 
from binascii import hexlify
 
18
import sys
 
19
import os
21
20
 
22
21
import bzrlib
23
 
from inventory import Inventory
24
 
from trace import mutter, note
25
 
from tree import Tree, EmptyTree, RevisionTree
26
 
from inventory import InventoryEntry, Inventory
27
 
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
28
 
     format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
29
 
     joinpath, sha_file, sha_string, file_kind, local_time_offset, appendpath
30
 
from store import ImmutableStore
31
 
from revision import Revision
32
 
from errors import BzrError
33
 
from textui import show_status
 
22
from bzrlib.trace import mutter, note
 
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
 
24
     rename, splitpath, sha_file, appendpath, file_kind
 
25
 
 
26
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
 
27
     DivergedBranches, NotBranchError
 
28
from bzrlib.textui import show_status
 
29
from bzrlib.revision import Revision
 
30
from bzrlib.delta import compare_trees
 
31
from bzrlib.tree import EmptyTree, RevisionTree
 
32
import bzrlib.xml
 
33
import bzrlib.ui
 
34
 
 
35
 
34
36
 
35
37
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
36
38
## TODO: Maybe include checks for common corruption of newlines, etc?
37
39
 
38
40
 
39
 
 
40
 
def find_branch(f, **args):
41
 
    if f and (f.startswith('http://') or f.startswith('https://')):
42
 
        import remotebranch 
43
 
        return remotebranch.RemoteBranch(f, **args)
44
 
    else:
45
 
        return Branch(f, **args)
46
 
 
47
 
 
 
41
# TODO: Some operations like log might retrieve the same revisions
 
42
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
43
# cache in memory to make this faster.
 
44
 
 
45
def find_branch(*ignored, **ignored_too):
 
46
    # XXX: leave this here for about one release, then remove it
 
47
    raise NotImplementedError('find_branch() is not supported anymore, '
 
48
                              'please use one of the new branch constructors')
48
49
 
49
50
def _relpath(base, path):
50
51
    """Return path relative to base, or raise exception.
68
69
        if tail:
69
70
            s.insert(0, tail)
70
71
    else:
71
 
        from errors import NotBranchError
72
72
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
73
73
 
74
74
    return os.sep.join(s)
82
82
    It is not necessary that f exists.
83
83
 
84
84
    Basically we keep looking up until we find the control directory or
85
 
    run into the root."""
 
85
    run into the root.  If there isn't one, raises NotBranchError.
 
86
    """
86
87
    if f == None:
87
88
        f = os.getcwd()
88
89
    elif hasattr(os.path, 'realpath'):
101
102
        head, tail = os.path.split(f)
102
103
        if head == f:
103
104
            # reached the root, whatever that may be
104
 
            raise BzrError('%r is not in a branch' % orig_f)
 
105
            raise NotBranchError('%s is not in a branch' % orig_f)
105
106
        f = head
106
 
    
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.")
112
 
 
113
 
 
114
 
class NoSuchRevision(BzrError):
115
 
    def __init__(self, branch, revision):
116
 
        self.branch = branch
117
 
        self.revision = revision
118
 
        msg = "Branch %s has no revision %d" % (branch, revision)
119
 
        BzrError.__init__(self, msg)
 
107
 
 
108
 
120
109
 
121
110
 
122
111
######################################################################
126
115
    """Branch holding a history of revisions.
127
116
 
128
117
    base
129
 
        Base directory of the branch.
 
118
        Base directory/url of the branch.
 
119
    """
 
120
    base = None
 
121
 
 
122
    def __init__(self, *ignored, **ignored_too):
 
123
        raise NotImplementedError('The Branch class is abstract')
 
124
 
 
125
    @staticmethod
 
126
    def open(base):
 
127
        """Open an existing branch, rooted at 'base' (url)"""
 
128
        if base and (base.startswith('http://') or base.startswith('https://')):
 
129
            from bzrlib.remotebranch import RemoteBranch
 
130
            return RemoteBranch(base, find_root=False)
 
131
        else:
 
132
            return LocalBranch(base, find_root=False)
 
133
 
 
134
    @staticmethod
 
135
    def open_containing(url):
 
136
        """Open an existing branch, containing url (search upwards for the root)
 
137
        """
 
138
        if url and (url.startswith('http://') or url.startswith('https://')):
 
139
            from bzrlib.remotebranch import RemoteBranch
 
140
            return RemoteBranch(url)
 
141
        else:
 
142
            return LocalBranch(url)
 
143
 
 
144
    @staticmethod
 
145
    def initialize(base):
 
146
        """Create a new branch, rooted at 'base' (url)"""
 
147
        if base and (base.startswith('http://') or base.startswith('https://')):
 
148
            from bzrlib.remotebranch import RemoteBranch
 
149
            return RemoteBranch(base, init=True)
 
150
        else:
 
151
            return LocalBranch(base, init=True)
 
152
 
 
153
    def setup_caching(self, cache_root):
 
154
        """Subclasses that care about caching should override this, and set
 
155
        up cached stores located under cache_root.
 
156
        """
 
157
 
 
158
 
 
159
class LocalBranch(Branch):
 
160
    """A branch stored in the actual filesystem.
 
161
 
 
162
    Note that it's "local" in the context of the filesystem; it doesn't
 
163
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
164
    it's writable, and can be accessed via the normal filesystem API.
130
165
 
131
166
    _lock_mode
132
167
        None, or 'r' or 'w'
138
173
    _lock
139
174
        Lock object from bzrlib.lock.
140
175
    """
141
 
    base = None
 
176
    # We actually expect this class to be somewhat short-lived; part of its
 
177
    # purpose is to try to isolate what bits of the branch logic are tied to
 
178
    # filesystem access, so that in a later step, we can extricate them to
 
179
    # a separarte ("storage") class.
142
180
    _lock_mode = None
143
181
    _lock_count = None
144
182
    _lock = None
145
 
    
 
183
 
146
184
    def __init__(self, base, init=False, find_root=True):
147
185
        """Create new branch object at a particular location.
148
186
 
149
 
        base -- Base directory for the branch.
 
187
        base -- Base directory for the branch. May be a file:// url.
150
188
        
151
189
        init -- If True, create new control files in a previously
152
190
             unversioned directory.  If False, the branch must already
158
196
        In the test suite, creation of new trees is tested using the
159
197
        `ScratchBranch` class.
160
198
        """
 
199
        from bzrlib.store import ImmutableStore
161
200
        if init:
162
201
            self.base = os.path.realpath(base)
163
202
            self._make_control()
164
203
        elif find_root:
165
204
            self.base = find_branch_root(base)
166
205
        else:
 
206
            if base.startswith("file://"):
 
207
                base = base[7:]
167
208
            self.base = os.path.realpath(base)
168
209
            if not isdir(self.controlfilename('.')):
169
 
                from errors import NotBranchError
170
210
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
171
211
                                     ['use "bzr init" to initialize a new working tree',
172
212
                                      'current bzr can only operate from top-of-tree'])
186
226
 
187
227
    def __del__(self):
188
228
        if self._lock_mode or self._lock:
189
 
            from warnings import warn
 
229
            from bzrlib.warnings import warn
190
230
            warn("branch %r was not explicitly unlocked" % self)
191
231
            self._lock.unlock()
192
232
 
193
 
 
194
 
 
195
233
    def lock_write(self):
196
234
        if self._lock_mode:
197
235
            if self._lock_mode != 'w':
198
 
                from errors import LockError
 
236
                from bzrlib.errors import LockError
199
237
                raise LockError("can't upgrade to a write lock from %r" %
200
238
                                self._lock_mode)
201
239
            self._lock_count += 1
207
245
            self._lock_count = 1
208
246
 
209
247
 
210
 
 
211
248
    def lock_read(self):
212
249
        if self._lock_mode:
213
250
            assert self._lock_mode in ('r', 'w'), \
220
257
            self._lock_mode = 'r'
221
258
            self._lock_count = 1
222
259
                        
223
 
 
224
 
            
225
260
    def unlock(self):
226
261
        if not self._lock_mode:
227
 
            from errors import LockError
 
262
            from bzrlib.errors import LockError
228
263
            raise LockError('branch %r is not locked' % (self))
229
264
 
230
265
        if self._lock_count > 1:
234
269
            self._lock = None
235
270
            self._lock_mode = self._lock_count = None
236
271
 
237
 
 
238
272
    def abspath(self, name):
239
273
        """Return absolute filename for something in the branch"""
240
274
        return os.path.join(self.base, name)
241
275
 
242
 
 
243
276
    def relpath(self, path):
244
277
        """Return path relative to this branch of something inside it.
245
278
 
246
279
        Raises an error if path is not in this branch."""
247
280
        return _relpath(self.base, path)
248
281
 
249
 
 
250
282
    def controlfilename(self, file_or_path):
251
283
        """Return location relative to branch."""
252
 
        if isinstance(file_or_path, types.StringTypes):
 
284
        if isinstance(file_or_path, basestring):
253
285
            file_or_path = [file_or_path]
254
286
        return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
255
287
 
279
311
        else:
280
312
            raise BzrError("invalid controlfile mode %r" % mode)
281
313
 
282
 
 
283
 
 
284
314
    def _make_control(self):
 
315
        from bzrlib.inventory import Inventory
 
316
        
285
317
        os.mkdir(self.controlfilename([]))
286
318
        self.controlfile('README', 'w').write(
287
319
            "This is a Bazaar-NG control directory.\n"
291
323
            os.mkdir(self.controlfilename(d))
292
324
        for f in ('revision-history', 'merged-patches',
293
325
                  'pending-merged-patches', 'branch-name',
294
 
                  'branch-lock'):
 
326
                  'branch-lock',
 
327
                  'pending-merges'):
295
328
            self.controlfile(f, 'w').write('')
296
329
        mutter('created control directory in ' + self.base)
297
 
        Inventory().write_xml(self.controlfile('inventory','w'))
 
330
 
 
331
        # if we want per-tree root ids then this is the place to set
 
332
        # them; they're not needed for now and so ommitted for
 
333
        # simplicity.
 
334
        f = self.controlfile('inventory','w')
 
335
        bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
298
336
 
299
337
 
300
338
    def _check_format(self):
309
347
        # on Windows from Linux and so on.  I think it might be better
310
348
        # to always make all internal files in unix format.
311
349
        fmt = self.controlfile('branch-format', 'r').read()
312
 
        fmt.replace('\r\n', '')
 
350
        fmt = fmt.replace('\r\n', '\n')
313
351
        if fmt != BZR_BRANCH_FORMAT:
314
352
            raise BzrError('sorry, branch format %r not supported' % fmt,
315
353
                           ['use a different bzr version',
316
354
                            'or remove the .bzr directory and "bzr init" again'])
317
355
 
 
356
    def get_root_id(self):
 
357
        """Return the id of this branches root"""
 
358
        inv = self.read_working_inventory()
 
359
        return inv.root.file_id
318
360
 
 
361
    def set_root_id(self, file_id):
 
362
        inv = self.read_working_inventory()
 
363
        orig_root_id = inv.root.file_id
 
364
        del inv._byid[inv.root.file_id]
 
365
        inv.root.file_id = file_id
 
366
        inv._byid[inv.root.file_id] = inv.root
 
367
        for fid in inv:
 
368
            entry = inv[fid]
 
369
            if entry.parent_id in (None, orig_root_id):
 
370
                entry.parent_id = inv.root.file_id
 
371
        self._write_inventory(inv)
319
372
 
320
373
    def read_working_inventory(self):
321
374
        """Read the working inventory."""
322
 
        before = time.time()
323
 
        # ElementTree does its own conversion from UTF-8, so open in
324
 
        # binary.
 
375
        from bzrlib.inventory import Inventory
325
376
        self.lock_read()
326
377
        try:
327
 
            inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
328
 
            mutter("loaded inventory of %d items in %f"
329
 
                   % (len(inv), time.time() - before))
330
 
            return inv
 
378
            # ElementTree does its own conversion from UTF-8, so open in
 
379
            # binary.
 
380
            f = self.controlfile('inventory', 'rb')
 
381
            return bzrlib.xml.serializer_v4.read_inventory(f)
331
382
        finally:
332
383
            self.unlock()
333
384
            
338
389
        That is to say, the inventory describing changes underway, that
339
390
        will be committed to the next revision.
340
391
        """
341
 
        ## TODO: factor out to atomicfile?  is rename safe on windows?
342
 
        ## TODO: Maybe some kind of clean/dirty marker on inventory?
343
 
        tmpfname = self.controlfilename('inventory.tmp')
344
 
        tmpf = file(tmpfname, 'wb')
345
 
        inv.write_xml(tmpf)
346
 
        tmpf.close()
347
 
        inv_fname = self.controlfilename('inventory')
348
 
        if sys.platform == 'win32':
349
 
            os.remove(inv_fname)
350
 
        os.rename(tmpfname, inv_fname)
 
392
        from bzrlib.atomicfile import AtomicFile
 
393
        
 
394
        self.lock_write()
 
395
        try:
 
396
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
 
397
            try:
 
398
                bzrlib.xml.serializer_v4.write_inventory(inv, f)
 
399
                f.commit()
 
400
            finally:
 
401
                f.close()
 
402
        finally:
 
403
            self.unlock()
 
404
        
351
405
        mutter('wrote working inventory')
352
406
            
353
407
 
355
409
                         """Inventory for the working copy.""")
356
410
 
357
411
 
358
 
    def add(self, files, verbose=False, ids=None):
 
412
    def add(self, files, ids=None):
359
413
        """Make files versioned.
360
414
 
361
 
        Note that the command line normally calls smart_add instead.
 
415
        Note that the command line normally calls smart_add instead,
 
416
        which can automatically recurse.
362
417
 
363
418
        This puts the files in the Added state, so that they will be
364
419
        recorded by the next commit.
374
429
        TODO: Perhaps have an option to add the ids even if the files do
375
430
              not (yet) exist.
376
431
 
377
 
        TODO: Perhaps return the ids of the files?  But then again it
378
 
              is easy to retrieve them if they're needed.
379
 
 
380
 
        TODO: Adding a directory should optionally recurse down and
381
 
              add all non-ignored children.  Perhaps do that in a
382
 
              higher-level method.
 
432
        TODO: Perhaps yield the ids and paths as they're added.
383
433
        """
384
434
        # TODO: Re-adding a file that is removed in the working copy
385
435
        # should probably put it back with the previous ID.
386
 
        if isinstance(files, types.StringTypes):
387
 
            assert(ids is None or isinstance(ids, types.StringTypes))
 
436
        if isinstance(files, basestring):
 
437
            assert(ids is None or isinstance(ids, basestring))
388
438
            files = [files]
389
439
            if ids is not None:
390
440
                ids = [ids]
421
471
                    file_id = gen_file_id(f)
422
472
                inv.add_path(f, kind=kind, file_id=file_id)
423
473
 
424
 
                if verbose:
425
 
                    show_status('A', kind, quotefn(f))
426
 
 
427
474
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
428
475
 
429
476
            self._write_inventory(inv)
435
482
        """Print `file` to stdout."""
436
483
        self.lock_read()
437
484
        try:
438
 
            tree = self.revision_tree(self.lookup_revision(revno))
 
485
            tree = self.revision_tree(self.get_rev_id(revno))
439
486
            # use inventory as it was in that revision
440
487
            file_id = tree.inventory.path2id(file)
441
488
            if not file_id:
442
 
                raise BzrError("%r is not present in revision %d" % (file, revno))
 
489
                raise BzrError("%r is not present in revision %s" % (file, revno))
443
490
            tree.print_file(file_id)
444
491
        finally:
445
492
            self.unlock()
461
508
        """
462
509
        ## TODO: Normalize names
463
510
        ## TODO: Remove nested loops; better scalability
464
 
        if isinstance(files, types.StringTypes):
 
511
        if isinstance(files, basestring):
465
512
            files = [files]
466
513
 
467
514
        self.lock_write()
492
539
 
493
540
    # FIXME: this doesn't need to be a branch method
494
541
    def set_inventory(self, new_inventory_list):
495
 
        inv = Inventory()
 
542
        from bzrlib.inventory import Inventory, InventoryEntry
 
543
        inv = Inventory(self.get_root_id())
496
544
        for path, file_id, parent, kind in new_inventory_list:
497
545
            name = os.path.basename(path)
498
546
            if name == "":
520
568
        return self.working_tree().unknowns()
521
569
 
522
570
 
523
 
    def append_revision(self, revision_id):
524
 
        mutter("add {%s} to revision-history" % revision_id)
 
571
    def append_revision(self, *revision_ids):
 
572
        from bzrlib.atomicfile import AtomicFile
 
573
 
 
574
        for revision_id in revision_ids:
 
575
            mutter("add {%s} to revision-history" % revision_id)
 
576
 
525
577
        rev_history = self.revision_history()
526
 
 
527
 
        tmprhname = self.controlfilename('revision-history.tmp')
528
 
        rhname = self.controlfilename('revision-history')
529
 
        
530
 
        f = file(tmprhname, 'wt')
531
 
        rev_history.append(revision_id)
532
 
        f.write('\n'.join(rev_history))
533
 
        f.write('\n')
534
 
        f.close()
535
 
 
536
 
        if sys.platform == 'win32':
537
 
            os.remove(rhname)
538
 
        os.rename(tmprhname, rhname)
539
 
        
 
578
        rev_history.extend(revision_ids)
 
579
 
 
580
        f = AtomicFile(self.controlfilename('revision-history'))
 
581
        try:
 
582
            for rev_id in rev_history:
 
583
                print >>f, rev_id
 
584
            f.commit()
 
585
        finally:
 
586
            f.close()
 
587
 
 
588
 
 
589
    def get_revision_xml_file(self, revision_id):
 
590
        """Return XML file object for revision object."""
 
591
        if not revision_id or not isinstance(revision_id, basestring):
 
592
            raise InvalidRevisionId(revision_id)
 
593
 
 
594
        self.lock_read()
 
595
        try:
 
596
            try:
 
597
                return self.revision_store[revision_id]
 
598
            except (IndexError, KeyError):
 
599
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
600
        finally:
 
601
            self.unlock()
 
602
 
 
603
 
 
604
    #deprecated
 
605
    get_revision_xml = get_revision_xml_file
540
606
 
541
607
 
542
608
    def get_revision(self, revision_id):
543
609
        """Return the Revision object for a named revision"""
544
 
        if not revision_id or not isinstance(revision_id, basestring):
545
 
            raise ValueError('invalid revision-id: %r' % revision_id)
546
 
        r = Revision.read_xml(self.revision_store[revision_id])
 
610
        xml_file = self.get_revision_xml_file(revision_id)
 
611
 
 
612
        try:
 
613
            r = bzrlib.xml.serializer_v4.read_revision(xml_file)
 
614
        except SyntaxError, e:
 
615
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
 
616
                                         [revision_id,
 
617
                                          str(e)])
 
618
            
547
619
        assert r.revision_id == revision_id
548
620
        return r
549
621
 
 
622
 
 
623
    def get_revision_delta(self, revno):
 
624
        """Return the delta for one revision.
 
625
 
 
626
        The delta is relative to its mainline predecessor, or the
 
627
        empty tree for revision 1.
 
628
        """
 
629
        assert isinstance(revno, int)
 
630
        rh = self.revision_history()
 
631
        if not (1 <= revno <= len(rh)):
 
632
            raise InvalidRevisionNumber(revno)
 
633
 
 
634
        # revno is 1-based; list is 0-based
 
635
 
 
636
        new_tree = self.revision_tree(rh[revno-1])
 
637
        if revno == 1:
 
638
            old_tree = EmptyTree()
 
639
        else:
 
640
            old_tree = self.revision_tree(rh[revno-2])
 
641
 
 
642
        return compare_trees(old_tree, new_tree)
 
643
 
 
644
        
 
645
 
550
646
    def get_revision_sha1(self, revision_id):
551
647
        """Hash the stored value of a revision, and return it."""
552
648
        # In the future, revision entries will be signed. At that
555
651
        # the revision, (add signatures/remove signatures) and still
556
652
        # have all hash pointers stay consistent.
557
653
        # But for now, just hash the contents.
558
 
        return sha_file(self.revision_store[revision_id])
 
654
        return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
559
655
 
560
656
 
561
657
    def get_inventory(self, inventory_id):
564
660
        TODO: Perhaps for this and similar methods, take a revision
565
661
               parameter which can be either an integer revno or a
566
662
               string hash."""
567
 
        i = Inventory.read_xml(self.inventory_store[inventory_id])
568
 
        return i
 
663
        from bzrlib.inventory import Inventory
 
664
 
 
665
        f = self.get_inventory_xml_file(inventory_id)
 
666
        return bzrlib.xml.serializer_v4.read_inventory(f)
 
667
 
 
668
 
 
669
    def get_inventory_xml(self, inventory_id):
 
670
        """Get inventory XML as a file object."""
 
671
        return self.inventory_store[inventory_id]
 
672
 
 
673
    get_inventory_xml_file = get_inventory_xml
 
674
            
569
675
 
570
676
    def get_inventory_sha1(self, inventory_id):
571
677
        """Return the sha1 hash of the inventory entry
572
678
        """
573
 
        return sha_file(self.inventory_store[inventory_id])
 
679
        return sha_file(self.get_inventory_xml(inventory_id))
574
680
 
575
681
 
576
682
    def get_revision_inventory(self, revision_id):
577
683
        """Return inventory of a past revision."""
 
684
        # bzr 0.0.6 imposes the constraint that the inventory_id
 
685
        # must be the same as its revision, so this is trivial.
578
686
        if revision_id == None:
579
 
            return Inventory()
 
687
            from bzrlib.inventory import Inventory
 
688
            return Inventory(self.get_root_id())
580
689
        else:
581
 
            return self.get_inventory(self.get_revision(revision_id).inventory_id)
 
690
            return self.get_inventory(revision_id)
582
691
 
583
692
 
584
693
    def revision_history(self):
597
706
 
598
707
    def common_ancestor(self, other, self_revno=None, other_revno=None):
599
708
        """
600
 
        >>> import commit
 
709
        >>> from bzrlib.commit import commit
601
710
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
602
711
        >>> sb.common_ancestor(sb) == (None, None)
603
712
        True
604
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
713
        >>> commit(sb, "Committing first revision", verbose=False)
605
714
        >>> sb.common_ancestor(sb)[0]
606
715
        1
607
716
        >>> clone = sb.clone()
608
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
717
        >>> commit(sb, "Committing second revision", verbose=False)
609
718
        >>> sb.common_ancestor(sb)[0]
610
719
        2
611
720
        >>> sb.common_ancestor(clone)[0]
612
721
        1
613
 
        >>> commit.commit(clone, "Committing divergent second revision", 
 
722
        >>> commit(clone, "Committing divergent second revision", 
614
723
        ...               verbose=False)
615
724
        >>> sb.common_ancestor(clone)[0]
616
725
        1
639
748
                return r+1, my_history[r]
640
749
        return None, None
641
750
 
642
 
    def enum_history(self, direction):
643
 
        """Return (revno, revision_id) for history of branch.
644
 
 
645
 
        direction
646
 
            'forward' is from earliest to latest
647
 
            'reverse' is from latest to earliest
648
 
        """
649
 
        rh = self.revision_history()
650
 
        if direction == 'forward':
651
 
            i = 1
652
 
            for rid in rh:
653
 
                yield i, rid
654
 
                i += 1
655
 
        elif direction == 'reverse':
656
 
            i = len(rh)
657
 
            while i > 0:
658
 
                yield i, rh[i-1]
659
 
                i -= 1
660
 
        else:
661
 
            raise ValueError('invalid history direction', direction)
662
 
 
663
751
 
664
752
    def revno(self):
665
753
        """Return current revision number for this branch.
680
768
            return None
681
769
 
682
770
 
683
 
    def missing_revisions(self, other, stop_revision=None):
 
771
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
684
772
        """
685
773
        If self and other have not diverged, return a list of the revisions
686
774
        present in other, but missing from self.
719
807
        if stop_revision is None:
720
808
            stop_revision = other_len
721
809
        elif stop_revision > other_len:
722
 
            raise NoSuchRevision(self, stop_revision)
 
810
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
723
811
        
724
812
        return other_history[self_len:stop_revision]
725
813
 
726
814
 
727
815
    def update_revisions(self, other, stop_revision=None):
728
816
        """Pull in all new revisions from other branch.
729
 
        
730
 
        >>> from bzrlib.commit import commit
731
 
        >>> bzrlib.trace.silent = True
732
 
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
733
 
        >>> br1.add('foo')
734
 
        >>> br1.add('bar')
735
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
736
 
        >>> br2 = ScratchBranch()
737
 
        >>> br2.update_revisions(br1)
738
 
        Added 2 texts.
739
 
        Added 1 inventories.
740
 
        Added 1 revisions.
741
 
        >>> br2.revision_history()
742
 
        [u'REVISION-ID-1']
743
 
        >>> br2.update_revisions(br1)
744
 
        Added 0 texts.
745
 
        Added 0 inventories.
746
 
        Added 0 revisions.
747
 
        >>> br1.text_store.total_size() == br2.text_store.total_size()
748
 
        True
749
817
        """
750
 
        from bzrlib.progress import ProgressBar
751
 
 
752
 
        pb = ProgressBar()
753
 
 
 
818
        from bzrlib.fetch import greedy_fetch
 
819
        from bzrlib.revision import get_intervening_revisions
 
820
 
 
821
        pb = bzrlib.ui.ui_factory.progress_bar()
754
822
        pb.update('comparing histories')
755
 
        revision_ids = self.missing_revisions(other, stop_revision)
 
823
        if stop_revision is None:
 
824
            other_revision = other.last_patch()
 
825
        else:
 
826
            other_revision = other.get_rev_id(stop_revision)
 
827
        count = greedy_fetch(self, other, other_revision, pb)[0]
 
828
        try:
 
829
            revision_ids = self.missing_revisions(other, stop_revision)
 
830
        except DivergedBranches, e:
 
831
            try:
 
832
                revision_ids = get_intervening_revisions(self.last_patch(), 
 
833
                                                         other_revision, self)
 
834
                assert self.last_patch() not in revision_ids
 
835
            except bzrlib.errors.NotAncestor:
 
836
                raise e
 
837
 
 
838
        self.append_revision(*revision_ids)
 
839
        pb.clear()
 
840
 
 
841
    def install_revisions(self, other, revision_ids, pb):
 
842
        if hasattr(other.revision_store, "prefetch"):
 
843
            other.revision_store.prefetch(revision_ids)
 
844
        if hasattr(other.inventory_store, "prefetch"):
 
845
            inventory_ids = []
 
846
            for rev_id in revision_ids:
 
847
                try:
 
848
                    revision = other.get_revision(rev_id).inventory_id
 
849
                    inventory_ids.append(revision)
 
850
                except bzrlib.errors.NoSuchRevision:
 
851
                    pass
 
852
            other.inventory_store.prefetch(inventory_ids)
 
853
 
 
854
        if pb is None:
 
855
            pb = bzrlib.ui.ui_factory.progress_bar()
 
856
                
756
857
        revisions = []
757
 
        needed_texts = sets.Set()
 
858
        needed_texts = set()
758
859
        i = 0
759
 
        for rev_id in revision_ids:
760
 
            i += 1
761
 
            pb.update('fetching revision', i, len(revision_ids))
762
 
            rev = other.get_revision(rev_id)
 
860
 
 
861
        failures = set()
 
862
        for i, rev_id in enumerate(revision_ids):
 
863
            pb.update('fetching revision', i+1, len(revision_ids))
 
864
            try:
 
865
                rev = other.get_revision(rev_id)
 
866
            except bzrlib.errors.NoSuchRevision:
 
867
                failures.add(rev_id)
 
868
                continue
 
869
 
763
870
            revisions.append(rev)
764
871
            inv = other.get_inventory(str(rev.inventory_id))
765
872
            for key, entry in inv.iter_entries():
770
877
 
771
878
        pb.clear()
772
879
                    
773
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
774
 
        print "Added %d texts." % count 
 
880
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
 
881
                                                    needed_texts)
 
882
        #print "Added %d texts." % count 
775
883
        inventory_ids = [ f.inventory_id for f in revisions ]
776
 
        count = self.inventory_store.copy_multi(other.inventory_store, 
777
 
                                                inventory_ids)
778
 
        print "Added %d inventories." % count 
 
884
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
 
885
                                                         inventory_ids)
 
886
        #print "Added %d inventories." % count 
779
887
        revision_ids = [ f.revision_id for f in revisions]
780
 
        count = self.revision_store.copy_multi(other.revision_store, 
781
 
                                               revision_ids)
782
 
        for revision_id in revision_ids:
783
 
            self.append_revision(revision_id)
784
 
        print "Added %d revisions." % count
785
 
                    
786
 
        
 
888
 
 
889
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
 
890
                                                          revision_ids,
 
891
                                                          permit_failure=True)
 
892
        assert len(cp_fail) == 0 
 
893
        return count, failures
 
894
       
 
895
 
787
896
    def commit(self, *args, **kw):
788
 
        """Deprecated"""
789
897
        from bzrlib.commit import commit
790
898
        commit(self, *args, **kw)
791
899
        
 
900
    def revision_id_to_revno(self, revision_id):
 
901
        """Given a revision id, return its revno"""
 
902
        history = self.revision_history()
 
903
        try:
 
904
            return history.index(revision_id) + 1
 
905
        except ValueError:
 
906
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
792
907
 
793
 
    def lookup_revision(self, revno):
794
 
        """Return revision hash for revision number."""
 
908
    def get_rev_id(self, revno, history=None):
 
909
        """Find the revision id of the specified revno."""
795
910
        if revno == 0:
796
911
            return None
797
 
 
798
 
        try:
799
 
            # list is 0-based; revisions are 1-based
800
 
            return self.revision_history()[revno-1]
801
 
        except IndexError:
802
 
            raise BzrError("no such revision %s" % revno)
 
912
        if history is None:
 
913
            history = self.revision_history()
 
914
        elif revno <= 0 or revno > len(history):
 
915
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
916
        return history[revno - 1]
803
917
 
804
918
 
805
919
    def revision_tree(self, revision_id):
818
932
 
819
933
    def working_tree(self):
820
934
        """Return a `Tree` for the working copy."""
821
 
        from workingtree import WorkingTree
 
935
        from bzrlib.workingtree import WorkingTree
822
936
        return WorkingTree(self.base, self.read_working_inventory())
823
937
 
824
938
 
870
984
 
871
985
            inv.rename(file_id, to_dir_id, to_tail)
872
986
 
873
 
            print "%s => %s" % (from_rel, to_rel)
874
 
 
875
987
            from_abs = self.abspath(from_rel)
876
988
            to_abs = self.abspath(to_rel)
877
989
            try:
878
 
                os.rename(from_abs, to_abs)
 
990
                rename(from_abs, to_abs)
879
991
            except OSError, e:
880
992
                raise BzrError("failed to rename %r to %r: %s"
881
993
                        % (from_abs, to_abs, e[1]),
896
1008
 
897
1009
        Note that to_name is only the last component of the new name;
898
1010
        this doesn't change the directory.
 
1011
 
 
1012
        This returns a list of (from_path, to_path) pairs for each
 
1013
        entry that is moved.
899
1014
        """
 
1015
        result = []
900
1016
        self.lock_write()
901
1017
        try:
902
1018
            ## TODO: Option to move IDs only
937
1053
            for f in from_paths:
938
1054
                name_tail = splitpath(f)[-1]
939
1055
                dest_path = appendpath(to_name, name_tail)
940
 
                print "%s => %s" % (f, dest_path)
 
1056
                result.append((f, dest_path))
941
1057
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
942
1058
                try:
943
 
                    os.rename(self.abspath(f), self.abspath(dest_path))
 
1059
                    rename(self.abspath(f), self.abspath(dest_path))
944
1060
                except OSError, e:
945
1061
                    raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
946
1062
                            ["rename rolled back"])
949
1065
        finally:
950
1066
            self.unlock()
951
1067
 
952
 
 
953
 
 
954
 
class ScratchBranch(Branch):
 
1068
        return result
 
1069
 
 
1070
 
 
1071
    def revert(self, filenames, old_tree=None, backups=True):
 
1072
        """Restore selected files to the versions from a previous tree.
 
1073
 
 
1074
        backups
 
1075
            If true (default) backups are made of files before
 
1076
            they're renamed.
 
1077
        """
 
1078
        from bzrlib.errors import NotVersionedError, BzrError
 
1079
        from bzrlib.atomicfile import AtomicFile
 
1080
        from bzrlib.osutils import backup_file
 
1081
        
 
1082
        inv = self.read_working_inventory()
 
1083
        if old_tree is None:
 
1084
            old_tree = self.basis_tree()
 
1085
        old_inv = old_tree.inventory
 
1086
 
 
1087
        nids = []
 
1088
        for fn in filenames:
 
1089
            file_id = inv.path2id(fn)
 
1090
            if not file_id:
 
1091
                raise NotVersionedError("not a versioned file", fn)
 
1092
            if not old_inv.has_id(file_id):
 
1093
                raise BzrError("file not present in old tree", fn, file_id)
 
1094
            nids.append((fn, file_id))
 
1095
            
 
1096
        # TODO: Rename back if it was previously at a different location
 
1097
 
 
1098
        # TODO: If given a directory, restore the entire contents from
 
1099
        # the previous version.
 
1100
 
 
1101
        # TODO: Make a backup to a temporary file.
 
1102
 
 
1103
        # TODO: If the file previously didn't exist, delete it?
 
1104
        for fn, file_id in nids:
 
1105
            backup_file(fn)
 
1106
            
 
1107
            f = AtomicFile(fn, 'wb')
 
1108
            try:
 
1109
                f.write(old_tree.get_file(file_id).read())
 
1110
                f.commit()
 
1111
            finally:
 
1112
                f.close()
 
1113
 
 
1114
 
 
1115
    def pending_merges(self):
 
1116
        """Return a list of pending merges.
 
1117
 
 
1118
        These are revisions that have been merged into the working
 
1119
        directory but not yet committed.
 
1120
        """
 
1121
        cfn = self.controlfilename('pending-merges')
 
1122
        if not os.path.exists(cfn):
 
1123
            return []
 
1124
        p = []
 
1125
        for l in self.controlfile('pending-merges', 'r').readlines():
 
1126
            p.append(l.rstrip('\n'))
 
1127
        return p
 
1128
 
 
1129
 
 
1130
    def add_pending_merge(self, revision_id):
 
1131
        from bzrlib.revision import validate_revision_id
 
1132
 
 
1133
        validate_revision_id(revision_id)
 
1134
 
 
1135
        p = self.pending_merges()
 
1136
        if revision_id in p:
 
1137
            return
 
1138
        p.append(revision_id)
 
1139
        self.set_pending_merges(p)
 
1140
 
 
1141
 
 
1142
    def set_pending_merges(self, rev_list):
 
1143
        from bzrlib.atomicfile import AtomicFile
 
1144
        self.lock_write()
 
1145
        try:
 
1146
            f = AtomicFile(self.controlfilename('pending-merges'))
 
1147
            try:
 
1148
                for l in rev_list:
 
1149
                    print >>f, l
 
1150
                f.commit()
 
1151
            finally:
 
1152
                f.close()
 
1153
        finally:
 
1154
            self.unlock()
 
1155
 
 
1156
 
 
1157
    def get_parent(self):
 
1158
        """Return the parent location of the branch.
 
1159
 
 
1160
        This is the default location for push/pull/missing.  The usual
 
1161
        pattern is that the user can override it by specifying a
 
1162
        location.
 
1163
        """
 
1164
        import errno
 
1165
        _locs = ['parent', 'pull', 'x-pull']
 
1166
        for l in _locs:
 
1167
            try:
 
1168
                return self.controlfile(l, 'r').read().strip('\n')
 
1169
            except IOError, e:
 
1170
                if e.errno != errno.ENOENT:
 
1171
                    raise
 
1172
        return None
 
1173
 
 
1174
 
 
1175
    def set_parent(self, url):
 
1176
        # TODO: Maybe delete old location files?
 
1177
        from bzrlib.atomicfile import AtomicFile
 
1178
        self.lock_write()
 
1179
        try:
 
1180
            f = AtomicFile(self.controlfilename('parent'))
 
1181
            try:
 
1182
                f.write(url + '\n')
 
1183
                f.commit()
 
1184
            finally:
 
1185
                f.close()
 
1186
        finally:
 
1187
            self.unlock()
 
1188
 
 
1189
    def check_revno(self, revno):
 
1190
        """\
 
1191
        Check whether a revno corresponds to any revision.
 
1192
        Zero (the NULL revision) is considered valid.
 
1193
        """
 
1194
        if revno != 0:
 
1195
            self.check_real_revno(revno)
 
1196
            
 
1197
    def check_real_revno(self, revno):
 
1198
        """\
 
1199
        Check whether a revno corresponds to a real revision.
 
1200
        Zero (the NULL revision) is considered invalid
 
1201
        """
 
1202
        if revno < 1 or revno > self.revno():
 
1203
            raise InvalidRevisionNumber(revno)
 
1204
        
 
1205
        
 
1206
        
 
1207
 
 
1208
 
 
1209
class ScratchBranch(LocalBranch):
955
1210
    """Special test class: a branch that cleans up after itself.
956
1211
 
957
1212
    >>> b = ScratchBranch()
969
1224
 
970
1225
        If any files are listed, they are created in the working copy.
971
1226
        """
 
1227
        from tempfile import mkdtemp
972
1228
        init = False
973
1229
        if base is None:
974
 
            base = tempfile.mkdtemp()
 
1230
            base = mkdtemp()
975
1231
            init = True
976
 
        Branch.__init__(self, base, init=init)
 
1232
        LocalBranch.__init__(self, base, init=init)
977
1233
        for d in dirs:
978
1234
            os.mkdir(self.abspath(d))
979
1235
            
985
1241
        """
986
1242
        >>> orig = ScratchBranch(files=["file1", "file2"])
987
1243
        >>> clone = orig.clone()
988
 
        >>> os.path.samefile(orig.base, clone.base)
 
1244
        >>> if os.name != 'nt':
 
1245
        ...   os.path.samefile(orig.base, clone.base)
 
1246
        ... else:
 
1247
        ...   orig.base == clone.base
 
1248
        ...
989
1249
        False
990
1250
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
991
1251
        True
992
1252
        """
993
 
        base = tempfile.mkdtemp()
 
1253
        from shutil import copytree
 
1254
        from tempfile import mkdtemp
 
1255
        base = mkdtemp()
994
1256
        os.rmdir(base)
995
 
        shutil.copytree(self.base, base, symlinks=True)
 
1257
        copytree(self.base, base, symlinks=True)
996
1258
        return ScratchBranch(base=base)
 
1259
 
 
1260
 
997
1261
        
998
1262
    def __del__(self):
999
1263
        self.destroy()
1000
1264
 
1001
1265
    def destroy(self):
1002
1266
        """Destroy the test branch, removing the scratch directory."""
 
1267
        from shutil import rmtree
1003
1268
        try:
1004
1269
            if self.base:
1005
1270
                mutter("delete ScratchBranch %s" % self.base)
1006
 
                shutil.rmtree(self.base)
 
1271
                rmtree(self.base)
1007
1272
        except OSError, e:
1008
1273
            # Work around for shutil.rmtree failing on Windows when
1009
1274
            # readonly files are encountered
1011
1276
            for root, dirs, files in os.walk(self.base, topdown=False):
1012
1277
                for name in files:
1013
1278
                    os.chmod(os.path.join(root, name), 0700)
1014
 
            shutil.rmtree(self.base)
 
1279
            rmtree(self.base)
1015
1280
        self.base = None
1016
1281
 
1017
1282
    
1042
1307
    cope with just randomness because running uuidgen every time is
1043
1308
    slow."""
1044
1309
    import re
 
1310
    from binascii import hexlify
 
1311
    from time import time
1045
1312
 
1046
1313
    # get last component
1047
1314
    idx = name.rfind('/')
1059
1326
    name = re.sub(r'[^\w.]', '', name)
1060
1327
 
1061
1328
    s = hexlify(rand_bytes(8))
1062
 
    return '-'.join((name, compact_date(time.time()), s))
 
1329
    return '-'.join((name, compact_date(time()), s))
 
1330
 
 
1331
 
 
1332
def gen_root_id():
 
1333
    """Return a new tree-root file id."""
 
1334
    return gen_file_id('TREE_ROOT')
 
1335
 
 
1336
 
 
1337
def copy_branch(branch_from, to_location, revno=None):
 
1338
    """Copy branch_from into the existing directory to_location.
 
1339
 
 
1340
    revision
 
1341
        If not None, only revisions up to this point will be copied.
 
1342
        The head of the new branch will be that revision.
 
1343
 
 
1344
    to_location
 
1345
        The name of a local directory that exists but is empty.
 
1346
    """
 
1347
    from bzrlib.merge import merge
 
1348
 
 
1349
    assert isinstance(branch_from, Branch)
 
1350
    assert isinstance(to_location, basestring)
 
1351
    
 
1352
    br_to = Branch.initialize(to_location)
 
1353
    br_to.set_root_id(branch_from.get_root_id())
 
1354
    if revno is None:
 
1355
        revno = branch_from.revno()
 
1356
    br_to.update_revisions(branch_from, stop_revision=revno)
 
1357
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1358
          check_clean=False, ignore_zero=True)
 
1359
    br_to.set_parent(branch_from.base)
 
1360
    return br_to