~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-09-06 02:26:28 UTC
  • Revision ID: mbp@sourcefrog.net-20050906022628-66d65f0feb4a9e80
- implement version 5 xml storage, and tests

  This stores files identified by the version that introduced the 
  text, and the version that introduced the name.  Entry kinds are
  given by the xml tag not an explicit kind field.

Show diffs side-by-side

added added

removed removed

Lines of Context:
28
28
import bzrlib.errors
29
29
from bzrlib.textui import show_status
30
30
from bzrlib.revision import Revision
31
 
from bzrlib.xml import unpack_xml
32
31
from bzrlib.delta import compare_trees
33
32
from bzrlib.tree import EmptyTree, RevisionTree
 
33
import bzrlib.xml
34
34
import bzrlib.ui
35
35
 
36
36
 
219
219
            self._lock.unlock()
220
220
 
221
221
 
222
 
 
223
222
    def lock_write(self):
224
223
        if self._lock_mode:
225
224
            if self._lock_mode != 'w':
235
234
            self._lock_count = 1
236
235
 
237
236
 
238
 
 
239
237
    def lock_read(self):
240
238
        if self._lock_mode:
241
239
            assert self._lock_mode in ('r', 'w'), \
248
246
            self._lock_mode = 'r'
249
247
            self._lock_count = 1
250
248
                        
251
 
 
252
 
            
253
249
    def unlock(self):
254
250
        if not self._lock_mode:
255
251
            from errors import LockError
262
258
            self._lock = None
263
259
            self._lock_mode = self._lock_count = None
264
260
 
265
 
 
266
261
    def abspath(self, name):
267
262
        """Return absolute filename for something in the branch"""
268
263
        return os.path.join(self.base, name)
269
264
 
270
 
 
271
265
    def relpath(self, path):
272
266
        """Return path relative to this branch of something inside it.
273
267
 
274
268
        Raises an error if path is not in this branch."""
275
269
        return _relpath(self.base, path)
276
270
 
277
 
 
278
271
    def controlfilename(self, file_or_path):
279
272
        """Return location relative to branch."""
280
273
        if isinstance(file_or_path, basestring):
307
300
        else:
308
301
            raise BzrError("invalid controlfile mode %r" % mode)
309
302
 
310
 
 
311
 
 
312
303
    def _make_control(self):
313
304
        from bzrlib.inventory import Inventory
314
 
        from bzrlib.xml import pack_xml
315
305
        
316
306
        os.mkdir(self.controlfilename([]))
