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, \
96
"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)
67
inv_text = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
68
inv_sha1 = bzrlib.osutils.sha_string(inv_text)
101
69
inv_vf = self.control_weaves.get_weave('inventory',
102
70
self.get_transaction())
103
self._inventory_add_lines(inv_vf, revision_id, parents,
104
osutils.split_lines(inv_text))
71
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.
75
def add_revision(self, rev_id, rev, inv=None, config=None):
76
"""Add rev to the revision store as rev_id.
119
:param revision_id: the revision id to use.
78
:param rev_id: the revision id to use.
120
79
:param rev: The revision object.
121
80
:param inv: The inventory for the revision. if None, it will be looked
122
81
up in the inventory storer
257
179
def get_physical_lock_status(self):
258
180
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
183
def missing_revision_ids(self, other, revision_id=None):
328
184
"""Return the revision ids that other has that this does not.
341
196
For instance, if the repository is at URL/.bzr/repository,
342
197
Repository.open(URL) -> a Repository instance.
344
control = bzrdir.BzrDir.open(base)
199
control = bzrlib.bzrdir.BzrDir.open(base)
345
200
return control.open_repository()
347
def copy_content_into(self, destination, revision_id=None):
202
def copy_content_into(self, destination, revision_id=None, basis=None):
348
203
"""Make a complete copy of the content in self into destination.
350
205
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)
208
return InterRepository.get(self, destination).copy_content(revision_id, basis)
356
210
def fetch(self, source, revision_id=None, pb=None):
357
211
"""Fetch the content required to construct revision_id from source.
359
213
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)
215
return InterRepository.get(source, self).fetch(revision_id=revision_id,
386
218
def unlock(self):
387
219
self.control_files.unlock()
390
def clone(self, a_bzrdir, revision_id=None):
222
def clone(self, a_bzrdir, revision_id=None, basis=None):
391
223
"""Clone this repository into a_bzrdir using the current format.
393
225
Currently no check is made that the format of this repository and
394
226
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
228
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
416
229
# use target default format.
417
dest_repo = a_bzrdir.create_repository()
230
result = a_bzrdir.create_repository()
231
# FIXME RBC 20060209 split out the repository type to avoid this check ?
232
elif isinstance(a_bzrdir._format,
233
(bzrlib.bzrdir.BzrDirFormat4,
234
bzrlib.bzrdir.BzrDirFormat5,
235
bzrlib.bzrdir.BzrDirFormat6)):
236
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()
238
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
239
self.copy_content_into(result, revision_id, basis)
428
243
def has_revision(self, revision_id):
429
244
"""True if this repository has a copy of the revision."""
430
revision_id = osutils.safe_revision_id(revision_id)
431
245
return self._revision_store.has_revision_id(revision_id,
432
246
self.get_transaction())
549
314
revision_ids. Each altered file-ids has the exact revision_ids that
550
315
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)
317
assert isinstance(self._format, (RepositoryFormat5,
320
RepositoryFormatKnit1)), \
321
"fileid_involved only supported for branches which store inventory as unnested xml"
322
selected_revision_ids = set(revision_ids)
557
323
w = self.get_inventory_weave()
560
326
# this code needs to read every new line in every inventory for the
561
327
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
562
# not present in one of those inventories is unnecessary but not
328
# not pesent in one of those inventories is unnecessary but not
563
329
# harmful because we are filtering by the revision id marker in the
564
330
# 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
331
# revisions. We dont need to see all lines in the inventory because
566
332
# 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)
334
for line in w.iter_lines_added_or_present_in_versions(selected_revision_ids):
335
start = line.find('file_id="')+9
336
if start < 9: continue
337
end = line.find('"', start)
339
file_id = _unescape_xml(line[start:end])
341
start = line.find('revision="')+10
342
if start < 10: continue
343
end = line.find('"', start)
345
revision_id = _unescape_xml(line[start:end])
346
if revision_id in selected_revision_ids:
347
result.setdefault(file_id, set()).add(revision_id)
624
356
def get_inventory(self, revision_id):
625
357
"""Get Inventory object by hash."""
626
# TODO: jam 20070210 Technically we don't need to sanitize, since all
627
# called functions must sanitize.
628
revision_id = osutils.safe_revision_id(revision_id)
629
return self.deserialise_inventory(
630
revision_id, self.get_inventory_xml(revision_id))
632
def deserialise_inventory(self, revision_id, xml):
633
"""Transform the xml into an inventory object.
635
:param revision_id: The expected revision id of the inventory.
636
: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)
358
xml = self.get_inventory_xml(revision_id)
359
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
647
362
def get_inventory_xml(self, revision_id):
648
363
"""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)
365
assert isinstance(revision_id, basestring), type(revision_id)
652
366
iw = self.get_inventory_weave()
653
367
return iw.get_text(revision_id)
654
368
except IndexError:
655
raise errors.HistoryMissing(self, 'inventory', revision_id)
369
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
658
372
def get_inventory_sha1(self, revision_id):
659
373
"""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
375
return self.get_revision(revision_id).inventory_sha1
666
378
def get_revision_graph(self, revision_id=None):
667
379
"""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
381
: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
383
weave = self.get_inventory_weave()
384
all_revisions = self._eliminate_revisions_not_present(weave.versions())
385
entire_graph = dict([(node, weave.get_parents(node)) for
682
386
node in all_revisions])
683
387
if revision_id is None:
684
388
return entire_graph
788
463
reconciler = RepoReconciler(self, thorough=thorough)
789
464
reconciler.reconcile()
790
465
return reconciler
793
468
def revision_tree(self, revision_id):
794
469
"""Return Tree for a revision on this branch.
796
`revision_id` may be None for the empty tree revision.
471
`revision_id` may be None for the null revision, in which case
472
an `EmptyTree` is returned."""
798
473
# TODO: refactor this to use an existing revision object
799
474
# 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)
475
if revision_id is None or revision_id == NULL_REVISION:
804
revision_id = osutils.safe_revision_id(revision_id)
805
478
inv = self.get_revision_inventory(revision_id)
806
479
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):
482
def get_ancestry(self, revision_id):
822
483
"""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
485
This is topologically sorted.
830
if _mod_revision.is_null(revision_id):
487
if revision_id is None:
832
revision_id = osutils.safe_revision_id(revision_id)
833
489
if not self.has_revision(revision_id):
834
490
raise errors.NoSuchRevision(self, revision_id)
835
491
w = self.get_inventory_weave()
836
candidates = w.get_ancestry(revision_id, topo_sorted)
492
candidates = w.get_ancestry(revision_id)
837
493
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
840
"""Compress the data within the repository.
842
This operation only makes sense for some repository types. For other
843
types it should be a no-op that just returns.
845
This stub method does not require a lock, but subclasses should use
846
@needs_write_lock as this is a long running call its reasonable to
847
implicitly lock for the user.
851
496
def print_file(self, file, revision_id):
852
497
"""Print `file` to stdout.
855
500
- it writes to stdout, it assumes that that is valid etc. Fix
856
501
by creating a new more flexible convenience function.
858
revision_id = osutils.safe_revision_id(revision_id)
859
503
tree = self.revision_tree(revision_id)
860
504
# use inventory as it was in that revision
861
505
file_id = tree.inventory.path2id(file)
863
# TODO: jam 20060427 Write a test for this code path
864
# it had a bug in it, and was raising the wrong
866
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
507
raise BzrError("%r is not present in revision %s" % (file, revno))
509
revno = self.revision_id_to_revno(revision_id)
510
except errors.NoSuchRevision:
511
# TODO: This should not be BzrError,
512
# but NoSuchFile doesn't fit either
513
raise BzrError('%r is not present in revision %s'
514
% (file, revision_id))
516
raise BzrError('%r is not present in revision %s'
867
518
tree.print_file(file_id)
869
520
def get_transaction(self):
870
521
return self.control_files.get_transaction()
872
def revision_parents(self, revision_id):
873
revision_id = osutils.safe_revision_id(revision_id)
874
return self.get_inventory_weave().parent_names(revision_id)
876
def get_parents(self, revision_ids):
877
"""See StackedParentsProvider.get_parents"""
879
for revision_id in revision_ids:
880
if revision_id == _mod_revision.NULL_REVISION:
884
parents = self.get_revision(revision_id).parent_ids
885
except errors.NoSuchRevision:
888
if len(parents) == 0:
889
parents = [_mod_revision.NULL_REVISION]
890
parents_list.append(parents)
893
def _make_parents_provider(self):
896
def get_graph(self, other_repository=None):
897
"""Return the graph walker for this repository format"""
898
parents_provider = self._make_parents_provider()
899
if (other_repository is not None and
900
other_repository.bzrdir.transport.base !=
901
self.bzrdir.transport.base):
902
parents_provider = graph._StackedParentsProvider(
903
[parents_provider, other_repository._make_parents_provider()])
904
return graph.Graph(parents_provider)
523
def revision_parents(self, revid):
524
return self.get_inventory_weave().parent_names(revid)
906
526
@needs_write_lock
907
527
def set_make_working_trees(self, new_value):
922
542
@needs_write_lock
923
543
def sign_revision(self, revision_id, gpg_strategy):
924
revision_id = osutils.safe_revision_id(revision_id)
925
544
plaintext = Testament.from_revision(self, revision_id).as_short_text()
926
545
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
929
548
def has_signature_for_revision_id(self, revision_id):
930
549
"""Query for a revision signature for revision_id in the repository."""
931
revision_id = osutils.safe_revision_id(revision_id)
932
550
return self._revision_store.has_signature(revision_id,
933
551
self.get_transaction())
936
554
def get_signature_text(self, revision_id):
937
555
"""Return the text for a signature."""
938
revision_id = osutils.safe_revision_id(revision_id)
939
556
return self._revision_store.get_signature_text(revision_id,
940
557
self.get_transaction())
560
class AllInOneRepository(Repository):
561
"""Legacy support - the repository behaviour for all-in-one branches."""
563
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
564
# we reuse one control files instance.
565
dir_mode = a_bzrdir._control_files._dir_mode
566
file_mode = a_bzrdir._control_files._file_mode
568
def get_store(name, compressed=True, prefixed=False):
569
# FIXME: This approach of assuming stores are all entirely compressed
570
# or entirely uncompressed is tidy, but breaks upgrade from
571
# some existing branches where there's a mixture; we probably
572
# still want the option to look for both.
573
relpath = a_bzrdir._control_files._escape(name)
574
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
575
prefixed=prefixed, compressed=compressed,
578
#if self._transport.should_cache():
579
# cache_path = os.path.join(self.cache_root, name)
580
# os.mkdir(cache_path)
581
# store = bzrlib.store.CachedStore(store, cache_path)
584
# not broken out yet because the controlweaves|inventory_store
585
# and text_store | weave_store bits are still different.
586
if isinstance(_format, RepositoryFormat4):
587
# cannot remove these - there is still no consistent api
588
# which allows access to this old info.
589
self.inventory_store = get_store('inventory-store')
590
text_store = get_store('text-store')
591
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
943
def check(self, revision_ids):
944
"""Check consistency of all history of given revision_ids.
946
Different repository implementations should override _check().
948
:param revision_ids: A non-empty list of revision_ids whose ancestry
949
will be checked. Typically the last revision_id of a branch.
595
"""AllInOne repositories cannot be shared."""
599
def set_make_working_trees(self, new_value):
600
"""Set the policy flag for making working trees when creating branches.
602
This only applies to branches that use this repository.
604
The default is 'True'.
605
:param new_value: True to restore the default, False to disable making
952
raise ValueError("revision_ids must be non-empty in %s.check"
954
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
955
return self._check(revision_ids)
957
def _check(self, revision_ids):
958
result = check.Check(self)
962
def _warn_if_deprecated(self):
963
global _deprecation_warning_done
964
if _deprecation_warning_done:
966
_deprecation_warning_done = True
967
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
968
% (self._format, self.bzrdir.transport.base))
970
def supports_rich_root(self):
971
return self._format.rich_root_data
973
def _check_ascii_revisionid(self, revision_id, method):
974
"""Private helper for ascii-only repositories."""
975
# weave repositories refuse to store revisionids that are non-ascii.
976
if revision_id is not None:
977
# weaves require ascii revision ids.
978
if isinstance(revision_id, unicode):
980
revision_id.encode('ascii')
981
except UnicodeEncodeError:
982
raise errors.NonAsciiRevisionId(method, self)
985
revision_id.decode('ascii')
986
except UnicodeDecodeError:
987
raise errors.NonAsciiRevisionId(method, self)
991
# remove these delegates a while after bzr 0.15
992
def __make_delegated(name, from_module):
993
def _deprecated_repository_forwarder():
994
symbol_versioning.warn('%s moved to %s in bzr 0.15'
995
% (name, from_module),
998
m = __import__(from_module, globals(), locals(), [name])
1000
return getattr(m, name)
1001
except AttributeError:
1002
raise AttributeError('module %s has no name %s'
1004
globals()[name] = _deprecated_repository_forwarder
1007
'AllInOneRepository',
1008
'WeaveMetaDirRepository',
1009
'PreSplitOutRepositoryFormat',
1010
'RepositoryFormat4',
1011
'RepositoryFormat5',
1012
'RepositoryFormat6',
1013
'RepositoryFormat7',
1015
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
1019
'RepositoryFormatKnit',
1020
'RepositoryFormatKnit1',
1022
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
1025
def install_revision(repository, rev, revision_tree):
1026
"""Install all revision data into a repository."""
1027
present_parents = []
1029
for p_id in rev.parent_ids:
1030
if repository.has_revision(p_id):
1031
present_parents.append(p_id)
1032
parent_trees[p_id] = repository.revision_tree(p_id)
1034
parent_trees[p_id] = repository.revision_tree(None)
1036
inv = revision_tree.inventory
1037
entries = inv.iter_entries()
1038
# backwards compatability hack: skip the root id.
1039
if not repository.supports_rich_root():
1040
path, root = entries.next()
1041
if root.revision != rev.revision_id:
1042
raise errors.IncompatibleRevision(repr(repository))
1043
# Add the texts that are not already present
1044
for path, ie in entries:
1045
w = repository.weave_store.get_weave_or_empty(ie.file_id,
1046
repository.get_transaction())
1047
if ie.revision not in w:
1049
# FIXME: TODO: The following loop *may* be overlapping/duplicate
1050
# with InventoryEntry.find_previous_heads(). if it is, then there
1051
# is a latent bug here where the parents may have ancestors of each
1053
for revision, tree in parent_trees.iteritems():
1054
if ie.file_id not in tree:
1056
parent_id = tree.inventory[ie.file_id].revision
1057
if parent_id in text_parents:
1059
text_parents.append(parent_id)
1061
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
1062
repository.get_transaction())
1063
lines = revision_tree.get_file(ie.file_id).readlines()
1064
vfile.add_lines(rev.revision_id, text_parents, lines)
1066
# install the inventory
1067
repository.add_inventory(rev.revision_id, inv, present_parents)
1068
except errors.RevisionAlreadyPresent:
1070
repository.add_revision(rev.revision_id, rev, inv)
608
raise NotImplementedError(self.set_make_working_trees)
610
def make_working_trees(self):
611
"""Returns the policy for making working trees on new branches."""
1073
615
class MetaDirRepository(Repository):
1111
654
return not self.control_files._transport.has('no-working-trees')
1114
class RepositoryFormatRegistry(registry.Registry):
1115
"""Registry of RepositoryFormats.
1118
def get(self, format_string):
1119
r = registry.Registry.get(self, format_string)
657
class KnitRepository(MetaDirRepository):
658
"""Knit format repository."""
661
def all_revision_ids(self):
662
"""See Repository.all_revision_ids()."""
663
return self._revision_store.all_revision_ids(self.get_transaction())
665
def fileid_involved_between_revs(self, from_revid, to_revid):
666
"""Find file_id(s) which are involved in the changes between revisions.
668
This determines the set of revisions which are involved, and then
669
finds all file ids affected by those revisions.
671
vf = self._get_revision_vf()
672
from_set = set(vf.get_ancestry(from_revid))
673
to_set = set(vf.get_ancestry(to_revid))
674
changed = to_set.difference(from_set)
675
return self._fileid_involved_by_set(changed)
677
def fileid_involved(self, last_revid=None):
678
"""Find all file_ids modified in the ancestry of last_revid.
680
:param last_revid: If None, last_revision() will be used.
683
changed = set(self.all_revision_ids())
685
changed = set(self.get_ancestry(last_revid))
688
return self._fileid_involved_by_set(changed)
691
def get_ancestry(self, revision_id):
692
"""Return a list of revision-ids integrated by a revision.
694
This is topologically sorted.
696
if revision_id is None:
698
vf = self._get_revision_vf()
700
return [None] + vf.get_ancestry(revision_id)
701
except errors.RevisionNotPresent:
702
raise errors.NoSuchRevision(self, revision_id)
705
def get_revision(self, revision_id):
706
"""Return the Revision object for a named revision"""
707
return self.get_revision_reconcile(revision_id)
710
def get_revision_graph(self, revision_id=None):
711
"""Return a dictionary containing the revision graph.
713
:return: a dictionary of revision_id->revision_parents_list.
715
weave = self._get_revision_vf()
716
entire_graph = weave.get_graph()
717
if revision_id is None:
718
return weave.get_graph()
719
elif revision_id not in weave:
720
raise errors.NoSuchRevision(self, revision_id)
722
# add what can be reached from revision_id
724
pending = set([revision_id])
725
while len(pending) > 0:
727
result[node] = weave.get_parents(node)
728
for revision_id in result[node]:
729
if revision_id not in result:
730
pending.add(revision_id)
734
def get_revision_graph_with_ghosts(self, revision_ids=None):
735
"""Return a graph of the revisions with ghosts marked as applicable.
737
:param revision_ids: an iterable of revisions to graph or None for all.
738
:return: a Graph object with the graph reachable from revision_ids.
741
vf = self._get_revision_vf()
742
versions = set(vf.versions())
744
pending = set(self.all_revision_ids())
747
pending = set(revision_ids)
748
required = set(revision_ids)
751
revision_id = pending.pop()
752
if not revision_id in versions:
753
if revision_id in required:
754
raise errors.NoSuchRevision(self, revision_id)
756
result.add_ghost(revision_id)
757
# mark it as done so we dont try for it again.
758
done.add(revision_id)
760
parent_ids = vf.get_parents_with_ghosts(revision_id)
761
for parent_id in parent_ids:
762
# is this queued or done ?
763
if (parent_id not in pending and
764
parent_id not in done):
766
pending.add(parent_id)
767
result.add_node(revision_id, parent_ids)
768
done.add(revision_id)
771
def _get_revision_vf(self):
772
""":return: a versioned file containing the revisions."""
773
vf = self._revision_store.get_revision_file(self.get_transaction())
777
def reconcile(self, other=None, thorough=False):
778
"""Reconcile this repository."""
779
from bzrlib.reconcile import KnitReconciler
780
reconciler = KnitReconciler(self, thorough=thorough)
781
reconciler.reconcile()
1125
format_registry = RepositoryFormatRegistry()
1126
"""Registry of formats, indexed by their identifying format string.
1128
This can contain either format instances themselves, or classes/factories that
1129
can be called to obtain one.
1133
#####################################################################
1134
# Repository Formats
784
def revision_parents(self, revid):
785
return self._get_revision_vf().get_parents(rev_id)
1136
787
class RepositoryFormat(object):
1137
788
"""A repository format.
1295
917
raise NotImplementedError(self.open)
920
def register_format(klass, format):
921
klass._formats[format.get_format_string()] = format
924
def set_default_format(klass, format):
925
klass._default_format = format
928
def unregister_format(klass, format):
929
assert klass._formats[format.get_format_string()] is format
930
del klass._formats[format.get_format_string()]
933
class PreSplitOutRepositoryFormat(RepositoryFormat):
934
"""Base class for the pre split out repository formats."""
936
def initialize(self, a_bzrdir, shared=False, _internal=False):
937
"""Create a weave repository.
939
TODO: when creating split out bzr branch formats, move this to a common
940
base for Format5, Format6. or something like that.
942
from bzrlib.weavefile import write_weave_v5
943
from bzrlib.weave import Weave
946
raise errors.IncompatibleFormat(self, a_bzrdir._format)
949
# always initialized when the bzrdir is.
950
return self.open(a_bzrdir, _found=True)
952
# Create an empty weave
954
bzrlib.weavefile.write_weave_v5(Weave(), sio)
955
empty_weave = sio.getvalue()
957
mutter('creating repository in %s.', a_bzrdir.transport.base)
958
dirs = ['revision-store', 'weaves']
959
files = [('inventory.weave', StringIO(empty_weave)),
962
# FIXME: RBC 20060125 dont peek under the covers
963
# NB: no need to escape relative paths that are url safe.
964
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock',
966
control_files.create_lock()
967
control_files.lock_write()
968
control_files._transport.mkdir_multi(dirs,
969
mode=control_files._dir_mode)
971
for file, content in files:
972
control_files.put(file, content)
974
control_files.unlock()
975
return self.open(a_bzrdir, _found=True)
977
def _get_control_store(self, repo_transport, control_files):
978
"""Return the control store for this repository."""
979
return self._get_versioned_file_store('',
984
def _get_text_store(self, transport, control_files):
985
"""Get a store for file texts for this format."""
986
raise NotImplementedError(self._get_text_store)
988
def open(self, a_bzrdir, _found=False):
989
"""See RepositoryFormat.open()."""
991
# we are being called directly and must probe.
992
raise NotImplementedError
994
repo_transport = a_bzrdir.get_repository_transport(None)
995
control_files = a_bzrdir._control_files
996
text_store = self._get_text_store(repo_transport, control_files)
997
control_store = self._get_control_store(repo_transport, control_files)
998
_revision_store = self._get_revision_store(repo_transport, control_files)
999
return AllInOneRepository(_format=self,
1001
_revision_store=_revision_store,
1002
control_store=control_store,
1003
text_store=text_store)
1006
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1007
"""Bzr repository format 4.
1009
This repository format has:
1011
- TextStores for texts, inventories,revisions.
1013
This format is deprecated: it indexes texts using a text id which is
1014
removed in format 5; initializationa and write support for this format
1019
super(RepositoryFormat4, self).__init__()
1020
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
1022
def get_format_description(self):
1023
"""See RepositoryFormat.get_format_description()."""
1024
return "Repository format 4"
1026
def initialize(self, url, shared=False, _internal=False):
1027
"""Format 4 branches cannot be created."""
1028
raise errors.UninitializableFormat(self)
1030
def is_supported(self):
1031
"""Format 4 is not supported.
1033
It is not supported because the model changed from 4 to 5 and the
1034
conversion logic is expensive - so doing it on the fly was not
1039
def _get_control_store(self, repo_transport, control_files):
1040
"""Format 4 repositories have no formal control store at this point.
1042
This will cause any control-file-needing apis to fail - this is desired.
1046
def _get_revision_store(self, repo_transport, control_files):
1047
"""See RepositoryFormat._get_revision_store()."""
1048
from bzrlib.xml4 import serializer_v4
1049
return self._get_text_rev_store(repo_transport,
1052
serializer=serializer_v4)
1054
def _get_text_store(self, transport, control_files):
1055
"""See RepositoryFormat._get_text_store()."""
1058
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1059
"""Bzr control format 5.
1061
This repository format has:
1062
- weaves for file texts and inventory
1064
- TextStores for revisions and signatures.
1068
super(RepositoryFormat5, self).__init__()
1069
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
1071
def get_format_description(self):
1072
"""See RepositoryFormat.get_format_description()."""
1073
return "Weave repository format 5"
1075
def _get_revision_store(self, repo_transport, control_files):
1076
"""See RepositoryFormat._get_revision_store()."""
1077
"""Return the revision store object for this a_bzrdir."""
1078
return self._get_text_rev_store(repo_transport,
1083
def _get_text_store(self, transport, control_files):
1084
"""See RepositoryFormat._get_text_store()."""
1085
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1088
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1089
"""Bzr control format 6.
1091
This repository format has:
1092
- weaves for file texts and inventory
1093
- hash subdirectory based stores.
1094
- TextStores for revisions and signatures.
1098
super(RepositoryFormat6, self).__init__()
1099
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
1101
def get_format_description(self):
1102
"""See RepositoryFormat.get_format_description()."""
1103
return "Weave repository format 6"
1105
def _get_revision_store(self, repo_transport, control_files):
1106
"""See RepositoryFormat._get_revision_store()."""
1107
return self._get_text_rev_store(repo_transport,
1113
def _get_text_store(self, transport, control_files):
1114
"""See RepositoryFormat._get_text_store()."""
1115
return self._get_versioned_file_store('weaves', transport, control_files)
1298
1118
class MetaDirRepositoryFormat(RepositoryFormat):
1299
"""Common base class for the new repositories using the metadir layout."""
1301
rich_root_data = False
1302
supports_tree_reference = False
1303
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1119
"""Common base class for the new repositories using the metadir layour."""
1305
1121
def __init__(self):
1306
1122
super(MetaDirRepositoryFormat, self).__init__()
1123
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
1308
1125
def _create_control_files(self, a_bzrdir):
1309
1126
"""Create the required files and the initial control_files object."""
1310
# FIXME: RBC 20060125 don't peek under the covers
1127
# FIXME: RBC 20060125 dont peek under the covers
1311
1128
# NB: no need to escape relative paths that are url safe.
1312
1129
repository_transport = a_bzrdir.get_repository_transport(self)
1313
control_files = lockable_files.LockableFiles(repository_transport,
1314
'lock', lockdir.LockDir)
1130
control_files = LockableFiles(repository_transport, 'lock', LockDir)
1315
1131
control_files.create_lock()
1316
1132
return control_files
1332
1148
control_files.unlock()
1151
class RepositoryFormat7(MetaDirRepositoryFormat):
1152
"""Bzr repository 7.
1154
This repository format has:
1155
- weaves for file texts and inventory
1156
- hash subdirectory based stores.
1157
- TextStores for revisions and signatures.
1158
- a format marker of its own
1159
- an optional 'shared-storage' flag
1160
- an optional 'no-working-trees' flag
1163
def _get_control_store(self, repo_transport, control_files):
1164
"""Return the control store for this repository."""
1165
return self._get_versioned_file_store('',
1170
def get_format_string(self):
1171
"""See RepositoryFormat.get_format_string()."""
1172
return "Bazaar-NG Repository format 7"
1174
def get_format_description(self):
1175
"""See RepositoryFormat.get_format_description()."""
1176
return "Weave repository format 7"
1178
def _get_revision_store(self, repo_transport, control_files):
1179
"""See RepositoryFormat._get_revision_store()."""
1180
return self._get_text_rev_store(repo_transport,
1187
def _get_text_store(self, transport, control_files):
1188
"""See RepositoryFormat._get_text_store()."""
1189
return self._get_versioned_file_store('weaves',
1193
def initialize(self, a_bzrdir, shared=False):
1194
"""Create a weave repository.
1196
:param shared: If true the repository will be initialized as a shared
1199
from bzrlib.weavefile import write_weave_v5
1200
from bzrlib.weave import Weave
1202
# Create an empty weave
1204
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1205
empty_weave = sio.getvalue()
1207
mutter('creating repository in %s.', a_bzrdir.transport.base)
1208
dirs = ['revision-store', 'weaves']
1209
files = [('inventory.weave', StringIO(empty_weave)),
1211
utf8_files = [('format', self.get_format_string())]
1213
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1214
return self.open(a_bzrdir=a_bzrdir, _found=True)
1216
def open(self, a_bzrdir, _found=False, _override_transport=None):
1217
"""See RepositoryFormat.open().
1219
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1220
repository at a slightly different url
1221
than normal. I.e. during 'upgrade'.
1224
format = RepositoryFormat.find_format(a_bzrdir)
1225
assert format.__class__ == self.__class__
1226
if _override_transport is not None:
1227
repo_transport = _override_transport
1229
repo_transport = a_bzrdir.get_repository_transport(None)
1230
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1231
text_store = self._get_text_store(repo_transport, control_files)
1232
control_store = self._get_control_store(repo_transport, control_files)
1233
_revision_store = self._get_revision_store(repo_transport, control_files)
1234
return MetaDirRepository(_format=self,
1236
control_files=control_files,
1237
_revision_store=_revision_store,
1238
control_store=control_store,
1239
text_store=text_store)
1242
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1243
"""Bzr repository knit format 1.
1245
This repository format has:
1246
- knits for file texts and inventory
1247
- hash subdirectory based stores.
1248
- knits for revisions and signatures
1249
- TextStores for revisions and signatures.
1250
- a format marker of its own
1251
- an optional 'shared-storage' flag
1252
- an optional 'no-working-trees' flag
1255
This format was introduced in bzr 0.8.
1258
def _get_control_store(self, repo_transport, control_files):
1259
"""Return the control store for this repository."""
1260
return VersionedFileStore(
1263
file_mode=control_files._file_mode,
1264
versionedfile_class=KnitVersionedFile,
1265
versionedfile_kwargs={'factory':KnitPlainFactory()},
1268
def get_format_string(self):
1269
"""See RepositoryFormat.get_format_string()."""
1270
return "Bazaar-NG Knit Repository Format 1"
1272
def get_format_description(self):
1273
"""See RepositoryFormat.get_format_description()."""
1274
return "Knit repository format 1"
1276
def _get_revision_store(self, repo_transport, control_files):
1277
"""See RepositoryFormat._get_revision_store()."""
1278
from bzrlib.store.revision.knit import KnitRevisionStore
1279
versioned_file_store = VersionedFileStore(
1281
file_mode=control_files._file_mode,
1284
versionedfile_class=KnitVersionedFile,
1285
versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory()},
1288
return KnitRevisionStore(versioned_file_store)
1290
def _get_text_store(self, transport, control_files):
1291
"""See RepositoryFormat._get_text_store()."""
1292
return self._get_versioned_file_store('knits',
1295
versionedfile_class=KnitVersionedFile,
1298
def initialize(self, a_bzrdir, shared=False):
1299
"""Create a knit format 1 repository.
1301
:param a_bzrdir: bzrdir to contain the new repository; must already
1303
:param shared: If true the repository will be initialized as a shared
1306
mutter('creating repository in %s.', a_bzrdir.transport.base)
1307
dirs = ['revision-store', 'knits']
1309
utf8_files = [('format', self.get_format_string())]
1311
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1312
repo_transport = a_bzrdir.get_repository_transport(None)
1313
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1314
control_store = self._get_control_store(repo_transport, control_files)
1315
transaction = bzrlib.transactions.WriteTransaction()
1316
# trigger a write of the inventory store.
1317
control_store.get_weave_or_empty('inventory', transaction)
1318
_revision_store = self._get_revision_store(repo_transport, control_files)
1319
_revision_store.has_revision_id('A', transaction)
1320
_revision_store.get_signature_file(transaction)
1321
return self.open(a_bzrdir=a_bzrdir, _found=True)
1323
def open(self, a_bzrdir, _found=False, _override_transport=None):
1324
"""See RepositoryFormat.open().
1326
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1327
repository at a slightly different url
1328
than normal. I.e. during 'upgrade'.
1331
format = RepositoryFormat.find_format(a_bzrdir)
1332
assert format.__class__ == self.__class__
1333
if _override_transport is not None:
1334
repo_transport = _override_transport
1336
repo_transport = a_bzrdir.get_repository_transport(None)
1337
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1338
text_store = self._get_text_store(repo_transport, control_files)
1339
control_store = self._get_control_store(repo_transport, control_files)
1340
_revision_store = self._get_revision_store(repo_transport, control_files)
1341
return KnitRepository(_format=self,
1343
control_files=control_files,
1344
_revision_store=_revision_store,
1345
control_store=control_store,
1346
text_store=text_store)
1335
1349
# formats which have no format string are not discoverable
1336
# and not independently creatable, so are not registered. They're
1337
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
1338
# needed, it's constructed directly by the BzrDir. Non-native formats where
1339
# the repository is not separately opened are similar.
1341
format_registry.register_lazy(
1342
'Bazaar-NG Repository format 7',
1343
'bzrlib.repofmt.weaverepo',
1346
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1347
# default control directory format
1349
format_registry.register_lazy(
1350
'Bazaar-NG Knit Repository Format 1',
1351
'bzrlib.repofmt.knitrepo',
1352
'RepositoryFormatKnit1',
1354
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1356
format_registry.register_lazy(
1357
'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
1358
'bzrlib.repofmt.knitrepo',
1359
'RepositoryFormatKnit3',
1350
# and not independently creatable, so are not registered.
1351
RepositoryFormat.register_format(RepositoryFormat7())
1352
_default_format = RepositoryFormatKnit1()
1353
RepositoryFormat.register_format(_default_format)
1354
RepositoryFormat.set_default_format(_default_format)
1355
_legacy_formats = [RepositoryFormat4(),
1356
RepositoryFormat5(),
1357
RepositoryFormat6()]
1363
1360
class InterRepository(InterObject):
1419
1468
# that we've decided we need.
1420
1469
return [rev_id for rev_id in source_ids if rev_id in result_set]
1423
class InterSameDataRepository(InterRepository):
1424
"""Code for converting between repositories that represent the same data.
1426
Data format and model must match for this to work.
1430
def _get_repo_format_to_test(self):
1431
"""Repository format for testing with."""
1432
return RepositoryFormat.get_default_format()
1435
def is_compatible(source, target):
1436
if source.supports_rich_root() != target.supports_rich_root():
1438
if source._serializer != target._serializer:
1443
def copy_content(self, revision_id=None):
1444
"""Make a complete copy of the content in self into destination.
1446
This copies both the repository's revision data, and configuration information
1447
such as the make_working_trees setting.
1449
This is a destructive operation! Do not use it on existing
1452
:param revision_id: Only copy the content needed to construct
1453
revision_id and its parents.
1472
"""Release the locks on source and target."""
1456
self.target.set_make_working_trees(self.source.make_working_trees())
1457
except NotImplementedError:
1459
# TODO: jam 20070210 This is fairly internal, so we should probably
1460
# just assert that revision_id is not unicode.
1461
revision_id = osutils.safe_revision_id(revision_id)
1462
# but don't bother fetching if we have the needed data now.
1463
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1464
self.target.has_revision(revision_id)):
1466
self.target.fetch(self.source, revision_id=revision_id)
1469
def fetch(self, revision_id=None, pb=None):
1470
"""See InterRepository.fetch()."""
1471
from bzrlib.fetch import GenericRepoFetcher
1472
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1473
self.source, self.source._format, self.target,
1474
self.target._format)
1475
# TODO: jam 20070210 This should be an assert, not a translate
1476
revision_id = osutils.safe_revision_id(revision_id)
1477
f = GenericRepoFetcher(to_repository=self.target,
1478
from_repository=self.source,
1479
last_revision=revision_id,
1481
return f.count_copied, f.failed_revisions
1484
class InterWeaveRepo(InterSameDataRepository):
1474
self.target.unlock()
1476
self.source.unlock()
1479
class InterWeaveRepo(InterRepository):
1485
1480
"""Optimised code paths between Weave based repositories."""
1488
def _get_repo_format_to_test(self):
1489
from bzrlib.repofmt import weaverepo
1490
return weaverepo.RepositoryFormat7()
1482
_matching_repo_format = RepositoryFormat7()
1483
"""Repository format for testing with."""
1493
1486
def is_compatible(source, target):
1494
1487
"""Be compatible with known Weave formats.
1496
We don't test for the stores being of specific types because that
1489
We dont test for the stores being of specific types becase that
1497
1490
could lead to confusing results, and there is no need to be
1498
1491
overly general.
1500
from bzrlib.repofmt.weaverepo import (
1506
1494
return (isinstance(source._format, (RepositoryFormat5,
1507
1495
RepositoryFormat6,
1515
1503
@needs_write_lock
1516
def copy_content(self, revision_id=None):
1504
def copy_content(self, revision_id=None, basis=None):
1517
1505
"""See InterRepository.copy_content()."""
1518
1506
# weave specific optimised path:
1519
# TODO: jam 20070210 Internal, should be an assert, not translate
1520
revision_id = osutils.safe_revision_id(revision_id)
1522
self.target.set_make_working_trees(self.source.make_working_trees())
1523
except NotImplementedError:
1525
# FIXME do not peek!
1526
if self.source.control_files._transport.listable():
1527
pb = ui.ui_factory.nested_progress_bar()
1507
if basis is not None:
1508
# copy the basis in, then fetch remaining data.
1509
basis.copy_content_into(self.target, revision_id)
1510
# the basis copy_content_into could misset this.
1529
self.target.weave_store.copy_all_ids(
1530
self.source.weave_store,
1532
from_transaction=self.source.get_transaction(),
1533
to_transaction=self.target.get_transaction())
1534
pb.update('copying inventory', 0, 1)
1535
self.target.control_weaves.copy_multi(
1536
self.source.control_weaves, ['inventory'],
1537
from_transaction=self.source.get_transaction(),
1538
to_transaction=self.target.get_transaction())
1539
self.target._revision_store.text_store.copy_all_ids(
1540
self.source._revision_store.text_store,
1512
self.target.set_make_working_trees(self.source.make_working_trees())
1513
except NotImplementedError:
1545
1515
self.target.fetch(self.source, revision_id=revision_id)
1518
self.target.set_make_working_trees(self.source.make_working_trees())
1519
except NotImplementedError:
1521
# FIXME do not peek!
1522
if self.source.control_files._transport.listable():
1523
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1525
self.target.weave_store.copy_all_ids(
1526
self.source.weave_store,
1528
from_transaction=self.source.get_transaction(),
1529
to_transaction=self.target.get_transaction())
1530
pb.update('copying inventory', 0, 1)
1531
self.target.control_weaves.copy_multi(
1532
self.source.control_weaves, ['inventory'],
1533
from_transaction=self.source.get_transaction(),
1534
to_transaction=self.target.get_transaction())
1535
self.target._revision_store.text_store.copy_all_ids(
1536
self.source._revision_store.text_store,
1541
self.target.fetch(self.source, revision_id=revision_id)
1547
1543
@needs_write_lock
1548
1544
def fetch(self, revision_id=None, pb=None):
1667
1654
# that against the revision records.
1668
1655
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1671
class InterModel1and2(InterRepository):
1674
def _get_repo_format_to_test(self):
1678
def is_compatible(source, target):
1679
if not source.supports_rich_root() and target.supports_rich_root():
1685
def fetch(self, revision_id=None, pb=None):
1686
"""See InterRepository.fetch()."""
1687
from bzrlib.fetch import Model1toKnit2Fetcher
1688
# TODO: jam 20070210 This should be an assert, not a translate
1689
revision_id = osutils.safe_revision_id(revision_id)
1690
f = Model1toKnit2Fetcher(to_repository=self.target,
1691
from_repository=self.source,
1692
last_revision=revision_id,
1694
return f.count_copied, f.failed_revisions
1697
def copy_content(self, revision_id=None):
1698
"""Make a complete copy of the content in self into destination.
1700
This is a destructive operation! Do not use it on existing
1703
:param revision_id: Only copy the content needed to construct
1704
revision_id and its parents.
1707
self.target.set_make_working_trees(self.source.make_working_trees())
1708
except NotImplementedError:
1710
# TODO: jam 20070210 Internal, assert, don't translate
1711
revision_id = osutils.safe_revision_id(revision_id)
1712
# but don't bother fetching if we have the needed data now.
1713
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1714
self.target.has_revision(revision_id)):
1716
self.target.fetch(self.source, revision_id=revision_id)
1719
class InterKnit1and2(InterKnitRepo):
1722
def _get_repo_format_to_test(self):
1726
def is_compatible(source, target):
1727
"""Be compatible with Knit1 source and Knit3 target"""
1728
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
1730
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1731
RepositoryFormatKnit3
1732
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1733
isinstance(target._format, (RepositoryFormatKnit3)))
1734
except AttributeError:
1738
def fetch(self, revision_id=None, pb=None):
1739
"""See InterRepository.fetch()."""
1740
from bzrlib.fetch import Knit1to2Fetcher
1741
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1742
self.source, self.source._format, self.target,
1743
self.target._format)
1744
# TODO: jam 20070210 This should be an assert, not a translate
1745
revision_id = osutils.safe_revision_id(revision_id)
1746
f = Knit1to2Fetcher(to_repository=self.target,
1747
from_repository=self.source,
1748
last_revision=revision_id,
1750
return f.count_copied, f.failed_revisions
1753
class InterRemoteRepository(InterRepository):
1754
"""Code for converting between RemoteRepository objects.
1756
This just gets an non-remote repository from the RemoteRepository, and calls
1757
InterRepository.get again.
1760
def __init__(self, source, target):
1761
if isinstance(source, remote.RemoteRepository):
1762
source._ensure_real()
1763
real_source = source._real_repository
1765
real_source = source
1766
if isinstance(target, remote.RemoteRepository):
1767
target._ensure_real()
1768
real_target = target._real_repository
1770
real_target = target
1771
self.real_inter = InterRepository.get(real_source, real_target)
1774
def is_compatible(source, target):
1775
if isinstance(source, remote.RemoteRepository):
1777
if isinstance(target, remote.RemoteRepository):
1781
def copy_content(self, revision_id=None):
1782
self.real_inter.copy_content(revision_id=revision_id)
1784
def fetch(self, revision_id=None, pb=None):
1785
self.real_inter.fetch(revision_id=revision_id, pb=pb)
1788
def _get_repo_format_to_test(self):
1792
InterRepository.register_optimiser(InterSameDataRepository)
1793
1657
InterRepository.register_optimiser(InterWeaveRepo)
1794
1658
InterRepository.register_optimiser(InterKnitRepo)
1795
InterRepository.register_optimiser(InterModel1and2)
1796
InterRepository.register_optimiser(InterKnit1and2)
1797
InterRepository.register_optimiser(InterRemoteRepository)
1661
class RepositoryTestProviderAdapter(object):
1662
"""A tool to generate a suite testing multiple repository formats at once.
1664
This is done by copying the test once for each transport and injecting
1665
the transport_server, transport_readonly_server, and bzrdir_format and
1666
repository_format classes into each copy. Each copy is also given a new id()
1667
to make it easy to identify.
1670
def __init__(self, transport_server, transport_readonly_server, formats):
1671
self._transport_server = transport_server
1672
self._transport_readonly_server = transport_readonly_server
1673
self._formats = formats
1675
def adapt(self, test):
1676
result = TestSuite()
1677
for repository_format, bzrdir_format in self._formats:
1678
new_test = deepcopy(test)
1679
new_test.transport_server = self._transport_server
1680
new_test.transport_readonly_server = self._transport_readonly_server
1681
new_test.bzrdir_format = bzrdir_format
1682
new_test.repository_format = repository_format
1683
def make_new_test_id():
1684
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1685
return lambda: new_id
1686
new_test.id = make_new_test_id()
1687
result.addTest(new_test)
1691
class InterRepositoryTestProviderAdapter(object):
1692
"""A tool to generate a suite testing multiple inter repository formats.
1694
This is done by copying the test once for each interrepo provider and injecting
1695
the transport_server, transport_readonly_server, repository_format and
1696
repository_to_format classes into each copy.
1697
Each copy is also given a new id() to make it easy to identify.
1700
def __init__(self, transport_server, transport_readonly_server, formats):
1701
self._transport_server = transport_server
1702
self._transport_readonly_server = transport_readonly_server
1703
self._formats = formats
1705
def adapt(self, test):
1706
result = TestSuite()
1707
for interrepo_class, repository_format, repository_format_to in self._formats:
1708
new_test = deepcopy(test)
1709
new_test.transport_server = self._transport_server
1710
new_test.transport_readonly_server = self._transport_readonly_server
1711
new_test.interrepo_class = interrepo_class
1712
new_test.repository_format = repository_format
1713
new_test.repository_format_to = repository_format_to
1714
def make_new_test_id():
1715
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1716
return lambda: new_id
1717
new_test.id = make_new_test_id()
1718
result.addTest(new_test)
1722
def default_test_list():
1723
"""Generate the default list of interrepo permutations to test."""
1725
# test the default InterRepository between format 6 and the current
1727
# XXX: robertc 20060220 reinstate this when there are two supported
1728
# formats which do not have an optimal code path between them.
1729
result.append((InterRepository,
1730
RepositoryFormat6(),
1731
RepositoryFormatKnit1()))
1732
for optimiser in InterRepository._optimisers:
1733
result.append((optimiser,
1734
optimiser._matching_repo_format,
1735
optimiser._matching_repo_format
1737
# if there are specific combinations we want to use, we can add them
1800
1742
class CopyConverter(object):
1849
1790
self.pb.update(message, self.count, self.total)
1852
class CommitBuilder(object):
1853
"""Provides an interface to build up a commit.
1855
This allows describing a tree to be committed without needing to
1856
know the internals of the format of the repository.
1859
record_root_entry = False
1860
def __init__(self, repository, parents, config, timestamp=None,
1861
timezone=None, committer=None, revprops=None,
1863
"""Initiate a CommitBuilder.
1865
:param repository: Repository to commit to.
1866
:param parents: Revision ids of the parents of the new revision.
1867
:param config: Configuration to use.
1868
:param timestamp: Optional timestamp recorded for commit.
1869
:param timezone: Optional timezone for timestamp.
1870
:param committer: Optional committer to set for commit.
1871
:param revprops: Optional dictionary of revision properties.
1872
:param revision_id: Optional revision id.
1874
self._config = config
1876
if committer is None:
1877
self._committer = self._config.username()
1879
assert isinstance(committer, basestring), type(committer)
1880
self._committer = committer
1882
self.new_inventory = Inventory(None)
1883
self._new_revision_id = osutils.safe_revision_id(revision_id)
1884
self.parents = parents
1885
self.repository = repository
1888
if revprops is not None:
1889
self._revprops.update(revprops)
1891
if timestamp is None:
1892
timestamp = time.time()
1893
# Restrict resolution to 1ms
1894
self._timestamp = round(timestamp, 3)
1896
if timezone is None:
1897
self._timezone = osutils.local_time_offset()
1899
self._timezone = int(timezone)
1901
self._generate_revision_if_needed()
1903
def commit(self, message):
1904
"""Make the actual commit.
1906
:return: The revision id of the recorded revision.
1908
rev = _mod_revision.Revision(
1909
timestamp=self._timestamp,
1910
timezone=self._timezone,
1911
committer=self._committer,
1913
inventory_sha1=self.inv_sha1,
1914
revision_id=self._new_revision_id,
1915
properties=self._revprops)
1916
rev.parent_ids = self.parents
1917
self.repository.add_revision(self._new_revision_id, rev,
1918
self.new_inventory, self._config)
1919
return self._new_revision_id
1921
def revision_tree(self):
1922
"""Return the tree that was just committed.
1924
After calling commit() this can be called to get a RevisionTree
1925
representing the newly committed tree. This is preferred to
1926
calling Repository.revision_tree() because that may require
1927
deserializing the inventory, while we already have a copy in
1930
return RevisionTree(self.repository, self.new_inventory,
1931
self._new_revision_id)
1933
def finish_inventory(self):
1934
"""Tell the builder that the inventory is finished."""
1935
if self.new_inventory.root is None:
1936
symbol_versioning.warn('Root entry should be supplied to'
1937
' record_entry_contents, as of bzr 0.10.',
1938
DeprecationWarning, stacklevel=2)
1939
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1940
self.new_inventory.revision_id = self._new_revision_id
1941
self.inv_sha1 = self.repository.add_inventory(
1942
self._new_revision_id,
1947
def _gen_revision_id(self):
1948
"""Return new revision-id."""
1949
return generate_ids.gen_revision_id(self._config.username(),
1952
def _generate_revision_if_needed(self):
1953
"""Create a revision id if None was supplied.
1955
If the repository can not support user-specified revision ids
1956
they should override this function and raise CannotSetRevisionId
1957
if _new_revision_id is not None.
1959
:raises: CannotSetRevisionId
1961
if self._new_revision_id is None:
1962
self._new_revision_id = self._gen_revision_id()
1964
def record_entry_contents(self, ie, parent_invs, path, tree):
1965
"""Record the content of ie from tree into the commit if needed.
1967
Side effect: sets ie.revision when unchanged
1969
:param ie: An inventory entry present in the commit.
1970
:param parent_invs: The inventories of the parent revisions of the
1972
:param path: The path the entry is at in the tree.
1973
:param tree: The tree which contains this entry and should be used to
1976
if self.new_inventory.root is None and ie.parent_id is not None:
1977
symbol_versioning.warn('Root entry should be supplied to'
1978
' record_entry_contents, as of bzr 0.10.',
1979
DeprecationWarning, stacklevel=2)
1980
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
1982
self.new_inventory.add(ie)
1984
# ie.revision is always None if the InventoryEntry is considered
1985
# for committing. ie.snapshot will record the correct revision
1986
# which may be the sole parent if it is untouched.
1987
if ie.revision is not None:
1990
# In this revision format, root entries have no knit or weave
1991
if ie is self.new_inventory.root:
1992
# When serializing out to disk and back in
1993
# root.revision is always _new_revision_id
1994
ie.revision = self._new_revision_id
1996
previous_entries = ie.find_previous_heads(
1998
self.repository.weave_store,
1999
self.repository.get_transaction())
2000
# we are creating a new revision for ie in the history store
2002
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2004
def modified_directory(self, file_id, file_parents):
2005
"""Record the presence of a symbolic link.
2007
:param file_id: The file_id of the link to record.
2008
:param file_parents: The per-file parent revision ids.
2010
self._add_text_to_weave(file_id, [], file_parents.keys())
2012
def modified_reference(self, file_id, file_parents):
2013
"""Record the modification of a reference.
2015
:param file_id: The file_id of the link to record.
2016
:param file_parents: The per-file parent revision ids.
2018
self._add_text_to_weave(file_id, [], file_parents.keys())
2020
def modified_file_text(self, file_id, file_parents,
2021
get_content_byte_lines, text_sha1=None,
2023
"""Record the text of file file_id
2025
:param file_id: The file_id of the file to record the text of.
2026
:param file_parents: The per-file parent revision ids.
2027
:param get_content_byte_lines: A callable which will return the byte
2029
:param text_sha1: Optional SHA1 of the file contents.
2030
:param text_size: Optional size of the file contents.
2032
# mutter('storing text of file {%s} in revision {%s} into %r',
2033
# file_id, self._new_revision_id, self.repository.weave_store)
2034
# special case to avoid diffing on renames or
2036
if (len(file_parents) == 1
2037
and text_sha1 == file_parents.values()[0].text_sha1
2038
and text_size == file_parents.values()[0].text_size):
2039
previous_ie = file_parents.values()[0]
2040
versionedfile = self.repository.weave_store.get_weave(file_id,
2041
self.repository.get_transaction())
2042
versionedfile.clone_text(self._new_revision_id,
2043
previous_ie.revision, file_parents.keys())
2044
return text_sha1, text_size
2046
new_lines = get_content_byte_lines()
2047
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2048
# should return the SHA1 and size
2049
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2050
return osutils.sha_strings(new_lines), \
2051
sum(map(len, new_lines))
2053
def modified_link(self, file_id, file_parents, link_target):
2054
"""Record the presence of a symbolic link.
2056
:param file_id: The file_id of the link to record.
2057
:param file_parents: The per-file parent revision ids.
2058
:param link_target: Target location of this link.
2060
self._add_text_to_weave(file_id, [], file_parents.keys())
2062
def _add_text_to_weave(self, file_id, new_lines, parents):
2063
versionedfile = self.repository.weave_store.get_weave_or_empty(
2064
file_id, self.repository.get_transaction())
2065
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2066
versionedfile.clear_cache()
2069
class _CommitBuilder(CommitBuilder):
2070
"""Temporary class so old CommitBuilders are detected properly
2072
Note: CommitBuilder works whether or not root entry is recorded.
2075
record_root_entry = True
2078
class RootCommitBuilder(CommitBuilder):
2079
"""This commitbuilder actually records the root id"""
2081
record_root_entry = True
2083
def record_entry_contents(self, ie, parent_invs, path, tree):
2084
"""Record the content of ie from tree into the commit if needed.
2086
Side effect: sets ie.revision when unchanged
2088
:param ie: An inventory entry present in the commit.
2089
:param parent_invs: The inventories of the parent revisions of the
2091
:param path: The path the entry is at in the tree.
2092
:param tree: The tree which contains this entry and should be used to
2095
assert self.new_inventory.root is not None or ie.parent_id is None
2096
self.new_inventory.add(ie)
2098
# ie.revision is always None if the InventoryEntry is considered
2099
# for committing. ie.snapshot will record the correct revision
2100
# which may be the sole parent if it is untouched.
2101
if ie.revision is not None:
2104
previous_entries = ie.find_previous_heads(
2106
self.repository.weave_store,
2107
self.repository.get_transaction())
2108
# we are creating a new revision for ie in the history store
2110
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2122
def _unescaper(match, _map=_unescape_map):
2123
code = match.group(1)
2127
if not code.startswith('#'):
2129
return unichr(int(code[1:])).encode('utf8')
1793
# Copied from xml.sax.saxutils
2135
1794
def _unescape_xml(data):
2136
"""Unescape predefined XML entities in a string of data."""
2138
if _unescape_re is None:
2139
_unescape_re = re.compile('\&([^;]*);')
2140
return _unescape_re.sub(_unescaper, data)
1795
"""Unescape &, <, and > in a string of data.
1797
data = data.replace("<", "<")
1798
data = data.replace(">", ">")
1799
# must do ampersand last
1800
return data.replace("&", "&")