1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1
# Copyright (C) 2005, 2006 Canonical Ltd
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
from copy import deepcopy
17
18
from cStringIO import StringIO
19
from bzrlib.lazy_import import lazy_import
20
lazy_import(globals(), """
38
revision as _mod_revision,
43
from bzrlib.revisiontree import RevisionTree
44
from bzrlib.store.versioned import VersionedFileStore
19
from unittest import TestSuite
21
import bzrlib.bzrdir as bzrdir
22
from bzrlib.decorators import needs_read_lock, needs_write_lock
23
import bzrlib.errors as errors
24
from bzrlib.errors import InvalidRevisionId
25
import bzrlib.gpg as gpg
26
from bzrlib.graph import Graph
27
from bzrlib.inter import InterObject
28
from bzrlib.knit import KnitVersionedFile, KnitPlainFactory
29
from bzrlib.lockable_files import LockableFiles, TransportLock
30
from bzrlib.lockdir import LockDir
31
from bzrlib.osutils import safe_unicode
32
from bzrlib.revision import NULL_REVISION
33
from bzrlib.store.versioned import VersionedFileStore, WeaveStore
45
34
from bzrlib.store.text import TextStore
35
from bzrlib.symbol_versioning import *
36
from bzrlib.trace import mutter, note
37
from bzrlib.tree import RevisionTree
38
from bzrlib.tsort import topo_sort
46
39
from bzrlib.testament import Testament
50
from bzrlib.decorators import needs_read_lock, needs_write_lock
51
from bzrlib.inter import InterObject
52
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
53
from bzrlib.symbol_versioning import (
57
from bzrlib.trace import mutter, note, warning
60
# Old formats display a warning, but only once
61
_deprecation_warning_done = False
64
######################################################################
40
from bzrlib.tree import EmptyTree
42
from bzrlib.weave import WeaveFile
67
46
class Repository(object):
68
47
"""Repository holding history for one or more branches.
79
_file_ids_altered_regex = lazy_regex.lazy_compile(
80
r'file_id="(?P<file_id>[^"]+)"'
81
r'.*revision="(?P<revision_id>[^"]+)"'
85
def add_inventory(self, revision_id, inv, parents):
86
"""Add the inventory inv to the repository as revision_id.
59
def add_inventory(self, revid, inv, parents):
60
"""Add the inventory inv to the repository as revid.
88
:param parents: The revision ids of the parents that revision_id
62
:param parents: The revision ids of the parents that revid
89
63
is known to have and are in the repository already.
91
65
returns the sha1 of the serialized inventory.
93
revision_id = osutils.safe_revision_id(revision_id)
94
_mod_revision.check_not_reserved_id(revision_id)
95
assert inv.revision_id is None or inv.revision_id == revision_id, \
67
assert inv.revision_id is None or inv.revision_id == revid, \
96
68
"Mismatch between inventory revision" \
97
" id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
98
assert inv.root is not None
99
inv_text = self.serialise_inventory(inv)
100
inv_sha1 = osutils.sha_string(inv_text)
69
" id and insertion revid (%r, %r)" % (inv.revision_id, revid)
70
inv_text = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
71
inv_sha1 = bzrlib.osutils.sha_string(inv_text)
101
72
inv_vf = self.control_weaves.get_weave('inventory',
102
73
self.get_transaction())
103
self._inventory_add_lines(inv_vf, revision_id, parents,
104
osutils.split_lines(inv_text))
74
inv_vf.add_lines(revid, parents, bzrlib.osutils.split_lines(inv_text))
107
def _inventory_add_lines(self, inv_vf, revision_id, parents, lines):
109
for parent in parents:
111
final_parents.append(parent)
113
inv_vf.add_lines(revision_id, final_parents, lines)
116
def add_revision(self, revision_id, rev, inv=None, config=None):
117
"""Add rev to the revision store as revision_id.
78
def add_revision(self, rev_id, rev, inv=None, config=None):
79
"""Add rev to the revision store as rev_id.
119
:param revision_id: the revision id to use.
81
:param rev_id: the revision id to use.
120
82
:param rev: The revision object.
121
83
:param inv: The inventory for the revision. if None, it will be looked
122
84
up in the inventory storer
257
186
def get_physical_lock_status(self):
258
187
return self.control_files.get_physical_lock_status()
260
def leave_lock_in_place(self):
261
"""Tell this repository not to release the physical lock when this
264
If lock_write doesn't return a token, then this method is not supported.
266
self.control_files.leave_in_place()
268
def dont_leave_lock_in_place(self):
269
"""Tell this repository to release the physical lock when this
270
object is unlocked, even if it didn't originally acquire it.
272
If lock_write doesn't return a token, then this method is not supported.
274
self.control_files.dont_leave_in_place()
277
def gather_stats(self, revid=None, committers=None):
278
"""Gather statistics from a revision id.
280
:param revid: The revision id to gather statistics from, if None, then
281
no revision specific statistics are gathered.
282
:param committers: Optional parameter controlling whether to grab
283
a count of committers from the revision specific statistics.
284
:return: A dictionary of statistics. Currently this contains:
285
committers: The number of committers if requested.
286
firstrev: A tuple with timestamp, timezone for the penultimate left
287
most ancestor of revid, if revid is not the NULL_REVISION.
288
latestrev: A tuple with timestamp, timezone for revid, if revid is
289
not the NULL_REVISION.
290
revisions: The total revision count in the repository.
291
size: An estimate disk size of the repository in bytes.
294
if revid and committers:
295
result['committers'] = 0
296
if revid and revid != _mod_revision.NULL_REVISION:
298
all_committers = set()
299
revisions = self.get_ancestry(revid)
300
# pop the leading None
302
first_revision = None
304
# ignore the revisions in the middle - just grab first and last
305
revisions = revisions[0], revisions[-1]
306
for revision in self.get_revisions(revisions):
307
if not first_revision:
308
first_revision = revision
310
all_committers.add(revision.committer)
311
last_revision = revision
313
result['committers'] = len(all_committers)
314
result['firstrev'] = (first_revision.timestamp,
315
first_revision.timezone)
316
result['latestrev'] = (last_revision.timestamp,
317
last_revision.timezone)
319
# now gather global repository information
320
if self.bzrdir.root_transport.listable():
321
c, t = self._revision_store.total_size(self.get_transaction())
322
result['revisions'] = c
327
190
def missing_revision_ids(self, other, revision_id=None):
328
191
"""Return the revision ids that other has that this does not.
341
203
For instance, if the repository is at URL/.bzr/repository,
342
204
Repository.open(URL) -> a Repository instance.
344
control = bzrdir.BzrDir.open(base)
206
control = bzrlib.bzrdir.BzrDir.open(base)
345
207
return control.open_repository()
347
def copy_content_into(self, destination, revision_id=None):
209
def copy_content_into(self, destination, revision_id=None, basis=None):
348
210
"""Make a complete copy of the content in self into destination.
350
212
This is a destructive operation! Do not use it on existing
353
revision_id = osutils.safe_revision_id(revision_id)
354
return InterRepository.get(self, destination).copy_content(revision_id)
215
return InterRepository.get(self, destination).copy_content(revision_id, basis)
356
217
def fetch(self, source, revision_id=None, pb=None):
357
218
"""Fetch the content required to construct revision_id from source.
359
220
If revision_id is None all content is copied.
361
revision_id = osutils.safe_revision_id(revision_id)
362
inter = InterRepository.get(source, self)
364
return inter.fetch(revision_id=revision_id, pb=pb)
365
except NotImplementedError:
366
raise errors.IncompatibleRepositories(source, self)
368
def get_commit_builder(self, branch, parents, config, timestamp=None,
369
timezone=None, committer=None, revprops=None,
371
"""Obtain a CommitBuilder for this repository.
373
:param branch: Branch to commit to.
374
:param parents: Revision ids of the parents of the new revision.
375
:param config: Configuration to use.
376
:param timestamp: Optional timestamp recorded for commit.
377
:param timezone: Optional timezone for timestamp.
378
:param committer: Optional committer to set for commit.
379
:param revprops: Optional dictionary of revision properties.
380
:param revision_id: Optional revision id.
382
revision_id = osutils.safe_revision_id(revision_id)
383
return _CommitBuilder(self, parents, config, timestamp, timezone,
384
committer, revprops, revision_id)
222
return InterRepository.get(source, self).fetch(revision_id=revision_id,
386
225
def unlock(self):
387
226
self.control_files.unlock()
390
def clone(self, a_bzrdir, revision_id=None):
229
def clone(self, a_bzrdir, revision_id=None, basis=None):
391
230
"""Clone this repository into a_bzrdir using the current format.
393
232
Currently no check is made that the format of this repository and
394
233
the bzrdir format are compatible. FIXME RBC 20060201.
396
:return: The newly created destination repository.
398
# TODO: deprecate after 0.16; cloning this with all its settings is
399
# probably not very useful -- mbp 20070423
400
dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
401
self.copy_content_into(dest_repo, revision_id)
405
def sprout(self, to_bzrdir, revision_id=None):
406
"""Create a descendent repository for new development.
408
Unlike clone, this does not copy the settings of the repository.
410
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
411
dest_repo.fetch(self, revision_id=revision_id)
414
def _create_sprouting_repo(self, a_bzrdir, shared):
415
235
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
416
236
# use target default format.
417
dest_repo = a_bzrdir.create_repository()
237
result = a_bzrdir.create_repository()
238
# FIXME RBC 20060209 split out the repository type to avoid this check ?
239
elif isinstance(a_bzrdir._format,
240
(bzrlib.bzrdir.BzrDirFormat4,
241
bzrlib.bzrdir.BzrDirFormat5,
242
bzrlib.bzrdir.BzrDirFormat6)):
243
result = a_bzrdir.open_repository()
419
# Most control formats need the repository to be specifically
420
# created, but on some old all-in-one formats it's not needed
422
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
423
except errors.UninitializableFormat:
424
dest_repo = a_bzrdir.open_repository()
245
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
246
self.copy_content_into(result, revision_id, basis)
428
250
def has_revision(self, revision_id):
429
251
"""True if this repository has a copy of the revision."""
430
revision_id = osutils.safe_revision_id(revision_id)
431
252
return self._revision_store.has_revision_id(revision_id,
432
253
self.get_transaction())
549
321
revision_ids. Each altered file-ids has the exact revision_ids that
550
322
altered it listed explicitly.
552
assert self._serializer.support_altered_by_hack, \
553
("fileids_altered_by_revision_ids only supported for branches "
554
"which store inventory as unnested xml, not on %r" % self)
555
selected_revision_ids = set(osutils.safe_revision_id(r)
556
for r in revision_ids)
324
assert isinstance(self._format, (RepositoryFormat5,
327
RepositoryFormatKnit1)), \
328
"fileid_involved only supported for branches which store inventory as unnested xml"
329
selected_revision_ids = set(revision_ids)
557
330
w = self.get_inventory_weave()
560
333
# this code needs to read every new line in every inventory for the
561
334
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
562
# not present in one of those inventories is unnecessary but not
335
# not pesent in one of those inventories is unnecessary but not
563
336
# harmful because we are filtering by the revision id marker in the
564
337
# inventory lines : we only select file ids altered in one of those
565
# revisions. We don't need to see all lines in the inventory because
338
# revisions. We dont need to see all lines in the inventory because
566
339
# only those added in an inventory in rev X can contain a revision=X
568
unescape_revid_cache = {}
569
unescape_fileid_cache = {}
571
# jam 20061218 In a big fetch, this handles hundreds of thousands
572
# of lines, so it has had a lot of inlining and optimizing done.
573
# Sorry that it is a little bit messy.
574
# Move several functions to be local variables, since this is a long
576
search = self._file_ids_altered_regex.search
577
unescape = _unescape_xml
578
setdefault = result.setdefault
579
pb = ui.ui_factory.nested_progress_bar()
581
for line in w.iter_lines_added_or_present_in_versions(
582
selected_revision_ids, pb=pb):
586
# One call to match.group() returning multiple items is quite a
587
# bit faster than 2 calls to match.group() each returning 1
588
file_id, revision_id = match.group('file_id', 'revision_id')
590
# Inlining the cache lookups helps a lot when you make 170,000
591
# lines and 350k ids, versus 8.4 unique ids.
592
# Using a cache helps in 2 ways:
593
# 1) Avoids unnecessary decoding calls
594
# 2) Re-uses cached strings, which helps in future set and
596
# (2) is enough that removing encoding entirely along with
597
# the cache (so we are using plain strings) results in no
598
# performance improvement.
600
revision_id = unescape_revid_cache[revision_id]
602
unescaped = unescape(revision_id)
603
unescape_revid_cache[revision_id] = unescaped
604
revision_id = unescaped
606
if revision_id in selected_revision_ids:
608
file_id = unescape_fileid_cache[file_id]
610
unescaped = unescape(file_id)
611
unescape_fileid_cache[file_id] = unescaped
613
setdefault(file_id, set()).add(revision_id)
341
for line in w.iter_lines_added_or_present_in_versions(selected_revision_ids):
342
start = line.find('file_id="')+9
343
if start < 9: continue
344
end = line.find('"', start)
346
file_id = _unescape_xml(line[start:end])
348
start = line.find('revision="')+10
349
if start < 10: continue
350
end = line.find('"', start)
352
revision_id = _unescape_xml(line[start:end])
353
if revision_id in selected_revision_ids:
354
result.setdefault(file_id, set()).add(revision_id)
635
371
:param revision_id: The expected revision id of the inventory.
636
372
:param xml: A serialised inventory.
638
revision_id = osutils.safe_revision_id(revision_id)
639
result = self._serializer.read_inventory_from_string(xml)
640
result.root.revision = revision_id
643
def serialise_inventory(self, inv):
644
return self._serializer.write_inventory_to_string(inv)
374
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
647
377
def get_inventory_xml(self, revision_id):
648
378
"""Get inventory XML as a file object."""
649
revision_id = osutils.safe_revision_id(revision_id)
651
assert isinstance(revision_id, str), type(revision_id)
380
assert isinstance(revision_id, basestring), type(revision_id)
652
381
iw = self.get_inventory_weave()
653
382
return iw.get_text(revision_id)
654
383
except IndexError:
655
raise errors.HistoryMissing(self, 'inventory', revision_id)
384
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
658
387
def get_inventory_sha1(self, revision_id):
659
388
"""Return the sha1 hash of the inventory entry
661
# TODO: jam 20070210 Shouldn't this be deprecated / removed?
662
revision_id = osutils.safe_revision_id(revision_id)
663
390
return self.get_revision(revision_id).inventory_sha1
666
393
def get_revision_graph(self, revision_id=None):
667
394
"""Return a dictionary containing the revision graph.
669
:param revision_id: The revision_id to get a graph from. If None, then
670
the entire revision graph is returned. This is a deprecated mode of
671
operation and will be removed in the future.
672
396
:return: a dictionary of revision_id->revision_parents_list.
674
# special case NULL_REVISION
675
if revision_id == _mod_revision.NULL_REVISION:
677
revision_id = osutils.safe_revision_id(revision_id)
678
a_weave = self.get_inventory_weave()
679
all_revisions = self._eliminate_revisions_not_present(
681
entire_graph = dict([(node, a_weave.get_parents(node)) for
398
weave = self.get_inventory_weave()
399
all_revisions = self._eliminate_revisions_not_present(weave.versions())
400
entire_graph = dict([(node, weave.get_parents(node)) for
682
401
node in all_revisions])
683
402
if revision_id is None:
684
403
return entire_graph
788
478
reconciler = RepoReconciler(self, thorough=thorough)
789
479
reconciler.reconcile()
790
480
return reconciler
793
483
def revision_tree(self, revision_id):
794
484
"""Return Tree for a revision on this branch.
796
`revision_id` may be None for the empty tree revision.
486
`revision_id` may be None for the null revision, in which case
487
an `EmptyTree` is returned."""
798
488
# TODO: refactor this to use an existing revision object
799
489
# so we don't need to read it in twice.
800
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
801
return RevisionTree(self, Inventory(root_id=None),
802
_mod_revision.NULL_REVISION)
490
if revision_id is None or revision_id == NULL_REVISION:
804
revision_id = osutils.safe_revision_id(revision_id)
805
493
inv = self.get_revision_inventory(revision_id)
806
494
return RevisionTree(self, inv, revision_id)
809
def revision_trees(self, revision_ids):
810
"""Return Tree for a revision on this branch.
812
`revision_id` may not be None or 'null:'"""
813
assert None not in revision_ids
814
assert _mod_revision.NULL_REVISION not in revision_ids
815
texts = self.get_inventory_weave().get_texts(revision_ids)
816
for text, revision_id in zip(texts, revision_ids):
817
inv = self.deserialise_inventory(revision_id, text)
818
yield RevisionTree(self, inv, revision_id)
821
def get_ancestry(self, revision_id, topo_sorted=True):
497
def get_ancestry(self, revision_id):
822
498
"""Return a list of revision-ids integrated by a revision.
824
The first element of the list is always None, indicating the origin
825
revision. This might change when we have history horizons, or
826
perhaps we should have a new API.
828
500
This is topologically sorted.
830
502
if revision_id is None:
832
revision_id = osutils.safe_revision_id(revision_id)
833
504
if not self.has_revision(revision_id):
834
505
raise errors.NoSuchRevision(self, revision_id)
835
506
w = self.get_inventory_weave()
836
candidates = w.get_ancestry(revision_id, topo_sorted)
507
candidates = w.get_ancestry(revision_id)
837
508
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
911
550
@needs_write_lock
912
551
def sign_revision(self, revision_id, gpg_strategy):
913
revision_id = osutils.safe_revision_id(revision_id)
914
552
plaintext = Testament.from_revision(self, revision_id).as_short_text()
915
553
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
918
556
def has_signature_for_revision_id(self, revision_id):
919
557
"""Query for a revision signature for revision_id in the repository."""
920
revision_id = osutils.safe_revision_id(revision_id)
921
558
return self._revision_store.has_signature(revision_id,
922
559
self.get_transaction())
925
562
def get_signature_text(self, revision_id):
926
563
"""Return the text for a signature."""
927
revision_id = osutils.safe_revision_id(revision_id)
928
564
return self._revision_store.get_signature_text(revision_id,
929
565
self.get_transaction())
568
class AllInOneRepository(Repository):
569
"""Legacy support - the repository behaviour for all-in-one branches."""
571
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
572
# we reuse one control files instance.
573
dir_mode = a_bzrdir._control_files._dir_mode
574
file_mode = a_bzrdir._control_files._file_mode
576
def get_store(name, compressed=True, prefixed=False):
577
# FIXME: This approach of assuming stores are all entirely compressed
578
# or entirely uncompressed is tidy, but breaks upgrade from
579
# some existing branches where there's a mixture; we probably
580
# still want the option to look for both.
581
relpath = a_bzrdir._control_files._escape(name)
582
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
583
prefixed=prefixed, compressed=compressed,
586
#if self._transport.should_cache():
587
# cache_path = os.path.join(self.cache_root, name)
588
# os.mkdir(cache_path)
589
# store = bzrlib.store.CachedStore(store, cache_path)
592
# not broken out yet because the controlweaves|inventory_store
593
# and text_store | weave_store bits are still different.
594
if isinstance(_format, RepositoryFormat4):
595
# cannot remove these - there is still no consistent api
596
# which allows access to this old info.
597
self.inventory_store = get_store('inventory-store')
598
text_store = get_store('text-store')
599
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
932
def check(self, revision_ids):
933
"""Check consistency of all history of given revision_ids.
935
Different repository implementations should override _check().
937
:param revision_ids: A non-empty list of revision_ids whose ancestry
938
will be checked. Typically the last revision_id of a branch.
603
"""AllInOne repositories cannot be shared."""
607
def set_make_working_trees(self, new_value):
608
"""Set the policy flag for making working trees when creating branches.
610
This only applies to branches that use this repository.
612
The default is 'True'.
613
:param new_value: True to restore the default, False to disable making
941
raise ValueError("revision_ids must be non-empty in %s.check"
943
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
944
return self._check(revision_ids)
946
def _check(self, revision_ids):
947
result = check.Check(self)
951
def _warn_if_deprecated(self):
952
global _deprecation_warning_done
953
if _deprecation_warning_done:
955
_deprecation_warning_done = True
956
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
957
% (self._format, self.bzrdir.transport.base))
959
def supports_rich_root(self):
960
return self._format.rich_root_data
962
def _check_ascii_revisionid(self, revision_id, method):
963
"""Private helper for ascii-only repositories."""
964
# weave repositories refuse to store revisionids that are non-ascii.
965
if revision_id is not None:
966
# weaves require ascii revision ids.
967
if isinstance(revision_id, unicode):
969
revision_id.encode('ascii')
970
except UnicodeEncodeError:
971
raise errors.NonAsciiRevisionId(method, self)
974
revision_id.decode('ascii')
975
except UnicodeDecodeError:
976
raise errors.NonAsciiRevisionId(method, self)
980
# remove these delegates a while after bzr 0.15
981
def __make_delegated(name, from_module):
982
def _deprecated_repository_forwarder():
983
symbol_versioning.warn('%s moved to %s in bzr 0.15'
984
% (name, from_module),
987
m = __import__(from_module, globals(), locals(), [name])
989
return getattr(m, name)
990
except AttributeError:
991
raise AttributeError('module %s has no name %s'
993
globals()[name] = _deprecated_repository_forwarder
996
'AllInOneRepository',
997
'WeaveMetaDirRepository',
998
'PreSplitOutRepositoryFormat',
1000
'RepositoryFormat5',
1001
'RepositoryFormat6',
1002
'RepositoryFormat7',
1004
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
1008
'RepositoryFormatKnit',
1009
'RepositoryFormatKnit1',
1011
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
616
raise NotImplementedError(self.set_make_working_trees)
618
def make_working_trees(self):
619
"""Returns the policy for making working trees on new branches."""
1014
623
def install_revision(repository, rev, revision_tree):
1100
705
return not self.control_files._transport.has('no-working-trees')
1103
class RepositoryFormatRegistry(registry.Registry):
1104
"""Registry of RepositoryFormats.
1107
def get(self, format_string):
1108
r = registry.Registry.get(self, format_string)
708
class KnitRepository(MetaDirRepository):
709
"""Knit format repository."""
712
def all_revision_ids(self):
713
"""See Repository.all_revision_ids()."""
714
return self._revision_store.all_revision_ids(self.get_transaction())
716
def fileid_involved_between_revs(self, from_revid, to_revid):
717
"""Find file_id(s) which are involved in the changes between revisions.
719
This determines the set of revisions which are involved, and then
720
finds all file ids affected by those revisions.
722
vf = self._get_revision_vf()
723
from_set = set(vf.get_ancestry(from_revid))
724
to_set = set(vf.get_ancestry(to_revid))
725
changed = to_set.difference(from_set)
726
return self._fileid_involved_by_set(changed)
728
def fileid_involved(self, last_revid=None):
729
"""Find all file_ids modified in the ancestry of last_revid.
731
:param last_revid: If None, last_revision() will be used.
734
changed = set(self.all_revision_ids())
736
changed = set(self.get_ancestry(last_revid))
739
return self._fileid_involved_by_set(changed)
742
def get_ancestry(self, revision_id):
743
"""Return a list of revision-ids integrated by a revision.
745
This is topologically sorted.
747
if revision_id is None:
749
vf = self._get_revision_vf()
751
return [None] + vf.get_ancestry(revision_id)
752
except errors.RevisionNotPresent:
753
raise errors.NoSuchRevision(self, revision_id)
756
def get_revision(self, revision_id):
757
"""Return the Revision object for a named revision"""
758
return self.get_revision_reconcile(revision_id)
761
def get_revision_graph(self, revision_id=None):
762
"""Return a dictionary containing the revision graph.
764
:return: a dictionary of revision_id->revision_parents_list.
766
weave = self._get_revision_vf()
767
entire_graph = weave.get_graph()
768
if revision_id is None:
769
return weave.get_graph()
770
elif revision_id not in weave:
771
raise errors.NoSuchRevision(self, revision_id)
773
# add what can be reached from revision_id
775
pending = set([revision_id])
776
while len(pending) > 0:
778
result[node] = weave.get_parents(node)
779
for revision_id in result[node]:
780
if revision_id not in result:
781
pending.add(revision_id)
785
def get_revision_graph_with_ghosts(self, revision_ids=None):
786
"""Return a graph of the revisions with ghosts marked as applicable.
788
:param revision_ids: an iterable of revisions to graph or None for all.
789
:return: a Graph object with the graph reachable from revision_ids.
792
vf = self._get_revision_vf()
793
versions = set(vf.versions())
795
pending = set(self.all_revision_ids())
798
pending = set(revision_ids)
799
required = set(revision_ids)
802
revision_id = pending.pop()
803
if not revision_id in versions:
804
if revision_id in required:
805
raise errors.NoSuchRevision(self, revision_id)
807
result.add_ghost(revision_id)
808
# mark it as done so we dont try for it again.
809
done.add(revision_id)
811
parent_ids = vf.get_parents_with_ghosts(revision_id)
812
for parent_id in parent_ids:
813
# is this queued or done ?
814
if (parent_id not in pending and
815
parent_id not in done):
817
pending.add(parent_id)
818
result.add_node(revision_id, parent_ids)
819
done.add(revision_id)
822
def _get_revision_vf(self):
823
""":return: a versioned file containing the revisions."""
824
vf = self._revision_store.get_revision_file(self.get_transaction())
828
def reconcile(self, other=None, thorough=False):
829
"""Reconcile this repository."""
830
from bzrlib.reconcile import KnitReconciler
831
reconciler = KnitReconciler(self, thorough=thorough)
832
reconciler.reconcile()
1114
format_registry = RepositoryFormatRegistry()
1115
"""Registry of formats, indexed by their identifying format string.
1117
This can contain either format instances themselves, or classes/factories that
1118
can be called to obtain one.
1122
#####################################################################
1123
# Repository Formats
835
def revision_parents(self, revid):
836
return self._get_revision_vf().get_parents(rev_id)
1125
838
class RepositoryFormat(object):
1126
839
"""A repository format.
1284
968
raise NotImplementedError(self.open)
971
def register_format(klass, format):
972
klass._formats[format.get_format_string()] = format
975
def set_default_format(klass, format):
976
klass._default_format = format
979
def unregister_format(klass, format):
980
assert klass._formats[format.get_format_string()] is format
981
del klass._formats[format.get_format_string()]
984
class PreSplitOutRepositoryFormat(RepositoryFormat):
985
"""Base class for the pre split out repository formats."""
987
def initialize(self, a_bzrdir, shared=False, _internal=False):
988
"""Create a weave repository.
990
TODO: when creating split out bzr branch formats, move this to a common
991
base for Format5, Format6. or something like that.
993
from bzrlib.weavefile import write_weave_v5
994
from bzrlib.weave import Weave
997
raise errors.IncompatibleFormat(self, a_bzrdir._format)
1000
# always initialized when the bzrdir is.
1001
return self.open(a_bzrdir, _found=True)
1003
# Create an empty weave
1005
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1006
empty_weave = sio.getvalue()
1008
mutter('creating repository in %s.', a_bzrdir.transport.base)
1009
dirs = ['revision-store', 'weaves']
1010
files = [('inventory.weave', StringIO(empty_weave)),
1013
# FIXME: RBC 20060125 dont peek under the covers
1014
# NB: no need to escape relative paths that are url safe.
1015
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock',
1017
control_files.create_lock()
1018
control_files.lock_write()
1019
control_files._transport.mkdir_multi(dirs,
1020
mode=control_files._dir_mode)
1022
for file, content in files:
1023
control_files.put(file, content)
1025
control_files.unlock()
1026
return self.open(a_bzrdir, _found=True)
1028
def _get_control_store(self, repo_transport, control_files):
1029
"""Return the control store for this repository."""
1030
return self._get_versioned_file_store('',
1035
def _get_text_store(self, transport, control_files):
1036
"""Get a store for file texts for this format."""
1037
raise NotImplementedError(self._get_text_store)
1039
def open(self, a_bzrdir, _found=False):
1040
"""See RepositoryFormat.open()."""
1042
# we are being called directly and must probe.
1043
raise NotImplementedError
1045
repo_transport = a_bzrdir.get_repository_transport(None)
1046
control_files = a_bzrdir._control_files
1047
text_store = self._get_text_store(repo_transport, control_files)
1048
control_store = self._get_control_store(repo_transport, control_files)
1049
_revision_store = self._get_revision_store(repo_transport, control_files)
1050
return AllInOneRepository(_format=self,
1052
_revision_store=_revision_store,
1053
control_store=control_store,
1054
text_store=text_store)
1057
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1058
"""Bzr repository format 4.
1060
This repository format has:
1062
- TextStores for texts, inventories,revisions.
1064
This format is deprecated: it indexes texts using a text id which is
1065
removed in format 5; initializationa and write support for this format
1070
super(RepositoryFormat4, self).__init__()
1071
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
1073
def get_format_description(self):
1074
"""See RepositoryFormat.get_format_description()."""
1075
return "Repository format 4"
1077
def initialize(self, url, shared=False, _internal=False):
1078
"""Format 4 branches cannot be created."""
1079
raise errors.UninitializableFormat(self)
1081
def is_supported(self):
1082
"""Format 4 is not supported.
1084
It is not supported because the model changed from 4 to 5 and the
1085
conversion logic is expensive - so doing it on the fly was not
1090
def _get_control_store(self, repo_transport, control_files):
1091
"""Format 4 repositories have no formal control store at this point.
1093
This will cause any control-file-needing apis to fail - this is desired.
1097
def _get_revision_store(self, repo_transport, control_files):
1098
"""See RepositoryFormat._get_revision_store()."""
1099
from bzrlib.xml4 import serializer_v4
1100
return self._get_text_rev_store(repo_transport,
1103
serializer=serializer_v4)
1105
def _get_text_store(self, transport, control_files):
1106
"""See RepositoryFormat._get_text_store()."""
1109
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1110
"""Bzr control format 5.
1112
This repository format has:
1113
- weaves for file texts and inventory
1115
- TextStores for revisions and signatures.
1119
super(RepositoryFormat5, self).__init__()
1120
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
1122
def get_format_description(self):
1123
"""See RepositoryFormat.get_format_description()."""
1124
return "Weave repository format 5"
1126
def _get_revision_store(self, repo_transport, control_files):
1127
"""See RepositoryFormat._get_revision_store()."""
1128
"""Return the revision store object for this a_bzrdir."""
1129
return self._get_text_rev_store(repo_transport,
1134
def _get_text_store(self, transport, control_files):
1135
"""See RepositoryFormat._get_text_store()."""
1136
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1139
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1140
"""Bzr control format 6.
1142
This repository format has:
1143
- weaves for file texts and inventory
1144
- hash subdirectory based stores.
1145
- TextStores for revisions and signatures.
1149
super(RepositoryFormat6, self).__init__()
1150
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
1152
def get_format_description(self):
1153
"""See RepositoryFormat.get_format_description()."""
1154
return "Weave repository format 6"
1156
def _get_revision_store(self, repo_transport, control_files):
1157
"""See RepositoryFormat._get_revision_store()."""
1158
return self._get_text_rev_store(repo_transport,
1164
def _get_text_store(self, transport, control_files):
1165
"""See RepositoryFormat._get_text_store()."""
1166
return self._get_versioned_file_store('weaves', transport, control_files)
1287
1169
class MetaDirRepositoryFormat(RepositoryFormat):
1288
"""Common base class for the new repositories using the metadir layout."""
1290
rich_root_data = False
1291
supports_tree_reference = False
1292
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1170
"""Common base class for the new repositories using the metadir layour."""
1294
1172
def __init__(self):
1295
1173
super(MetaDirRepositoryFormat, self).__init__()
1174
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
1297
1176
def _create_control_files(self, a_bzrdir):
1298
1177
"""Create the required files and the initial control_files object."""
1299
# FIXME: RBC 20060125 don't peek under the covers
1178
# FIXME: RBC 20060125 dont peek under the covers
1300
1179
# NB: no need to escape relative paths that are url safe.
1301
1180
repository_transport = a_bzrdir.get_repository_transport(self)
1302
control_files = lockable_files.LockableFiles(repository_transport,
1303
'lock', lockdir.LockDir)
1181
control_files = LockableFiles(repository_transport, 'lock', LockDir)
1304
1182
control_files.create_lock()
1305
1183
return control_files
1321
1199
control_files.unlock()
1202
class RepositoryFormat7(MetaDirRepositoryFormat):
1203
"""Bzr repository 7.
1205
This repository format has:
1206
- weaves for file texts and inventory
1207
- hash subdirectory based stores.
1208
- TextStores for revisions and signatures.
1209
- a format marker of its own
1210
- an optional 'shared-storage' flag
1211
- an optional 'no-working-trees' flag
1214
def _get_control_store(self, repo_transport, control_files):
1215
"""Return the control store for this repository."""
1216
return self._get_versioned_file_store('',
1221
def get_format_string(self):
1222
"""See RepositoryFormat.get_format_string()."""
1223
return "Bazaar-NG Repository format 7"
1225
def get_format_description(self):
1226
"""See RepositoryFormat.get_format_description()."""
1227
return "Weave repository format 7"
1229
def _get_revision_store(self, repo_transport, control_files):
1230
"""See RepositoryFormat._get_revision_store()."""
1231
return self._get_text_rev_store(repo_transport,
1238
def _get_text_store(self, transport, control_files):
1239
"""See RepositoryFormat._get_text_store()."""
1240
return self._get_versioned_file_store('weaves',
1244
def initialize(self, a_bzrdir, shared=False):
1245
"""Create a weave repository.
1247
:param shared: If true the repository will be initialized as a shared
1250
from bzrlib.weavefile import write_weave_v5
1251
from bzrlib.weave import Weave
1253
# Create an empty weave
1255
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1256
empty_weave = sio.getvalue()
1258
mutter('creating repository in %s.', a_bzrdir.transport.base)
1259
dirs = ['revision-store', 'weaves']
1260
files = [('inventory.weave', StringIO(empty_weave)),
1262
utf8_files = [('format', self.get_format_string())]
1264
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1265
return self.open(a_bzrdir=a_bzrdir, _found=True)
1267
def open(self, a_bzrdir, _found=False, _override_transport=None):
1268
"""See RepositoryFormat.open().
1270
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1271
repository at a slightly different url
1272
than normal. I.e. during 'upgrade'.
1275
format = RepositoryFormat.find_format(a_bzrdir)
1276
assert format.__class__ == self.__class__
1277
if _override_transport is not None:
1278
repo_transport = _override_transport
1280
repo_transport = a_bzrdir.get_repository_transport(None)
1281
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1282
text_store = self._get_text_store(repo_transport, control_files)
1283
control_store = self._get_control_store(repo_transport, control_files)
1284
_revision_store = self._get_revision_store(repo_transport, control_files)
1285
return MetaDirRepository(_format=self,
1287
control_files=control_files,
1288
_revision_store=_revision_store,
1289
control_store=control_store,
1290
text_store=text_store)
1293
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1294
"""Bzr repository knit format 1.
1296
This repository format has:
1297
- knits for file texts and inventory
1298
- hash subdirectory based stores.
1299
- knits for revisions and signatures
1300
- TextStores for revisions and signatures.
1301
- a format marker of its own
1302
- an optional 'shared-storage' flag
1303
- an optional 'no-working-trees' flag
1306
This format was introduced in bzr 0.8.
1309
def _get_control_store(self, repo_transport, control_files):
1310
"""Return the control store for this repository."""
1311
return VersionedFileStore(
1314
file_mode=control_files._file_mode,
1315
versionedfile_class=KnitVersionedFile,
1316
versionedfile_kwargs={'factory':KnitPlainFactory()},
1319
def get_format_string(self):
1320
"""See RepositoryFormat.get_format_string()."""
1321
return "Bazaar-NG Knit Repository Format 1"
1323
def get_format_description(self):
1324
"""See RepositoryFormat.get_format_description()."""
1325
return "Knit repository format 1"
1327
def _get_revision_store(self, repo_transport, control_files):
1328
"""See RepositoryFormat._get_revision_store()."""
1329
from bzrlib.store.revision.knit import KnitRevisionStore
1330
versioned_file_store = VersionedFileStore(
1332
file_mode=control_files._file_mode,
1335
versionedfile_class=KnitVersionedFile,
1336
versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory()},
1339
return KnitRevisionStore(versioned_file_store)
1341
def _get_text_store(self, transport, control_files):
1342
"""See RepositoryFormat._get_text_store()."""
1343
return self._get_versioned_file_store('knits',
1346
versionedfile_class=KnitVersionedFile,
1349
def initialize(self, a_bzrdir, shared=False):
1350
"""Create a knit format 1 repository.
1352
:param a_bzrdir: bzrdir to contain the new repository; must already
1354
:param shared: If true the repository will be initialized as a shared
1357
mutter('creating repository in %s.', a_bzrdir.transport.base)
1358
dirs = ['revision-store', 'knits']
1360
utf8_files = [('format', self.get_format_string())]
1362
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1363
repo_transport = a_bzrdir.get_repository_transport(None)
1364
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1365
control_store = self._get_control_store(repo_transport, control_files)
1366
transaction = bzrlib.transactions.WriteTransaction()
1367
# trigger a write of the inventory store.
1368
control_store.get_weave_or_empty('inventory', transaction)
1369
_revision_store = self._get_revision_store(repo_transport, control_files)
1370
_revision_store.has_revision_id('A', transaction)
1371
_revision_store.get_signature_file(transaction)
1372
return self.open(a_bzrdir=a_bzrdir, _found=True)
1374
def open(self, a_bzrdir, _found=False, _override_transport=None):
1375
"""See RepositoryFormat.open().
1377
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1378
repository at a slightly different url
1379
than normal. I.e. during 'upgrade'.
1382
format = RepositoryFormat.find_format(a_bzrdir)
1383
assert format.__class__ == self.__class__
1384
if _override_transport is not None:
1385
repo_transport = _override_transport
1387
repo_transport = a_bzrdir.get_repository_transport(None)
1388
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1389
text_store = self._get_text_store(repo_transport, control_files)
1390
control_store = self._get_control_store(repo_transport, control_files)
1391
_revision_store = self._get_revision_store(repo_transport, control_files)
1392
return KnitRepository(_format=self,
1394
control_files=control_files,
1395
_revision_store=_revision_store,
1396
control_store=control_store,
1397
text_store=text_store)
1324
1400
# formats which have no format string are not discoverable
1325
# and not independently creatable, so are not registered. They're
1326
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
1327
# needed, it's constructed directly by the BzrDir. Non-native formats where
1328
# the repository is not separately opened are similar.
1330
format_registry.register_lazy(
1331
'Bazaar-NG Repository format 7',
1332
'bzrlib.repofmt.weaverepo',
1335
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1336
# default control directory format
1338
format_registry.register_lazy(
1339
'Bazaar-NG Knit Repository Format 1',
1340
'bzrlib.repofmt.knitrepo',
1341
'RepositoryFormatKnit1',
1343
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1345
format_registry.register_lazy(
1346
'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
1347
'bzrlib.repofmt.knitrepo',
1348
'RepositoryFormatKnit3',
1401
# and not independently creatable, so are not registered.
1402
RepositoryFormat.register_format(RepositoryFormat7())
1403
_default_format = RepositoryFormatKnit1()
1404
RepositoryFormat.register_format(_default_format)
1405
RepositoryFormat.set_default_format(_default_format)
1406
_legacy_formats = [RepositoryFormat4(),
1407
RepositoryFormat5(),
1408
RepositoryFormat6()]
1352
1411
class InterRepository(InterObject):
1408
1520
# that we've decided we need.
1409
1521
return [rev_id for rev_id in source_ids if rev_id in result_set]
1412
class InterSameDataRepository(InterRepository):
1413
"""Code for converting between repositories that represent the same data.
1415
Data format and model must match for this to work.
1419
def _get_repo_format_to_test(self):
1420
"""Repository format for testing with."""
1421
return RepositoryFormat.get_default_format()
1424
def is_compatible(source, target):
1425
if source.supports_rich_root() != target.supports_rich_root():
1427
if source._serializer != target._serializer:
1432
def copy_content(self, revision_id=None):
1433
"""Make a complete copy of the content in self into destination.
1435
This copies both the repository's revision data, and configuration information
1436
such as the make_working_trees setting.
1438
This is a destructive operation! Do not use it on existing
1441
:param revision_id: Only copy the content needed to construct
1442
revision_id and its parents.
1524
"""Release the locks on source and target."""
1445
self.target.set_make_working_trees(self.source.make_working_trees())
1446
except NotImplementedError:
1448
# TODO: jam 20070210 This is fairly internal, so we should probably
1449
# just assert that revision_id is not unicode.
1450
revision_id = osutils.safe_revision_id(revision_id)
1451
# but don't bother fetching if we have the needed data now.
1452
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1453
self.target.has_revision(revision_id)):
1455
self.target.fetch(self.source, revision_id=revision_id)
1458
def fetch(self, revision_id=None, pb=None):
1459
"""See InterRepository.fetch()."""
1460
from bzrlib.fetch import GenericRepoFetcher
1461
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1462
self.source, self.source._format, self.target,
1463
self.target._format)
1464
# TODO: jam 20070210 This should be an assert, not a translate
1465
revision_id = osutils.safe_revision_id(revision_id)
1466
f = GenericRepoFetcher(to_repository=self.target,
1467
from_repository=self.source,
1468
last_revision=revision_id,
1470
return f.count_copied, f.failed_revisions
1473
class InterWeaveRepo(InterSameDataRepository):
1526
self.target.unlock()
1528
self.source.unlock()
1531
class InterWeaveRepo(InterRepository):
1474
1532
"""Optimised code paths between Weave based repositories."""
1477
def _get_repo_format_to_test(self):
1478
from bzrlib.repofmt import weaverepo
1479
return weaverepo.RepositoryFormat7()
1534
_matching_repo_format = RepositoryFormat7()
1535
"""Repository format for testing with."""
1482
1538
def is_compatible(source, target):
1483
1539
"""Be compatible with known Weave formats.
1485
We don't test for the stores being of specific types because that
1541
We dont test for the stores being of specific types becase that
1486
1542
could lead to confusing results, and there is no need to be
1487
1543
overly general.
1489
from bzrlib.repofmt.weaverepo import (
1495
1546
return (isinstance(source._format, (RepositoryFormat5,
1496
1547
RepositoryFormat6,
1504
1555
@needs_write_lock
1505
def copy_content(self, revision_id=None):
1556
def copy_content(self, revision_id=None, basis=None):
1506
1557
"""See InterRepository.copy_content()."""
1507
1558
# weave specific optimised path:
1508
# TODO: jam 20070210 Internal, should be an assert, not translate
1509
revision_id = osutils.safe_revision_id(revision_id)
1511
self.target.set_make_working_trees(self.source.make_working_trees())
1512
except NotImplementedError:
1514
# FIXME do not peek!
1515
if self.source.control_files._transport.listable():
1516
pb = ui.ui_factory.nested_progress_bar()
1559
if basis is not None:
1560
# copy the basis in, then fetch remaining data.
1561
basis.copy_content_into(self.target, revision_id)
1562
# the basis copy_content_into could misset this.
1518
self.target.weave_store.copy_all_ids(
1519
self.source.weave_store,
1521
from_transaction=self.source.get_transaction(),
1522
to_transaction=self.target.get_transaction())
1523
pb.update('copying inventory', 0, 1)
1524
self.target.control_weaves.copy_multi(
1525
self.source.control_weaves, ['inventory'],
1526
from_transaction=self.source.get_transaction(),
1527
to_transaction=self.target.get_transaction())
1528
self.target._revision_store.text_store.copy_all_ids(
1529
self.source._revision_store.text_store,
1564
self.target.set_make_working_trees(self.source.make_working_trees())
1565
except NotImplementedError:
1534
1567
self.target.fetch(self.source, revision_id=revision_id)
1570
self.target.set_make_working_trees(self.source.make_working_trees())
1571
except NotImplementedError:
1573
# FIXME do not peek!
1574
if self.source.control_files._transport.listable():
1575
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1577
self.target.weave_store.copy_all_ids(
1578
self.source.weave_store,
1580
from_transaction=self.source.get_transaction(),
1581
to_transaction=self.target.get_transaction())
1582
pb.update('copying inventory', 0, 1)
1583
self.target.control_weaves.copy_multi(
1584
self.source.control_weaves, ['inventory'],
1585
from_transaction=self.source.get_transaction(),
1586
to_transaction=self.target.get_transaction())
1587
self.target._revision_store.text_store.copy_all_ids(
1588
self.source._revision_store.text_store,
1593
self.target.fetch(self.source, revision_id=revision_id)
1536
1595
@needs_write_lock
1537
1596
def fetch(self, revision_id=None, pb=None):
1656
1708
# that against the revision records.
1657
1709
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1660
class InterModel1and2(InterRepository):
1663
def _get_repo_format_to_test(self):
1667
def is_compatible(source, target):
1668
if not source.supports_rich_root() and target.supports_rich_root():
1674
def fetch(self, revision_id=None, pb=None):
1675
"""See InterRepository.fetch()."""
1676
from bzrlib.fetch import Model1toKnit2Fetcher
1677
# TODO: jam 20070210 This should be an assert, not a translate
1678
revision_id = osutils.safe_revision_id(revision_id)
1679
f = Model1toKnit2Fetcher(to_repository=self.target,
1680
from_repository=self.source,
1681
last_revision=revision_id,
1683
return f.count_copied, f.failed_revisions
1686
def copy_content(self, revision_id=None):
1687
"""Make a complete copy of the content in self into destination.
1689
This is a destructive operation! Do not use it on existing
1692
:param revision_id: Only copy the content needed to construct
1693
revision_id and its parents.
1696
self.target.set_make_working_trees(self.source.make_working_trees())
1697
except NotImplementedError:
1699
# TODO: jam 20070210 Internal, assert, don't translate
1700
revision_id = osutils.safe_revision_id(revision_id)
1701
# but don't bother fetching if we have the needed data now.
1702
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1703
self.target.has_revision(revision_id)):
1705
self.target.fetch(self.source, revision_id=revision_id)
1708
class InterKnit1and2(InterKnitRepo):
1711
def _get_repo_format_to_test(self):
1715
def is_compatible(source, target):
1716
"""Be compatible with Knit1 source and Knit3 target"""
1717
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
1719
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1720
RepositoryFormatKnit3
1721
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1722
isinstance(target._format, (RepositoryFormatKnit3)))
1723
except AttributeError:
1727
def fetch(self, revision_id=None, pb=None):
1728
"""See InterRepository.fetch()."""
1729
from bzrlib.fetch import Knit1to2Fetcher
1730
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1731
self.source, self.source._format, self.target,
1732
self.target._format)
1733
# TODO: jam 20070210 This should be an assert, not a translate
1734
revision_id = osutils.safe_revision_id(revision_id)
1735
f = Knit1to2Fetcher(to_repository=self.target,
1736
from_repository=self.source,
1737
last_revision=revision_id,
1739
return f.count_copied, f.failed_revisions
1742
class InterRemoteRepository(InterRepository):
1743
"""Code for converting between RemoteRepository objects.
1745
This just gets an non-remote repository from the RemoteRepository, and calls
1746
InterRepository.get again.
1749
def __init__(self, source, target):
1750
if isinstance(source, remote.RemoteRepository):
1751
source._ensure_real()
1752
real_source = source._real_repository
1754
real_source = source
1755
if isinstance(target, remote.RemoteRepository):
1756
target._ensure_real()
1757
real_target = target._real_repository
1759
real_target = target
1760
self.real_inter = InterRepository.get(real_source, real_target)
1763
def is_compatible(source, target):
1764
if isinstance(source, remote.RemoteRepository):
1766
if isinstance(target, remote.RemoteRepository):
1770
def copy_content(self, revision_id=None):
1771
self.real_inter.copy_content(revision_id=revision_id)
1773
def fetch(self, revision_id=None, pb=None):
1774
self.real_inter.fetch(revision_id=revision_id, pb=pb)
1777
def _get_repo_format_to_test(self):
1781
InterRepository.register_optimiser(InterSameDataRepository)
1782
1711
InterRepository.register_optimiser(InterWeaveRepo)
1783
1712
InterRepository.register_optimiser(InterKnitRepo)
1784
InterRepository.register_optimiser(InterModel1and2)
1785
InterRepository.register_optimiser(InterKnit1and2)
1786
InterRepository.register_optimiser(InterRemoteRepository)
1715
class RepositoryTestProviderAdapter(object):
1716
"""A tool to generate a suite testing multiple repository formats at once.
1718
This is done by copying the test once for each transport and injecting
1719
the transport_server, transport_readonly_server, and bzrdir_format and
1720
repository_format classes into each copy. Each copy is also given a new id()
1721
to make it easy to identify.
1724
def __init__(self, transport_server, transport_readonly_server, formats):
1725
self._transport_server = transport_server
1726
self._transport_readonly_server = transport_readonly_server
1727
self._formats = formats
1729
def adapt(self, test):
1730
result = TestSuite()
1731
for repository_format, bzrdir_format in self._formats:
1732
new_test = deepcopy(test)
1733
new_test.transport_server = self._transport_server
1734
new_test.transport_readonly_server = self._transport_readonly_server
1735
new_test.bzrdir_format = bzrdir_format
1736
new_test.repository_format = repository_format
1737
def make_new_test_id():
1738
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1739
return lambda: new_id
1740
new_test.id = make_new_test_id()
1741
result.addTest(new_test)
1745
class InterRepositoryTestProviderAdapter(object):
1746
"""A tool to generate a suite testing multiple inter repository formats.
1748
This is done by copying the test once for each interrepo provider and injecting
1749
the transport_server, transport_readonly_server, repository_format and
1750
repository_to_format classes into each copy.
1751
Each copy is also given a new id() to make it easy to identify.
1754
def __init__(self, transport_server, transport_readonly_server, formats):
1755
self._transport_server = transport_server
1756
self._transport_readonly_server = transport_readonly_server
1757
self._formats = formats
1759
def adapt(self, test):
1760
result = TestSuite()
1761
for interrepo_class, repository_format, repository_format_to in self._formats:
1762
new_test = deepcopy(test)
1763
new_test.transport_server = self._transport_server
1764
new_test.transport_readonly_server = self._transport_readonly_server
1765
new_test.interrepo_class = interrepo_class
1766
new_test.repository_format = repository_format
1767
new_test.repository_format_to = repository_format_to
1768
def make_new_test_id():
1769
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1770
return lambda: new_id
1771
new_test.id = make_new_test_id()
1772
result.addTest(new_test)
1776
def default_test_list():
1777
"""Generate the default list of interrepo permutations to test."""
1779
# test the default InterRepository between format 6 and the current
1781
# XXX: robertc 20060220 reinstate this when there are two supported
1782
# formats which do not have an optimal code path between them.
1783
result.append((InterRepository,
1784
RepositoryFormat6(),
1785
RepositoryFormatKnit1()))
1786
for optimiser in InterRepository._optimisers:
1787
result.append((optimiser,
1788
optimiser._matching_repo_format,
1789
optimiser._matching_repo_format
1791
# if there are specific combinations we want to use, we can add them
1789
1796
class CopyConverter(object):
1838
1844
self.pb.update(message, self.count, self.total)
1841
class CommitBuilder(object):
1842
"""Provides an interface to build up a commit.
1844
This allows describing a tree to be committed without needing to
1845
know the internals of the format of the repository.
1848
record_root_entry = False
1849
def __init__(self, repository, parents, config, timestamp=None,
1850
timezone=None, committer=None, revprops=None,
1852
"""Initiate a CommitBuilder.
1854
:param repository: Repository to commit to.
1855
:param parents: Revision ids of the parents of the new revision.
1856
:param config: Configuration to use.
1857
:param timestamp: Optional timestamp recorded for commit.
1858
:param timezone: Optional timezone for timestamp.
1859
:param committer: Optional committer to set for commit.
1860
:param revprops: Optional dictionary of revision properties.
1861
:param revision_id: Optional revision id.
1863
self._config = config
1865
if committer is None:
1866
self._committer = self._config.username()
1868
assert isinstance(committer, basestring), type(committer)
1869
self._committer = committer
1871
self.new_inventory = Inventory(None)
1872
self._new_revision_id = osutils.safe_revision_id(revision_id)
1873
self.parents = parents
1874
self.repository = repository
1877
if revprops is not None:
1878
self._revprops.update(revprops)
1880
if timestamp is None:
1881
timestamp = time.time()
1882
# Restrict resolution to 1ms
1883
self._timestamp = round(timestamp, 3)
1885
if timezone is None:
1886
self._timezone = osutils.local_time_offset()
1888
self._timezone = int(timezone)
1890
self._generate_revision_if_needed()
1892
def commit(self, message):
1893
"""Make the actual commit.
1895
:return: The revision id of the recorded revision.
1897
rev = _mod_revision.Revision(
1898
timestamp=self._timestamp,
1899
timezone=self._timezone,
1900
committer=self._committer,
1902
inventory_sha1=self.inv_sha1,
1903
revision_id=self._new_revision_id,
1904
properties=self._revprops)
1905
rev.parent_ids = self.parents
1906
self.repository.add_revision(self._new_revision_id, rev,
1907
self.new_inventory, self._config)
1908
return self._new_revision_id
1910
def revision_tree(self):
1911
"""Return the tree that was just committed.
1913
After calling commit() this can be called to get a RevisionTree
1914
representing the newly committed tree. This is preferred to
1915
calling Repository.revision_tree() because that may require
1916
deserializing the inventory, while we already have a copy in
1919
return RevisionTree(self.repository, self.new_inventory,
1920
self._new_revision_id)
1922
def finish_inventory(self):
1923
"""Tell the builder that the inventory is finished."""
1924
if self.new_inventory.root is None:
1925
symbol_versioning.warn('Root entry should be supplied to'
1926
' record_entry_contents, as of bzr 0.10.',
1927
DeprecationWarning, stacklevel=2)
1928
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1929
self.new_inventory.revision_id = self._new_revision_id
1930
self.inv_sha1 = self.repository.add_inventory(
1931
self._new_revision_id,
1936
def _gen_revision_id(self):
1937
"""Return new revision-id."""
1938
return generate_ids.gen_revision_id(self._config.username(),
1941
def _generate_revision_if_needed(self):
1942
"""Create a revision id if None was supplied.
1944
If the repository can not support user-specified revision ids
1945
they should override this function and raise CannotSetRevisionId
1946
if _new_revision_id is not None.
1948
:raises: CannotSetRevisionId
1950
if self._new_revision_id is None:
1951
self._new_revision_id = self._gen_revision_id()
1953
def record_entry_contents(self, ie, parent_invs, path, tree):
1954
"""Record the content of ie from tree into the commit if needed.
1956
Side effect: sets ie.revision when unchanged
1958
:param ie: An inventory entry present in the commit.
1959
:param parent_invs: The inventories of the parent revisions of the
1961
:param path: The path the entry is at in the tree.
1962
:param tree: The tree which contains this entry and should be used to
1965
if self.new_inventory.root is None and ie.parent_id is not None:
1966
symbol_versioning.warn('Root entry should be supplied to'
1967
' record_entry_contents, as of bzr 0.10.',
1968
DeprecationWarning, stacklevel=2)
1969
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
1971
self.new_inventory.add(ie)
1973
# ie.revision is always None if the InventoryEntry is considered
1974
# for committing. ie.snapshot will record the correct revision
1975
# which may be the sole parent if it is untouched.
1976
if ie.revision is not None:
1979
# In this revision format, root entries have no knit or weave
1980
if ie is self.new_inventory.root:
1981
# When serializing out to disk and back in
1982
# root.revision is always _new_revision_id
1983
ie.revision = self._new_revision_id
1985
previous_entries = ie.find_previous_heads(
1987
self.repository.weave_store,
1988
self.repository.get_transaction())
1989
# we are creating a new revision for ie in the history store
1991
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
1993
def modified_directory(self, file_id, file_parents):
1994
"""Record the presence of a symbolic link.
1996
:param file_id: The file_id of the link to record.
1997
:param file_parents: The per-file parent revision ids.
1999
self._add_text_to_weave(file_id, [], file_parents.keys())
2001
def modified_reference(self, file_id, file_parents):
2002
"""Record the modification of a reference.
2004
:param file_id: The file_id of the link to record.
2005
:param file_parents: The per-file parent revision ids.
2007
self._add_text_to_weave(file_id, [], file_parents.keys())
2009
def modified_file_text(self, file_id, file_parents,
2010
get_content_byte_lines, text_sha1=None,
2012
"""Record the text of file file_id
2014
:param file_id: The file_id of the file to record the text of.
2015
:param file_parents: The per-file parent revision ids.
2016
:param get_content_byte_lines: A callable which will return the byte
2018
:param text_sha1: Optional SHA1 of the file contents.
2019
:param text_size: Optional size of the file contents.
2021
# mutter('storing text of file {%s} in revision {%s} into %r',
2022
# file_id, self._new_revision_id, self.repository.weave_store)
2023
# special case to avoid diffing on renames or
2025
if (len(file_parents) == 1
2026
and text_sha1 == file_parents.values()[0].text_sha1
2027
and text_size == file_parents.values()[0].text_size):
2028
previous_ie = file_parents.values()[0]
2029
versionedfile = self.repository.weave_store.get_weave(file_id,
2030
self.repository.get_transaction())
2031
versionedfile.clone_text(self._new_revision_id,
2032
previous_ie.revision, file_parents.keys())
2033
return text_sha1, text_size
2035
new_lines = get_content_byte_lines()
2036
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2037
# should return the SHA1 and size
2038
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2039
return osutils.sha_strings(new_lines), \
2040
sum(map(len, new_lines))
2042
def modified_link(self, file_id, file_parents, link_target):
2043
"""Record the presence of a symbolic link.
2045
:param file_id: The file_id of the link to record.
2046
:param file_parents: The per-file parent revision ids.
2047
:param link_target: Target location of this link.
2049
self._add_text_to_weave(file_id, [], file_parents.keys())
2051
def _add_text_to_weave(self, file_id, new_lines, parents):
2052
versionedfile = self.repository.weave_store.get_weave_or_empty(
2053
file_id, self.repository.get_transaction())
2054
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2055
versionedfile.clear_cache()
2058
class _CommitBuilder(CommitBuilder):
2059
"""Temporary class so old CommitBuilders are detected properly
2061
Note: CommitBuilder works whether or not root entry is recorded.
2064
record_root_entry = True
2067
class RootCommitBuilder(CommitBuilder):
2068
"""This commitbuilder actually records the root id"""
2070
record_root_entry = True
2072
def record_entry_contents(self, ie, parent_invs, path, tree):
2073
"""Record the content of ie from tree into the commit if needed.
2075
Side effect: sets ie.revision when unchanged
2077
:param ie: An inventory entry present in the commit.
2078
:param parent_invs: The inventories of the parent revisions of the
2080
:param path: The path the entry is at in the tree.
2081
:param tree: The tree which contains this entry and should be used to
2084
assert self.new_inventory.root is not None or ie.parent_id is None
2085
self.new_inventory.add(ie)
2087
# ie.revision is always None if the InventoryEntry is considered
2088
# for committing. ie.snapshot will record the correct revision
2089
# which may be the sole parent if it is untouched.
2090
if ie.revision is not None:
2093
previous_entries = ie.find_previous_heads(
2095
self.repository.weave_store,
2096
self.repository.get_transaction())
2097
# we are creating a new revision for ie in the history store
2099
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2111
def _unescaper(match, _map=_unescape_map):
2112
code = match.group(1)
2116
if not code.startswith('#'):
2118
return unichr(int(code[1:])).encode('utf8')
1847
# Copied from xml.sax.saxutils
2124
1848
def _unescape_xml(data):
2125
"""Unescape predefined XML entities in a string of data."""
2127
if _unescape_re is None:
2128
_unescape_re = re.compile('\&([^;]*);')
2129
return _unescape_re.sub(_unescaper, data)
1849
"""Unescape &, <, and > in a string of data.
1851
data = data.replace("<", "<")
1852
data = data.replace(">", ">")
1853
# must do ampersand last
1854
return data.replace("&", "&")