317
307
        self.controlfile('README', 'w').write(
330
320
        # if we want per-tree root ids then this is the place to set
331
321
        # them; they're not needed for now and so ommitted for
332
322
        # simplicity.
333
 
        pack_xml(Inventory(), self.controlfile('inventory','w'))
 
323
        f = self.controlfile('inventory','w')
 
324
        bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
334
325
 
335
326
 
336
327
    def _check_format(self):
371
362
    def read_working_inventory(self):
372
363
        """Read the working inventory."""
373
364
        from bzrlib.inventory import Inventory
374
 
        from bzrlib.xml import unpack_xml
375
 
        from time import time
376
 
        before = time()
377
365
        self.lock_read()
378
366
        try:
379
367
            # ElementTree does its own conversion from UTF-8, so open in
380
368
            # binary.
381
 
            inv = unpack_xml(Inventory,
382
 
                             self.controlfile('inventory', 'rb'))
383
 
            mutter("loaded inventory of %d items in %f"
384
 
                   % (len(inv), time() - before))
385
 
            return inv
 
369
            f = self.controlfile('inventory', 'rb')
 
370
            return bzrlib.xml.serializer_v4.read_inventory(f)
386
371
        finally:
387
372
            self.unlock()
388
373
            
394
379
        will be committed to the next revision.
395
380
        """
396
381
        from bzrlib.atomicfile import AtomicFile
397
 
        from bzrlib.xml import pack_xml
398
382
        
399
383
        self.lock_write()
400
384
        try:
401
385
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
402
386
            try:
403
 
                pack_xml(inv, f)
 
387
                bzrlib.xml.serializer_v4.write_inventory(inv, f)
404
388
                f.commit()
405
389
            finally:
406
390
                f.close()
414
398
                         """Inventory for the working copy.""")
415
399
 
416
400
 
417
 
    def add(self, files, verbose=False, ids=None):
 
401
    def add(self, files, ids=None):
418
402
        """Make files versioned.
419
403
 
420
 
        Note that the command line normally calls smart_add instead.
 
404
        Note that the command line normally calls smart_add instead,
 
405
        which can automatically recurse.
421
406
 
422
407
        This puts the files in the Added state, so that they will be
423
408
        recorded by the next commit.
433
418
        TODO: Perhaps have an option to add the ids even if the files do
434
419
              not (yet) exist.
435
420
 
436
 
        TODO: Perhaps return the ids of the files?  But then again it
437
 
              is easy to retrieve them if they're needed.
438
 
 
439
 
        TODO: Adding a directory should optionally recurse down and
440
 
              add all non-ignored children.  Perhaps do that in a
441
 
              higher-level method.
 
421
        TODO: Perhaps yield the ids and paths as they're added.
442
422
        """
443
423
        # TODO: Re-adding a file that is removed in the working copy
444
424
        # should probably put it back with the previous ID.
480
460
                    file_id = gen_file_id(f)
481
461
                inv.add_path(f, kind=kind, file_id=file_id)
482
462
 
483
 
                if verbose:
484
 
                    print 'added', quotefn(f)
485
 
 
486
463
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
487
464
 
488
465
            self._write_inventory(inv)
598
575
            f.close()
599
576
 
600
577
 
601
 
    def get_revision_xml(self, revision_id):
 
578
    def get_revision_xml_file(self, revision_id):
602
579
        """Return XML file object for revision object."""
603
580
        if not revision_id or not isinstance(revision_id, basestring):
604
581
            raise InvalidRevisionId(revision_id)
613
590
            self.unlock()
614
591
 
615
592
 
 
593
    #deprecated
 
594
    get_revision_xml = get_revision_xml_file
 
595
 
 
596
 
616
597
    def get_revision(self, revision_id):
617
598
        """Return the Revision object for a named revision"""
618
 
        xml_file = self.get_revision_xml(revision_id)
 
599
        xml_file = self.get_revision_xml_file(revision_id)
619
600
 
620
601
        try:
621
 
            r = unpack_xml(Revision, xml_file)
 
602
            r = bzrlib.xml.serializer_v4.read_revision(xml_file)
622
603
        except SyntaxError, e:
623
604
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
624
605
                                         [revision_id,
669
650
               parameter which can be either an integer revno or a
670
651
               string hash."""
671
652
        from bzrlib.inventory import Inventory
672
 
        from bzrlib.xml import unpack_xml
673
653
 
674
 
        return unpack_xml(Inventory, self.get_inventory_xml(inventory_id))
 
654
        f = self.get_inventory_xml_file(inventory_id)
 
655
        return bzrlib.xml.serializer_v4.read_inventory(f)
675
656
 
676
657
 
677
658
    def get_inventory_xml(self, inventory_id):
678
659
        """Get inventory XML as a file object."""
679
660
        return self.inventory_store[inventory_id]
 
661
 
 
662
    get_inventory_xml_file = get_inventory_xml
680
663
            
681
664
 
682
665
    def get_inventory_sha1(self, inventory_id):
836
819
        ## note("Added %d revisions." % count)
837
820
        pb.clear()
838
821
 
839
 
        
840
 
        
841
822
    def install_revisions(self, other, revision_ids, pb):
842
823
        if hasattr(other.revision_store, "prefetch"):
843
824
            other.revision_store.prefetch(revision_ids)
895
876
 
896
877
    def lookup_revision(self, revision):
897
878
        """Return the revision identifier for a given revision information."""
898
 
        revno, info = self.get_revision_info(revision)
 
879
        revno, info = self._get_revision_info(revision)
899
880
        return info
900
881
 
901
882
 
916
897
        revision can also be a string, in which case it is parsed for something like
917
898
            'date:' or 'revid:' etc.
918
899
        """
 
900
        revno, rev_id = self._get_revision_info(revision)
 
901
        if revno is None:
 
902
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
903
        return revno, rev_id
 
904
 
 
905
    def get_rev_id(self, revno, history=None):
 
906
        """Find the revision id of the specified revno."""
 
907
        if revno == 0:
 
908
            return None
 
909
        if history is None:
 
910
            history = self.revision_history()
 
911
        elif revno <= 0 or revno > len(history):
 
912
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
913
        return history[revno - 1]
 
914
 
 
915
    def _get_revision_info(self, revision):
 
916
        """Return (revno, revision id) for revision specifier.
 
917
 
 
918
        revision can be an integer, in which case it is assumed to be revno
 
919
        (though this will translate negative values into positive ones)
 
920
        revision can also be a string, in which case it is parsed for something
 
921
        like 'date:' or 'revid:' etc.
 
922
 
 
923
        A revid is always returned.  If it is None, the specifier referred to
 
924
        the null revision.  If the revid does not occur in the revision
 
925
        history, revno will be None.
 
926
        """
 
927
        
919
928
        if revision is None:
920
929
            return 0, None
921
930
        revno = None
925
934
            pass
926
935
        revs = self.revision_history()
927
936
        if isinstance(revision, int):
928
 
            if revision == 0:
929
 
                return 0, None
930
 
            # Mabye we should do this first, but we don't need it if revision == 0
931
937
            if revision < 0:
932
938
                revno = len(revs) + revision + 1
933
939
            else:
934
940
                revno = revision
 
941
            rev_id = self.get_rev_id(revno, revs)
935
942
        elif isinstance(revision, basestring):
936
943
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
937
944
                if revision.startswith(prefix):
938
 
                    revno = func(self, revs, revision)
 
945
                    result = func(self, revs, revision)
 
946
                    if len(result) > 1:
 
947
                        revno, rev_id = result
 
948
                    else:
 
949
                        revno = result[0]
 
950
                        rev_id = self.get_rev_id(revno, revs)
939
951
                    break
940
952
            else:
941
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
953
                raise BzrError('No namespace registered for string: %r' %
 
954
                               revision)
 
955
        else:
 
956
            raise TypeError('Unhandled revision type %s' % revision)
942
957
 
943
 
        if revno is None or revno <= 0 or revno > len(revs):
944
 
            raise BzrError("no such revision %s" % revision)
945
 
        return revno, revs[revno-1]
 
958
        if revno is None:
 
959
            if rev_id is None:
 
960
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
961
        return revno, rev_id
946
962
 
947
963
    def _namespace_revno(self, revs, revision):
948
964
        """Lookup a revision by revision number"""
949
965
        assert revision.startswith('revno:')
950
966
        try:
951
 
            return int(revision[6:])
 
967
            return (int(revision[6:]),)
952
968
        except ValueError:
953
969
            return None
954
970
    REVISION_NAMESPACES['revno:'] = _namespace_revno
955
971
 
956
972
    def _namespace_revid(self, revs, revision):
957
973
        assert revision.startswith('revid:')
 
974
        rev_id = revision[len('revid:'):]
958
975
        try:
959
 
            return revs.index(revision[6:]) + 1
 
976
            return revs.index(rev_id) + 1, rev_id
960
977
        except ValueError:
961
 
            return None
 
978
            return None, rev_id
962
979
    REVISION_NAMESPACES['revid:'] = _namespace_revid
963
980
 
964
981
    def _namespace_last(self, revs, revision):
966
983
        try:
967
984
            offset = int(revision[5:])
968
985
        except ValueError:
969
 
            return None
 
986
            return (None,)
970
987
        else:
971
988
            if offset <= 0:
972
989
                raise BzrError('You must supply a positive value for --revision last:XXX')
973
 
            return len(revs) - offset + 1
 
990
            return (len(revs) - offset + 1,)
974
991
    REVISION_NAMESPACES['last:'] = _namespace_last
975
992
 
976
993
    def _namespace_tag(self, revs, revision):
1051
1068
                # TODO: Handle timezone.
1052
1069
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1053
1070
                if first >= dt and (last is None or dt >= last):
1054
 
                    return i+1
 
1071
                    return (i+1,)
1055
1072
        else:
1056
1073
            for i in range(len(revs)):
1057
1074
                r = self.get_revision(revs[i])
1058
1075
                # TODO: Handle timezone.
1059
1076
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1060
1077
                if first <= dt and (last is None or dt <= last):
1061
 
                    return i+1
 
1078
                    return (i+1,)
1062
1079
    REVISION_NAMESPACES['date:'] = _namespace_date
1063
1080
 
1064
1081
    def revision_tree(self, revision_id):
1129
1146
 
1130
1147
            inv.rename(file_id, to_dir_id, to_tail)
1131
1148
 
1132
 
            print "%s => %s" % (from_rel, to_rel)
1133
 
 
1134
1149
            from_abs = self.abspath(from_rel)
1135
1150
            to_abs = self.abspath(to_rel)
1136
1151
            try:
1155
1170
 
1156
1171
        Note that to_name is only the last component of the new name;
1157
1172
        this doesn't change the directory.
 
1173
 
 
1174
        This returns a list of (from_path, to_path) pairs for each
 
1175
        entry that is moved.
1158
1176
        """
 
1177
        result = []
1159
1178
        self.lock_write()
1160
1179
        try:
1161
1180
            ## TODO: Option to move IDs only
1196
1215
            for f in from_paths:
1197
1216
                name_tail = splitpath(f)[-1]
1198
1217
                dest_path = appendpath(to_name, name_tail)
1199
 
                print "%s => %s" % (f, dest_path)
 
1218
                result.append((f, dest_path))
1200
1219
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1201
1220
                try:
1202
1221
                    os.rename(self.abspath(f), self.abspath(dest_path))
1208
1227
        finally:
1209
1228
            self.unlock()
1210
1229
 
 
1230
        return result
 
1231
 
1211
1232
 
1212
1233
    def revert(self, filenames, old_tree=None, backups=True):
1213
1234
        """Restore selected files to the versions from a previous tree.
1295
1316
            self.unlock()
1296
1317
 
1297
1318
 
 
1319
    def get_parent(self):
 
1320
        """Return the parent location of the branch.
 
1321
 
 
1322
        This is the default location for push/pull/missing.  The usual
 
1323
        pattern is that the user can override it by specifying a
 
1324
        location.
 
1325
        """
 
1326
        import errno
 
1327
        _locs = ['parent', 'pull', 'x-pull']
 
1328
        for l in _locs:
 
1329
            try:
 
1330
                return self.controlfile(l, 'r').read().strip('\n')
 
1331
            except IOError, e:
 
1332
                if e.errno != errno.ENOENT:
 
1333
                    raise
 
1334
        return None
 
1335
 
 
1336
 
 
1337
    def set_parent(self, url):
 
1338
        # TODO: Maybe delete old location files?
 
1339
        from bzrlib.atomicfile import AtomicFile
 
1340
        self.lock_write()
 
1341
        try:
 
1342
            f = AtomicFile(self.controlfilename('parent'))
 
1343
            try:
 
1344
                f.write(url + '\n')
 
1345
                f.commit()
 
1346
            finally:
 
1347
                f.close()
 
1348
        finally:
 
1349
            self.unlock()
 
1350
 
 
1351
    def check_revno(self, revno):
 
1352
        """\
 
1353
        Check whether a revno corresponds to any revision.
 
1354
        Zero (the NULL revision) is considered valid.
 
1355
        """
 
1356
        if revno != 0:
 
1357
            self.check_real_revno(revno)
 
1358
            
 
1359
    def check_real_revno(self, revno):
 
1360
        """\
 
1361
        Check whether a revno corresponds to a real revision.
 
1362
        Zero (the NULL revision) is considered invalid
 
1363
        """
 
1364
        if revno < 1 or revno > self.revno():
 
1365
            raise InvalidRevisionNumber(revno)
 
1366
        
 
1367
        
 
1368
 
1298
1369
 
1299
1370
class ScratchBranch(Branch):
1300
1371
    """Special test class: a branch that cleans up after itself.
1342
1413
        os.rmdir(base)
1343
1414
        copytree(self.base, base, symlinks=True)
1344
1415
        return ScratchBranch(base=base)
 
1416
 
 
1417
 
1345
1418
        
1346
1419
    def __del__(self):
1347
1420
        self.destroy()
1417
1490
    """Return a new tree-root file id."""
1418
1491
    return gen_file_id('TREE_ROOT')
1419
1492
 
 
1493
 
 
1494
def pull_loc(branch):
 
1495
    # TODO: Should perhaps just make attribute be 'base' in
 
1496
    # RemoteBranch and Branch?
 
1497
    if hasattr(branch, "baseurl"):
 
1498
        return branch.baseurl
 
1499
    else:
 
1500
        return branch.base
 
1501
 
 
1502
 
 
1503
def copy_branch(branch_from, to_location, revision=None):
 
1504
    """Copy branch_from into the existing directory to_location.
 
1505
 
 
1506
    revision
 
1507
        If not None, only revisions up to this point will be copied.
 
1508
        The head of the new branch will be that revision.
 
1509
 
 
1510
    to_location
 
1511
        The name of a local directory that exists but is empty.
 
1512
    """
 
1513
    from bzrlib.merge import merge
 
1514
    from bzrlib.branch import Branch
 
1515
 
 
1516
    assert isinstance(branch_from, Branch)
 
1517
    assert isinstance(to_location, basestring)
 
1518
    
 
1519
    br_to = Branch(to_location, init=True)
 
1520
    br_to.set_root_id(branch_from.get_root_id())
 
1521
    if revision is None:
 
1522
        revno = branch_from.revno()
 
1523
    else:
 
1524
        revno, rev_id = branch_from.get_revision_info(revision)
 
1525
    br_to.update_revisions(branch_from, stop_revision=revno)
 
1526
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1527
          check_clean=False, ignore_zero=True)
 
1528
    
 
1529
    from_location = pull_loc(branch_from)
 
1530
    br_to.set_parent(pull_loc(branch_from))
 
1531