1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
from cStringIO import StringIO
19
from bzrlib.lazy_import import lazy_import
20
lazy_import(globals(), """
21
from binascii import hexlify
22
from copy import deepcopy
41
revision as _mod_revision,
50
from bzrlib.osutils import (
55
from bzrlib.revisiontree import RevisionTree
56
from bzrlib.store.versioned import VersionedFileStore
57
from bzrlib.store.text import TextStore
58
from bzrlib.testament import Testament
61
from bzrlib.decorators import needs_read_lock, needs_write_lock
62
from bzrlib.inter import InterObject
63
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
64
from bzrlib.symbol_versioning import (
68
from bzrlib.trace import mutter, note, warning
71
# Old formats display a warning, but only once
72
_deprecation_warning_done = False
75
class Repository(object):
76
"""Repository holding history for one or more branches.
78
The repository holds and retrieves historical information including
79
revisions and file history. It's normally accessed only by the Branch,
80
which views a particular line of development through that history.
82
The Repository builds on top of Stores and a Transport, which respectively
83
describe the disk data format and the way of accessing the (possibly
87
_file_ids_altered_regex = lazy_regex.lazy_compile(
88
r'file_id="(?P<file_id>[^"]+)"'
89
r'.*revision="(?P<revision_id>[^"]+)"'
93
def add_inventory(self, revid, inv, parents):
94
"""Add the inventory inv to the repository as revid.
96
:param parents: The revision ids of the parents that revid
97
is known to have and are in the repository already.
99
returns the sha1 of the serialized inventory.
101
_mod_revision.check_not_reserved_id(revid)
102
assert inv.revision_id is None or inv.revision_id == revid, \
103
"Mismatch between inventory revision" \
104
" id and insertion revid (%r, %r)" % (inv.revision_id, revid)
105
assert inv.root is not None
106
inv_text = self.serialise_inventory(inv)
107
inv_sha1 = osutils.sha_string(inv_text)
108
inv_vf = self.control_weaves.get_weave('inventory',
109
self.get_transaction())
110
self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
113
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
115
for parent in parents:
117
final_parents.append(parent)
119
inv_vf.add_lines(revid, final_parents, lines)
122
def add_revision(self, rev_id, rev, inv=None, config=None):
123
"""Add rev to the revision store as rev_id.
125
:param rev_id: the revision id to use.
126
:param rev: The revision object.
127
:param inv: The inventory for the revision. if None, it will be looked
128
up in the inventory storer
129
:param config: If None no digital signature will be created.
130
If supplied its signature_needed method will be used
131
to determine if a signature should be made.
133
_mod_revision.check_not_reserved_id(rev_id)
134
if config is not None and config.signature_needed():
136
inv = self.get_inventory(rev_id)
137
plaintext = Testament(rev, inv).as_short_text()
138
self.store_revision_signature(
139
gpg.GPGStrategy(config), plaintext, rev_id)
140
if not rev_id in self.get_inventory_weave():
142
raise errors.WeaveRevisionNotPresent(rev_id,
143
self.get_inventory_weave())
145
# yes, this is not suitable for adding with ghosts.
146
self.add_inventory(rev_id, inv, rev.parent_ids)
147
self._revision_store.add_revision(rev, self.get_transaction())
150
def _all_possible_ids(self):
151
"""Return all the possible revisions that we could find."""
152
return self.get_inventory_weave().versions()
154
def all_revision_ids(self):
155
"""Returns a list of all the revision ids in the repository.
157
This is deprecated because code should generally work on the graph
158
reachable from a particular revision, and ignore any other revisions
159
that might be present. There is no direct replacement method.
161
return self._all_revision_ids()
164
def _all_revision_ids(self):
165
"""Returns a list of all the revision ids in the repository.
167
These are in as much topological order as the underlying store can
168
present: for weaves ghosts may lead to a lack of correctness until
169
the reweave updates the parents list.
171
if self._revision_store.text_store.listable():
172
return self._revision_store.all_revision_ids(self.get_transaction())
173
result = self._all_possible_ids()
174
return self._eliminate_revisions_not_present(result)
176
def break_lock(self):
177
"""Break a lock if one is present from another instance.
179
Uses the ui factory to ask for confirmation if the lock may be from
182
self.control_files.break_lock()
185
def _eliminate_revisions_not_present(self, revision_ids):
186
"""Check every revision id in revision_ids to see if we have it.
188
Returns a set of the present revisions.
191
for id in revision_ids:
192
if self.has_revision(id):
197
def create(a_bzrdir):
198
"""Construct the current default format repository in a_bzrdir."""
199
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
201
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
202
"""instantiate a Repository.
204
:param _format: The format of the repository on disk.
205
:param a_bzrdir: The BzrDir of the repository.
207
In the future we will have a single api for all stores for
208
getting file texts, inventories and revisions, then
209
this construct will accept instances of those things.
211
super(Repository, self).__init__()
212
self._format = _format
213
# the following are part of the public API for Repository:
214
self.bzrdir = a_bzrdir
215
self.control_files = control_files
216
self._revision_store = _revision_store
217
self.text_store = text_store
218
# backwards compatibility
219
self.weave_store = text_store
220
# not right yet - should be more semantically clear ?
222
self.control_store = control_store
223
self.control_weaves = control_store
224
# TODO: make sure to construct the right store classes, etc, depending
225
# on whether escaping is required.
226
self._warn_if_deprecated()
227
self._serializer = xml5.serializer_v5
230
return '%s(%r)' % (self.__class__.__name__,
231
self.bzrdir.transport.base)
234
return self.control_files.is_locked()
236
def lock_write(self):
237
self.control_files.lock_write()
240
self.control_files.lock_read()
242
def get_physical_lock_status(self):
243
return self.control_files.get_physical_lock_status()
246
def gather_stats(self, revid=None, committers=None):
247
"""Gather statistics from a revision id.
249
:param revid: The revision id to gather statistics from, if None, then
250
no revision specific statistics are gathered.
251
:param committers: Optional parameter controlling whether to grab
252
a count of committers from the revision specific statistics.
253
:return: A dictionary of statistics. Currently this contains:
254
committers: The number of committers if requested.
255
firstrev: A tuple with timestamp, timezone for the penultimate left
256
most ancestor of revid, if revid is not the NULL_REVISION.
257
latestrev: A tuple with timestamp, timezone for revid, if revid is
258
not the NULL_REVISION.
259
revisions: The total revision count in the repository.
260
size: An estimate disk size of the repository in bytes.
263
if revid and committers:
264
result['committers'] = 0
265
if revid and revid != _mod_revision.NULL_REVISION:
267
all_committers = set()
268
revisions = self.get_ancestry(revid)
269
# pop the leading None
271
first_revision = None
273
# ignore the revisions in the middle - just grab first and last
274
revisions = revisions[0], revisions[-1]
275
for revision in self.get_revisions(revisions):
276
if not first_revision:
277
first_revision = revision
279
all_committers.add(revision.committer)
280
last_revision = revision
282
result['committers'] = len(all_committers)
283
result['firstrev'] = (first_revision.timestamp,
284
first_revision.timezone)
285
result['latestrev'] = (last_revision.timestamp,
286
last_revision.timezone)
288
# now gather global repository information
289
if self.bzrdir.root_transport.listable():
290
c, t = self._revision_store.total_size(self.get_transaction())
291
result['revisions'] = c
296
def missing_revision_ids(self, other, revision_id=None):
297
"""Return the revision ids that other has that this does not.
299
These are returned in topological order.
301
revision_id: only return revision ids included by revision_id.
303
return InterRepository.get(other, self).missing_revision_ids(revision_id)
307
"""Open the repository rooted at base.
309
For instance, if the repository is at URL/.bzr/repository,
310
Repository.open(URL) -> a Repository instance.
312
control = bzrdir.BzrDir.open(base)
313
return control.open_repository()
315
def copy_content_into(self, destination, revision_id=None, basis=None):
316
"""Make a complete copy of the content in self into destination.
318
This is a destructive operation! Do not use it on existing
321
return InterRepository.get(self, destination).copy_content(revision_id, basis)
323
def fetch(self, source, revision_id=None, pb=None):
324
"""Fetch the content required to construct revision_id from source.
326
If revision_id is None all content is copied.
328
return InterRepository.get(source, self).fetch(revision_id=revision_id,
331
def get_commit_builder(self, branch, parents, config, timestamp=None,
332
timezone=None, committer=None, revprops=None,
334
"""Obtain a CommitBuilder for this repository.
336
:param branch: Branch to commit to.
337
:param parents: Revision ids of the parents of the new revision.
338
:param config: Configuration to use.
339
:param timestamp: Optional timestamp recorded for commit.
340
:param timezone: Optional timezone for timestamp.
341
:param committer: Optional committer to set for commit.
342
:param revprops: Optional dictionary of revision properties.
343
:param revision_id: Optional revision id.
345
return _CommitBuilder(self, parents, config, timestamp, timezone,
346
committer, revprops, revision_id)
349
self.control_files.unlock()
352
def clone(self, a_bzrdir, revision_id=None, basis=None):
353
"""Clone this repository into a_bzrdir using the current format.
355
Currently no check is made that the format of this repository and
356
the bzrdir format are compatible. FIXME RBC 20060201.
358
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
359
# use target default format.
360
result = a_bzrdir.create_repository()
361
# FIXME RBC 20060209 split out the repository type to avoid this check ?
362
elif isinstance(a_bzrdir._format,
363
(bzrdir.BzrDirFormat4,
364
bzrdir.BzrDirFormat5,
365
bzrdir.BzrDirFormat6)):
366
result = a_bzrdir.open_repository()
368
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
369
self.copy_content_into(result, revision_id, basis)
373
def has_revision(self, revision_id):
374
"""True if this repository has a copy of the revision."""
375
return self._revision_store.has_revision_id(revision_id,
376
self.get_transaction())
379
def get_revision_reconcile(self, revision_id):
380
"""'reconcile' helper routine that allows access to a revision always.
382
This variant of get_revision does not cross check the weave graph
383
against the revision one as get_revision does: but it should only
384
be used by reconcile, or reconcile-alike commands that are correcting
385
or testing the revision graph.
387
if not revision_id or not isinstance(revision_id, basestring):
388
raise errors.InvalidRevisionId(revision_id=revision_id,
390
return self._revision_store.get_revisions([revision_id],
391
self.get_transaction())[0]
393
def get_revisions(self, revision_ids):
394
return self._revision_store.get_revisions(revision_ids,
395
self.get_transaction())
398
def get_revision_xml(self, revision_id):
399
rev = self.get_revision(revision_id)
401
# the current serializer..
402
self._revision_store._serializer.write_revision(rev, rev_tmp)
404
return rev_tmp.getvalue()
407
def get_revision(self, revision_id):
408
"""Return the Revision object for a named revision"""
409
r = self.get_revision_reconcile(revision_id)
410
# weave corruption can lead to absent revision markers that should be
412
# the following test is reasonably cheap (it needs a single weave read)
413
# and the weave is cached in read transactions. In write transactions
414
# it is not cached but typically we only read a small number of
415
# revisions. For knits when they are introduced we will probably want
416
# to ensure that caching write transactions are in use.
417
inv = self.get_inventory_weave()
418
self._check_revision_parents(r, inv)
422
def get_deltas_for_revisions(self, revisions):
423
"""Produce a generator of revision deltas.
425
Note that the input is a sequence of REVISIONS, not revision_ids.
426
Trees will be held in memory until the generator exits.
427
Each delta is relative to the revision's lefthand predecessor.
429
required_trees = set()
430
for revision in revisions:
431
required_trees.add(revision.revision_id)
432
required_trees.update(revision.parent_ids[:1])
433
trees = dict((t.get_revision_id(), t) for
434
t in self.revision_trees(required_trees))
435
for revision in revisions:
436
if not revision.parent_ids:
437
old_tree = self.revision_tree(None)
439
old_tree = trees[revision.parent_ids[0]]
440
yield trees[revision.revision_id].changes_from(old_tree)
443
def get_revision_delta(self, revision_id):
444
"""Return the delta for one revision.
446
The delta is relative to the left-hand predecessor of the
449
r = self.get_revision(revision_id)
450
return list(self.get_deltas_for_revisions([r]))[0]
452
def _check_revision_parents(self, revision, inventory):
453
"""Private to Repository and Fetch.
455
This checks the parentage of revision in an inventory weave for
456
consistency and is only applicable to inventory-weave-for-ancestry
457
using repository formats & fetchers.
459
weave_parents = inventory.get_parents(revision.revision_id)
460
weave_names = inventory.versions()
461
for parent_id in revision.parent_ids:
462
if parent_id in weave_names:
463
# this parent must not be a ghost.
464
if not parent_id in weave_parents:
466
raise errors.CorruptRepository(self)
469
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
470
signature = gpg_strategy.sign(plaintext)
471
self._revision_store.add_revision_signature_text(revision_id,
473
self.get_transaction())
475
def fileids_altered_by_revision_ids(self, revision_ids):
476
"""Find the file ids and versions affected by revisions.
478
:param revisions: an iterable containing revision ids.
479
:return: a dictionary mapping altered file-ids to an iterable of
480
revision_ids. Each altered file-ids has the exact revision_ids that
481
altered it listed explicitly.
483
assert self._serializer.support_altered_by_hack, \
484
("fileids_altered_by_revision_ids only supported for branches "
485
"which store inventory as unnested xml, not on %r" % self)
486
selected_revision_ids = set(revision_ids)
487
w = self.get_inventory_weave()
490
# this code needs to read every new line in every inventory for the
491
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
492
# not present in one of those inventories is unnecessary but not
493
# harmful because we are filtering by the revision id marker in the
494
# inventory lines : we only select file ids altered in one of those
495
# revisions. We don't need to see all lines in the inventory because
496
# only those added in an inventory in rev X can contain a revision=X
498
unescape_revid_cache = {}
499
unescape_fileid_cache = {}
501
# jam 20061218 In a big fetch, this handles hundreds of thousands
502
# of lines, so it has had a lot of inlining and optimizing done.
503
# Sorry that it is a little bit messy.
504
# Move several functions to be local variables, since this is a long
506
search = self._file_ids_altered_regex.search
507
unescape = _unescape_xml
508
setdefault = result.setdefault
509
pb = ui.ui_factory.nested_progress_bar()
511
for line in w.iter_lines_added_or_present_in_versions(
512
selected_revision_ids, pb=pb):
516
# One call to match.group() returning multiple items is quite a
517
# bit faster than 2 calls to match.group() each returning 1
518
file_id, revision_id = match.group('file_id', 'revision_id')
520
# Inlining the cache lookups helps a lot when you make 170,000
521
# lines and 350k ids, versus 8.4 unique ids.
522
# Using a cache helps in 2 ways:
523
# 1) Avoids unnecessary decoding calls
524
# 2) Re-uses cached strings, which helps in future set and
526
# (2) is enough that removing encoding entirely along with
527
# the cache (so we are using plain strings) results in no
528
# performance improvement.
530
revision_id = unescape_revid_cache[revision_id]
532
unescaped = unescape(revision_id)
533
unescape_revid_cache[revision_id] = unescaped
534
revision_id = unescaped
536
if revision_id in selected_revision_ids:
538
file_id = unescape_fileid_cache[file_id]
540
unescaped = unescape(file_id)
541
unescape_fileid_cache[file_id] = unescaped
543
setdefault(file_id, set()).add(revision_id)
549
def get_inventory_weave(self):
550
return self.control_weaves.get_weave('inventory',
551
self.get_transaction())
554
def get_inventory(self, revision_id):
555
"""Get Inventory object by hash."""
556
return self.deserialise_inventory(
557
revision_id, self.get_inventory_xml(revision_id))
559
def deserialise_inventory(self, revision_id, xml):
560
"""Transform the xml into an inventory object.
562
:param revision_id: The expected revision id of the inventory.
563
:param xml: A serialised inventory.
565
result = self._serializer.read_inventory_from_string(xml)
566
result.root.revision = revision_id
569
def serialise_inventory(self, inv):
570
return self._serializer.write_inventory_to_string(inv)
573
def get_inventory_xml(self, revision_id):
574
"""Get inventory XML as a file object."""
576
assert isinstance(revision_id, basestring), type(revision_id)
577
iw = self.get_inventory_weave()
578
return iw.get_text(revision_id)
580
raise errors.HistoryMissing(self, 'inventory', revision_id)
583
def get_inventory_sha1(self, revision_id):
584
"""Return the sha1 hash of the inventory entry
586
return self.get_revision(revision_id).inventory_sha1
589
def get_revision_graph(self, revision_id=None):
590
"""Return a dictionary containing the revision graph.
592
:param revision_id: The revision_id to get a graph from. If None, then
593
the entire revision graph is returned. This is a deprecated mode of
594
operation and will be removed in the future.
595
:return: a dictionary of revision_id->revision_parents_list.
597
# special case NULL_REVISION
598
if revision_id == _mod_revision.NULL_REVISION:
600
a_weave = self.get_inventory_weave()
601
all_revisions = self._eliminate_revisions_not_present(
603
entire_graph = dict([(node, a_weave.get_parents(node)) for
604
node in all_revisions])
605
if revision_id is None:
607
elif revision_id not in entire_graph:
608
raise errors.NoSuchRevision(self, revision_id)
610
# add what can be reached from revision_id
612
pending = set([revision_id])
613
while len(pending) > 0:
615
result[node] = entire_graph[node]
616
for revision_id in result[node]:
617
if revision_id not in result:
618
pending.add(revision_id)
622
def get_revision_graph_with_ghosts(self, revision_ids=None):
623
"""Return a graph of the revisions with ghosts marked as applicable.
625
:param revision_ids: an iterable of revisions to graph or None for all.
626
:return: a Graph object with the graph reachable from revision_ids.
628
result = graph.Graph()
630
pending = set(self.all_revision_ids())
633
pending = set(revision_ids)
634
# special case NULL_REVISION
635
if _mod_revision.NULL_REVISION in pending:
636
pending.remove(_mod_revision.NULL_REVISION)
637
required = set(pending)
640
revision_id = pending.pop()
642
rev = self.get_revision(revision_id)
643
except errors.NoSuchRevision:
644
if revision_id in required:
647
result.add_ghost(revision_id)
649
for parent_id in rev.parent_ids:
650
# is this queued or done ?
651
if (parent_id not in pending and
652
parent_id not in done):
654
pending.add(parent_id)
655
result.add_node(revision_id, rev.parent_ids)
656
done.add(revision_id)
660
def get_revision_inventory(self, revision_id):
661
"""Return inventory of a past revision."""
662
# TODO: Unify this with get_inventory()
663
# bzr 0.0.6 and later imposes the constraint that the inventory_id
664
# must be the same as its revision, so this is trivial.
665
if revision_id is None:
666
# This does not make sense: if there is no revision,
667
# then it is the current tree inventory surely ?!
668
# and thus get_root_id() is something that looks at the last
669
# commit on the branch, and the get_root_id is an inventory check.
670
raise NotImplementedError
671
# return Inventory(self.get_root_id())
673
return self.get_inventory(revision_id)
677
"""Return True if this repository is flagged as a shared repository."""
678
raise NotImplementedError(self.is_shared)
681
def reconcile(self, other=None, thorough=False):
682
"""Reconcile this repository."""
683
from bzrlib.reconcile import RepoReconciler
684
reconciler = RepoReconciler(self, thorough=thorough)
685
reconciler.reconcile()
689
def revision_tree(self, revision_id):
690
"""Return Tree for a revision on this branch.
692
`revision_id` may be None for the empty tree revision.
694
# TODO: refactor this to use an existing revision object
695
# so we don't need to read it in twice.
696
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
697
return RevisionTree(self, Inventory(root_id=None),
698
_mod_revision.NULL_REVISION)
700
inv = self.get_revision_inventory(revision_id)
701
return RevisionTree(self, inv, revision_id)
704
def revision_trees(self, revision_ids):
705
"""Return Tree for a revision on this branch.
707
`revision_id` may not be None or 'null:'"""
708
assert None not in revision_ids
709
assert _mod_revision.NULL_REVISION not in revision_ids
710
texts = self.get_inventory_weave().get_texts(revision_ids)
711
for text, revision_id in zip(texts, revision_ids):
712
inv = self.deserialise_inventory(revision_id, text)
713
yield RevisionTree(self, inv, revision_id)
716
def get_ancestry(self, revision_id):
717
"""Return a list of revision-ids integrated by a revision.
719
The first element of the list is always None, indicating the origin
720
revision. This might change when we have history horizons, or
721
perhaps we should have a new API.
723
This is topologically sorted.
725
if revision_id is None:
727
if not self.has_revision(revision_id):
728
raise errors.NoSuchRevision(self, revision_id)
729
w = self.get_inventory_weave()
730
candidates = w.get_ancestry(revision_id)
731
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
734
def print_file(self, file, revision_id):
735
"""Print `file` to stdout.
737
FIXME RBC 20060125 as John Meinel points out this is a bad api
738
- it writes to stdout, it assumes that that is valid etc. Fix
739
by creating a new more flexible convenience function.
741
tree = self.revision_tree(revision_id)
742
# use inventory as it was in that revision
743
file_id = tree.inventory.path2id(file)
745
# TODO: jam 20060427 Write a test for this code path
746
# it had a bug in it, and was raising the wrong
748
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
749
tree.print_file(file_id)
751
def get_transaction(self):
752
return self.control_files.get_transaction()
754
def revision_parents(self, revid):
755
return self.get_inventory_weave().parent_names(revid)
758
def set_make_working_trees(self, new_value):
759
"""Set the policy flag for making working trees when creating branches.
761
This only applies to branches that use this repository.
763
The default is 'True'.
764
:param new_value: True to restore the default, False to disable making
767
raise NotImplementedError(self.set_make_working_trees)
769
def make_working_trees(self):
770
"""Returns the policy for making working trees on new branches."""
771
raise NotImplementedError(self.make_working_trees)
774
def sign_revision(self, revision_id, gpg_strategy):
775
plaintext = Testament.from_revision(self, revision_id).as_short_text()
776
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
779
def has_signature_for_revision_id(self, revision_id):
780
"""Query for a revision signature for revision_id in the repository."""
781
return self._revision_store.has_signature(revision_id,
782
self.get_transaction())
785
def get_signature_text(self, revision_id):
786
"""Return the text for a signature."""
787
return self._revision_store.get_signature_text(revision_id,
788
self.get_transaction())
791
def check(self, revision_ids):
792
"""Check consistency of all history of given revision_ids.
794
Different repository implementations should override _check().
796
:param revision_ids: A non-empty list of revision_ids whose ancestry
797
will be checked. Typically the last revision_id of a branch.
800
raise ValueError("revision_ids must be non-empty in %s.check"
802
return self._check(revision_ids)
804
def _check(self, revision_ids):
805
result = check.Check(self)
809
def _warn_if_deprecated(self):
810
global _deprecation_warning_done
811
if _deprecation_warning_done:
813
_deprecation_warning_done = True
814
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
815
% (self._format, self.bzrdir.transport.base))
817
def supports_rich_root(self):
818
return self._format.rich_root_data
820
def _check_ascii_revisionid(self, revision_id, method):
821
"""Private helper for ascii-only repositories."""
822
# weave repositories refuse to store revisionids that are non-ascii.
823
if revision_id is not None:
824
# weaves require ascii revision ids.
825
if isinstance(revision_id, unicode):
827
revision_id.encode('ascii')
828
except UnicodeEncodeError:
829
raise errors.NonAsciiRevisionId(method, self)
832
class AllInOneRepository(Repository):
833
"""Legacy support - the repository behaviour for all-in-one branches."""
835
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
836
# we reuse one control files instance.
837
dir_mode = a_bzrdir._control_files._dir_mode
838
file_mode = a_bzrdir._control_files._file_mode
840
def get_store(name, compressed=True, prefixed=False):
841
# FIXME: This approach of assuming stores are all entirely compressed
842
# or entirely uncompressed is tidy, but breaks upgrade from
843
# some existing branches where there's a mixture; we probably
844
# still want the option to look for both.
845
relpath = a_bzrdir._control_files._escape(name)
846
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
847
prefixed=prefixed, compressed=compressed,
850
#if self._transport.should_cache():
851
# cache_path = os.path.join(self.cache_root, name)
852
# os.mkdir(cache_path)
853
# store = bzrlib.store.CachedStore(store, cache_path)
856
# not broken out yet because the controlweaves|inventory_store
857
# and text_store | weave_store bits are still different.
858
if isinstance(_format, RepositoryFormat4):
859
# cannot remove these - there is still no consistent api
860
# which allows access to this old info.
861
self.inventory_store = get_store('inventory-store')
862
text_store = get_store('text-store')
863
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
865
def get_commit_builder(self, branch, parents, config, timestamp=None,
866
timezone=None, committer=None, revprops=None,
868
self._check_ascii_revisionid(revision_id, self.get_commit_builder)
869
return Repository.get_commit_builder(self, branch, parents, config,
870
timestamp, timezone, committer, revprops, revision_id)
874
"""AllInOne repositories cannot be shared."""
878
def set_make_working_trees(self, new_value):
879
"""Set the policy flag for making working trees when creating branches.
881
This only applies to branches that use this repository.
883
The default is 'True'.
884
:param new_value: True to restore the default, False to disable making
887
raise NotImplementedError(self.set_make_working_trees)
889
def make_working_trees(self):
890
"""Returns the policy for making working trees on new branches."""
894
def install_revision(repository, rev, revision_tree):
895
"""Install all revision data into a repository."""
898
for p_id in rev.parent_ids:
899
if repository.has_revision(p_id):
900
present_parents.append(p_id)
901
parent_trees[p_id] = repository.revision_tree(p_id)
903
parent_trees[p_id] = repository.revision_tree(None)
905
inv = revision_tree.inventory
906
entries = inv.iter_entries()
907
# backwards compatability hack: skip the root id.
908
if not repository.supports_rich_root():
909
path, root = entries.next()
910
if root.revision != rev.revision_id:
911
raise errors.IncompatibleRevision(repr(repository))
912
# Add the texts that are not already present
913
for path, ie in entries:
914
w = repository.weave_store.get_weave_or_empty(ie.file_id,
915
repository.get_transaction())
916
if ie.revision not in w:
918
# FIXME: TODO: The following loop *may* be overlapping/duplicate
919
# with InventoryEntry.find_previous_heads(). if it is, then there
920
# is a latent bug here where the parents may have ancestors of each
922
for revision, tree in parent_trees.iteritems():
923
if ie.file_id not in tree:
925
parent_id = tree.inventory[ie.file_id].revision
926
if parent_id in text_parents:
928
text_parents.append(parent_id)
930
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
931
repository.get_transaction())
932
lines = revision_tree.get_file(ie.file_id).readlines()
933
vfile.add_lines(rev.revision_id, text_parents, lines)
935
# install the inventory
936
repository.add_inventory(rev.revision_id, inv, present_parents)
937
except errors.RevisionAlreadyPresent:
939
repository.add_revision(rev.revision_id, rev, inv)
942
class MetaDirRepository(Repository):
943
"""Repositories in the new meta-dir layout."""
945
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
946
super(MetaDirRepository, self).__init__(_format,
952
dir_mode = self.control_files._dir_mode
953
file_mode = self.control_files._file_mode
957
"""Return True if this repository is flagged as a shared repository."""
958
return self.control_files._transport.has('shared-storage')
961
def set_make_working_trees(self, new_value):
962
"""Set the policy flag for making working trees when creating branches.
964
This only applies to branches that use this repository.
966
The default is 'True'.
967
:param new_value: True to restore the default, False to disable making
972
self.control_files._transport.delete('no-working-trees')
973
except errors.NoSuchFile:
976
self.control_files.put_utf8('no-working-trees', '')
978
def make_working_trees(self):
979
"""Returns the policy for making working trees on new branches."""
980
return not self.control_files._transport.has('no-working-trees')
983
class WeaveMetaDirRepository(MetaDirRepository):
984
"""A subclass of MetaDirRepository to set weave specific policy."""
986
def get_commit_builder(self, branch, parents, config, timestamp=None,
987
timezone=None, committer=None, revprops=None,
989
self._check_ascii_revisionid(revision_id, self.get_commit_builder)
990
return MetaDirRepository.get_commit_builder(self, branch, parents,
991
config, timestamp, timezone, committer, revprops, revision_id)
994
class KnitRepository(MetaDirRepository):
995
"""Knit format repository."""
997
def _warn_if_deprecated(self):
998
# This class isn't deprecated
1001
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
1002
inv_vf.add_lines_with_ghosts(revid, parents, lines)
1005
def _all_revision_ids(self):
1006
"""See Repository.all_revision_ids()."""
1007
# Knits get the revision graph from the index of the revision knit, so
1008
# it's always possible even if they're on an unlistable transport.
1009
return self._revision_store.all_revision_ids(self.get_transaction())
1011
def fileid_involved_between_revs(self, from_revid, to_revid):
1012
"""Find file_id(s) which are involved in the changes between revisions.
1014
This determines the set of revisions which are involved, and then
1015
finds all file ids affected by those revisions.
1017
vf = self._get_revision_vf()
1018
from_set = set(vf.get_ancestry(from_revid))
1019
to_set = set(vf.get_ancestry(to_revid))
1020
changed = to_set.difference(from_set)
1021
return self._fileid_involved_by_set(changed)
1023
def fileid_involved(self, last_revid=None):
1024
"""Find all file_ids modified in the ancestry of last_revid.
1026
:param last_revid: If None, last_revision() will be used.
1029
changed = set(self.all_revision_ids())
1031
changed = set(self.get_ancestry(last_revid))
1033
changed.remove(None)
1034
return self._fileid_involved_by_set(changed)
1037
def get_ancestry(self, revision_id):
1038
"""Return a list of revision-ids integrated by a revision.
1040
This is topologically sorted.
1042
if revision_id is None:
1044
vf = self._get_revision_vf()
1046
return [None] + vf.get_ancestry(revision_id)
1047
except errors.RevisionNotPresent:
1048
raise errors.NoSuchRevision(self, revision_id)
1051
def get_revision(self, revision_id):
1052
"""Return the Revision object for a named revision"""
1053
return self.get_revision_reconcile(revision_id)
1056
def get_revision_graph(self, revision_id=None):
1057
"""Return a dictionary containing the revision graph.
1059
:param revision_id: The revision_id to get a graph from. If None, then
1060
the entire revision graph is returned. This is a deprecated mode of
1061
operation and will be removed in the future.
1062
:return: a dictionary of revision_id->revision_parents_list.
1064
# special case NULL_REVISION
1065
if revision_id == _mod_revision.NULL_REVISION:
1067
a_weave = self._get_revision_vf()
1068
entire_graph = a_weave.get_graph()
1069
if revision_id is None:
1070
return a_weave.get_graph()
1071
elif revision_id not in a_weave:
1072
raise errors.NoSuchRevision(self, revision_id)
1074
# add what can be reached from revision_id
1076
pending = set([revision_id])
1077
while len(pending) > 0:
1078
node = pending.pop()
1079
result[node] = a_weave.get_parents(node)
1080
for revision_id in result[node]:
1081
if revision_id not in result:
1082
pending.add(revision_id)
1086
def get_revision_graph_with_ghosts(self, revision_ids=None):
1087
"""Return a graph of the revisions with ghosts marked as applicable.
1089
:param revision_ids: an iterable of revisions to graph or None for all.
1090
:return: a Graph object with the graph reachable from revision_ids.
1092
result = graph.Graph()
1093
vf = self._get_revision_vf()
1094
versions = set(vf.versions())
1095
if not revision_ids:
1096
pending = set(self.all_revision_ids())
1099
pending = set(revision_ids)
1100
# special case NULL_REVISION
1101
if _mod_revision.NULL_REVISION in pending:
1102
pending.remove(_mod_revision.NULL_REVISION)
1103
required = set(pending)
1106
revision_id = pending.pop()
1107
if not revision_id in versions:
1108
if revision_id in required:
1109
raise errors.NoSuchRevision(self, revision_id)
1111
result.add_ghost(revision_id)
1112
# mark it as done so we don't try for it again.
1113
done.add(revision_id)
1115
parent_ids = vf.get_parents_with_ghosts(revision_id)
1116
for parent_id in parent_ids:
1117
# is this queued or done ?
1118
if (parent_id not in pending and
1119
parent_id not in done):
1121
pending.add(parent_id)
1122
result.add_node(revision_id, parent_ids)
1123
done.add(revision_id)
1126
def _get_revision_vf(self):
1127
""":return: a versioned file containing the revisions."""
1128
vf = self._revision_store.get_revision_file(self.get_transaction())
1132
def reconcile(self, other=None, thorough=False):
1133
"""Reconcile this repository."""
1134
from bzrlib.reconcile import KnitReconciler
1135
reconciler = KnitReconciler(self, thorough=thorough)
1136
reconciler.reconcile()
1139
def revision_parents(self, revision_id):
1140
return self._get_revision_vf().get_parents(revision_id)
1143
class KnitRepository2(KnitRepository):
1145
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1146
control_store, text_store):
1147
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1148
_revision_store, control_store, text_store)
1149
self._serializer = xml6.serializer_v6
1151
def deserialise_inventory(self, revision_id, xml):
1152
"""Transform the xml into an inventory object.
1154
:param revision_id: The expected revision id of the inventory.
1155
:param xml: A serialised inventory.
1157
result = self._serializer.read_inventory_from_string(xml)
1158
assert result.root.revision is not None
1161
def serialise_inventory(self, inv):
1162
"""Transform the inventory object into XML text.
1164
:param revision_id: The expected revision id of the inventory.
1165
:param xml: A serialised inventory.
1167
assert inv.revision_id is not None
1168
assert inv.root.revision is not None
1169
return KnitRepository.serialise_inventory(self, inv)
1171
def get_commit_builder(self, branch, parents, config, timestamp=None,
1172
timezone=None, committer=None, revprops=None,
1174
"""Obtain a CommitBuilder for this repository.
1176
:param branch: Branch to commit to.
1177
:param parents: Revision ids of the parents of the new revision.
1178
:param config: Configuration to use.
1179
:param timestamp: Optional timestamp recorded for commit.
1180
:param timezone: Optional timezone for timestamp.
1181
:param committer: Optional committer to set for commit.
1182
:param revprops: Optional dictionary of revision properties.
1183
:param revision_id: Optional revision id.
1185
return RootCommitBuilder(self, parents, config, timestamp, timezone,
1186
committer, revprops, revision_id)
1189
class RepositoryFormatRegistry(registry.Registry):
1190
"""Registry of RepositoryFormats.
1194
format_registry = RepositoryFormatRegistry()
1195
"""Registry of formats, indexed by their identifying format string."""
1198
class RepositoryFormat(object):
1199
"""A repository format.
1201
Formats provide three things:
1202
* An initialization routine to construct repository data on disk.
1203
* a format string which is used when the BzrDir supports versioned
1205
* an open routine which returns a Repository instance.
1207
Formats are placed in an dict by their format string for reference
1208
during opening. These should be subclasses of RepositoryFormat
1211
Once a format is deprecated, just deprecate the initialize and open
1212
methods on the format class. Do not deprecate the object, as the
1213
object will be created every system load.
1215
Common instance attributes:
1216
_matchingbzrdir - the bzrdir format that the repository format was
1217
originally written to work with. This can be used if manually
1218
constructing a bzrdir and repository, or more commonly for test suite
1223
return "<%s>" % self.__class__.__name__
1226
def find_format(klass, a_bzrdir):
1227
"""Return the format for the repository object in a_bzrdir.
1229
This is used by bzr native formats that have a "format" file in
1230
the repository. Other methods may be used by different types of
1234
transport = a_bzrdir.get_repository_transport(None)
1235
format_string = transport.get("format").read()
1236
return format_registry.get(format_string)
1237
except errors.NoSuchFile:
1238
raise errors.NoRepositoryPresent(a_bzrdir)
1240
raise errors.UnknownFormatError(format=format_string)
1243
def register_format(klass, format):
1244
format_registry.register(format.get_format_string(), format)
1247
def unregister_format(klass, format):
1248
format_registry.remove(format.get_format_string())
1251
def get_default_format(klass):
1252
"""Return the current default format."""
1253
from bzrlib import bzrdir
1254
return bzrdir.format_registry.make_bzrdir('default').repository_format
1256
def _get_control_store(self, repo_transport, control_files):
1257
"""Return the control store for this repository."""
1258
raise NotImplementedError(self._get_control_store)
1260
def get_format_string(self):
1261
"""Return the ASCII format string that identifies this format.
1263
Note that in pre format ?? repositories the format string is
1264
not permitted nor written to disk.
1266
raise NotImplementedError(self.get_format_string)
1268
def get_format_description(self):
1269
"""Return the short description for this format."""
1270
raise NotImplementedError(self.get_format_description)
1272
def _get_revision_store(self, repo_transport, control_files):
1273
"""Return the revision store object for this a_bzrdir."""
1274
raise NotImplementedError(self._get_revision_store)
1276
def _get_text_rev_store(self,
1283
"""Common logic for getting a revision store for a repository.
1285
see self._get_revision_store for the subclass-overridable method to
1286
get the store for a repository.
1288
from bzrlib.store.revision.text import TextRevisionStore
1289
dir_mode = control_files._dir_mode
1290
file_mode = control_files._file_mode
1291
text_store =TextStore(transport.clone(name),
1293
compressed=compressed,
1295
file_mode=file_mode)
1296
_revision_store = TextRevisionStore(text_store, serializer)
1297
return _revision_store
1299
def _get_versioned_file_store(self,
1304
versionedfile_class=weave.WeaveFile,
1305
versionedfile_kwargs={},
1307
weave_transport = control_files._transport.clone(name)
1308
dir_mode = control_files._dir_mode
1309
file_mode = control_files._file_mode
1310
return VersionedFileStore(weave_transport, prefixed=prefixed,
1312
file_mode=file_mode,
1313
versionedfile_class=versionedfile_class,
1314
versionedfile_kwargs=versionedfile_kwargs,
1317
def initialize(self, a_bzrdir, shared=False):
1318
"""Initialize a repository of this format in a_bzrdir.
1320
:param a_bzrdir: The bzrdir to put the new repository in it.
1321
:param shared: The repository should be initialized as a sharable one.
1322
:returns: The new repository object.
1324
This may raise UninitializableFormat if shared repository are not
1325
compatible the a_bzrdir.
1327
raise NotImplementedError(self.initialize)
1329
def is_supported(self):
1330
"""Is this format supported?
1332
Supported formats must be initializable and openable.
1333
Unsupported formats may not support initialization or committing or
1334
some other features depending on the reason for not being supported.
1338
def check_conversion_target(self, target_format):
1339
raise NotImplementedError(self.check_conversion_target)
1341
def open(self, a_bzrdir, _found=False):
1342
"""Return an instance of this format for the bzrdir a_bzrdir.
1344
_found is a private parameter, do not use it.
1346
raise NotImplementedError(self.open)
1349
class PreSplitOutRepositoryFormat(RepositoryFormat):
1350
"""Base class for the pre split out repository formats."""
1352
rich_root_data = False
1354
def initialize(self, a_bzrdir, shared=False, _internal=False):
1355
"""Create a weave repository.
1357
TODO: when creating split out bzr branch formats, move this to a common
1358
base for Format5, Format6. or something like that.
1361
raise errors.IncompatibleFormat(self, a_bzrdir._format)
1364
# always initialized when the bzrdir is.
1365
return self.open(a_bzrdir, _found=True)
1367
# Create an empty weave
1369
weavefile.write_weave_v5(weave.Weave(), sio)
1370
empty_weave = sio.getvalue()
1372
mutter('creating repository in %s.', a_bzrdir.transport.base)
1373
dirs = ['revision-store', 'weaves']
1374
files = [('inventory.weave', StringIO(empty_weave)),
1377
# FIXME: RBC 20060125 don't peek under the covers
1378
# NB: no need to escape relative paths that are url safe.
1379
control_files = lockable_files.LockableFiles(a_bzrdir.transport,
1380
'branch-lock', lockable_files.TransportLock)
1381
control_files.create_lock()
1382
control_files.lock_write()
1383
control_files._transport.mkdir_multi(dirs,
1384
mode=control_files._dir_mode)
1386
for file, content in files:
1387
control_files.put(file, content)
1389
control_files.unlock()
1390
return self.open(a_bzrdir, _found=True)
1392
def _get_control_store(self, repo_transport, control_files):
1393
"""Return the control store for this repository."""
1394
return self._get_versioned_file_store('',
1399
def _get_text_store(self, transport, control_files):
1400
"""Get a store for file texts for this format."""
1401
raise NotImplementedError(self._get_text_store)
1403
def open(self, a_bzrdir, _found=False):
1404
"""See RepositoryFormat.open()."""
1406
# we are being called directly and must probe.
1407
raise NotImplementedError
1409
repo_transport = a_bzrdir.get_repository_transport(None)
1410
control_files = a_bzrdir._control_files
1411
text_store = self._get_text_store(repo_transport, control_files)
1412
control_store = self._get_control_store(repo_transport, control_files)
1413
_revision_store = self._get_revision_store(repo_transport, control_files)
1414
return AllInOneRepository(_format=self,
1416
_revision_store=_revision_store,
1417
control_store=control_store,
1418
text_store=text_store)
1420
def check_conversion_target(self, target_format):
1424
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1425
"""Bzr repository format 4.
1427
This repository format has:
1429
- TextStores for texts, inventories,revisions.
1431
This format is deprecated: it indexes texts using a text id which is
1432
removed in format 5; initialization and write support for this format
1437
super(RepositoryFormat4, self).__init__()
1438
self._matchingbzrdir = bzrdir.BzrDirFormat4()
1440
def get_format_description(self):
1441
"""See RepositoryFormat.get_format_description()."""
1442
return "Repository format 4"
1444
def initialize(self, url, shared=False, _internal=False):
1445
"""Format 4 branches cannot be created."""
1446
raise errors.UninitializableFormat(self)
1448
def is_supported(self):
1449
"""Format 4 is not supported.
1451
It is not supported because the model changed from 4 to 5 and the
1452
conversion logic is expensive - so doing it on the fly was not
1457
def _get_control_store(self, repo_transport, control_files):
1458
"""Format 4 repositories have no formal control store at this point.
1460
This will cause any control-file-needing apis to fail - this is desired.
1464
def _get_revision_store(self, repo_transport, control_files):
1465
"""See RepositoryFormat._get_revision_store()."""
1466
from bzrlib.xml4 import serializer_v4
1467
return self._get_text_rev_store(repo_transport,
1470
serializer=serializer_v4)
1472
def _get_text_store(self, transport, control_files):
1473
"""See RepositoryFormat._get_text_store()."""
1476
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1477
"""Bzr control format 5.
1479
This repository format has:
1480
- weaves for file texts and inventory
1482
- TextStores for revisions and signatures.
1486
super(RepositoryFormat5, self).__init__()
1487
self._matchingbzrdir = bzrdir.BzrDirFormat5()
1489
def get_format_description(self):
1490
"""See RepositoryFormat.get_format_description()."""
1491
return "Weave repository format 5"
1493
def _get_revision_store(self, repo_transport, control_files):
1494
"""See RepositoryFormat._get_revision_store()."""
1495
"""Return the revision store object for this a_bzrdir."""
1496
return self._get_text_rev_store(repo_transport,
1501
def _get_text_store(self, transport, control_files):
1502
"""See RepositoryFormat._get_text_store()."""
1503
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1506
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1507
"""Bzr control format 6.
1509
This repository format has:
1510
- weaves for file texts and inventory
1511
- hash subdirectory based stores.
1512
- TextStores for revisions and signatures.
1516
super(RepositoryFormat6, self).__init__()
1517
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1519
def get_format_description(self):
1520
"""See RepositoryFormat.get_format_description()."""
1521
return "Weave repository format 6"
1523
def _get_revision_store(self, repo_transport, control_files):
1524
"""See RepositoryFormat._get_revision_store()."""
1525
return self._get_text_rev_store(repo_transport,
1531
def _get_text_store(self, transport, control_files):
1532
"""See RepositoryFormat._get_text_store()."""
1533
return self._get_versioned_file_store('weaves', transport, control_files)
1536
class MetaDirRepositoryFormat(RepositoryFormat):
1537
"""Common base class for the new repositories using the metadir layout."""
1539
rich_root_data = False
1542
super(MetaDirRepositoryFormat, self).__init__()
1543
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1545
def _create_control_files(self, a_bzrdir):
1546
"""Create the required files and the initial control_files object."""
1547
# FIXME: RBC 20060125 don't peek under the covers
1548
# NB: no need to escape relative paths that are url safe.
1549
repository_transport = a_bzrdir.get_repository_transport(self)
1550
control_files = lockable_files.LockableFiles(repository_transport,
1551
'lock', lockdir.LockDir)
1552
control_files.create_lock()
1553
return control_files
1555
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1556
"""Upload the initial blank content."""
1557
control_files = self._create_control_files(a_bzrdir)
1558
control_files.lock_write()
1560
control_files._transport.mkdir_multi(dirs,
1561
mode=control_files._dir_mode)
1562
for file, content in files:
1563
control_files.put(file, content)
1564
for file, content in utf8_files:
1565
control_files.put_utf8(file, content)
1567
control_files.put_utf8('shared-storage', '')
1569
control_files.unlock()
1572
class RepositoryFormat7(MetaDirRepositoryFormat):
1573
"""Bzr repository 7.
1575
This repository format has:
1576
- weaves for file texts and inventory
1577
- hash subdirectory based stores.
1578
- TextStores for revisions and signatures.
1579
- a format marker of its own
1580
- an optional 'shared-storage' flag
1581
- an optional 'no-working-trees' flag
1584
def _get_control_store(self, repo_transport, control_files):
1585
"""Return the control store for this repository."""
1586
return self._get_versioned_file_store('',
1591
def get_format_string(self):
1592
"""See RepositoryFormat.get_format_string()."""
1593
return "Bazaar-NG Repository format 7"
1595
def get_format_description(self):
1596
"""See RepositoryFormat.get_format_description()."""
1597
return "Weave repository format 7"
1599
def check_conversion_target(self, target_format):
1602
def _get_revision_store(self, repo_transport, control_files):
1603
"""See RepositoryFormat._get_revision_store()."""
1604
return self._get_text_rev_store(repo_transport,
1611
def _get_text_store(self, transport, control_files):
1612
"""See RepositoryFormat._get_text_store()."""
1613
return self._get_versioned_file_store('weaves',
1617
def initialize(self, a_bzrdir, shared=False):
1618
"""Create a weave repository.
1620
:param shared: If true the repository will be initialized as a shared
1623
# Create an empty weave
1625
weavefile.write_weave_v5(weave.Weave(), sio)
1626
empty_weave = sio.getvalue()
1628
mutter('creating repository in %s.', a_bzrdir.transport.base)
1629
dirs = ['revision-store', 'weaves']
1630
files = [('inventory.weave', StringIO(empty_weave)),
1632
utf8_files = [('format', self.get_format_string())]
1634
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1635
return self.open(a_bzrdir=a_bzrdir, _found=True)
1637
def open(self, a_bzrdir, _found=False, _override_transport=None):
1638
"""See RepositoryFormat.open().
1640
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1641
repository at a slightly different url
1642
than normal. I.e. during 'upgrade'.
1645
format = RepositoryFormat.find_format(a_bzrdir)
1646
assert format.__class__ == self.__class__
1647
if _override_transport is not None:
1648
repo_transport = _override_transport
1650
repo_transport = a_bzrdir.get_repository_transport(None)
1651
control_files = lockable_files.LockableFiles(repo_transport,
1652
'lock', lockdir.LockDir)
1653
text_store = self._get_text_store(repo_transport, control_files)
1654
control_store = self._get_control_store(repo_transport, control_files)
1655
_revision_store = self._get_revision_store(repo_transport, control_files)
1656
return WeaveMetaDirRepository(_format=self,
1658
control_files=control_files,
1659
_revision_store=_revision_store,
1660
control_store=control_store,
1661
text_store=text_store)
1664
class RepositoryFormatKnit(MetaDirRepositoryFormat):
1665
"""Bzr repository knit format (generalized).
1667
This repository format has:
1668
- knits for file texts and inventory
1669
- hash subdirectory based stores.
1670
- knits for revisions and signatures
1671
- TextStores for revisions and signatures.
1672
- a format marker of its own
1673
- an optional 'shared-storage' flag
1674
- an optional 'no-working-trees' flag
1678
def _get_control_store(self, repo_transport, control_files):
1679
"""Return the control store for this repository."""
1680
return VersionedFileStore(
1683
file_mode=control_files._file_mode,
1684
versionedfile_class=knit.KnitVersionedFile,
1685
versionedfile_kwargs={'factory':knit.KnitPlainFactory()},
1688
def _get_revision_store(self, repo_transport, control_files):
1689
"""See RepositoryFormat._get_revision_store()."""
1690
from bzrlib.store.revision.knit import KnitRevisionStore
1691
versioned_file_store = VersionedFileStore(
1693
file_mode=control_files._file_mode,
1696
versionedfile_class=knit.KnitVersionedFile,
1697
versionedfile_kwargs={'delta':False,
1698
'factory':knit.KnitPlainFactory(),
1702
return KnitRevisionStore(versioned_file_store)
1704
def _get_text_store(self, transport, control_files):
1705
"""See RepositoryFormat._get_text_store()."""
1706
return self._get_versioned_file_store('knits',
1709
versionedfile_class=knit.KnitVersionedFile,
1710
versionedfile_kwargs={
1711
'create_parent_dir':True,
1712
'delay_create':True,
1713
'dir_mode':control_files._dir_mode,
1717
def initialize(self, a_bzrdir, shared=False):
1718
"""Create a knit format 1 repository.
1720
:param a_bzrdir: bzrdir to contain the new repository; must already
1722
:param shared: If true the repository will be initialized as a shared
1725
mutter('creating repository in %s.', a_bzrdir.transport.base)
1726
dirs = ['revision-store', 'knits']
1728
utf8_files = [('format', self.get_format_string())]
1730
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1731
repo_transport = a_bzrdir.get_repository_transport(None)
1732
control_files = lockable_files.LockableFiles(repo_transport,
1733
'lock', lockdir.LockDir)
1734
control_store = self._get_control_store(repo_transport, control_files)
1735
transaction = transactions.WriteTransaction()
1736
# trigger a write of the inventory store.
1737
control_store.get_weave_or_empty('inventory', transaction)
1738
_revision_store = self._get_revision_store(repo_transport, control_files)
1739
# the revision id here is irrelevant: it will not be stored, and cannot
1741
_revision_store.has_revision_id('A', transaction)
1742
_revision_store.get_signature_file(transaction)
1743
return self.open(a_bzrdir=a_bzrdir, _found=True)
1745
def open(self, a_bzrdir, _found=False, _override_transport=None):
1746
"""See RepositoryFormat.open().
1748
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1749
repository at a slightly different url
1750
than normal. I.e. during 'upgrade'.
1753
format = RepositoryFormat.find_format(a_bzrdir)
1754
assert format.__class__ == self.__class__
1755
if _override_transport is not None:
1756
repo_transport = _override_transport
1758
repo_transport = a_bzrdir.get_repository_transport(None)
1759
control_files = lockable_files.LockableFiles(repo_transport,
1760
'lock', lockdir.LockDir)
1761
text_store = self._get_text_store(repo_transport, control_files)
1762
control_store = self._get_control_store(repo_transport, control_files)
1763
_revision_store = self._get_revision_store(repo_transport, control_files)
1764
return KnitRepository(_format=self,
1766
control_files=control_files,
1767
_revision_store=_revision_store,
1768
control_store=control_store,
1769
text_store=text_store)
1772
class RepositoryFormatKnit1(RepositoryFormatKnit):
1773
"""Bzr repository knit format 1.
1775
This repository format has:
1776
- knits for file texts and inventory
1777
- hash subdirectory based stores.
1778
- knits for revisions and signatures
1779
- TextStores for revisions and signatures.
1780
- a format marker of its own
1781
- an optional 'shared-storage' flag
1782
- an optional 'no-working-trees' flag
1785
This format was introduced in bzr 0.8.
1787
def get_format_string(self):
1788
"""See RepositoryFormat.get_format_string()."""
1789
return "Bazaar-NG Knit Repository Format 1"
1791
def get_format_description(self):
1792
"""See RepositoryFormat.get_format_description()."""
1793
return "Knit repository format 1"
1795
def check_conversion_target(self, target_format):
1799
class RepositoryFormatKnit2(RepositoryFormatKnit):
1800
"""Bzr repository knit format 2.
1802
THIS FORMAT IS EXPERIMENTAL
1803
This repository format has:
1804
- knits for file texts and inventory
1805
- hash subdirectory based stores.
1806
- knits for revisions and signatures
1807
- TextStores for revisions and signatures.
1808
- a format marker of its own
1809
- an optional 'shared-storage' flag
1810
- an optional 'no-working-trees' flag
1812
- Support for recording full info about the tree root
1816
rich_root_data = True
1818
def get_format_string(self):
1819
"""See RepositoryFormat.get_format_string()."""
1820
return "Bazaar Knit Repository Format 2\n"
1822
def get_format_description(self):
1823
"""See RepositoryFormat.get_format_description()."""
1824
return "Knit repository format 2"
1826
def check_conversion_target(self, target_format):
1827
if not target_format.rich_root_data:
1828
raise errors.BadConversionTarget(
1829
'Does not support rich root data.', target_format)
1831
def open(self, a_bzrdir, _found=False, _override_transport=None):
1832
"""See RepositoryFormat.open().
1834
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1835
repository at a slightly different url
1836
than normal. I.e. during 'upgrade'.
1839
format = RepositoryFormat.find_format(a_bzrdir)
1840
assert format.__class__ == self.__class__
1841
if _override_transport is not None:
1842
repo_transport = _override_transport
1844
repo_transport = a_bzrdir.get_repository_transport(None)
1845
control_files = lockable_files.LockableFiles(repo_transport, 'lock',
1847
text_store = self._get_text_store(repo_transport, control_files)
1848
control_store = self._get_control_store(repo_transport, control_files)
1849
_revision_store = self._get_revision_store(repo_transport, control_files)
1850
return KnitRepository2(_format=self,
1852
control_files=control_files,
1853
_revision_store=_revision_store,
1854
control_store=control_store,
1855
text_store=text_store)
1859
# formats which have no format string are not discoverable
1860
# and not independently creatable, so are not registered.
1861
RepositoryFormat.register_format(RepositoryFormat7())
1862
# KEEP in sync with bzrdir.format_registry default
1863
RepositoryFormat.register_format(RepositoryFormatKnit1())
1864
RepositoryFormat.register_format(RepositoryFormatKnit2())
1865
_legacy_formats = [RepositoryFormat4(),
1866
RepositoryFormat5(),
1867
RepositoryFormat6()]
1870
class InterRepository(InterObject):
1871
"""This class represents operations taking place between two repositories.
1873
Its instances have methods like copy_content and fetch, and contain
1874
references to the source and target repositories these operations can be
1877
Often we will provide convenience methods on 'repository' which carry out
1878
operations with another repository - they will always forward to
1879
InterRepository.get(other).method_name(parameters).
1883
"""The available optimised InterRepository types."""
1885
def copy_content(self, revision_id=None, basis=None):
1886
raise NotImplementedError(self.copy_content)
1888
def fetch(self, revision_id=None, pb=None):
1889
"""Fetch the content required to construct revision_id.
1891
The content is copied from self.source to self.target.
1893
:param revision_id: if None all content is copied, if NULL_REVISION no
1895
:param pb: optional progress bar to use for progress reports. If not
1896
provided a default one will be created.
1898
Returns the copied revision count and the failed revisions in a tuple:
1901
raise NotImplementedError(self.fetch)
1904
def missing_revision_ids(self, revision_id=None):
1905
"""Return the revision ids that source has that target does not.
1907
These are returned in topological order.
1909
:param revision_id: only return revision ids included by this
1912
# generic, possibly worst case, slow code path.
1913
target_ids = set(self.target.all_revision_ids())
1914
if revision_id is not None:
1915
source_ids = self.source.get_ancestry(revision_id)
1916
assert source_ids[0] is None
1919
source_ids = self.source.all_revision_ids()
1920
result_set = set(source_ids).difference(target_ids)
1921
# this may look like a no-op: its not. It preserves the ordering
1922
# other_ids had while only returning the members from other_ids
1923
# that we've decided we need.
1924
return [rev_id for rev_id in source_ids if rev_id in result_set]
1927
class InterSameDataRepository(InterRepository):
1928
"""Code for converting between repositories that represent the same data.
1930
Data format and model must match for this to work.
1933
_matching_repo_format = RepositoryFormat4()
1934
"""Repository format for testing with."""
1937
def is_compatible(source, target):
1938
if source._format.rich_root_data == target._format.rich_root_data:
1944
def copy_content(self, revision_id=None, basis=None):
1945
"""Make a complete copy of the content in self into destination.
1947
This is a destructive operation! Do not use it on existing
1950
:param revision_id: Only copy the content needed to construct
1951
revision_id and its parents.
1952
:param basis: Copy the needed data preferentially from basis.
1955
self.target.set_make_working_trees(self.source.make_working_trees())
1956
except NotImplementedError:
1958
# grab the basis available data
1959
if basis is not None:
1960
self.target.fetch(basis, revision_id=revision_id)
1961
# but don't bother fetching if we have the needed data now.
1962
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1963
self.target.has_revision(revision_id)):
1965
self.target.fetch(self.source, revision_id=revision_id)
1968
def fetch(self, revision_id=None, pb=None):
1969
"""See InterRepository.fetch()."""
1970
from bzrlib.fetch import GenericRepoFetcher
1971
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1972
self.source, self.source._format, self.target,
1973
self.target._format)
1974
f = GenericRepoFetcher(to_repository=self.target,
1975
from_repository=self.source,
1976
last_revision=revision_id,
1978
return f.count_copied, f.failed_revisions
1981
class InterWeaveRepo(InterSameDataRepository):
1982
"""Optimised code paths between Weave based repositories."""
1984
_matching_repo_format = RepositoryFormat7()
1985
"""Repository format for testing with."""
1988
def is_compatible(source, target):
1989
"""Be compatible with known Weave formats.
1991
We don't test for the stores being of specific types because that
1992
could lead to confusing results, and there is no need to be
1996
return (isinstance(source._format, (RepositoryFormat5,
1998
RepositoryFormat7)) and
1999
isinstance(target._format, (RepositoryFormat5,
2001
RepositoryFormat7)))
2002
except AttributeError:
2006
def copy_content(self, revision_id=None, basis=None):
2007
"""See InterRepository.copy_content()."""
2008
# weave specific optimised path:
2009
if basis is not None:
2010
# copy the basis in, then fetch remaining data.
2011
basis.copy_content_into(self.target, revision_id)
2012
# the basis copy_content_into could miss-set this.
2014
self.target.set_make_working_trees(self.source.make_working_trees())
2015
except NotImplementedError:
2017
self.target.fetch(self.source, revision_id=revision_id)
2020
self.target.set_make_working_trees(self.source.make_working_trees())
2021
except NotImplementedError:
2023
# FIXME do not peek!
2024
if self.source.control_files._transport.listable():
2025
pb = ui.ui_factory.nested_progress_bar()
2027
self.target.weave_store.copy_all_ids(
2028
self.source.weave_store,
2030
from_transaction=self.source.get_transaction(),
2031
to_transaction=self.target.get_transaction())
2032
pb.update('copying inventory', 0, 1)
2033
self.target.control_weaves.copy_multi(
2034
self.source.control_weaves, ['inventory'],
2035
from_transaction=self.source.get_transaction(),
2036
to_transaction=self.target.get_transaction())
2037
self.target._revision_store.text_store.copy_all_ids(
2038
self.source._revision_store.text_store,
2043
self.target.fetch(self.source, revision_id=revision_id)
2046
def fetch(self, revision_id=None, pb=None):
2047
"""See InterRepository.fetch()."""
2048
from bzrlib.fetch import GenericRepoFetcher
2049
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2050
self.source, self.source._format, self.target, self.target._format)
2051
f = GenericRepoFetcher(to_repository=self.target,
2052
from_repository=self.source,
2053
last_revision=revision_id,
2055
return f.count_copied, f.failed_revisions
2058
def missing_revision_ids(self, revision_id=None):
2059
"""See InterRepository.missing_revision_ids()."""
2060
# we want all revisions to satisfy revision_id in source.
2061
# but we don't want to stat every file here and there.
2062
# we want then, all revisions other needs to satisfy revision_id
2063
# checked, but not those that we have locally.
2064
# so the first thing is to get a subset of the revisions to
2065
# satisfy revision_id in source, and then eliminate those that
2066
# we do already have.
2067
# this is slow on high latency connection to self, but as as this
2068
# disk format scales terribly for push anyway due to rewriting
2069
# inventory.weave, this is considered acceptable.
2071
if revision_id is not None:
2072
source_ids = self.source.get_ancestry(revision_id)
2073
assert source_ids[0] is None
2076
source_ids = self.source._all_possible_ids()
2077
source_ids_set = set(source_ids)
2078
# source_ids is the worst possible case we may need to pull.
2079
# now we want to filter source_ids against what we actually
2080
# have in target, but don't try to check for existence where we know
2081
# we do not have a revision as that would be pointless.
2082
target_ids = set(self.target._all_possible_ids())
2083
possibly_present_revisions = target_ids.intersection(source_ids_set)
2084
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2085
required_revisions = source_ids_set.difference(actually_present_revisions)
2086
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2087
if revision_id is not None:
2088
# we used get_ancestry to determine source_ids then we are assured all
2089
# revisions referenced are present as they are installed in topological order.
2090
# and the tip revision was validated by get_ancestry.
2091
return required_topo_revisions
2093
# if we just grabbed the possibly available ids, then
2094
# we only have an estimate of whats available and need to validate
2095
# that against the revision records.
2096
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2099
class InterKnitRepo(InterSameDataRepository):
2100
"""Optimised code paths between Knit based repositories."""
2102
_matching_repo_format = RepositoryFormatKnit1()
2103
"""Repository format for testing with."""
2106
def is_compatible(source, target):
2107
"""Be compatible with known Knit formats.
2109
We don't test for the stores being of specific types because that
2110
could lead to confusing results, and there is no need to be
2114
return (isinstance(source._format, (RepositoryFormatKnit1)) and
2115
isinstance(target._format, (RepositoryFormatKnit1)))
2116
except AttributeError:
2120
def fetch(self, revision_id=None, pb=None):
2121
"""See InterRepository.fetch()."""
2122
from bzrlib.fetch import KnitRepoFetcher
2123
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2124
self.source, self.source._format, self.target, self.target._format)
2125
f = KnitRepoFetcher(to_repository=self.target,
2126
from_repository=self.source,
2127
last_revision=revision_id,
2129
return f.count_copied, f.failed_revisions
2132
def missing_revision_ids(self, revision_id=None):
2133
"""See InterRepository.missing_revision_ids()."""
2134
if revision_id is not None:
2135
source_ids = self.source.get_ancestry(revision_id)
2136
assert source_ids[0] is None
2139
source_ids = self.source._all_possible_ids()
2140
source_ids_set = set(source_ids)
2141
# source_ids is the worst possible case we may need to pull.
2142
# now we want to filter source_ids against what we actually
2143
# have in target, but don't try to check for existence where we know
2144
# we do not have a revision as that would be pointless.
2145
target_ids = set(self.target._all_possible_ids())
2146
possibly_present_revisions = target_ids.intersection(source_ids_set)
2147
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2148
required_revisions = source_ids_set.difference(actually_present_revisions)
2149
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2150
if revision_id is not None:
2151
# we used get_ancestry to determine source_ids then we are assured all
2152
# revisions referenced are present as they are installed in topological order.
2153
# and the tip revision was validated by get_ancestry.
2154
return required_topo_revisions
2156
# if we just grabbed the possibly available ids, then
2157
# we only have an estimate of whats available and need to validate
2158
# that against the revision records.
2159
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2162
class InterModel1and2(InterRepository):
2164
_matching_repo_format = None
2167
def is_compatible(source, target):
2168
if not isinstance(source, Repository):
2170
if not isinstance(target, Repository):
2172
if not source._format.rich_root_data and target._format.rich_root_data:
2178
def fetch(self, revision_id=None, pb=None):
2179
"""See InterRepository.fetch()."""
2180
from bzrlib.fetch import Model1toKnit2Fetcher
2181
f = Model1toKnit2Fetcher(to_repository=self.target,
2182
from_repository=self.source,
2183
last_revision=revision_id,
2185
return f.count_copied, f.failed_revisions
2188
def copy_content(self, revision_id=None, basis=None):
2189
"""Make a complete copy of the content in self into destination.
2191
This is a destructive operation! Do not use it on existing
2194
:param revision_id: Only copy the content needed to construct
2195
revision_id and its parents.
2196
:param basis: Copy the needed data preferentially from basis.
2199
self.target.set_make_working_trees(self.source.make_working_trees())
2200
except NotImplementedError:
2202
# grab the basis available data
2203
if basis is not None:
2204
self.target.fetch(basis, revision_id=revision_id)
2205
# but don't bother fetching if we have the needed data now.
2206
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
2207
self.target.has_revision(revision_id)):
2209
self.target.fetch(self.source, revision_id=revision_id)
2212
class InterKnit1and2(InterKnitRepo):
2214
_matching_repo_format = None
2217
def is_compatible(source, target):
2218
"""Be compatible with Knit1 source and Knit2 target"""
2220
return (isinstance(source._format, (RepositoryFormatKnit1)) and
2221
isinstance(target._format, (RepositoryFormatKnit2)))
2222
except AttributeError:
2226
def fetch(self, revision_id=None, pb=None):
2227
"""See InterRepository.fetch()."""
2228
from bzrlib.fetch import Knit1to2Fetcher
2229
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2230
self.source, self.source._format, self.target,
2231
self.target._format)
2232
f = Knit1to2Fetcher(to_repository=self.target,
2233
from_repository=self.source,
2234
last_revision=revision_id,
2236
return f.count_copied, f.failed_revisions
2239
InterRepository.register_optimiser(InterSameDataRepository)
2240
InterRepository.register_optimiser(InterWeaveRepo)
2241
InterRepository.register_optimiser(InterKnitRepo)
2242
InterRepository.register_optimiser(InterModel1and2)
2243
InterRepository.register_optimiser(InterKnit1and2)
2246
class RepositoryTestProviderAdapter(object):
2247
"""A tool to generate a suite testing multiple repository formats at once.
2249
This is done by copying the test once for each transport and injecting
2250
the transport_server, transport_readonly_server, and bzrdir_format and
2251
repository_format classes into each copy. Each copy is also given a new id()
2252
to make it easy to identify.
2255
def __init__(self, transport_server, transport_readonly_server, formats,
2256
vfs_transport_factory=None):
2257
self._transport_server = transport_server
2258
self._transport_readonly_server = transport_readonly_server
2259
self._vfs_transport_factory = vfs_transport_factory
2260
self._formats = formats
2262
def adapt(self, test):
2263
result = unittest.TestSuite()
2264
for repository_format, bzrdir_format in self._formats:
2265
new_test = deepcopy(test)
2266
new_test.transport_server = self._transport_server
2267
new_test.transport_readonly_server = self._transport_readonly_server
2268
if self._vfs_transport_factory:
2269
new_test.vfs_transport_factory = self._vfs_transport_factory
2270
new_test.bzrdir_format = bzrdir_format
2271
new_test.repository_format = repository_format
2272
def make_new_test_id():
2273
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
2274
return lambda: new_id
2275
new_test.id = make_new_test_id()
2276
result.addTest(new_test)
2280
class InterRepositoryTestProviderAdapter(object):
2281
"""A tool to generate a suite testing multiple inter repository formats.
2283
This is done by copying the test once for each interrepo provider and injecting
2284
the transport_server, transport_readonly_server, repository_format and
2285
repository_to_format classes into each copy.
2286
Each copy is also given a new id() to make it easy to identify.
2289
def __init__(self, transport_server, transport_readonly_server, formats):
2290
self._transport_server = transport_server
2291
self._transport_readonly_server = transport_readonly_server
2292
self._formats = formats
2294
def adapt(self, test):
2295
result = unittest.TestSuite()
2296
for interrepo_class, repository_format, repository_format_to in self._formats:
2297
new_test = deepcopy(test)
2298
new_test.transport_server = self._transport_server
2299
new_test.transport_readonly_server = self._transport_readonly_server
2300
new_test.interrepo_class = interrepo_class
2301
new_test.repository_format = repository_format
2302
new_test.repository_format_to = repository_format_to
2303
def make_new_test_id():
2304
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
2305
return lambda: new_id
2306
new_test.id = make_new_test_id()
2307
result.addTest(new_test)
2311
def default_test_list():
2312
"""Generate the default list of interrepo permutations to test."""
2314
# test the default InterRepository between format 6 and the current
2316
# XXX: robertc 20060220 reinstate this when there are two supported
2317
# formats which do not have an optimal code path between them.
2318
#result.append((InterRepository,
2319
# RepositoryFormat6(),
2320
# RepositoryFormatKnit1()))
2321
for optimiser in InterRepository._optimisers:
2322
if optimiser._matching_repo_format is not None:
2323
result.append((optimiser,
2324
optimiser._matching_repo_format,
2325
optimiser._matching_repo_format
2327
# if there are specific combinations we want to use, we can add them
2329
result.append((InterModel1and2, RepositoryFormat5(),
2330
RepositoryFormatKnit2()))
2331
result.append((InterKnit1and2, RepositoryFormatKnit1(),
2332
RepositoryFormatKnit2()))
2336
class CopyConverter(object):
2337
"""A repository conversion tool which just performs a copy of the content.
2339
This is slow but quite reliable.
2342
def __init__(self, target_format):
2343
"""Create a CopyConverter.
2345
:param target_format: The format the resulting repository should be.
2347
self.target_format = target_format
2349
def convert(self, repo, pb):
2350
"""Perform the conversion of to_convert, giving feedback via pb.
2352
:param to_convert: The disk object to convert.
2353
:param pb: a progress bar to use for progress information.
2358
# this is only useful with metadir layouts - separated repo content.
2359
# trigger an assertion if not such
2360
repo._format.get_format_string()
2361
self.repo_dir = repo.bzrdir
2362
self.step('Moving repository to repository.backup')
2363
self.repo_dir.transport.move('repository', 'repository.backup')
2364
backup_transport = self.repo_dir.transport.clone('repository.backup')
2365
repo._format.check_conversion_target(self.target_format)
2366
self.source_repo = repo._format.open(self.repo_dir,
2368
_override_transport=backup_transport)
2369
self.step('Creating new repository')
2370
converted = self.target_format.initialize(self.repo_dir,
2371
self.source_repo.is_shared())
2372
converted.lock_write()
2374
self.step('Copying content into repository.')
2375
self.source_repo.copy_content_into(converted)
2378
self.step('Deleting old repository content.')
2379
self.repo_dir.transport.delete_tree('repository.backup')
2380
self.pb.note('repository converted')
2382
def step(self, message):
2383
"""Update the pb by a step."""
2385
self.pb.update(message, self.count, self.total)
2388
class CommitBuilder(object):
2389
"""Provides an interface to build up a commit.
2391
This allows describing a tree to be committed without needing to
2392
know the internals of the format of the repository.
2395
record_root_entry = False
2396
def __init__(self, repository, parents, config, timestamp=None,
2397
timezone=None, committer=None, revprops=None,
2399
"""Initiate a CommitBuilder.
2401
:param repository: Repository to commit to.
2402
:param parents: Revision ids of the parents of the new revision.
2403
:param config: Configuration to use.
2404
:param timestamp: Optional timestamp recorded for commit.
2405
:param timezone: Optional timezone for timestamp.
2406
:param committer: Optional committer to set for commit.
2407
:param revprops: Optional dictionary of revision properties.
2408
:param revision_id: Optional revision id.
2410
self._config = config
2412
if committer is None:
2413
self._committer = self._config.username()
2415
assert isinstance(committer, basestring), type(committer)
2416
self._committer = committer
2418
self.new_inventory = Inventory(None)
2419
self._new_revision_id = revision_id
2420
self.parents = parents
2421
self.repository = repository
2424
if revprops is not None:
2425
self._revprops.update(revprops)
2427
if timestamp is None:
2428
timestamp = time.time()
2429
# Restrict resolution to 1ms
2430
self._timestamp = round(timestamp, 3)
2432
if timezone is None:
2433
self._timezone = local_time_offset()
2435
self._timezone = int(timezone)
2437
self._generate_revision_if_needed()
2439
def commit(self, message):
2440
"""Make the actual commit.
2442
:return: The revision id of the recorded revision.
2444
rev = _mod_revision.Revision(
2445
timestamp=self._timestamp,
2446
timezone=self._timezone,
2447
committer=self._committer,
2449
inventory_sha1=self.inv_sha1,
2450
revision_id=self._new_revision_id,
2451
properties=self._revprops)
2452
rev.parent_ids = self.parents
2453
self.repository.add_revision(self._new_revision_id, rev,
2454
self.new_inventory, self._config)
2455
return self._new_revision_id
2457
def revision_tree(self):
2458
"""Return the tree that was just committed.
2460
After calling commit() this can be called to get a RevisionTree
2461
representing the newly committed tree. This is preferred to
2462
calling Repository.revision_tree() because that may require
2463
deserializing the inventory, while we already have a copy in
2466
return RevisionTree(self.repository, self.new_inventory,
2467
self._new_revision_id)
2469
def finish_inventory(self):
2470
"""Tell the builder that the inventory is finished."""
2471
if self.new_inventory.root is None:
2472
symbol_versioning.warn('Root entry should be supplied to'
2473
' record_entry_contents, as of bzr 0.10.',
2474
DeprecationWarning, stacklevel=2)
2475
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
2476
self.new_inventory.revision_id = self._new_revision_id
2477
self.inv_sha1 = self.repository.add_inventory(
2478
self._new_revision_id,
2483
def _gen_revision_id(self):
2484
"""Return new revision-id."""
2485
return generate_ids.gen_revision_id(self._config.username(),
2488
def _generate_revision_if_needed(self):
2489
"""Create a revision id if None was supplied.
2491
If the repository can not support user-specified revision ids
2492
they should override this function and raise CannotSetRevisionId
2493
if _new_revision_id is not None.
2495
:raises: CannotSetRevisionId
2497
if self._new_revision_id is None:
2498
self._new_revision_id = self._gen_revision_id()
2500
def record_entry_contents(self, ie, parent_invs, path, tree):
2501
"""Record the content of ie from tree into the commit if needed.
2503
Side effect: sets ie.revision when unchanged
2505
:param ie: An inventory entry present in the commit.
2506
:param parent_invs: The inventories of the parent revisions of the
2508
:param path: The path the entry is at in the tree.
2509
:param tree: The tree which contains this entry and should be used to
2512
if self.new_inventory.root is None and ie.parent_id is not None:
2513
symbol_versioning.warn('Root entry should be supplied to'
2514
' record_entry_contents, as of bzr 0.10.',
2515
DeprecationWarning, stacklevel=2)
2516
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2518
self.new_inventory.add(ie)
2520
# ie.revision is always None if the InventoryEntry is considered
2521
# for committing. ie.snapshot will record the correct revision
2522
# which may be the sole parent if it is untouched.
2523
if ie.revision is not None:
2526
# In this revision format, root entries have no knit or weave
2527
if ie is self.new_inventory.root:
2528
# When serializing out to disk and back in
2529
# root.revision is always _new_revision_id
2530
ie.revision = self._new_revision_id
2532
previous_entries = ie.find_previous_heads(
2534
self.repository.weave_store,
2535
self.repository.get_transaction())
2536
# we are creating a new revision for ie in the history store
2538
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2540
def modified_directory(self, file_id, file_parents):
2541
"""Record the presence of a symbolic link.
2543
:param file_id: The file_id of the link to record.
2544
:param file_parents: The per-file parent revision ids.
2546
self._add_text_to_weave(file_id, [], file_parents.keys())
2548
def modified_file_text(self, file_id, file_parents,
2549
get_content_byte_lines, text_sha1=None,
2551
"""Record the text of file file_id
2553
:param file_id: The file_id of the file to record the text of.
2554
:param file_parents: The per-file parent revision ids.
2555
:param get_content_byte_lines: A callable which will return the byte
2557
:param text_sha1: Optional SHA1 of the file contents.
2558
:param text_size: Optional size of the file contents.
2560
# mutter('storing text of file {%s} in revision {%s} into %r',
2561
# file_id, self._new_revision_id, self.repository.weave_store)
2562
# special case to avoid diffing on renames or
2564
if (len(file_parents) == 1
2565
and text_sha1 == file_parents.values()[0].text_sha1
2566
and text_size == file_parents.values()[0].text_size):
2567
previous_ie = file_parents.values()[0]
2568
versionedfile = self.repository.weave_store.get_weave(file_id,
2569
self.repository.get_transaction())
2570
versionedfile.clone_text(self._new_revision_id,
2571
previous_ie.revision, file_parents.keys())
2572
return text_sha1, text_size
2574
new_lines = get_content_byte_lines()
2575
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2576
# should return the SHA1 and size
2577
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2578
return osutils.sha_strings(new_lines), \
2579
sum(map(len, new_lines))
2581
def modified_link(self, file_id, file_parents, link_target):
2582
"""Record the presence of a symbolic link.
2584
:param file_id: The file_id of the link to record.
2585
:param file_parents: The per-file parent revision ids.
2586
:param link_target: Target location of this link.
2588
self._add_text_to_weave(file_id, [], file_parents.keys())
2590
def _add_text_to_weave(self, file_id, new_lines, parents):
2591
versionedfile = self.repository.weave_store.get_weave_or_empty(
2592
file_id, self.repository.get_transaction())
2593
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2594
versionedfile.clear_cache()
2597
class _CommitBuilder(CommitBuilder):
2598
"""Temporary class so old CommitBuilders are detected properly
2600
Note: CommitBuilder works whether or not root entry is recorded.
2603
record_root_entry = True
2606
class RootCommitBuilder(CommitBuilder):
2607
"""This commitbuilder actually records the root id"""
2609
record_root_entry = True
2611
def record_entry_contents(self, ie, parent_invs, path, tree):
2612
"""Record the content of ie from tree into the commit if needed.
2614
Side effect: sets ie.revision when unchanged
2616
:param ie: An inventory entry present in the commit.
2617
:param parent_invs: The inventories of the parent revisions of the
2619
:param path: The path the entry is at in the tree.
2620
:param tree: The tree which contains this entry and should be used to
2623
assert self.new_inventory.root is not None or ie.parent_id is None
2624
self.new_inventory.add(ie)
2626
# ie.revision is always None if the InventoryEntry is considered
2627
# for committing. ie.snapshot will record the correct revision
2628
# which may be the sole parent if it is untouched.
2629
if ie.revision is not None:
2632
previous_entries = ie.find_previous_heads(
2634
self.repository.weave_store,
2635
self.repository.get_transaction())
2636
# we are creating a new revision for ie in the history store
2638
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2650
def _unescaper(match, _map=_unescape_map):
2651
return _map[match.group(1)]
2657
def _unescape_xml(data):
2658
"""Unescape predefined XML entities in a string of data."""
2660
if _unescape_re is None:
2661
_unescape_re = re.compile('\&([^;]*);')
2662
return _unescape_re.sub(_unescaper, data)