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 missing_revision_ids(self, other, revision_id=None):
247
"""Return the revision ids that other has that this does not.
249
These are returned in topological order.
251
revision_id: only return revision ids included by revision_id.
253
return InterRepository.get(other, self).missing_revision_ids(revision_id)
257
"""Open the repository rooted at base.
259
For instance, if the repository is at URL/.bzr/repository,
260
Repository.open(URL) -> a Repository instance.
262
control = bzrdir.BzrDir.open(base)
263
return control.open_repository()
265
def copy_content_into(self, destination, revision_id=None, basis=None):
266
"""Make a complete copy of the content in self into destination.
268
This is a destructive operation! Do not use it on existing
271
return InterRepository.get(self, destination).copy_content(revision_id, basis)
273
def fetch(self, source, revision_id=None, pb=None):
274
"""Fetch the content required to construct revision_id from source.
276
If revision_id is None all content is copied.
278
return InterRepository.get(source, self).fetch(revision_id=revision_id,
281
def get_commit_builder(self, branch, parents, config, timestamp=None,
282
timezone=None, committer=None, revprops=None,
284
"""Obtain a CommitBuilder for this repository.
286
:param branch: Branch to commit to.
287
:param parents: Revision ids of the parents of the new revision.
288
:param config: Configuration to use.
289
:param timestamp: Optional timestamp recorded for commit.
290
:param timezone: Optional timezone for timestamp.
291
:param committer: Optional committer to set for commit.
292
:param revprops: Optional dictionary of revision properties.
293
:param revision_id: Optional revision id.
295
return _CommitBuilder(self, parents, config, timestamp, timezone,
296
committer, revprops, revision_id)
299
self.control_files.unlock()
302
def clone(self, a_bzrdir, revision_id=None, basis=None):
303
"""Clone this repository into a_bzrdir using the current format.
305
Currently no check is made that the format of this repository and
306
the bzrdir format are compatible. FIXME RBC 20060201.
308
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
309
# use target default format.
310
result = a_bzrdir.create_repository()
311
# FIXME RBC 20060209 split out the repository type to avoid this check ?
312
elif isinstance(a_bzrdir._format,
313
(bzrdir.BzrDirFormat4,
314
bzrdir.BzrDirFormat5,
315
bzrdir.BzrDirFormat6)):
316
result = a_bzrdir.open_repository()
318
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
319
self.copy_content_into(result, revision_id, basis)
323
def has_revision(self, revision_id):
324
"""True if this repository has a copy of the revision."""
325
return self._revision_store.has_revision_id(revision_id,
326
self.get_transaction())
329
def get_revision_reconcile(self, revision_id):
330
"""'reconcile' helper routine that allows access to a revision always.
332
This variant of get_revision does not cross check the weave graph
333
against the revision one as get_revision does: but it should only
334
be used by reconcile, or reconcile-alike commands that are correcting
335
or testing the revision graph.
337
if not revision_id or not isinstance(revision_id, basestring):
338
raise errors.InvalidRevisionId(revision_id=revision_id,
340
return self._revision_store.get_revisions([revision_id],
341
self.get_transaction())[0]
343
def get_revisions(self, revision_ids):
344
return self._revision_store.get_revisions(revision_ids,
345
self.get_transaction())
348
def get_revision_xml(self, revision_id):
349
rev = self.get_revision(revision_id)
351
# the current serializer..
352
self._revision_store._serializer.write_revision(rev, rev_tmp)
354
return rev_tmp.getvalue()
357
def get_revision(self, revision_id):
358
"""Return the Revision object for a named revision"""
359
r = self.get_revision_reconcile(revision_id)
360
# weave corruption can lead to absent revision markers that should be
362
# the following test is reasonably cheap (it needs a single weave read)
363
# and the weave is cached in read transactions. In write transactions
364
# it is not cached but typically we only read a small number of
365
# revisions. For knits when they are introduced we will probably want
366
# to ensure that caching write transactions are in use.
367
inv = self.get_inventory_weave()
368
self._check_revision_parents(r, inv)
372
def get_deltas_for_revisions(self, revisions):
373
"""Produce a generator of revision deltas.
375
Note that the input is a sequence of REVISIONS, not revision_ids.
376
Trees will be held in memory until the generator exits.
377
Each delta is relative to the revision's lefthand predecessor.
379
required_trees = set()
380
for revision in revisions:
381
required_trees.add(revision.revision_id)
382
required_trees.update(revision.parent_ids[:1])
383
trees = dict((t.get_revision_id(), t) for
384
t in self.revision_trees(required_trees))
385
for revision in revisions:
386
if not revision.parent_ids:
387
old_tree = self.revision_tree(None)
389
old_tree = trees[revision.parent_ids[0]]
390
yield trees[revision.revision_id].changes_from(old_tree)
393
def get_revision_delta(self, revision_id):
394
"""Return the delta for one revision.
396
The delta is relative to the left-hand predecessor of the
399
r = self.get_revision(revision_id)
400
return list(self.get_deltas_for_revisions([r]))[0]
402
def _check_revision_parents(self, revision, inventory):
403
"""Private to Repository and Fetch.
405
This checks the parentage of revision in an inventory weave for
406
consistency and is only applicable to inventory-weave-for-ancestry
407
using repository formats & fetchers.
409
weave_parents = inventory.get_parents(revision.revision_id)
410
weave_names = inventory.versions()
411
for parent_id in revision.parent_ids:
412
if parent_id in weave_names:
413
# this parent must not be a ghost.
414
if not parent_id in weave_parents:
416
raise errors.CorruptRepository(self)
419
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
420
signature = gpg_strategy.sign(plaintext)
421
self._revision_store.add_revision_signature_text(revision_id,
423
self.get_transaction())
425
def fileids_altered_by_revision_ids(self, revision_ids):
426
"""Find the file ids and versions affected by revisions.
428
:param revisions: an iterable containing revision ids.
429
:return: a dictionary mapping altered file-ids to an iterable of
430
revision_ids. Each altered file-ids has the exact revision_ids that
431
altered it listed explicitly.
433
assert self._serializer.support_altered_by_hack, \
434
("fileids_altered_by_revision_ids only supported for branches "
435
"which store inventory as unnested xml, not on %r" % self)
436
selected_revision_ids = set(revision_ids)
437
w = self.get_inventory_weave()
440
# this code needs to read every new line in every inventory for the
441
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
442
# not present in one of those inventories is unnecessary but not
443
# harmful because we are filtering by the revision id marker in the
444
# inventory lines : we only select file ids altered in one of those
445
# revisions. We don't need to see all lines in the inventory because
446
# only those added in an inventory in rev X can contain a revision=X
448
unescape_revid_cache = {}
449
unescape_fileid_cache = {}
451
# jam 20061218 In a big fetch, this handles hundreds of thousands
452
# of lines, so it has had a lot of inlining and optimizing done.
453
# Sorry that it is a little bit messy.
454
# Move several functions to be local variables, since this is a long
456
search = self._file_ids_altered_regex.search
457
unescape = _unescape_xml
458
setdefault = result.setdefault
459
pb = ui.ui_factory.nested_progress_bar()
461
for line in w.iter_lines_added_or_present_in_versions(
462
selected_revision_ids, pb=pb):
466
# One call to match.group() returning multiple items is quite a
467
# bit faster than 2 calls to match.group() each returning 1
468
file_id, revision_id = match.group('file_id', 'revision_id')
470
# Inlining the cache lookups helps a lot when you make 170,000
471
# lines and 350k ids, versus 8.4 unique ids.
472
# Using a cache helps in 2 ways:
473
# 1) Avoids unnecessary decoding calls
474
# 2) Re-uses cached strings, which helps in future set and
476
# (2) is enough that removing encoding entirely along with
477
# the cache (so we are using plain strings) results in no
478
# performance improvement.
480
revision_id = unescape_revid_cache[revision_id]
482
unescaped = unescape(revision_id)
483
unescape_revid_cache[revision_id] = unescaped
484
revision_id = unescaped
486
if revision_id in selected_revision_ids:
488
file_id = unescape_fileid_cache[file_id]
490
unescaped = unescape(file_id)
491
unescape_fileid_cache[file_id] = unescaped
493
setdefault(file_id, set()).add(revision_id)
499
def get_inventory_weave(self):
500
return self.control_weaves.get_weave('inventory',
501
self.get_transaction())
504
def get_inventory(self, revision_id):
505
"""Get Inventory object by hash."""
506
return self.deserialise_inventory(
507
revision_id, self.get_inventory_xml(revision_id))
509
def deserialise_inventory(self, revision_id, xml):
510
"""Transform the xml into an inventory object.
512
:param revision_id: The expected revision id of the inventory.
513
:param xml: A serialised inventory.
515
result = self._serializer.read_inventory_from_string(xml)
516
result.root.revision = revision_id
519
def serialise_inventory(self, inv):
520
return self._serializer.write_inventory_to_string(inv)
523
def get_inventory_xml(self, revision_id):
524
"""Get inventory XML as a file object."""
526
assert isinstance(revision_id, basestring), type(revision_id)
527
iw = self.get_inventory_weave()
528
return iw.get_text(revision_id)
530
raise errors.HistoryMissing(self, 'inventory', revision_id)
533
def get_inventory_sha1(self, revision_id):
534
"""Return the sha1 hash of the inventory entry
536
return self.get_revision(revision_id).inventory_sha1
539
def get_revision_graph(self, revision_id=None):
540
"""Return a dictionary containing the revision graph.
542
:param revision_id: The revision_id to get a graph from. If None, then
543
the entire revision graph is returned. This is a deprecated mode of
544
operation and will be removed in the future.
545
:return: a dictionary of revision_id->revision_parents_list.
547
# special case NULL_REVISION
548
if revision_id == _mod_revision.NULL_REVISION:
550
a_weave = self.get_inventory_weave()
551
all_revisions = self._eliminate_revisions_not_present(
553
entire_graph = dict([(node, a_weave.get_parents(node)) for
554
node in all_revisions])
555
if revision_id is None:
557
elif revision_id not in entire_graph:
558
raise errors.NoSuchRevision(self, revision_id)
560
# add what can be reached from revision_id
562
pending = set([revision_id])
563
while len(pending) > 0:
565
result[node] = entire_graph[node]
566
for revision_id in result[node]:
567
if revision_id not in result:
568
pending.add(revision_id)
572
def get_revision_graph_with_ghosts(self, revision_ids=None):
573
"""Return a graph of the revisions with ghosts marked as applicable.
575
:param revision_ids: an iterable of revisions to graph or None for all.
576
:return: a Graph object with the graph reachable from revision_ids.
578
result = graph.Graph()
580
pending = set(self.all_revision_ids())
583
pending = set(revision_ids)
584
# special case NULL_REVISION
585
if _mod_revision.NULL_REVISION in pending:
586
pending.remove(_mod_revision.NULL_REVISION)
587
required = set(pending)
590
revision_id = pending.pop()
592
rev = self.get_revision(revision_id)
593
except errors.NoSuchRevision:
594
if revision_id in required:
597
result.add_ghost(revision_id)
599
for parent_id in rev.parent_ids:
600
# is this queued or done ?
601
if (parent_id not in pending and
602
parent_id not in done):
604
pending.add(parent_id)
605
result.add_node(revision_id, rev.parent_ids)
606
done.add(revision_id)
610
def get_revision_inventory(self, revision_id):
611
"""Return inventory of a past revision."""
612
# TODO: Unify this with get_inventory()
613
# bzr 0.0.6 and later imposes the constraint that the inventory_id
614
# must be the same as its revision, so this is trivial.
615
if revision_id is None:
616
# This does not make sense: if there is no revision,
617
# then it is the current tree inventory surely ?!
618
# and thus get_root_id() is something that looks at the last
619
# commit on the branch, and the get_root_id is an inventory check.
620
raise NotImplementedError
621
# return Inventory(self.get_root_id())
623
return self.get_inventory(revision_id)
627
"""Return True if this repository is flagged as a shared repository."""
628
raise NotImplementedError(self.is_shared)
631
def reconcile(self, other=None, thorough=False):
632
"""Reconcile this repository."""
633
from bzrlib.reconcile import RepoReconciler
634
reconciler = RepoReconciler(self, thorough=thorough)
635
reconciler.reconcile()
639
def revision_tree(self, revision_id):
640
"""Return Tree for a revision on this branch.
642
`revision_id` may be None for the empty tree revision.
644
# TODO: refactor this to use an existing revision object
645
# so we don't need to read it in twice.
646
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
647
return RevisionTree(self, Inventory(root_id=None),
648
_mod_revision.NULL_REVISION)
650
inv = self.get_revision_inventory(revision_id)
651
return RevisionTree(self, inv, revision_id)
654
def revision_trees(self, revision_ids):
655
"""Return Tree for a revision on this branch.
657
`revision_id` may not be None or 'null:'"""
658
assert None not in revision_ids
659
assert _mod_revision.NULL_REVISION not in revision_ids
660
texts = self.get_inventory_weave().get_texts(revision_ids)
661
for text, revision_id in zip(texts, revision_ids):
662
inv = self.deserialise_inventory(revision_id, text)
663
yield RevisionTree(self, inv, revision_id)
666
def get_ancestry(self, revision_id):
667
"""Return a list of revision-ids integrated by a revision.
669
The first element of the list is always None, indicating the origin
670
revision. This might change when we have history horizons, or
671
perhaps we should have a new API.
673
This is topologically sorted.
675
if revision_id is None:
677
if not self.has_revision(revision_id):
678
raise errors.NoSuchRevision(self, revision_id)
679
w = self.get_inventory_weave()
680
candidates = w.get_ancestry(revision_id)
681
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
684
def print_file(self, file, revision_id):
685
"""Print `file` to stdout.
687
FIXME RBC 20060125 as John Meinel points out this is a bad api
688
- it writes to stdout, it assumes that that is valid etc. Fix
689
by creating a new more flexible convenience function.
691
tree = self.revision_tree(revision_id)
692
# use inventory as it was in that revision
693
file_id = tree.inventory.path2id(file)
695
# TODO: jam 20060427 Write a test for this code path
696
# it had a bug in it, and was raising the wrong
698
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
699
tree.print_file(file_id)
701
def get_transaction(self):
702
return self.control_files.get_transaction()
704
def revision_parents(self, revid):
705
return self.get_inventory_weave().parent_names(revid)
708
def set_make_working_trees(self, new_value):
709
"""Set the policy flag for making working trees when creating branches.
711
This only applies to branches that use this repository.
713
The default is 'True'.
714
:param new_value: True to restore the default, False to disable making
717
raise NotImplementedError(self.set_make_working_trees)
719
def make_working_trees(self):
720
"""Returns the policy for making working trees on new branches."""
721
raise NotImplementedError(self.make_working_trees)
724
def sign_revision(self, revision_id, gpg_strategy):
725
plaintext = Testament.from_revision(self, revision_id).as_short_text()
726
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
729
def has_signature_for_revision_id(self, revision_id):
730
"""Query for a revision signature for revision_id in the repository."""
731
return self._revision_store.has_signature(revision_id,
732
self.get_transaction())
735
def get_signature_text(self, revision_id):
736
"""Return the text for a signature."""
737
return self._revision_store.get_signature_text(revision_id,
738
self.get_transaction())
741
def check(self, revision_ids):
742
"""Check consistency of all history of given revision_ids.
744
Different repository implementations should override _check().
746
:param revision_ids: A non-empty list of revision_ids whose ancestry
747
will be checked. Typically the last revision_id of a branch.
750
raise ValueError("revision_ids must be non-empty in %s.check"
752
return self._check(revision_ids)
754
def _check(self, revision_ids):
755
result = check.Check(self)
759
def _warn_if_deprecated(self):
760
global _deprecation_warning_done
761
if _deprecation_warning_done:
763
_deprecation_warning_done = True
764
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
765
% (self._format, self.bzrdir.transport.base))
767
def supports_rich_root(self):
768
return self._format.rich_root_data
770
def _check_ascii_revisionid(self, revision_id, method):
771
"""Private helper for ascii-only repositories."""
772
# weave repositories refuse to store revisionids that are non-ascii.
773
if revision_id is not None:
774
# weaves require ascii revision ids.
775
if isinstance(revision_id, unicode):
777
revision_id.encode('ascii')
778
except UnicodeEncodeError:
779
raise errors.NonAsciiRevisionId(method, self)
782
class AllInOneRepository(Repository):
783
"""Legacy support - the repository behaviour for all-in-one branches."""
785
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
786
# we reuse one control files instance.
787
dir_mode = a_bzrdir._control_files._dir_mode
788
file_mode = a_bzrdir._control_files._file_mode
790
def get_store(name, compressed=True, prefixed=False):
791
# FIXME: This approach of assuming stores are all entirely compressed
792
# or entirely uncompressed is tidy, but breaks upgrade from
793
# some existing branches where there's a mixture; we probably
794
# still want the option to look for both.
795
relpath = a_bzrdir._control_files._escape(name)
796
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
797
prefixed=prefixed, compressed=compressed,
800
#if self._transport.should_cache():
801
# cache_path = os.path.join(self.cache_root, name)
802
# os.mkdir(cache_path)
803
# store = bzrlib.store.CachedStore(store, cache_path)
806
# not broken out yet because the controlweaves|inventory_store
807
# and text_store | weave_store bits are still different.
808
if isinstance(_format, RepositoryFormat4):
809
# cannot remove these - there is still no consistent api
810
# which allows access to this old info.
811
self.inventory_store = get_store('inventory-store')
812
text_store = get_store('text-store')
813
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
815
def get_commit_builder(self, branch, parents, config, timestamp=None,
816
timezone=None, committer=None, revprops=None,
818
self._check_ascii_revisionid(revision_id, self.get_commit_builder)
819
return Repository.get_commit_builder(self, branch, parents, config,
820
timestamp, timezone, committer, revprops, revision_id)
824
"""AllInOne repositories cannot be shared."""
828
def set_make_working_trees(self, new_value):
829
"""Set the policy flag for making working trees when creating branches.
831
This only applies to branches that use this repository.
833
The default is 'True'.
834
:param new_value: True to restore the default, False to disable making
837
raise NotImplementedError(self.set_make_working_trees)
839
def make_working_trees(self):
840
"""Returns the policy for making working trees on new branches."""
844
def install_revision(repository, rev, revision_tree):
845
"""Install all revision data into a repository."""
848
for p_id in rev.parent_ids:
849
if repository.has_revision(p_id):
850
present_parents.append(p_id)
851
parent_trees[p_id] = repository.revision_tree(p_id)
853
parent_trees[p_id] = repository.revision_tree(None)
855
inv = revision_tree.inventory
856
entries = inv.iter_entries()
857
# backwards compatability hack: skip the root id.
858
if not repository.supports_rich_root():
859
path, root = entries.next()
860
if root.revision != rev.revision_id:
861
raise errors.IncompatibleRevision(repr(repository))
862
# Add the texts that are not already present
863
for path, ie in entries:
864
w = repository.weave_store.get_weave_or_empty(ie.file_id,
865
repository.get_transaction())
866
if ie.revision not in w:
868
# FIXME: TODO: The following loop *may* be overlapping/duplicate
869
# with InventoryEntry.find_previous_heads(). if it is, then there
870
# is a latent bug here where the parents may have ancestors of each
872
for revision, tree in parent_trees.iteritems():
873
if ie.file_id not in tree:
875
parent_id = tree.inventory[ie.file_id].revision
876
if parent_id in text_parents:
878
text_parents.append(parent_id)
880
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
881
repository.get_transaction())
882
lines = revision_tree.get_file(ie.file_id).readlines()
883
vfile.add_lines(rev.revision_id, text_parents, lines)
885
# install the inventory
886
repository.add_inventory(rev.revision_id, inv, present_parents)
887
except errors.RevisionAlreadyPresent:
889
repository.add_revision(rev.revision_id, rev, inv)
892
class MetaDirRepository(Repository):
893
"""Repositories in the new meta-dir layout."""
895
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
896
super(MetaDirRepository, self).__init__(_format,
902
dir_mode = self.control_files._dir_mode
903
file_mode = self.control_files._file_mode
907
"""Return True if this repository is flagged as a shared repository."""
908
return self.control_files._transport.has('shared-storage')
911
def set_make_working_trees(self, new_value):
912
"""Set the policy flag for making working trees when creating branches.
914
This only applies to branches that use this repository.
916
The default is 'True'.
917
:param new_value: True to restore the default, False to disable making
922
self.control_files._transport.delete('no-working-trees')
923
except errors.NoSuchFile:
926
self.control_files.put_utf8('no-working-trees', '')
928
def make_working_trees(self):
929
"""Returns the policy for making working trees on new branches."""
930
return not self.control_files._transport.has('no-working-trees')
933
class WeaveMetaDirRepository(MetaDirRepository):
934
"""A subclass of MetaDirRepository to set weave specific policy."""
936
def get_commit_builder(self, branch, parents, config, timestamp=None,
937
timezone=None, committer=None, revprops=None,
939
self._check_ascii_revisionid(revision_id, self.get_commit_builder)
940
return MetaDirRepository.get_commit_builder(self, branch, parents,
941
config, timestamp, timezone, committer, revprops, revision_id)
944
class KnitRepository(MetaDirRepository):
945
"""Knit format repository."""
947
def _warn_if_deprecated(self):
948
# This class isn't deprecated
951
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
952
inv_vf.add_lines_with_ghosts(revid, parents, lines)
955
def _all_revision_ids(self):
956
"""See Repository.all_revision_ids()."""
957
# Knits get the revision graph from the index of the revision knit, so
958
# it's always possible even if they're on an unlistable transport.
959
return self._revision_store.all_revision_ids(self.get_transaction())
961
def fileid_involved_between_revs(self, from_revid, to_revid):
962
"""Find file_id(s) which are involved in the changes between revisions.
964
This determines the set of revisions which are involved, and then
965
finds all file ids affected by those revisions.
967
vf = self._get_revision_vf()
968
from_set = set(vf.get_ancestry(from_revid))
969
to_set = set(vf.get_ancestry(to_revid))
970
changed = to_set.difference(from_set)
971
return self._fileid_involved_by_set(changed)
973
def fileid_involved(self, last_revid=None):
974
"""Find all file_ids modified in the ancestry of last_revid.
976
:param last_revid: If None, last_revision() will be used.
979
changed = set(self.all_revision_ids())
981
changed = set(self.get_ancestry(last_revid))
984
return self._fileid_involved_by_set(changed)
987
def get_ancestry(self, revision_id):
988
"""Return a list of revision-ids integrated by a revision.
990
This is topologically sorted.
992
if revision_id is None:
994
vf = self._get_revision_vf()
996
return [None] + vf.get_ancestry(revision_id)
997
except errors.RevisionNotPresent:
998
raise errors.NoSuchRevision(self, revision_id)
1001
def get_revision(self, revision_id):
1002
"""Return the Revision object for a named revision"""
1003
return self.get_revision_reconcile(revision_id)
1006
def get_revision_graph(self, revision_id=None):
1007
"""Return a dictionary containing the revision graph.
1009
:param revision_id: The revision_id to get a graph from. If None, then
1010
the entire revision graph is returned. This is a deprecated mode of
1011
operation and will be removed in the future.
1012
:return: a dictionary of revision_id->revision_parents_list.
1014
# special case NULL_REVISION
1015
if revision_id == _mod_revision.NULL_REVISION:
1017
a_weave = self._get_revision_vf()
1018
entire_graph = a_weave.get_graph()
1019
if revision_id is None:
1020
return a_weave.get_graph()
1021
elif revision_id not in a_weave:
1022
raise errors.NoSuchRevision(self, revision_id)
1024
# add what can be reached from revision_id
1026
pending = set([revision_id])
1027
while len(pending) > 0:
1028
node = pending.pop()
1029
result[node] = a_weave.get_parents(node)
1030
for revision_id in result[node]:
1031
if revision_id not in result:
1032
pending.add(revision_id)
1036
def get_revision_graph_with_ghosts(self, revision_ids=None):
1037
"""Return a graph of the revisions with ghosts marked as applicable.
1039
:param revision_ids: an iterable of revisions to graph or None for all.
1040
:return: a Graph object with the graph reachable from revision_ids.
1042
result = graph.Graph()
1043
vf = self._get_revision_vf()
1044
versions = set(vf.versions())
1045
if not revision_ids:
1046
pending = set(self.all_revision_ids())
1049
pending = set(revision_ids)
1050
# special case NULL_REVISION
1051
if _mod_revision.NULL_REVISION in pending:
1052
pending.remove(_mod_revision.NULL_REVISION)
1053
required = set(pending)
1056
revision_id = pending.pop()
1057
if not revision_id in versions:
1058
if revision_id in required:
1059
raise errors.NoSuchRevision(self, revision_id)
1061
result.add_ghost(revision_id)
1062
# mark it as done so we don't try for it again.
1063
done.add(revision_id)
1065
parent_ids = vf.get_parents_with_ghosts(revision_id)
1066
for parent_id in parent_ids:
1067
# is this queued or done ?
1068
if (parent_id not in pending and
1069
parent_id not in done):
1071
pending.add(parent_id)
1072
result.add_node(revision_id, parent_ids)
1073
done.add(revision_id)
1076
def _get_revision_vf(self):
1077
""":return: a versioned file containing the revisions."""
1078
vf = self._revision_store.get_revision_file(self.get_transaction())
1082
def reconcile(self, other=None, thorough=False):
1083
"""Reconcile this repository."""
1084
from bzrlib.reconcile import KnitReconciler
1085
reconciler = KnitReconciler(self, thorough=thorough)
1086
reconciler.reconcile()
1089
def revision_parents(self, revision_id):
1090
return self._get_revision_vf().get_parents(revision_id)
1093
class KnitRepository2(KnitRepository):
1095
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1096
control_store, text_store):
1097
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1098
_revision_store, control_store, text_store)
1099
self._serializer = xml6.serializer_v6
1101
def deserialise_inventory(self, revision_id, xml):
1102
"""Transform the xml into an inventory object.
1104
:param revision_id: The expected revision id of the inventory.
1105
:param xml: A serialised inventory.
1107
result = self._serializer.read_inventory_from_string(xml)
1108
assert result.root.revision is not None
1111
def serialise_inventory(self, inv):
1112
"""Transform the inventory object into XML text.
1114
:param revision_id: The expected revision id of the inventory.
1115
:param xml: A serialised inventory.
1117
assert inv.revision_id is not None
1118
assert inv.root.revision is not None
1119
return KnitRepository.serialise_inventory(self, inv)
1121
def get_commit_builder(self, branch, parents, config, timestamp=None,
1122
timezone=None, committer=None, revprops=None,
1124
"""Obtain a CommitBuilder for this repository.
1126
:param branch: Branch to commit to.
1127
:param parents: Revision ids of the parents of the new revision.
1128
:param config: Configuration to use.
1129
:param timestamp: Optional timestamp recorded for commit.
1130
:param timezone: Optional timezone for timestamp.
1131
:param committer: Optional committer to set for commit.
1132
:param revprops: Optional dictionary of revision properties.
1133
:param revision_id: Optional revision id.
1135
return RootCommitBuilder(self, parents, config, timestamp, timezone,
1136
committer, revprops, revision_id)
1139
class RepositoryFormatRegistry(registry.Registry):
1140
"""Registry of RepositoryFormats.
1144
format_registry = RepositoryFormatRegistry()
1145
"""Registry of formats, indexed by their identifying format string."""
1148
class RepositoryFormat(object):
1149
"""A repository format.
1151
Formats provide three things:
1152
* An initialization routine to construct repository data on disk.
1153
* a format string which is used when the BzrDir supports versioned
1155
* an open routine which returns a Repository instance.
1157
Formats are placed in an dict by their format string for reference
1158
during opening. These should be subclasses of RepositoryFormat
1161
Once a format is deprecated, just deprecate the initialize and open
1162
methods on the format class. Do not deprecate the object, as the
1163
object will be created every system load.
1165
Common instance attributes:
1166
_matchingbzrdir - the bzrdir format that the repository format was
1167
originally written to work with. This can be used if manually
1168
constructing a bzrdir and repository, or more commonly for test suite
1173
return "<%s>" % self.__class__.__name__
1176
def find_format(klass, a_bzrdir):
1177
"""Return the format for the repository object in a_bzrdir.
1179
This is used by bzr native formats that have a "format" file in
1180
the repository. Other methods may be used by different types of
1184
transport = a_bzrdir.get_repository_transport(None)
1185
format_string = transport.get("format").read()
1186
return format_registry.get(format_string)
1187
except errors.NoSuchFile:
1188
raise errors.NoRepositoryPresent(a_bzrdir)
1190
raise errors.UnknownFormatError(format=format_string)
1193
@deprecated_method(symbol_versioning.zero_fourteen)
1194
def set_default_format(klass, format):
1195
klass._set_default_format(format)
1198
def _set_default_format(klass, format):
1199
"""Set the default format for new Repository creation.
1201
The format must already be registered.
1203
format_registry.default_key = format.get_format_string()
1206
def register_format(klass, format):
1207
format_registry.register(format.get_format_string(), format)
1210
def unregister_format(klass, format):
1211
format_registry.remove(format.get_format_string())
1214
def get_default_format(klass):
1215
"""Return the current default format."""
1216
return format_registry.get(format_registry.default_key)
1218
def _get_control_store(self, repo_transport, control_files):
1219
"""Return the control store for this repository."""
1220
raise NotImplementedError(self._get_control_store)
1222
def get_format_string(self):
1223
"""Return the ASCII format string that identifies this format.
1225
Note that in pre format ?? repositories the format string is
1226
not permitted nor written to disk.
1228
raise NotImplementedError(self.get_format_string)
1230
def get_format_description(self):
1231
"""Return the short description for this format."""
1232
raise NotImplementedError(self.get_format_description)
1234
def _get_revision_store(self, repo_transport, control_files):
1235
"""Return the revision store object for this a_bzrdir."""
1236
raise NotImplementedError(self._get_revision_store)
1238
def _get_text_rev_store(self,
1245
"""Common logic for getting a revision store for a repository.
1247
see self._get_revision_store for the subclass-overridable method to
1248
get the store for a repository.
1250
from bzrlib.store.revision.text import TextRevisionStore
1251
dir_mode = control_files._dir_mode
1252
file_mode = control_files._file_mode
1253
text_store =TextStore(transport.clone(name),
1255
compressed=compressed,
1257
file_mode=file_mode)
1258
_revision_store = TextRevisionStore(text_store, serializer)
1259
return _revision_store
1261
def _get_versioned_file_store(self,
1266
versionedfile_class=weave.WeaveFile,
1267
versionedfile_kwargs={},
1269
weave_transport = control_files._transport.clone(name)
1270
dir_mode = control_files._dir_mode
1271
file_mode = control_files._file_mode
1272
return VersionedFileStore(weave_transport, prefixed=prefixed,
1274
file_mode=file_mode,
1275
versionedfile_class=versionedfile_class,
1276
versionedfile_kwargs=versionedfile_kwargs,
1279
def initialize(self, a_bzrdir, shared=False):
1280
"""Initialize a repository of this format in a_bzrdir.
1282
:param a_bzrdir: The bzrdir to put the new repository in it.
1283
:param shared: The repository should be initialized as a sharable one.
1284
:returns: The new repository object.
1286
This may raise UninitializableFormat if shared repository are not
1287
compatible the a_bzrdir.
1289
raise NotImplementedError(self.initialize)
1291
def is_supported(self):
1292
"""Is this format supported?
1294
Supported formats must be initializable and openable.
1295
Unsupported formats may not support initialization or committing or
1296
some other features depending on the reason for not being supported.
1300
def check_conversion_target(self, target_format):
1301
raise NotImplementedError(self.check_conversion_target)
1303
def open(self, a_bzrdir, _found=False):
1304
"""Return an instance of this format for the bzrdir a_bzrdir.
1306
_found is a private parameter, do not use it.
1308
raise NotImplementedError(self.open)
1311
class PreSplitOutRepositoryFormat(RepositoryFormat):
1312
"""Base class for the pre split out repository formats."""
1314
rich_root_data = False
1316
def initialize(self, a_bzrdir, shared=False, _internal=False):
1317
"""Create a weave repository.
1319
TODO: when creating split out bzr branch formats, move this to a common
1320
base for Format5, Format6. or something like that.
1323
raise errors.IncompatibleFormat(self, a_bzrdir._format)
1326
# always initialized when the bzrdir is.
1327
return self.open(a_bzrdir, _found=True)
1329
# Create an empty weave
1331
weavefile.write_weave_v5(weave.Weave(), sio)
1332
empty_weave = sio.getvalue()
1334
mutter('creating repository in %s.', a_bzrdir.transport.base)
1335
dirs = ['revision-store', 'weaves']
1336
files = [('inventory.weave', StringIO(empty_weave)),
1339
# FIXME: RBC 20060125 don't peek under the covers
1340
# NB: no need to escape relative paths that are url safe.
1341
control_files = lockable_files.LockableFiles(a_bzrdir.transport,
1342
'branch-lock', lockable_files.TransportLock)
1343
control_files.create_lock()
1344
control_files.lock_write()
1345
control_files._transport.mkdir_multi(dirs,
1346
mode=control_files._dir_mode)
1348
for file, content in files:
1349
control_files.put(file, content)
1351
control_files.unlock()
1352
return self.open(a_bzrdir, _found=True)
1354
def _get_control_store(self, repo_transport, control_files):
1355
"""Return the control store for this repository."""
1356
return self._get_versioned_file_store('',
1361
def _get_text_store(self, transport, control_files):
1362
"""Get a store for file texts for this format."""
1363
raise NotImplementedError(self._get_text_store)
1365
def open(self, a_bzrdir, _found=False):
1366
"""See RepositoryFormat.open()."""
1368
# we are being called directly and must probe.
1369
raise NotImplementedError
1371
repo_transport = a_bzrdir.get_repository_transport(None)
1372
control_files = a_bzrdir._control_files
1373
text_store = self._get_text_store(repo_transport, control_files)
1374
control_store = self._get_control_store(repo_transport, control_files)
1375
_revision_store = self._get_revision_store(repo_transport, control_files)
1376
return AllInOneRepository(_format=self,
1378
_revision_store=_revision_store,
1379
control_store=control_store,
1380
text_store=text_store)
1382
def check_conversion_target(self, target_format):
1386
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1387
"""Bzr repository format 4.
1389
This repository format has:
1391
- TextStores for texts, inventories,revisions.
1393
This format is deprecated: it indexes texts using a text id which is
1394
removed in format 5; initialization and write support for this format
1399
super(RepositoryFormat4, self).__init__()
1400
self._matchingbzrdir = bzrdir.BzrDirFormat4()
1402
def get_format_description(self):
1403
"""See RepositoryFormat.get_format_description()."""
1404
return "Repository format 4"
1406
def initialize(self, url, shared=False, _internal=False):
1407
"""Format 4 branches cannot be created."""
1408
raise errors.UninitializableFormat(self)
1410
def is_supported(self):
1411
"""Format 4 is not supported.
1413
It is not supported because the model changed from 4 to 5 and the
1414
conversion logic is expensive - so doing it on the fly was not
1419
def _get_control_store(self, repo_transport, control_files):
1420
"""Format 4 repositories have no formal control store at this point.
1422
This will cause any control-file-needing apis to fail - this is desired.
1426
def _get_revision_store(self, repo_transport, control_files):
1427
"""See RepositoryFormat._get_revision_store()."""
1428
from bzrlib.xml4 import serializer_v4
1429
return self._get_text_rev_store(repo_transport,
1432
serializer=serializer_v4)
1434
def _get_text_store(self, transport, control_files):
1435
"""See RepositoryFormat._get_text_store()."""
1438
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1439
"""Bzr control format 5.
1441
This repository format has:
1442
- weaves for file texts and inventory
1444
- TextStores for revisions and signatures.
1448
super(RepositoryFormat5, self).__init__()
1449
self._matchingbzrdir = bzrdir.BzrDirFormat5()
1451
def get_format_description(self):
1452
"""See RepositoryFormat.get_format_description()."""
1453
return "Weave repository format 5"
1455
def _get_revision_store(self, repo_transport, control_files):
1456
"""See RepositoryFormat._get_revision_store()."""
1457
"""Return the revision store object for this a_bzrdir."""
1458
return self._get_text_rev_store(repo_transport,
1463
def _get_text_store(self, transport, control_files):
1464
"""See RepositoryFormat._get_text_store()."""
1465
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1468
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1469
"""Bzr control format 6.
1471
This repository format has:
1472
- weaves for file texts and inventory
1473
- hash subdirectory based stores.
1474
- TextStores for revisions and signatures.
1478
super(RepositoryFormat6, self).__init__()
1479
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1481
def get_format_description(self):
1482
"""See RepositoryFormat.get_format_description()."""
1483
return "Weave repository format 6"
1485
def _get_revision_store(self, repo_transport, control_files):
1486
"""See RepositoryFormat._get_revision_store()."""
1487
return self._get_text_rev_store(repo_transport,
1493
def _get_text_store(self, transport, control_files):
1494
"""See RepositoryFormat._get_text_store()."""
1495
return self._get_versioned_file_store('weaves', transport, control_files)
1498
class MetaDirRepositoryFormat(RepositoryFormat):
1499
"""Common base class for the new repositories using the metadir layout."""
1501
rich_root_data = False
1504
super(MetaDirRepositoryFormat, self).__init__()
1505
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1507
def _create_control_files(self, a_bzrdir):
1508
"""Create the required files and the initial control_files object."""
1509
# FIXME: RBC 20060125 don't peek under the covers
1510
# NB: no need to escape relative paths that are url safe.
1511
repository_transport = a_bzrdir.get_repository_transport(self)
1512
control_files = lockable_files.LockableFiles(repository_transport,
1513
'lock', lockdir.LockDir)
1514
control_files.create_lock()
1515
return control_files
1517
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1518
"""Upload the initial blank content."""
1519
control_files = self._create_control_files(a_bzrdir)
1520
control_files.lock_write()
1522
control_files._transport.mkdir_multi(dirs,
1523
mode=control_files._dir_mode)
1524
for file, content in files:
1525
control_files.put(file, content)
1526
for file, content in utf8_files:
1527
control_files.put_utf8(file, content)
1529
control_files.put_utf8('shared-storage', '')
1531
control_files.unlock()
1534
class RepositoryFormat7(MetaDirRepositoryFormat):
1535
"""Bzr repository 7.
1537
This repository format has:
1538
- weaves for file texts and inventory
1539
- hash subdirectory based stores.
1540
- TextStores for revisions and signatures.
1541
- a format marker of its own
1542
- an optional 'shared-storage' flag
1543
- an optional 'no-working-trees' flag
1546
def _get_control_store(self, repo_transport, control_files):
1547
"""Return the control store for this repository."""
1548
return self._get_versioned_file_store('',
1553
def get_format_string(self):
1554
"""See RepositoryFormat.get_format_string()."""
1555
return "Bazaar-NG Repository format 7"
1557
def get_format_description(self):
1558
"""See RepositoryFormat.get_format_description()."""
1559
return "Weave repository format 7"
1561
def check_conversion_target(self, target_format):
1564
def _get_revision_store(self, repo_transport, control_files):
1565
"""See RepositoryFormat._get_revision_store()."""
1566
return self._get_text_rev_store(repo_transport,
1573
def _get_text_store(self, transport, control_files):
1574
"""See RepositoryFormat._get_text_store()."""
1575
return self._get_versioned_file_store('weaves',
1579
def initialize(self, a_bzrdir, shared=False):
1580
"""Create a weave repository.
1582
:param shared: If true the repository will be initialized as a shared
1585
# Create an empty weave
1587
weavefile.write_weave_v5(weave.Weave(), sio)
1588
empty_weave = sio.getvalue()
1590
mutter('creating repository in %s.', a_bzrdir.transport.base)
1591
dirs = ['revision-store', 'weaves']
1592
files = [('inventory.weave', StringIO(empty_weave)),
1594
utf8_files = [('format', self.get_format_string())]
1596
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1597
return self.open(a_bzrdir=a_bzrdir, _found=True)
1599
def open(self, a_bzrdir, _found=False, _override_transport=None):
1600
"""See RepositoryFormat.open().
1602
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1603
repository at a slightly different url
1604
than normal. I.e. during 'upgrade'.
1607
format = RepositoryFormat.find_format(a_bzrdir)
1608
assert format.__class__ == self.__class__
1609
if _override_transport is not None:
1610
repo_transport = _override_transport
1612
repo_transport = a_bzrdir.get_repository_transport(None)
1613
control_files = lockable_files.LockableFiles(repo_transport,
1614
'lock', lockdir.LockDir)
1615
text_store = self._get_text_store(repo_transport, control_files)
1616
control_store = self._get_control_store(repo_transport, control_files)
1617
_revision_store = self._get_revision_store(repo_transport, control_files)
1618
return WeaveMetaDirRepository(_format=self,
1620
control_files=control_files,
1621
_revision_store=_revision_store,
1622
control_store=control_store,
1623
text_store=text_store)
1626
class RepositoryFormatKnit(MetaDirRepositoryFormat):
1627
"""Bzr repository knit format (generalized).
1629
This repository format has:
1630
- knits for file texts and inventory
1631
- hash subdirectory based stores.
1632
- knits for revisions and signatures
1633
- TextStores for revisions and signatures.
1634
- a format marker of its own
1635
- an optional 'shared-storage' flag
1636
- an optional 'no-working-trees' flag
1640
def _get_control_store(self, repo_transport, control_files):
1641
"""Return the control store for this repository."""
1642
return VersionedFileStore(
1645
file_mode=control_files._file_mode,
1646
versionedfile_class=knit.KnitVersionedFile,
1647
versionedfile_kwargs={'factory':knit.KnitPlainFactory()},
1650
def _get_revision_store(self, repo_transport, control_files):
1651
"""See RepositoryFormat._get_revision_store()."""
1652
from bzrlib.store.revision.knit import KnitRevisionStore
1653
versioned_file_store = VersionedFileStore(
1655
file_mode=control_files._file_mode,
1658
versionedfile_class=knit.KnitVersionedFile,
1659
versionedfile_kwargs={'delta':False,
1660
'factory':knit.KnitPlainFactory(),
1664
return KnitRevisionStore(versioned_file_store)
1666
def _get_text_store(self, transport, control_files):
1667
"""See RepositoryFormat._get_text_store()."""
1668
return self._get_versioned_file_store('knits',
1671
versionedfile_class=knit.KnitVersionedFile,
1672
versionedfile_kwargs={
1673
'create_parent_dir':True,
1674
'delay_create':True,
1675
'dir_mode':control_files._dir_mode,
1679
def initialize(self, a_bzrdir, shared=False):
1680
"""Create a knit format 1 repository.
1682
:param a_bzrdir: bzrdir to contain the new repository; must already
1684
:param shared: If true the repository will be initialized as a shared
1687
mutter('creating repository in %s.', a_bzrdir.transport.base)
1688
dirs = ['revision-store', 'knits']
1690
utf8_files = [('format', self.get_format_string())]
1692
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1693
repo_transport = a_bzrdir.get_repository_transport(None)
1694
control_files = lockable_files.LockableFiles(repo_transport,
1695
'lock', lockdir.LockDir)
1696
control_store = self._get_control_store(repo_transport, control_files)
1697
transaction = transactions.WriteTransaction()
1698
# trigger a write of the inventory store.
1699
control_store.get_weave_or_empty('inventory', transaction)
1700
_revision_store = self._get_revision_store(repo_transport, control_files)
1701
# the revision id here is irrelevant: it will not be stored, and cannot
1703
_revision_store.has_revision_id('A', transaction)
1704
_revision_store.get_signature_file(transaction)
1705
return self.open(a_bzrdir=a_bzrdir, _found=True)
1707
def open(self, a_bzrdir, _found=False, _override_transport=None):
1708
"""See RepositoryFormat.open().
1710
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1711
repository at a slightly different url
1712
than normal. I.e. during 'upgrade'.
1715
format = RepositoryFormat.find_format(a_bzrdir)
1716
assert format.__class__ == self.__class__
1717
if _override_transport is not None:
1718
repo_transport = _override_transport
1720
repo_transport = a_bzrdir.get_repository_transport(None)
1721
control_files = lockable_files.LockableFiles(repo_transport,
1722
'lock', lockdir.LockDir)
1723
text_store = self._get_text_store(repo_transport, control_files)
1724
control_store = self._get_control_store(repo_transport, control_files)
1725
_revision_store = self._get_revision_store(repo_transport, control_files)
1726
return KnitRepository(_format=self,
1728
control_files=control_files,
1729
_revision_store=_revision_store,
1730
control_store=control_store,
1731
text_store=text_store)
1734
class RepositoryFormatKnit1(RepositoryFormatKnit):
1735
"""Bzr repository knit format 1.
1737
This repository format has:
1738
- knits for file texts and inventory
1739
- hash subdirectory based stores.
1740
- knits for revisions and signatures
1741
- TextStores for revisions and signatures.
1742
- a format marker of its own
1743
- an optional 'shared-storage' flag
1744
- an optional 'no-working-trees' flag
1747
This format was introduced in bzr 0.8.
1749
def get_format_string(self):
1750
"""See RepositoryFormat.get_format_string()."""
1751
return "Bazaar-NG Knit Repository Format 1"
1753
def get_format_description(self):
1754
"""See RepositoryFormat.get_format_description()."""
1755
return "Knit repository format 1"
1757
def check_conversion_target(self, target_format):
1761
class RepositoryFormatKnit2(RepositoryFormatKnit):
1762
"""Bzr repository knit format 2.
1764
THIS FORMAT IS EXPERIMENTAL
1765
This repository format has:
1766
- knits for file texts and inventory
1767
- hash subdirectory based stores.
1768
- knits for revisions and signatures
1769
- TextStores for revisions and signatures.
1770
- a format marker of its own
1771
- an optional 'shared-storage' flag
1772
- an optional 'no-working-trees' flag
1774
- Support for recording full info about the tree root
1778
rich_root_data = True
1780
def get_format_string(self):
1781
"""See RepositoryFormat.get_format_string()."""
1782
return "Bazaar Knit Repository Format 2\n"
1784
def get_format_description(self):
1785
"""See RepositoryFormat.get_format_description()."""
1786
return "Knit repository format 2"
1788
def check_conversion_target(self, target_format):
1789
if not target_format.rich_root_data:
1790
raise errors.BadConversionTarget(
1791
'Does not support rich root data.', target_format)
1793
def open(self, a_bzrdir, _found=False, _override_transport=None):
1794
"""See RepositoryFormat.open().
1796
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1797
repository at a slightly different url
1798
than normal. I.e. during 'upgrade'.
1801
format = RepositoryFormat.find_format(a_bzrdir)
1802
assert format.__class__ == self.__class__
1803
if _override_transport is not None:
1804
repo_transport = _override_transport
1806
repo_transport = a_bzrdir.get_repository_transport(None)
1807
control_files = lockable_files.LockableFiles(repo_transport, 'lock',
1809
text_store = self._get_text_store(repo_transport, control_files)
1810
control_store = self._get_control_store(repo_transport, control_files)
1811
_revision_store = self._get_revision_store(repo_transport, control_files)
1812
return KnitRepository2(_format=self,
1814
control_files=control_files,
1815
_revision_store=_revision_store,
1816
control_store=control_store,
1817
text_store=text_store)
1821
# formats which have no format string are not discoverable
1822
# and not independently creatable, so are not registered.
1823
RepositoryFormat.register_format(RepositoryFormat7())
1824
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1825
# default control directory format
1826
_default_format = RepositoryFormatKnit1()
1827
RepositoryFormat.register_format(_default_format)
1828
RepositoryFormat.register_format(RepositoryFormatKnit2())
1829
RepositoryFormat._set_default_format(_default_format)
1830
_legacy_formats = [RepositoryFormat4(),
1831
RepositoryFormat5(),
1832
RepositoryFormat6()]
1835
class InterRepository(InterObject):
1836
"""This class represents operations taking place between two repositories.
1838
Its instances have methods like copy_content and fetch, and contain
1839
references to the source and target repositories these operations can be
1842
Often we will provide convenience methods on 'repository' which carry out
1843
operations with another repository - they will always forward to
1844
InterRepository.get(other).method_name(parameters).
1848
"""The available optimised InterRepository types."""
1850
def copy_content(self, revision_id=None, basis=None):
1851
raise NotImplementedError(self.copy_content)
1853
def fetch(self, revision_id=None, pb=None):
1854
"""Fetch the content required to construct revision_id.
1856
The content is copied from self.source to self.target.
1858
:param revision_id: if None all content is copied, if NULL_REVISION no
1860
:param pb: optional progress bar to use for progress reports. If not
1861
provided a default one will be created.
1863
Returns the copied revision count and the failed revisions in a tuple:
1866
raise NotImplementedError(self.fetch)
1869
def missing_revision_ids(self, revision_id=None):
1870
"""Return the revision ids that source has that target does not.
1872
These are returned in topological order.
1874
:param revision_id: only return revision ids included by this
1877
# generic, possibly worst case, slow code path.
1878
target_ids = set(self.target.all_revision_ids())
1879
if revision_id is not None:
1880
source_ids = self.source.get_ancestry(revision_id)
1881
assert source_ids[0] is None
1884
source_ids = self.source.all_revision_ids()
1885
result_set = set(source_ids).difference(target_ids)
1886
# this may look like a no-op: its not. It preserves the ordering
1887
# other_ids had while only returning the members from other_ids
1888
# that we've decided we need.
1889
return [rev_id for rev_id in source_ids if rev_id in result_set]
1892
class InterSameDataRepository(InterRepository):
1893
"""Code for converting between repositories that represent the same data.
1895
Data format and model must match for this to work.
1898
_matching_repo_format = RepositoryFormat4()
1899
"""Repository format for testing with."""
1902
def is_compatible(source, target):
1903
if source._format.rich_root_data == target._format.rich_root_data:
1909
def copy_content(self, revision_id=None, basis=None):
1910
"""Make a complete copy of the content in self into destination.
1912
This is a destructive operation! Do not use it on existing
1915
:param revision_id: Only copy the content needed to construct
1916
revision_id and its parents.
1917
:param basis: Copy the needed data preferentially from basis.
1920
self.target.set_make_working_trees(self.source.make_working_trees())
1921
except NotImplementedError:
1923
# grab the basis available data
1924
if basis is not None:
1925
self.target.fetch(basis, revision_id=revision_id)
1926
# but don't bother fetching if we have the needed data now.
1927
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1928
self.target.has_revision(revision_id)):
1930
self.target.fetch(self.source, revision_id=revision_id)
1933
def fetch(self, revision_id=None, pb=None):
1934
"""See InterRepository.fetch()."""
1935
from bzrlib.fetch import GenericRepoFetcher
1936
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1937
self.source, self.source._format, self.target,
1938
self.target._format)
1939
f = GenericRepoFetcher(to_repository=self.target,
1940
from_repository=self.source,
1941
last_revision=revision_id,
1943
return f.count_copied, f.failed_revisions
1946
class InterWeaveRepo(InterSameDataRepository):
1947
"""Optimised code paths between Weave based repositories."""
1949
_matching_repo_format = RepositoryFormat7()
1950
"""Repository format for testing with."""
1953
def is_compatible(source, target):
1954
"""Be compatible with known Weave formats.
1956
We don't test for the stores being of specific types because that
1957
could lead to confusing results, and there is no need to be
1961
return (isinstance(source._format, (RepositoryFormat5,
1963
RepositoryFormat7)) and
1964
isinstance(target._format, (RepositoryFormat5,
1966
RepositoryFormat7)))
1967
except AttributeError:
1971
def copy_content(self, revision_id=None, basis=None):
1972
"""See InterRepository.copy_content()."""
1973
# weave specific optimised path:
1974
if basis is not None:
1975
# copy the basis in, then fetch remaining data.
1976
basis.copy_content_into(self.target, revision_id)
1977
# the basis copy_content_into could miss-set this.
1979
self.target.set_make_working_trees(self.source.make_working_trees())
1980
except NotImplementedError:
1982
self.target.fetch(self.source, revision_id=revision_id)
1985
self.target.set_make_working_trees(self.source.make_working_trees())
1986
except NotImplementedError:
1988
# FIXME do not peek!
1989
if self.source.control_files._transport.listable():
1990
pb = ui.ui_factory.nested_progress_bar()
1992
self.target.weave_store.copy_all_ids(
1993
self.source.weave_store,
1995
from_transaction=self.source.get_transaction(),
1996
to_transaction=self.target.get_transaction())
1997
pb.update('copying inventory', 0, 1)
1998
self.target.control_weaves.copy_multi(
1999
self.source.control_weaves, ['inventory'],
2000
from_transaction=self.source.get_transaction(),
2001
to_transaction=self.target.get_transaction())
2002
self.target._revision_store.text_store.copy_all_ids(
2003
self.source._revision_store.text_store,
2008
self.target.fetch(self.source, revision_id=revision_id)
2011
def fetch(self, revision_id=None, pb=None):
2012
"""See InterRepository.fetch()."""
2013
from bzrlib.fetch import GenericRepoFetcher
2014
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2015
self.source, self.source._format, self.target, self.target._format)
2016
f = GenericRepoFetcher(to_repository=self.target,
2017
from_repository=self.source,
2018
last_revision=revision_id,
2020
return f.count_copied, f.failed_revisions
2023
def missing_revision_ids(self, revision_id=None):
2024
"""See InterRepository.missing_revision_ids()."""
2025
# we want all revisions to satisfy revision_id in source.
2026
# but we don't want to stat every file here and there.
2027
# we want then, all revisions other needs to satisfy revision_id
2028
# checked, but not those that we have locally.
2029
# so the first thing is to get a subset of the revisions to
2030
# satisfy revision_id in source, and then eliminate those that
2031
# we do already have.
2032
# this is slow on high latency connection to self, but as as this
2033
# disk format scales terribly for push anyway due to rewriting
2034
# inventory.weave, this is considered acceptable.
2036
if revision_id is not None:
2037
source_ids = self.source.get_ancestry(revision_id)
2038
assert source_ids[0] is None
2041
source_ids = self.source._all_possible_ids()
2042
source_ids_set = set(source_ids)
2043
# source_ids is the worst possible case we may need to pull.
2044
# now we want to filter source_ids against what we actually
2045
# have in target, but don't try to check for existence where we know
2046
# we do not have a revision as that would be pointless.
2047
target_ids = set(self.target._all_possible_ids())
2048
possibly_present_revisions = target_ids.intersection(source_ids_set)
2049
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2050
required_revisions = source_ids_set.difference(actually_present_revisions)
2051
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2052
if revision_id is not None:
2053
# we used get_ancestry to determine source_ids then we are assured all
2054
# revisions referenced are present as they are installed in topological order.
2055
# and the tip revision was validated by get_ancestry.
2056
return required_topo_revisions
2058
# if we just grabbed the possibly available ids, then
2059
# we only have an estimate of whats available and need to validate
2060
# that against the revision records.
2061
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2064
class InterKnitRepo(InterSameDataRepository):
2065
"""Optimised code paths between Knit based repositories."""
2067
_matching_repo_format = RepositoryFormatKnit1()
2068
"""Repository format for testing with."""
2071
def is_compatible(source, target):
2072
"""Be compatible with known Knit formats.
2074
We don't test for the stores being of specific types because that
2075
could lead to confusing results, and there is no need to be
2079
return (isinstance(source._format, (RepositoryFormatKnit1)) and
2080
isinstance(target._format, (RepositoryFormatKnit1)))
2081
except AttributeError:
2085
def fetch(self, revision_id=None, pb=None):
2086
"""See InterRepository.fetch()."""
2087
from bzrlib.fetch import KnitRepoFetcher
2088
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2089
self.source, self.source._format, self.target, self.target._format)
2090
f = KnitRepoFetcher(to_repository=self.target,
2091
from_repository=self.source,
2092
last_revision=revision_id,
2094
return f.count_copied, f.failed_revisions
2097
def missing_revision_ids(self, revision_id=None):
2098
"""See InterRepository.missing_revision_ids()."""
2099
if revision_id is not None:
2100
source_ids = self.source.get_ancestry(revision_id)
2101
assert source_ids[0] is None
2104
source_ids = self.source._all_possible_ids()
2105
source_ids_set = set(source_ids)
2106
# source_ids is the worst possible case we may need to pull.
2107
# now we want to filter source_ids against what we actually
2108
# have in target, but don't try to check for existence where we know
2109
# we do not have a revision as that would be pointless.
2110
target_ids = set(self.target._all_possible_ids())
2111
possibly_present_revisions = target_ids.intersection(source_ids_set)
2112
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2113
required_revisions = source_ids_set.difference(actually_present_revisions)
2114
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2115
if revision_id is not None:
2116
# we used get_ancestry to determine source_ids then we are assured all
2117
# revisions referenced are present as they are installed in topological order.
2118
# and the tip revision was validated by get_ancestry.
2119
return required_topo_revisions
2121
# if we just grabbed the possibly available ids, then
2122
# we only have an estimate of whats available and need to validate
2123
# that against the revision records.
2124
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2127
class InterModel1and2(InterRepository):
2129
_matching_repo_format = None
2132
def is_compatible(source, target):
2133
if not isinstance(source, Repository):
2135
if not isinstance(target, Repository):
2137
if not source._format.rich_root_data and target._format.rich_root_data:
2143
def fetch(self, revision_id=None, pb=None):
2144
"""See InterRepository.fetch()."""
2145
from bzrlib.fetch import Model1toKnit2Fetcher
2146
f = Model1toKnit2Fetcher(to_repository=self.target,
2147
from_repository=self.source,
2148
last_revision=revision_id,
2150
return f.count_copied, f.failed_revisions
2153
def copy_content(self, revision_id=None, basis=None):
2154
"""Make a complete copy of the content in self into destination.
2156
This is a destructive operation! Do not use it on existing
2159
:param revision_id: Only copy the content needed to construct
2160
revision_id and its parents.
2161
:param basis: Copy the needed data preferentially from basis.
2164
self.target.set_make_working_trees(self.source.make_working_trees())
2165
except NotImplementedError:
2167
# grab the basis available data
2168
if basis is not None:
2169
self.target.fetch(basis, revision_id=revision_id)
2170
# but don't bother fetching if we have the needed data now.
2171
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
2172
self.target.has_revision(revision_id)):
2174
self.target.fetch(self.source, revision_id=revision_id)
2177
class InterKnit1and2(InterKnitRepo):
2179
_matching_repo_format = None
2182
def is_compatible(source, target):
2183
"""Be compatible with Knit1 source and Knit2 target"""
2185
return (isinstance(source._format, (RepositoryFormatKnit1)) and
2186
isinstance(target._format, (RepositoryFormatKnit2)))
2187
except AttributeError:
2191
def fetch(self, revision_id=None, pb=None):
2192
"""See InterRepository.fetch()."""
2193
from bzrlib.fetch import Knit1to2Fetcher
2194
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2195
self.source, self.source._format, self.target,
2196
self.target._format)
2197
f = Knit1to2Fetcher(to_repository=self.target,
2198
from_repository=self.source,
2199
last_revision=revision_id,
2201
return f.count_copied, f.failed_revisions
2204
InterRepository.register_optimiser(InterSameDataRepository)
2205
InterRepository.register_optimiser(InterWeaveRepo)
2206
InterRepository.register_optimiser(InterKnitRepo)
2207
InterRepository.register_optimiser(InterModel1and2)
2208
InterRepository.register_optimiser(InterKnit1and2)
2211
class RepositoryTestProviderAdapter(object):
2212
"""A tool to generate a suite testing multiple repository formats at once.
2214
This is done by copying the test once for each transport and injecting
2215
the transport_server, transport_readonly_server, and bzrdir_format and
2216
repository_format classes into each copy. Each copy is also given a new id()
2217
to make it easy to identify.
2220
def __init__(self, transport_server, transport_readonly_server, formats):
2221
self._transport_server = transport_server
2222
self._transport_readonly_server = transport_readonly_server
2223
self._formats = formats
2225
def adapt(self, test):
2226
result = unittest.TestSuite()
2227
for repository_format, bzrdir_format in self._formats:
2228
new_test = deepcopy(test)
2229
new_test.transport_server = self._transport_server
2230
new_test.transport_readonly_server = self._transport_readonly_server
2231
new_test.bzrdir_format = bzrdir_format
2232
new_test.repository_format = repository_format
2233
def make_new_test_id():
2234
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
2235
return lambda: new_id
2236
new_test.id = make_new_test_id()
2237
result.addTest(new_test)
2241
class InterRepositoryTestProviderAdapter(object):
2242
"""A tool to generate a suite testing multiple inter repository formats.
2244
This is done by copying the test once for each interrepo provider and injecting
2245
the transport_server, transport_readonly_server, repository_format and
2246
repository_to_format classes into each copy.
2247
Each copy is also given a new id() to make it easy to identify.
2250
def __init__(self, transport_server, transport_readonly_server, formats):
2251
self._transport_server = transport_server
2252
self._transport_readonly_server = transport_readonly_server
2253
self._formats = formats
2255
def adapt(self, test):
2256
result = unittest.TestSuite()
2257
for interrepo_class, repository_format, repository_format_to in self._formats:
2258
new_test = deepcopy(test)
2259
new_test.transport_server = self._transport_server
2260
new_test.transport_readonly_server = self._transport_readonly_server
2261
new_test.interrepo_class = interrepo_class
2262
new_test.repository_format = repository_format
2263
new_test.repository_format_to = repository_format_to
2264
def make_new_test_id():
2265
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
2266
return lambda: new_id
2267
new_test.id = make_new_test_id()
2268
result.addTest(new_test)
2272
def default_test_list():
2273
"""Generate the default list of interrepo permutations to test."""
2275
# test the default InterRepository between format 6 and the current
2277
# XXX: robertc 20060220 reinstate this when there are two supported
2278
# formats which do not have an optimal code path between them.
2279
#result.append((InterRepository,
2280
# RepositoryFormat6(),
2281
# RepositoryFormatKnit1()))
2282
for optimiser in InterRepository._optimisers:
2283
if optimiser._matching_repo_format is not None:
2284
result.append((optimiser,
2285
optimiser._matching_repo_format,
2286
optimiser._matching_repo_format
2288
# if there are specific combinations we want to use, we can add them
2290
result.append((InterModel1and2, RepositoryFormat5(),
2291
RepositoryFormatKnit2()))
2292
result.append((InterKnit1and2, RepositoryFormatKnit1(),
2293
RepositoryFormatKnit2()))
2297
class CopyConverter(object):
2298
"""A repository conversion tool which just performs a copy of the content.
2300
This is slow but quite reliable.
2303
def __init__(self, target_format):
2304
"""Create a CopyConverter.
2306
:param target_format: The format the resulting repository should be.
2308
self.target_format = target_format
2310
def convert(self, repo, pb):
2311
"""Perform the conversion of to_convert, giving feedback via pb.
2313
:param to_convert: The disk object to convert.
2314
:param pb: a progress bar to use for progress information.
2319
# this is only useful with metadir layouts - separated repo content.
2320
# trigger an assertion if not such
2321
repo._format.get_format_string()
2322
self.repo_dir = repo.bzrdir
2323
self.step('Moving repository to repository.backup')
2324
self.repo_dir.transport.move('repository', 'repository.backup')
2325
backup_transport = self.repo_dir.transport.clone('repository.backup')
2326
repo._format.check_conversion_target(self.target_format)
2327
self.source_repo = repo._format.open(self.repo_dir,
2329
_override_transport=backup_transport)
2330
self.step('Creating new repository')
2331
converted = self.target_format.initialize(self.repo_dir,
2332
self.source_repo.is_shared())
2333
converted.lock_write()
2335
self.step('Copying content into repository.')
2336
self.source_repo.copy_content_into(converted)
2339
self.step('Deleting old repository content.')
2340
self.repo_dir.transport.delete_tree('repository.backup')
2341
self.pb.note('repository converted')
2343
def step(self, message):
2344
"""Update the pb by a step."""
2346
self.pb.update(message, self.count, self.total)
2349
class CommitBuilder(object):
2350
"""Provides an interface to build up a commit.
2352
This allows describing a tree to be committed without needing to
2353
know the internals of the format of the repository.
2356
record_root_entry = False
2357
def __init__(self, repository, parents, config, timestamp=None,
2358
timezone=None, committer=None, revprops=None,
2360
"""Initiate a CommitBuilder.
2362
:param repository: Repository to commit to.
2363
:param parents: Revision ids of the parents of the new revision.
2364
:param config: Configuration to use.
2365
:param timestamp: Optional timestamp recorded for commit.
2366
:param timezone: Optional timezone for timestamp.
2367
:param committer: Optional committer to set for commit.
2368
:param revprops: Optional dictionary of revision properties.
2369
:param revision_id: Optional revision id.
2371
self._config = config
2373
if committer is None:
2374
self._committer = self._config.username()
2376
assert isinstance(committer, basestring), type(committer)
2377
self._committer = committer
2379
self.new_inventory = Inventory(None)
2380
self._new_revision_id = revision_id
2381
self.parents = parents
2382
self.repository = repository
2385
if revprops is not None:
2386
self._revprops.update(revprops)
2388
if timestamp is None:
2389
timestamp = time.time()
2390
# Restrict resolution to 1ms
2391
self._timestamp = round(timestamp, 3)
2393
if timezone is None:
2394
self._timezone = local_time_offset()
2396
self._timezone = int(timezone)
2398
self._generate_revision_if_needed()
2400
def commit(self, message):
2401
"""Make the actual commit.
2403
:return: The revision id of the recorded revision.
2405
rev = _mod_revision.Revision(
2406
timestamp=self._timestamp,
2407
timezone=self._timezone,
2408
committer=self._committer,
2410
inventory_sha1=self.inv_sha1,
2411
revision_id=self._new_revision_id,
2412
properties=self._revprops)
2413
rev.parent_ids = self.parents
2414
self.repository.add_revision(self._new_revision_id, rev,
2415
self.new_inventory, self._config)
2416
return self._new_revision_id
2418
def revision_tree(self):
2419
"""Return the tree that was just committed.
2421
After calling commit() this can be called to get a RevisionTree
2422
representing the newly committed tree. This is preferred to
2423
calling Repository.revision_tree() because that may require
2424
deserializing the inventory, while we already have a copy in
2427
return RevisionTree(self.repository, self.new_inventory,
2428
self._new_revision_id)
2430
def finish_inventory(self):
2431
"""Tell the builder that the inventory is finished."""
2432
if self.new_inventory.root is None:
2433
symbol_versioning.warn('Root entry should be supplied to'
2434
' record_entry_contents, as of bzr 0.10.',
2435
DeprecationWarning, stacklevel=2)
2436
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
2437
self.new_inventory.revision_id = self._new_revision_id
2438
self.inv_sha1 = self.repository.add_inventory(
2439
self._new_revision_id,
2444
def _gen_revision_id(self):
2445
"""Return new revision-id."""
2446
return generate_ids.gen_revision_id(self._config.username(),
2449
def _generate_revision_if_needed(self):
2450
"""Create a revision id if None was supplied.
2452
If the repository can not support user-specified revision ids
2453
they should override this function and raise CannotSetRevisionId
2454
if _new_revision_id is not None.
2456
:raises: CannotSetRevisionId
2458
if self._new_revision_id is None:
2459
self._new_revision_id = self._gen_revision_id()
2461
def record_entry_contents(self, ie, parent_invs, path, tree):
2462
"""Record the content of ie from tree into the commit if needed.
2464
Side effect: sets ie.revision when unchanged
2466
:param ie: An inventory entry present in the commit.
2467
:param parent_invs: The inventories of the parent revisions of the
2469
:param path: The path the entry is at in the tree.
2470
:param tree: The tree which contains this entry and should be used to
2473
if self.new_inventory.root is None and ie.parent_id is not None:
2474
symbol_versioning.warn('Root entry should be supplied to'
2475
' record_entry_contents, as of bzr 0.10.',
2476
DeprecationWarning, stacklevel=2)
2477
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2479
self.new_inventory.add(ie)
2481
# ie.revision is always None if the InventoryEntry is considered
2482
# for committing. ie.snapshot will record the correct revision
2483
# which may be the sole parent if it is untouched.
2484
if ie.revision is not None:
2487
# In this revision format, root entries have no knit or weave
2488
if ie is self.new_inventory.root:
2489
# When serializing out to disk and back in
2490
# root.revision is always _new_revision_id
2491
ie.revision = self._new_revision_id
2493
previous_entries = ie.find_previous_heads(
2495
self.repository.weave_store,
2496
self.repository.get_transaction())
2497
# we are creating a new revision for ie in the history store
2499
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2501
def modified_directory(self, file_id, file_parents):
2502
"""Record the presence of a symbolic link.
2504
:param file_id: The file_id of the link to record.
2505
:param file_parents: The per-file parent revision ids.
2507
self._add_text_to_weave(file_id, [], file_parents.keys())
2509
def modified_file_text(self, file_id, file_parents,
2510
get_content_byte_lines, text_sha1=None,
2512
"""Record the text of file file_id
2514
:param file_id: The file_id of the file to record the text of.
2515
:param file_parents: The per-file parent revision ids.
2516
:param get_content_byte_lines: A callable which will return the byte
2518
:param text_sha1: Optional SHA1 of the file contents.
2519
:param text_size: Optional size of the file contents.
2521
# mutter('storing text of file {%s} in revision {%s} into %r',
2522
# file_id, self._new_revision_id, self.repository.weave_store)
2523
# special case to avoid diffing on renames or
2525
if (len(file_parents) == 1
2526
and text_sha1 == file_parents.values()[0].text_sha1
2527
and text_size == file_parents.values()[0].text_size):
2528
previous_ie = file_parents.values()[0]
2529
versionedfile = self.repository.weave_store.get_weave(file_id,
2530
self.repository.get_transaction())
2531
versionedfile.clone_text(self._new_revision_id,
2532
previous_ie.revision, file_parents.keys())
2533
return text_sha1, text_size
2535
new_lines = get_content_byte_lines()
2536
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2537
# should return the SHA1 and size
2538
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2539
return osutils.sha_strings(new_lines), \
2540
sum(map(len, new_lines))
2542
def modified_link(self, file_id, file_parents, link_target):
2543
"""Record the presence of a symbolic link.
2545
:param file_id: The file_id of the link to record.
2546
:param file_parents: The per-file parent revision ids.
2547
:param link_target: Target location of this link.
2549
self._add_text_to_weave(file_id, [], file_parents.keys())
2551
def _add_text_to_weave(self, file_id, new_lines, parents):
2552
versionedfile = self.repository.weave_store.get_weave_or_empty(
2553
file_id, self.repository.get_transaction())
2554
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2555
versionedfile.clear_cache()
2558
class _CommitBuilder(CommitBuilder):
2559
"""Temporary class so old CommitBuilders are detected properly
2561
Note: CommitBuilder works whether or not root entry is recorded.
2564
record_root_entry = True
2567
class RootCommitBuilder(CommitBuilder):
2568
"""This commitbuilder actually records the root id"""
2570
record_root_entry = True
2572
def record_entry_contents(self, ie, parent_invs, path, tree):
2573
"""Record the content of ie from tree into the commit if needed.
2575
Side effect: sets ie.revision when unchanged
2577
:param ie: An inventory entry present in the commit.
2578
:param parent_invs: The inventories of the parent revisions of the
2580
:param path: The path the entry is at in the tree.
2581
:param tree: The tree which contains this entry and should be used to
2584
assert self.new_inventory.root is not None or ie.parent_id is None
2585
self.new_inventory.add(ie)
2587
# ie.revision is always None if the InventoryEntry is considered
2588
# for committing. ie.snapshot will record the correct revision
2589
# which may be the sole parent if it is untouched.
2590
if ie.revision is not None:
2593
previous_entries = ie.find_previous_heads(
2595
self.repository.weave_store,
2596
self.repository.get_transaction())
2597
# we are creating a new revision for ie in the history store
2599
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2611
def _unescaper(match, _map=_unescape_map):
2612
return _map[match.group(1)]
2618
def _unescape_xml(data):
2619
"""Unescape predefined XML entities in a string of data."""
2621
if _unescape_re is None:
2622
_unescape_re = re.compile('\&([^;]*);')
2623
return _unescape_re.sub(_unescaper, data)