1
# Copyright (C) 2005, 2006 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
38
revision as _mod_revision,
47
from bzrlib.osutils import (
52
from bzrlib.revisiontree import RevisionTree
53
from bzrlib.store.versioned import VersionedFileStore
54
from bzrlib.store.text import TextStore
55
from bzrlib.testament import Testament
58
from bzrlib.decorators import needs_read_lock, needs_write_lock
59
from bzrlib.inter import InterObject
60
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
61
from bzrlib.symbol_versioning import (
65
from bzrlib.trace import mutter, note, warning
68
# Old formats display a warning, but only once
69
_deprecation_warning_done = False
72
class Repository(object):
73
"""Repository holding history for one or more branches.
75
The repository holds and retrieves historical information including
76
revisions and file history. It's normally accessed only by the Branch,
77
which views a particular line of development through that history.
79
The Repository builds on top of Stores and a Transport, which respectively
80
describe the disk data format and the way of accessing the (possibly
85
def add_inventory(self, revid, inv, parents):
86
"""Add the inventory inv to the repository as revid.
88
:param parents: The revision ids of the parents that revid
89
is known to have and are in the repository already.
91
returns the sha1 of the serialized inventory.
93
assert inv.revision_id is None or inv.revision_id == revid, \
94
"Mismatch between inventory revision" \
95
" id and insertion revid (%r, %r)" % (inv.revision_id, revid)
96
assert inv.root is not None
97
inv_text = self.serialise_inventory(inv)
98
inv_sha1 = osutils.sha_string(inv_text)
99
inv_vf = self.control_weaves.get_weave('inventory',
100
self.get_transaction())
101
self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
104
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
106
for parent in parents:
108
final_parents.append(parent)
110
inv_vf.add_lines(revid, final_parents, lines)
113
def add_revision(self, rev_id, rev, inv=None, config=None):
114
"""Add rev to the revision store as rev_id.
116
:param rev_id: the revision id to use.
117
:param rev: The revision object.
118
:param inv: The inventory for the revision. if None, it will be looked
119
up in the inventory storer
120
:param config: If None no digital signature will be created.
121
If supplied its signature_needed method will be used
122
to determine if a signature should be made.
124
if config is not None and config.signature_needed():
126
inv = self.get_inventory(rev_id)
127
plaintext = Testament(rev, inv).as_short_text()
128
self.store_revision_signature(
129
gpg.GPGStrategy(config), plaintext, rev_id)
130
if not rev_id in self.get_inventory_weave():
132
raise errors.WeaveRevisionNotPresent(rev_id,
133
self.get_inventory_weave())
135
# yes, this is not suitable for adding with ghosts.
136
self.add_inventory(rev_id, inv, rev.parent_ids)
137
self._revision_store.add_revision(rev, self.get_transaction())
140
def _all_possible_ids(self):
141
"""Return all the possible revisions that we could find."""
142
return self.get_inventory_weave().versions()
144
def all_revision_ids(self):
145
"""Returns a list of all the revision ids in the repository.
147
This is deprecated because code should generally work on the graph
148
reachable from a particular revision, and ignore any other revisions
149
that might be present. There is no direct replacement method.
151
return self._all_revision_ids()
154
def _all_revision_ids(self):
155
"""Returns a list of all the revision ids in the repository.
157
These are in as much topological order as the underlying store can
158
present: for weaves ghosts may lead to a lack of correctness until
159
the reweave updates the parents list.
161
if self._revision_store.text_store.listable():
162
return self._revision_store.all_revision_ids(self.get_transaction())
163
result = self._all_possible_ids()
164
return self._eliminate_revisions_not_present(result)
166
def break_lock(self):
167
"""Break a lock if one is present from another instance.
169
Uses the ui factory to ask for confirmation if the lock may be from
172
self.control_files.break_lock()
175
def _eliminate_revisions_not_present(self, revision_ids):
176
"""Check every revision id in revision_ids to see if we have it.
178
Returns a set of the present revisions.
181
for id in revision_ids:
182
if self.has_revision(id):
187
def create(a_bzrdir):
188
"""Construct the current default format repository in a_bzrdir."""
189
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
191
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
192
"""instantiate a Repository.
194
:param _format: The format of the repository on disk.
195
:param a_bzrdir: The BzrDir of the repository.
197
In the future we will have a single api for all stores for
198
getting file texts, inventories and revisions, then
199
this construct will accept instances of those things.
201
super(Repository, self).__init__()
202
self._format = _format
203
# the following are part of the public API for Repository:
204
self.bzrdir = a_bzrdir
205
self.control_files = control_files
206
self._revision_store = _revision_store
207
self.text_store = text_store
208
# backwards compatibility
209
self.weave_store = text_store
210
# not right yet - should be more semantically clear ?
212
self.control_store = control_store
213
self.control_weaves = control_store
214
# TODO: make sure to construct the right store classes, etc, depending
215
# on whether escaping is required.
216
self._warn_if_deprecated()
217
self._serializer = xml5.serializer_v5
220
return '%s(%r)' % (self.__class__.__name__,
221
self.bzrdir.transport.base)
224
return self.control_files.is_locked()
226
def lock_write(self):
227
self.control_files.lock_write()
230
self.control_files.lock_read()
232
def get_physical_lock_status(self):
233
return self.control_files.get_physical_lock_status()
236
def missing_revision_ids(self, other, revision_id=None):
237
"""Return the revision ids that other has that this does not.
239
These are returned in topological order.
241
revision_id: only return revision ids included by revision_id.
243
return InterRepository.get(other, self).missing_revision_ids(revision_id)
247
"""Open the repository rooted at base.
249
For instance, if the repository is at URL/.bzr/repository,
250
Repository.open(URL) -> a Repository instance.
252
control = bzrdir.BzrDir.open(base)
253
return control.open_repository()
255
def copy_content_into(self, destination, revision_id=None, basis=None):
256
"""Make a complete copy of the content in self into destination.
258
This is a destructive operation! Do not use it on existing
261
return InterRepository.get(self, destination).copy_content(revision_id, basis)
263
def fetch(self, source, revision_id=None, pb=None):
264
"""Fetch the content required to construct revision_id from source.
266
If revision_id is None all content is copied.
268
return InterRepository.get(source, self).fetch(revision_id=revision_id,
271
def get_commit_builder(self, branch, parents, config, timestamp=None,
272
timezone=None, committer=None, revprops=None,
274
"""Obtain a CommitBuilder for this repository.
276
:param branch: Branch to commit to.
277
:param parents: Revision ids of the parents of the new revision.
278
:param config: Configuration to use.
279
:param timestamp: Optional timestamp recorded for commit.
280
:param timezone: Optional timezone for timestamp.
281
:param committer: Optional committer to set for commit.
282
:param revprops: Optional dictionary of revision properties.
283
:param revision_id: Optional revision id.
285
return _CommitBuilder(self, parents, config, timestamp, timezone,
286
committer, revprops, revision_id)
289
self.control_files.unlock()
292
def clone(self, a_bzrdir, revision_id=None, basis=None):
293
"""Clone this repository into a_bzrdir using the current format.
295
Currently no check is made that the format of this repository and
296
the bzrdir format are compatible. FIXME RBC 20060201.
298
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
299
# use target default format.
300
result = a_bzrdir.create_repository()
301
# FIXME RBC 20060209 split out the repository type to avoid this check ?
302
elif isinstance(a_bzrdir._format,
303
(bzrdir.BzrDirFormat4,
304
bzrdir.BzrDirFormat5,
305
bzrdir.BzrDirFormat6)):
306
result = a_bzrdir.open_repository()
308
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
309
self.copy_content_into(result, revision_id, basis)
313
def has_revision(self, revision_id):
314
"""True if this repository has a copy of the revision."""
315
return self._revision_store.has_revision_id(revision_id,
316
self.get_transaction())
319
def get_revision_reconcile(self, revision_id):
320
"""'reconcile' helper routine that allows access to a revision always.
322
This variant of get_revision does not cross check the weave graph
323
against the revision one as get_revision does: but it should only
324
be used by reconcile, or reconcile-alike commands that are correcting
325
or testing the revision graph.
327
if not revision_id or not isinstance(revision_id, basestring):
328
raise errors.InvalidRevisionId(revision_id=revision_id,
330
return self._revision_store.get_revisions([revision_id],
331
self.get_transaction())[0]
333
def get_revisions(self, revision_ids):
334
return self._revision_store.get_revisions(revision_ids,
335
self.get_transaction())
338
def get_revision_xml(self, revision_id):
339
rev = self.get_revision(revision_id)
341
# the current serializer..
342
self._revision_store._serializer.write_revision(rev, rev_tmp)
344
return rev_tmp.getvalue()
347
def get_revision(self, revision_id):
348
"""Return the Revision object for a named revision"""
349
r = self.get_revision_reconcile(revision_id)
350
# weave corruption can lead to absent revision markers that should be
352
# the following test is reasonably cheap (it needs a single weave read)
353
# and the weave is cached in read transactions. In write transactions
354
# it is not cached but typically we only read a small number of
355
# revisions. For knits when they are introduced we will probably want
356
# to ensure that caching write transactions are in use.
357
inv = self.get_inventory_weave()
358
self._check_revision_parents(r, inv)
362
def get_deltas_for_revisions(self, revisions):
363
"""Produce a generator of revision deltas.
365
Note that the input is a sequence of REVISIONS, not revision_ids.
366
Trees will be held in memory until the generator exits.
367
Each delta is relative to the revision's lefthand predecessor.
369
required_trees = set()
370
for revision in revisions:
371
required_trees.add(revision.revision_id)
372
required_trees.update(revision.parent_ids[:1])
373
trees = dict((t.get_revision_id(), t) for
374
t in self.revision_trees(required_trees))
375
for revision in revisions:
376
if not revision.parent_ids:
377
old_tree = self.revision_tree(None)
379
old_tree = trees[revision.parent_ids[0]]
380
yield trees[revision.revision_id].changes_from(old_tree)
383
def get_revision_delta(self, revision_id):
384
"""Return the delta for one revision.
386
The delta is relative to the left-hand predecessor of the
389
r = self.get_revision(revision_id)
390
return list(self.get_deltas_for_revisions([r]))[0]
392
def _check_revision_parents(self, revision, inventory):
393
"""Private to Repository and Fetch.
395
This checks the parentage of revision in an inventory weave for
396
consistency and is only applicable to inventory-weave-for-ancestry
397
using repository formats & fetchers.
399
weave_parents = inventory.get_parents(revision.revision_id)
400
weave_names = inventory.versions()
401
for parent_id in revision.parent_ids:
402
if parent_id in weave_names:
403
# this parent must not be a ghost.
404
if not parent_id in weave_parents:
406
raise errors.CorruptRepository(self)
409
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
410
signature = gpg_strategy.sign(plaintext)
411
self._revision_store.add_revision_signature_text(revision_id,
413
self.get_transaction())
415
def fileids_altered_by_revision_ids(self, revision_ids):
416
"""Find the file ids and versions affected by revisions.
418
:param revisions: an iterable containing revision ids.
419
:return: a dictionary mapping altered file-ids to an iterable of
420
revision_ids. Each altered file-ids has the exact revision_ids that
421
altered it listed explicitly.
423
assert self._serializer.support_altered_by_hack, \
424
("fileids_altered_by_revision_ids only supported for branches "
425
"which store inventory as unnested xml, not on %r" % self)
426
selected_revision_ids = set(revision_ids)
427
w = self.get_inventory_weave()
430
# this code needs to read every new line in every inventory for the
431
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
432
# not present in one of those inventories is unnecessary but not
433
# harmful because we are filtering by the revision id marker in the
434
# inventory lines : we only select file ids altered in one of those
435
# revisions. We don't need to see all lines in the inventory because
436
# only those added in an inventory in rev X can contain a revision=X
438
pb = ui.ui_factory.nested_progress_bar()
440
for line in w.iter_lines_added_or_present_in_versions(
441
selected_revision_ids, pb=pb):
442
start = line.find('file_id="')+9
443
if start < 9: continue
444
end = line.find('"', start)
446
file_id = _unescape_xml(line[start:end])
448
start = line.find('revision="')+10
449
if start < 10: continue
450
end = line.find('"', start)
452
revision_id = _unescape_xml(line[start:end])
453
if revision_id in selected_revision_ids:
454
result.setdefault(file_id, set()).add(revision_id)
460
def get_inventory_weave(self):
461
return self.control_weaves.get_weave('inventory',
462
self.get_transaction())
465
def get_inventory(self, revision_id):
466
"""Get Inventory object by hash."""
467
return self.deserialise_inventory(
468
revision_id, self.get_inventory_xml(revision_id))
470
def deserialise_inventory(self, revision_id, xml):
471
"""Transform the xml into an inventory object.
473
:param revision_id: The expected revision id of the inventory.
474
:param xml: A serialised inventory.
476
result = self._serializer.read_inventory_from_string(xml)
477
result.root.revision = revision_id
480
def serialise_inventory(self, inv):
481
return self._serializer.write_inventory_to_string(inv)
484
def get_inventory_xml(self, revision_id):
485
"""Get inventory XML as a file object."""
487
assert isinstance(revision_id, basestring), type(revision_id)
488
iw = self.get_inventory_weave()
489
return iw.get_text(revision_id)
491
raise errors.HistoryMissing(self, 'inventory', revision_id)
494
def get_inventory_sha1(self, revision_id):
495
"""Return the sha1 hash of the inventory entry
497
return self.get_revision(revision_id).inventory_sha1
500
def get_revision_graph(self, revision_id=None):
501
"""Return a dictionary containing the revision graph.
503
:param revision_id: The revision_id to get a graph from. If None, then
504
the entire revision graph is returned. This is a deprecated mode of
505
operation and will be removed in the future.
506
:return: a dictionary of revision_id->revision_parents_list.
508
# special case NULL_REVISION
509
if revision_id == _mod_revision.NULL_REVISION:
511
a_weave = self.get_inventory_weave()
512
all_revisions = self._eliminate_revisions_not_present(
514
entire_graph = dict([(node, a_weave.get_parents(node)) for
515
node in all_revisions])
516
if revision_id is None:
518
elif revision_id not in entire_graph:
519
raise errors.NoSuchRevision(self, revision_id)
521
# add what can be reached from revision_id
523
pending = set([revision_id])
524
while len(pending) > 0:
526
result[node] = entire_graph[node]
527
for revision_id in result[node]:
528
if revision_id not in result:
529
pending.add(revision_id)
533
def get_revision_graph_with_ghosts(self, revision_ids=None):
534
"""Return a graph of the revisions with ghosts marked as applicable.
536
:param revision_ids: an iterable of revisions to graph or None for all.
537
:return: a Graph object with the graph reachable from revision_ids.
539
result = graph.Graph()
541
pending = set(self.all_revision_ids())
544
pending = set(revision_ids)
545
# special case NULL_REVISION
546
if _mod_revision.NULL_REVISION in pending:
547
pending.remove(_mod_revision.NULL_REVISION)
548
required = set(pending)
551
revision_id = pending.pop()
553
rev = self.get_revision(revision_id)
554
except errors.NoSuchRevision:
555
if revision_id in required:
558
result.add_ghost(revision_id)
560
for parent_id in rev.parent_ids:
561
# is this queued or done ?
562
if (parent_id not in pending and
563
parent_id not in done):
565
pending.add(parent_id)
566
result.add_node(revision_id, rev.parent_ids)
567
done.add(revision_id)
571
def get_revision_inventory(self, revision_id):
572
"""Return inventory of a past revision."""
573
# TODO: Unify this with get_inventory()
574
# bzr 0.0.6 and later imposes the constraint that the inventory_id
575
# must be the same as its revision, so this is trivial.
576
if revision_id is None:
577
# This does not make sense: if there is no revision,
578
# then it is the current tree inventory surely ?!
579
# and thus get_root_id() is something that looks at the last
580
# commit on the branch, and the get_root_id is an inventory check.
581
raise NotImplementedError
582
# return Inventory(self.get_root_id())
584
return self.get_inventory(revision_id)
588
"""Return True if this repository is flagged as a shared repository."""
589
raise NotImplementedError(self.is_shared)
592
def reconcile(self, other=None, thorough=False):
593
"""Reconcile this repository."""
594
from bzrlib.reconcile import RepoReconciler
595
reconciler = RepoReconciler(self, thorough=thorough)
596
reconciler.reconcile()
600
def revision_tree(self, revision_id):
601
"""Return Tree for a revision on this branch.
603
`revision_id` may be None for the empty tree revision.
605
# TODO: refactor this to use an existing revision object
606
# so we don't need to read it in twice.
607
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
608
return RevisionTree(self, Inventory(root_id=None),
609
_mod_revision.NULL_REVISION)
611
inv = self.get_revision_inventory(revision_id)
612
return RevisionTree(self, inv, revision_id)
615
def revision_trees(self, revision_ids):
616
"""Return Tree for a revision on this branch.
618
`revision_id` may not be None or 'null:'"""
619
assert None not in revision_ids
620
assert _mod_revision.NULL_REVISION not in revision_ids
621
texts = self.get_inventory_weave().get_texts(revision_ids)
622
for text, revision_id in zip(texts, revision_ids):
623
inv = self.deserialise_inventory(revision_id, text)
624
yield RevisionTree(self, inv, revision_id)
627
def get_ancestry(self, revision_id):
628
"""Return a list of revision-ids integrated by a revision.
630
The first element of the list is always None, indicating the origin
631
revision. This might change when we have history horizons, or
632
perhaps we should have a new API.
634
This is topologically sorted.
636
if revision_id is None:
638
if not self.has_revision(revision_id):
639
raise errors.NoSuchRevision(self, revision_id)
640
w = self.get_inventory_weave()
641
candidates = w.get_ancestry(revision_id)
642
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
645
def print_file(self, file, revision_id):
646
"""Print `file` to stdout.
648
FIXME RBC 20060125 as John Meinel points out this is a bad api
649
- it writes to stdout, it assumes that that is valid etc. Fix
650
by creating a new more flexible convenience function.
652
tree = self.revision_tree(revision_id)
653
# use inventory as it was in that revision
654
file_id = tree.inventory.path2id(file)
656
# TODO: jam 20060427 Write a test for this code path
657
# it had a bug in it, and was raising the wrong
659
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
660
tree.print_file(file_id)
662
def get_transaction(self):
663
return self.control_files.get_transaction()
665
def revision_parents(self, revid):
666
return self.get_inventory_weave().parent_names(revid)
669
def set_make_working_trees(self, new_value):
670
"""Set the policy flag for making working trees when creating branches.
672
This only applies to branches that use this repository.
674
The default is 'True'.
675
:param new_value: True to restore the default, False to disable making
678
raise NotImplementedError(self.set_make_working_trees)
680
def make_working_trees(self):
681
"""Returns the policy for making working trees on new branches."""
682
raise NotImplementedError(self.make_working_trees)
685
def sign_revision(self, revision_id, gpg_strategy):
686
plaintext = Testament.from_revision(self, revision_id).as_short_text()
687
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
690
def has_signature_for_revision_id(self, revision_id):
691
"""Query for a revision signature for revision_id in the repository."""
692
return self._revision_store.has_signature(revision_id,
693
self.get_transaction())
696
def get_signature_text(self, revision_id):
697
"""Return the text for a signature."""
698
return self._revision_store.get_signature_text(revision_id,
699
self.get_transaction())
702
def check(self, revision_ids):
703
"""Check consistency of all history of given revision_ids.
705
Different repository implementations should override _check().
707
:param revision_ids: A non-empty list of revision_ids whose ancestry
708
will be checked. Typically the last revision_id of a branch.
711
raise ValueError("revision_ids must be non-empty in %s.check"
713
return self._check(revision_ids)
715
def _check(self, revision_ids):
716
result = check.Check(self)
720
def _warn_if_deprecated(self):
721
global _deprecation_warning_done
722
if _deprecation_warning_done:
724
_deprecation_warning_done = True
725
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
726
% (self._format, self.bzrdir.transport.base))
728
def supports_rich_root(self):
729
return self._format.rich_root_data
732
class AllInOneRepository(Repository):
733
"""Legacy support - the repository behaviour for all-in-one branches."""
735
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
736
# we reuse one control files instance.
737
dir_mode = a_bzrdir._control_files._dir_mode
738
file_mode = a_bzrdir._control_files._file_mode
740
def get_store(name, compressed=True, prefixed=False):
741
# FIXME: This approach of assuming stores are all entirely compressed
742
# or entirely uncompressed is tidy, but breaks upgrade from
743
# some existing branches where there's a mixture; we probably
744
# still want the option to look for both.
745
relpath = a_bzrdir._control_files._escape(name)
746
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
747
prefixed=prefixed, compressed=compressed,
750
#if self._transport.should_cache():
751
# cache_path = os.path.join(self.cache_root, name)
752
# os.mkdir(cache_path)
753
# store = bzrlib.store.CachedStore(store, cache_path)
756
# not broken out yet because the controlweaves|inventory_store
757
# and text_store | weave_store bits are still different.
758
if isinstance(_format, RepositoryFormat4):
759
# cannot remove these - there is still no consistent api
760
# which allows access to this old info.
761
self.inventory_store = get_store('inventory-store')
762
text_store = get_store('text-store')
763
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
767
"""AllInOne repositories cannot be shared."""
771
def set_make_working_trees(self, new_value):
772
"""Set the policy flag for making working trees when creating branches.
774
This only applies to branches that use this repository.
776
The default is 'True'.
777
:param new_value: True to restore the default, False to disable making
780
raise NotImplementedError(self.set_make_working_trees)
782
def make_working_trees(self):
783
"""Returns the policy for making working trees on new branches."""
787
def install_revision(repository, rev, revision_tree):
788
"""Install all revision data into a repository."""
791
for p_id in rev.parent_ids:
792
if repository.has_revision(p_id):
793
present_parents.append(p_id)
794
parent_trees[p_id] = repository.revision_tree(p_id)
796
parent_trees[p_id] = repository.revision_tree(None)
798
inv = revision_tree.inventory
799
entries = inv.iter_entries()
800
# backwards compatability hack: skip the root id.
801
if not repository.supports_rich_root():
802
path, root = entries.next()
803
if root.revision != rev.revision_id:
804
raise errors.IncompatibleRevision(repr(repository))
805
# Add the texts that are not already present
806
for path, ie in entries:
807
w = repository.weave_store.get_weave_or_empty(ie.file_id,
808
repository.get_transaction())
809
if ie.revision not in w:
811
# FIXME: TODO: The following loop *may* be overlapping/duplicate
812
# with InventoryEntry.find_previous_heads(). if it is, then there
813
# is a latent bug here where the parents may have ancestors of each
815
for revision, tree in parent_trees.iteritems():
816
if ie.file_id not in tree:
818
parent_id = tree.inventory[ie.file_id].revision
819
if parent_id in text_parents:
821
text_parents.append(parent_id)
823
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
824
repository.get_transaction())
825
lines = revision_tree.get_file(ie.file_id).readlines()
826
vfile.add_lines(rev.revision_id, text_parents, lines)
828
# install the inventory
829
repository.add_inventory(rev.revision_id, inv, present_parents)
830
except errors.RevisionAlreadyPresent:
832
repository.add_revision(rev.revision_id, rev, inv)
835
class MetaDirRepository(Repository):
836
"""Repositories in the new meta-dir layout."""
838
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
839
super(MetaDirRepository, self).__init__(_format,
845
dir_mode = self.control_files._dir_mode
846
file_mode = self.control_files._file_mode
850
"""Return True if this repository is flagged as a shared repository."""
851
return self.control_files._transport.has('shared-storage')
854
def set_make_working_trees(self, new_value):
855
"""Set the policy flag for making working trees when creating branches.
857
This only applies to branches that use this repository.
859
The default is 'True'.
860
:param new_value: True to restore the default, False to disable making
865
self.control_files._transport.delete('no-working-trees')
866
except errors.NoSuchFile:
869
self.control_files.put_utf8('no-working-trees', '')
871
def make_working_trees(self):
872
"""Returns the policy for making working trees on new branches."""
873
return not self.control_files._transport.has('no-working-trees')
876
class KnitRepository(MetaDirRepository):
877
"""Knit format repository."""
879
def _warn_if_deprecated(self):
880
# This class isn't deprecated
883
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
884
inv_vf.add_lines_with_ghosts(revid, parents, lines)
887
def _all_revision_ids(self):
888
"""See Repository.all_revision_ids()."""
889
# Knits get the revision graph from the index of the revision knit, so
890
# it's always possible even if they're on an unlistable transport.
891
return self._revision_store.all_revision_ids(self.get_transaction())
893
def fileid_involved_between_revs(self, from_revid, to_revid):
894
"""Find file_id(s) which are involved in the changes between revisions.
896
This determines the set of revisions which are involved, and then
897
finds all file ids affected by those revisions.
899
vf = self._get_revision_vf()
900
from_set = set(vf.get_ancestry(from_revid))
901
to_set = set(vf.get_ancestry(to_revid))
902
changed = to_set.difference(from_set)
903
return self._fileid_involved_by_set(changed)
905
def fileid_involved(self, last_revid=None):
906
"""Find all file_ids modified in the ancestry of last_revid.
908
:param last_revid: If None, last_revision() will be used.
911
changed = set(self.all_revision_ids())
913
changed = set(self.get_ancestry(last_revid))
916
return self._fileid_involved_by_set(changed)
919
def get_ancestry(self, revision_id):
920
"""Return a list of revision-ids integrated by a revision.
922
This is topologically sorted.
924
if revision_id is None:
926
vf = self._get_revision_vf()
928
return [None] + vf.get_ancestry(revision_id)
929
except errors.RevisionNotPresent:
930
raise errors.NoSuchRevision(self, revision_id)
933
def get_revision(self, revision_id):
934
"""Return the Revision object for a named revision"""
935
return self.get_revision_reconcile(revision_id)
938
def get_revision_graph(self, revision_id=None):
939
"""Return a dictionary containing the revision graph.
941
:param revision_id: The revision_id to get a graph from. If None, then
942
the entire revision graph is returned. This is a deprecated mode of
943
operation and will be removed in the future.
944
:return: a dictionary of revision_id->revision_parents_list.
946
# special case NULL_REVISION
947
if revision_id == _mod_revision.NULL_REVISION:
949
a_weave = self._get_revision_vf()
950
entire_graph = a_weave.get_graph()
951
if revision_id is None:
952
return a_weave.get_graph()
953
elif revision_id not in a_weave:
954
raise errors.NoSuchRevision(self, revision_id)
956
# add what can be reached from revision_id
958
pending = set([revision_id])
959
while len(pending) > 0:
961
result[node] = a_weave.get_parents(node)
962
for revision_id in result[node]:
963
if revision_id not in result:
964
pending.add(revision_id)
968
def get_revision_graph_with_ghosts(self, revision_ids=None):
969
"""Return a graph of the revisions with ghosts marked as applicable.
971
:param revision_ids: an iterable of revisions to graph or None for all.
972
:return: a Graph object with the graph reachable from revision_ids.
974
result = graph.Graph()
975
vf = self._get_revision_vf()
976
versions = set(vf.versions())
978
pending = set(self.all_revision_ids())
981
pending = set(revision_ids)
982
# special case NULL_REVISION
983
if _mod_revision.NULL_REVISION in pending:
984
pending.remove(_mod_revision.NULL_REVISION)
985
required = set(pending)
988
revision_id = pending.pop()
989
if not revision_id in versions:
990
if revision_id in required:
991
raise errors.NoSuchRevision(self, revision_id)
993
result.add_ghost(revision_id)
994
# mark it as done so we don't try for it again.
995
done.add(revision_id)
997
parent_ids = vf.get_parents_with_ghosts(revision_id)
998
for parent_id in parent_ids:
999
# is this queued or done ?
1000
if (parent_id not in pending and
1001
parent_id not in done):
1003
pending.add(parent_id)
1004
result.add_node(revision_id, parent_ids)
1005
done.add(revision_id)
1008
def _get_revision_vf(self):
1009
""":return: a versioned file containing the revisions."""
1010
vf = self._revision_store.get_revision_file(self.get_transaction())
1014
def reconcile(self, other=None, thorough=False):
1015
"""Reconcile this repository."""
1016
from bzrlib.reconcile import KnitReconciler
1017
reconciler = KnitReconciler(self, thorough=thorough)
1018
reconciler.reconcile()
1021
def revision_parents(self, revision_id):
1022
return self._get_revision_vf().get_parents(revision_id)
1025
class KnitRepository2(KnitRepository):
1027
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1028
control_store, text_store):
1029
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1030
_revision_store, control_store, text_store)
1031
self._serializer = xml6.serializer_v6
1033
def deserialise_inventory(self, revision_id, xml):
1034
"""Transform the xml into an inventory object.
1036
:param revision_id: The expected revision id of the inventory.
1037
:param xml: A serialised inventory.
1039
result = self._serializer.read_inventory_from_string(xml)
1040
assert result.root.revision is not None
1043
def serialise_inventory(self, inv):
1044
"""Transform the inventory object into XML text.
1046
:param revision_id: The expected revision id of the inventory.
1047
:param xml: A serialised inventory.
1049
assert inv.revision_id is not None
1050
assert inv.root.revision is not None
1051
return KnitRepository.serialise_inventory(self, inv)
1053
def get_commit_builder(self, branch, parents, config, timestamp=None,
1054
timezone=None, committer=None, revprops=None,
1056
"""Obtain a CommitBuilder for this repository.
1058
:param branch: Branch to commit to.
1059
:param parents: Revision ids of the parents of the new revision.
1060
:param config: Configuration to use.
1061
:param timestamp: Optional timestamp recorded for commit.
1062
:param timezone: Optional timezone for timestamp.
1063
:param committer: Optional committer to set for commit.
1064
:param revprops: Optional dictionary of revision properties.
1065
:param revision_id: Optional revision id.
1067
return RootCommitBuilder(self, parents, config, timestamp, timezone,
1068
committer, revprops, revision_id)
1071
class RepositoryFormat(object):
1072
"""A repository format.
1074
Formats provide three things:
1075
* An initialization routine to construct repository data on disk.
1076
* a format string which is used when the BzrDir supports versioned
1078
* an open routine which returns a Repository instance.
1080
Formats are placed in an dict by their format string for reference
1081
during opening. These should be subclasses of RepositoryFormat
1084
Once a format is deprecated, just deprecate the initialize and open
1085
methods on the format class. Do not deprecate the object, as the
1086
object will be created every system load.
1088
Common instance attributes:
1089
_matchingbzrdir - the bzrdir format that the repository format was
1090
originally written to work with. This can be used if manually
1091
constructing a bzrdir and repository, or more commonly for test suite
1095
_default_format = None
1096
"""The default format used for new repositories."""
1099
"""The known formats."""
1102
return "<%s>" % self.__class__.__name__
1105
def find_format(klass, a_bzrdir):
1106
"""Return the format for the repository object in a_bzrdir."""
1108
transport = a_bzrdir.get_repository_transport(None)
1109
format_string = transport.get("format").read()
1110
return klass._formats[format_string]
1111
except errors.NoSuchFile:
1112
raise errors.NoRepositoryPresent(a_bzrdir)
1114
raise errors.UnknownFormatError(format=format_string)
1116
def _get_control_store(self, repo_transport, control_files):
1117
"""Return the control store for this repository."""
1118
raise NotImplementedError(self._get_control_store)
1121
def get_default_format(klass):
1122
"""Return the current default format."""
1123
return klass._default_format
1125
def get_format_string(self):
1126
"""Return the ASCII format string that identifies this format.
1128
Note that in pre format ?? repositories the format string is
1129
not permitted nor written to disk.
1131
raise NotImplementedError(self.get_format_string)
1133
def get_format_description(self):
1134
"""Return the short description for this format."""
1135
raise NotImplementedError(self.get_format_description)
1137
def _get_revision_store(self, repo_transport, control_files):
1138
"""Return the revision store object for this a_bzrdir."""
1139
raise NotImplementedError(self._get_revision_store)
1141
def _get_text_rev_store(self,
1148
"""Common logic for getting a revision store for a repository.
1150
see self._get_revision_store for the subclass-overridable method to
1151
get the store for a repository.
1153
from bzrlib.store.revision.text import TextRevisionStore
1154
dir_mode = control_files._dir_mode
1155
file_mode = control_files._file_mode
1156
text_store =TextStore(transport.clone(name),
1158
compressed=compressed,
1160
file_mode=file_mode)
1161
_revision_store = TextRevisionStore(text_store, serializer)
1162
return _revision_store
1164
def _get_versioned_file_store(self,
1169
versionedfile_class=weave.WeaveFile,
1170
versionedfile_kwargs={},
1172
weave_transport = control_files._transport.clone(name)
1173
dir_mode = control_files._dir_mode
1174
file_mode = control_files._file_mode
1175
return VersionedFileStore(weave_transport, prefixed=prefixed,
1177
file_mode=file_mode,
1178
versionedfile_class=versionedfile_class,
1179
versionedfile_kwargs=versionedfile_kwargs,
1182
def initialize(self, a_bzrdir, shared=False):
1183
"""Initialize a repository of this format in a_bzrdir.
1185
:param a_bzrdir: The bzrdir to put the new repository in it.
1186
:param shared: The repository should be initialized as a sharable one.
1187
:returns: The new repository object.
1189
This may raise UninitializableFormat if shared repository are not
1190
compatible the a_bzrdir.
1192
raise NotImplementedError(self.initialize)
1194
def is_supported(self):
1195
"""Is this format supported?
1197
Supported formats must be initializable and openable.
1198
Unsupported formats may not support initialization or committing or
1199
some other features depending on the reason for not being supported.
1203
def check_conversion_target(self, target_format):
1204
raise NotImplementedError(self.check_conversion_target)
1206
def open(self, a_bzrdir, _found=False):
1207
"""Return an instance of this format for the bzrdir a_bzrdir.
1209
_found is a private parameter, do not use it.
1211
raise NotImplementedError(self.open)
1214
def register_format(klass, format):
1215
klass._formats[format.get_format_string()] = format
1218
def set_default_format(klass, format):
1219
klass._default_format = format
1222
def unregister_format(klass, format):
1223
assert klass._formats[format.get_format_string()] is format
1224
del klass._formats[format.get_format_string()]
1227
class PreSplitOutRepositoryFormat(RepositoryFormat):
1228
"""Base class for the pre split out repository formats."""
1230
rich_root_data = False
1232
def initialize(self, a_bzrdir, shared=False, _internal=False):
1233
"""Create a weave repository.
1235
TODO: when creating split out bzr branch formats, move this to a common
1236
base for Format5, Format6. or something like that.
1239
raise errors.IncompatibleFormat(self, a_bzrdir._format)
1242
# always initialized when the bzrdir is.
1243
return self.open(a_bzrdir, _found=True)
1245
# Create an empty weave
1247
weavefile.write_weave_v5(weave.Weave(), sio)
1248
empty_weave = sio.getvalue()
1250
mutter('creating repository in %s.', a_bzrdir.transport.base)
1251
dirs = ['revision-store', 'weaves']
1252
files = [('inventory.weave', StringIO(empty_weave)),
1255
# FIXME: RBC 20060125 don't peek under the covers
1256
# NB: no need to escape relative paths that are url safe.
1257
control_files = lockable_files.LockableFiles(a_bzrdir.transport,
1258
'branch-lock', lockable_files.TransportLock)
1259
control_files.create_lock()
1260
control_files.lock_write()
1261
control_files._transport.mkdir_multi(dirs,
1262
mode=control_files._dir_mode)
1264
for file, content in files:
1265
control_files.put(file, content)
1267
control_files.unlock()
1268
return self.open(a_bzrdir, _found=True)
1270
def _get_control_store(self, repo_transport, control_files):
1271
"""Return the control store for this repository."""
1272
return self._get_versioned_file_store('',
1277
def _get_text_store(self, transport, control_files):
1278
"""Get a store for file texts for this format."""
1279
raise NotImplementedError(self._get_text_store)
1281
def open(self, a_bzrdir, _found=False):
1282
"""See RepositoryFormat.open()."""
1284
# we are being called directly and must probe.
1285
raise NotImplementedError
1287
repo_transport = a_bzrdir.get_repository_transport(None)
1288
control_files = a_bzrdir._control_files
1289
text_store = self._get_text_store(repo_transport, control_files)
1290
control_store = self._get_control_store(repo_transport, control_files)
1291
_revision_store = self._get_revision_store(repo_transport, control_files)
1292
return AllInOneRepository(_format=self,
1294
_revision_store=_revision_store,
1295
control_store=control_store,
1296
text_store=text_store)
1298
def check_conversion_target(self, target_format):
1302
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1303
"""Bzr repository format 4.
1305
This repository format has:
1307
- TextStores for texts, inventories,revisions.
1309
This format is deprecated: it indexes texts using a text id which is
1310
removed in format 5; initialization and write support for this format
1315
super(RepositoryFormat4, self).__init__()
1316
self._matchingbzrdir = bzrdir.BzrDirFormat4()
1318
def get_format_description(self):
1319
"""See RepositoryFormat.get_format_description()."""
1320
return "Repository format 4"
1322
def initialize(self, url, shared=False, _internal=False):
1323
"""Format 4 branches cannot be created."""
1324
raise errors.UninitializableFormat(self)
1326
def is_supported(self):
1327
"""Format 4 is not supported.
1329
It is not supported because the model changed from 4 to 5 and the
1330
conversion logic is expensive - so doing it on the fly was not
1335
def _get_control_store(self, repo_transport, control_files):
1336
"""Format 4 repositories have no formal control store at this point.
1338
This will cause any control-file-needing apis to fail - this is desired.
1342
def _get_revision_store(self, repo_transport, control_files):
1343
"""See RepositoryFormat._get_revision_store()."""
1344
from bzrlib.xml4 import serializer_v4
1345
return self._get_text_rev_store(repo_transport,
1348
serializer=serializer_v4)
1350
def _get_text_store(self, transport, control_files):
1351
"""See RepositoryFormat._get_text_store()."""
1354
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1355
"""Bzr control format 5.
1357
This repository format has:
1358
- weaves for file texts and inventory
1360
- TextStores for revisions and signatures.
1364
super(RepositoryFormat5, self).__init__()
1365
self._matchingbzrdir = bzrdir.BzrDirFormat5()
1367
def get_format_description(self):
1368
"""See RepositoryFormat.get_format_description()."""
1369
return "Weave repository format 5"
1371
def _get_revision_store(self, repo_transport, control_files):
1372
"""See RepositoryFormat._get_revision_store()."""
1373
"""Return the revision store object for this a_bzrdir."""
1374
return self._get_text_rev_store(repo_transport,
1379
def _get_text_store(self, transport, control_files):
1380
"""See RepositoryFormat._get_text_store()."""
1381
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1384
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1385
"""Bzr control format 6.
1387
This repository format has:
1388
- weaves for file texts and inventory
1389
- hash subdirectory based stores.
1390
- TextStores for revisions and signatures.
1394
super(RepositoryFormat6, self).__init__()
1395
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1397
def get_format_description(self):
1398
"""See RepositoryFormat.get_format_description()."""
1399
return "Weave repository format 6"
1401
def _get_revision_store(self, repo_transport, control_files):
1402
"""See RepositoryFormat._get_revision_store()."""
1403
return self._get_text_rev_store(repo_transport,
1409
def _get_text_store(self, transport, control_files):
1410
"""See RepositoryFormat._get_text_store()."""
1411
return self._get_versioned_file_store('weaves', transport, control_files)
1414
class MetaDirRepositoryFormat(RepositoryFormat):
1415
"""Common base class for the new repositories using the metadir layout."""
1417
rich_root_data = False
1420
super(MetaDirRepositoryFormat, self).__init__()
1421
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1423
def _create_control_files(self, a_bzrdir):
1424
"""Create the required files and the initial control_files object."""
1425
# FIXME: RBC 20060125 don't peek under the covers
1426
# NB: no need to escape relative paths that are url safe.
1427
repository_transport = a_bzrdir.get_repository_transport(self)
1428
control_files = lockable_files.LockableFiles(repository_transport,
1429
'lock', lockdir.LockDir)
1430
control_files.create_lock()
1431
return control_files
1433
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1434
"""Upload the initial blank content."""
1435
control_files = self._create_control_files(a_bzrdir)
1436
control_files.lock_write()
1438
control_files._transport.mkdir_multi(dirs,
1439
mode=control_files._dir_mode)
1440
for file, content in files:
1441
control_files.put(file, content)
1442
for file, content in utf8_files:
1443
control_files.put_utf8(file, content)
1445
control_files.put_utf8('shared-storage', '')
1447
control_files.unlock()
1450
class RepositoryFormat7(MetaDirRepositoryFormat):
1451
"""Bzr repository 7.
1453
This repository format has:
1454
- weaves for file texts and inventory
1455
- hash subdirectory based stores.
1456
- TextStores for revisions and signatures.
1457
- a format marker of its own
1458
- an optional 'shared-storage' flag
1459
- an optional 'no-working-trees' flag
1462
def _get_control_store(self, repo_transport, control_files):
1463
"""Return the control store for this repository."""
1464
return self._get_versioned_file_store('',
1469
def get_format_string(self):
1470
"""See RepositoryFormat.get_format_string()."""
1471
return "Bazaar-NG Repository format 7"
1473
def get_format_description(self):
1474
"""See RepositoryFormat.get_format_description()."""
1475
return "Weave repository format 7"
1477
def check_conversion_target(self, target_format):
1480
def _get_revision_store(self, repo_transport, control_files):
1481
"""See RepositoryFormat._get_revision_store()."""
1482
return self._get_text_rev_store(repo_transport,
1489
def _get_text_store(self, transport, control_files):
1490
"""See RepositoryFormat._get_text_store()."""
1491
return self._get_versioned_file_store('weaves',
1495
def initialize(self, a_bzrdir, shared=False):
1496
"""Create a weave repository.
1498
:param shared: If true the repository will be initialized as a shared
1501
# Create an empty weave
1503
weavefile.write_weave_v5(weave.Weave(), sio)
1504
empty_weave = sio.getvalue()
1506
mutter('creating repository in %s.', a_bzrdir.transport.base)
1507
dirs = ['revision-store', 'weaves']
1508
files = [('inventory.weave', StringIO(empty_weave)),
1510
utf8_files = [('format', self.get_format_string())]
1512
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1513
return self.open(a_bzrdir=a_bzrdir, _found=True)
1515
def open(self, a_bzrdir, _found=False, _override_transport=None):
1516
"""See RepositoryFormat.open().
1518
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1519
repository at a slightly different url
1520
than normal. I.e. during 'upgrade'.
1523
format = RepositoryFormat.find_format(a_bzrdir)
1524
assert format.__class__ == self.__class__
1525
if _override_transport is not None:
1526
repo_transport = _override_transport
1528
repo_transport = a_bzrdir.get_repository_transport(None)
1529
control_files = lockable_files.LockableFiles(repo_transport,
1530
'lock', lockdir.LockDir)
1531
text_store = self._get_text_store(repo_transport, control_files)
1532
control_store = self._get_control_store(repo_transport, control_files)
1533
_revision_store = self._get_revision_store(repo_transport, control_files)
1534
return MetaDirRepository(_format=self,
1536
control_files=control_files,
1537
_revision_store=_revision_store,
1538
control_store=control_store,
1539
text_store=text_store)
1542
class RepositoryFormatKnit(MetaDirRepositoryFormat):
1543
"""Bzr repository knit format (generalized).
1545
This repository format has:
1546
- knits for file texts and inventory
1547
- hash subdirectory based stores.
1548
- knits for revisions and signatures
1549
- TextStores for revisions and signatures.
1550
- a format marker of its own
1551
- an optional 'shared-storage' flag
1552
- an optional 'no-working-trees' flag
1556
def _get_control_store(self, repo_transport, control_files):
1557
"""Return the control store for this repository."""
1558
return VersionedFileStore(
1561
file_mode=control_files._file_mode,
1562
versionedfile_class=knit.KnitVersionedFile,
1563
versionedfile_kwargs={'factory':knit.KnitPlainFactory()},
1566
def _get_revision_store(self, repo_transport, control_files):
1567
"""See RepositoryFormat._get_revision_store()."""
1568
from bzrlib.store.revision.knit import KnitRevisionStore
1569
versioned_file_store = VersionedFileStore(
1571
file_mode=control_files._file_mode,
1574
versionedfile_class=knit.KnitVersionedFile,
1575
versionedfile_kwargs={'delta':False,
1576
'factory':knit.KnitPlainFactory(),
1580
return KnitRevisionStore(versioned_file_store)
1582
def _get_text_store(self, transport, control_files):
1583
"""See RepositoryFormat._get_text_store()."""
1584
return self._get_versioned_file_store('knits',
1587
versionedfile_class=knit.KnitVersionedFile,
1588
versionedfile_kwargs={
1589
'create_parent_dir':True,
1590
'delay_create':True,
1591
'dir_mode':control_files._dir_mode,
1595
def initialize(self, a_bzrdir, shared=False):
1596
"""Create a knit format 1 repository.
1598
:param a_bzrdir: bzrdir to contain the new repository; must already
1600
:param shared: If true the repository will be initialized as a shared
1603
mutter('creating repository in %s.', a_bzrdir.transport.base)
1604
dirs = ['revision-store', 'knits']
1606
utf8_files = [('format', self.get_format_string())]
1608
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1609
repo_transport = a_bzrdir.get_repository_transport(None)
1610
control_files = lockable_files.LockableFiles(repo_transport,
1611
'lock', lockdir.LockDir)
1612
control_store = self._get_control_store(repo_transport, control_files)
1613
transaction = transactions.WriteTransaction()
1614
# trigger a write of the inventory store.
1615
control_store.get_weave_or_empty('inventory', transaction)
1616
_revision_store = self._get_revision_store(repo_transport, control_files)
1617
_revision_store.has_revision_id('A', transaction)
1618
_revision_store.get_signature_file(transaction)
1619
return self.open(a_bzrdir=a_bzrdir, _found=True)
1621
def open(self, a_bzrdir, _found=False, _override_transport=None):
1622
"""See RepositoryFormat.open().
1624
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1625
repository at a slightly different url
1626
than normal. I.e. during 'upgrade'.
1629
format = RepositoryFormat.find_format(a_bzrdir)
1630
assert format.__class__ == self.__class__
1631
if _override_transport is not None:
1632
repo_transport = _override_transport
1634
repo_transport = a_bzrdir.get_repository_transport(None)
1635
control_files = lockable_files.LockableFiles(repo_transport,
1636
'lock', lockdir.LockDir)
1637
text_store = self._get_text_store(repo_transport, control_files)
1638
control_store = self._get_control_store(repo_transport, control_files)
1639
_revision_store = self._get_revision_store(repo_transport, control_files)
1640
return KnitRepository(_format=self,
1642
control_files=control_files,
1643
_revision_store=_revision_store,
1644
control_store=control_store,
1645
text_store=text_store)
1648
class RepositoryFormatKnit1(RepositoryFormatKnit):
1649
"""Bzr repository knit format 1.
1651
This repository format has:
1652
- knits for file texts and inventory
1653
- hash subdirectory based stores.
1654
- knits for revisions and signatures
1655
- TextStores for revisions and signatures.
1656
- a format marker of its own
1657
- an optional 'shared-storage' flag
1658
- an optional 'no-working-trees' flag
1661
This format was introduced in bzr 0.8.
1663
def get_format_string(self):
1664
"""See RepositoryFormat.get_format_string()."""
1665
return "Bazaar-NG Knit Repository Format 1"
1667
def get_format_description(self):
1668
"""See RepositoryFormat.get_format_description()."""
1669
return "Knit repository format 1"
1671
def check_conversion_target(self, target_format):
1675
class RepositoryFormatKnit2(RepositoryFormatKnit):
1676
"""Bzr repository knit format 2.
1678
THIS FORMAT IS EXPERIMENTAL
1679
This repository format has:
1680
- knits for file texts and inventory
1681
- hash subdirectory based stores.
1682
- knits for revisions and signatures
1683
- TextStores for revisions and signatures.
1684
- a format marker of its own
1685
- an optional 'shared-storage' flag
1686
- an optional 'no-working-trees' flag
1688
- Support for recording full info about the tree root
1692
rich_root_data = True
1694
def get_format_string(self):
1695
"""See RepositoryFormat.get_format_string()."""
1696
return "Bazaar Knit Repository Format 2\n"
1698
def get_format_description(self):
1699
"""See RepositoryFormat.get_format_description()."""
1700
return "Knit repository format 2"
1702
def check_conversion_target(self, target_format):
1703
if not target_format.rich_root_data:
1704
raise errors.BadConversionTarget(
1705
'Does not support rich root data.', target_format)
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, 'lock',
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 KnitRepository2(_format=self,
1728
control_files=control_files,
1729
_revision_store=_revision_store,
1730
control_store=control_store,
1731
text_store=text_store)
1735
# formats which have no format string are not discoverable
1736
# and not independently creatable, so are not registered.
1737
RepositoryFormat.register_format(RepositoryFormat7())
1738
_default_format = RepositoryFormatKnit1()
1739
RepositoryFormat.register_format(_default_format)
1740
RepositoryFormat.register_format(RepositoryFormatKnit2())
1741
RepositoryFormat.set_default_format(_default_format)
1742
_legacy_formats = [RepositoryFormat4(),
1743
RepositoryFormat5(),
1744
RepositoryFormat6()]
1747
class InterRepository(InterObject):
1748
"""This class represents operations taking place between two repositories.
1750
Its instances have methods like copy_content and fetch, and contain
1751
references to the source and target repositories these operations can be
1754
Often we will provide convenience methods on 'repository' which carry out
1755
operations with another repository - they will always forward to
1756
InterRepository.get(other).method_name(parameters).
1760
"""The available optimised InterRepository types."""
1762
def copy_content(self, revision_id=None, basis=None):
1763
raise NotImplementedError(self.copy_content)
1765
def fetch(self, revision_id=None, pb=None):
1766
"""Fetch the content required to construct revision_id.
1768
The content is copied from self.source to self.target.
1770
:param revision_id: if None all content is copied, if NULL_REVISION no
1772
:param pb: optional progress bar to use for progress reports. If not
1773
provided a default one will be created.
1775
Returns the copied revision count and the failed revisions in a tuple:
1778
raise NotImplementedError(self.fetch)
1781
def missing_revision_ids(self, revision_id=None):
1782
"""Return the revision ids that source has that target does not.
1784
These are returned in topological order.
1786
:param revision_id: only return revision ids included by this
1789
# generic, possibly worst case, slow code path.
1790
target_ids = set(self.target.all_revision_ids())
1791
if revision_id is not None:
1792
source_ids = self.source.get_ancestry(revision_id)
1793
assert source_ids[0] is None
1796
source_ids = self.source.all_revision_ids()
1797
result_set = set(source_ids).difference(target_ids)
1798
# this may look like a no-op: its not. It preserves the ordering
1799
# other_ids had while only returning the members from other_ids
1800
# that we've decided we need.
1801
return [rev_id for rev_id in source_ids if rev_id in result_set]
1804
class InterSameDataRepository(InterRepository):
1805
"""Code for converting between repositories that represent the same data.
1807
Data format and model must match for this to work.
1810
_matching_repo_format = RepositoryFormat4()
1811
"""Repository format for testing with."""
1814
def is_compatible(source, target):
1815
if not isinstance(source, Repository):
1817
if not isinstance(target, Repository):
1819
if source._format.rich_root_data == target._format.rich_root_data:
1825
def copy_content(self, revision_id=None, basis=None):
1826
"""Make a complete copy of the content in self into destination.
1828
This is a destructive operation! Do not use it on existing
1831
:param revision_id: Only copy the content needed to construct
1832
revision_id and its parents.
1833
:param basis: Copy the needed data preferentially from basis.
1836
self.target.set_make_working_trees(self.source.make_working_trees())
1837
except NotImplementedError:
1839
# grab the basis available data
1840
if basis is not None:
1841
self.target.fetch(basis, revision_id=revision_id)
1842
# but don't bother fetching if we have the needed data now.
1843
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1844
self.target.has_revision(revision_id)):
1846
self.target.fetch(self.source, revision_id=revision_id)
1849
def fetch(self, revision_id=None, pb=None):
1850
"""See InterRepository.fetch()."""
1851
from bzrlib.fetch import GenericRepoFetcher
1852
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1853
self.source, self.source._format, self.target,
1854
self.target._format)
1855
f = GenericRepoFetcher(to_repository=self.target,
1856
from_repository=self.source,
1857
last_revision=revision_id,
1859
return f.count_copied, f.failed_revisions
1862
class InterWeaveRepo(InterSameDataRepository):
1863
"""Optimised code paths between Weave based repositories."""
1865
_matching_repo_format = RepositoryFormat7()
1866
"""Repository format for testing with."""
1869
def is_compatible(source, target):
1870
"""Be compatible with known Weave formats.
1872
We don't test for the stores being of specific types because that
1873
could lead to confusing results, and there is no need to be
1877
return (isinstance(source._format, (RepositoryFormat5,
1879
RepositoryFormat7)) and
1880
isinstance(target._format, (RepositoryFormat5,
1882
RepositoryFormat7)))
1883
except AttributeError:
1887
def copy_content(self, revision_id=None, basis=None):
1888
"""See InterRepository.copy_content()."""
1889
# weave specific optimised path:
1890
if basis is not None:
1891
# copy the basis in, then fetch remaining data.
1892
basis.copy_content_into(self.target, revision_id)
1893
# the basis copy_content_into could miss-set this.
1895
self.target.set_make_working_trees(self.source.make_working_trees())
1896
except NotImplementedError:
1898
self.target.fetch(self.source, revision_id=revision_id)
1901
self.target.set_make_working_trees(self.source.make_working_trees())
1902
except NotImplementedError:
1904
# FIXME do not peek!
1905
if self.source.control_files._transport.listable():
1906
pb = ui.ui_factory.nested_progress_bar()
1908
self.target.weave_store.copy_all_ids(
1909
self.source.weave_store,
1911
from_transaction=self.source.get_transaction(),
1912
to_transaction=self.target.get_transaction())
1913
pb.update('copying inventory', 0, 1)
1914
self.target.control_weaves.copy_multi(
1915
self.source.control_weaves, ['inventory'],
1916
from_transaction=self.source.get_transaction(),
1917
to_transaction=self.target.get_transaction())
1918
self.target._revision_store.text_store.copy_all_ids(
1919
self.source._revision_store.text_store,
1924
self.target.fetch(self.source, revision_id=revision_id)
1927
def fetch(self, revision_id=None, pb=None):
1928
"""See InterRepository.fetch()."""
1929
from bzrlib.fetch import GenericRepoFetcher
1930
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1931
self.source, self.source._format, self.target, self.target._format)
1932
f = GenericRepoFetcher(to_repository=self.target,
1933
from_repository=self.source,
1934
last_revision=revision_id,
1936
return f.count_copied, f.failed_revisions
1939
def missing_revision_ids(self, revision_id=None):
1940
"""See InterRepository.missing_revision_ids()."""
1941
# we want all revisions to satisfy revision_id in source.
1942
# but we don't want to stat every file here and there.
1943
# we want then, all revisions other needs to satisfy revision_id
1944
# checked, but not those that we have locally.
1945
# so the first thing is to get a subset of the revisions to
1946
# satisfy revision_id in source, and then eliminate those that
1947
# we do already have.
1948
# this is slow on high latency connection to self, but as as this
1949
# disk format scales terribly for push anyway due to rewriting
1950
# inventory.weave, this is considered acceptable.
1952
if revision_id is not None:
1953
source_ids = self.source.get_ancestry(revision_id)
1954
assert source_ids[0] is None
1957
source_ids = self.source._all_possible_ids()
1958
source_ids_set = set(source_ids)
1959
# source_ids is the worst possible case we may need to pull.
1960
# now we want to filter source_ids against what we actually
1961
# have in target, but don't try to check for existence where we know
1962
# we do not have a revision as that would be pointless.
1963
target_ids = set(self.target._all_possible_ids())
1964
possibly_present_revisions = target_ids.intersection(source_ids_set)
1965
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1966
required_revisions = source_ids_set.difference(actually_present_revisions)
1967
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1968
if revision_id is not None:
1969
# we used get_ancestry to determine source_ids then we are assured all
1970
# revisions referenced are present as they are installed in topological order.
1971
# and the tip revision was validated by get_ancestry.
1972
return required_topo_revisions
1974
# if we just grabbed the possibly available ids, then
1975
# we only have an estimate of whats available and need to validate
1976
# that against the revision records.
1977
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1980
class InterKnitRepo(InterSameDataRepository):
1981
"""Optimised code paths between Knit based repositories."""
1983
_matching_repo_format = RepositoryFormatKnit1()
1984
"""Repository format for testing with."""
1987
def is_compatible(source, target):
1988
"""Be compatible with known Knit formats.
1990
We don't test for the stores being of specific types because that
1991
could lead to confusing results, and there is no need to be
1995
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1996
isinstance(target._format, (RepositoryFormatKnit1)))
1997
except AttributeError:
2001
def fetch(self, revision_id=None, pb=None):
2002
"""See InterRepository.fetch()."""
2003
from bzrlib.fetch import KnitRepoFetcher
2004
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2005
self.source, self.source._format, self.target, self.target._format)
2006
f = KnitRepoFetcher(to_repository=self.target,
2007
from_repository=self.source,
2008
last_revision=revision_id,
2010
return f.count_copied, f.failed_revisions
2013
def missing_revision_ids(self, revision_id=None):
2014
"""See InterRepository.missing_revision_ids()."""
2015
if revision_id is not None:
2016
source_ids = self.source.get_ancestry(revision_id)
2017
assert source_ids[0] is None
2020
source_ids = self.source._all_possible_ids()
2021
source_ids_set = set(source_ids)
2022
# source_ids is the worst possible case we may need to pull.
2023
# now we want to filter source_ids against what we actually
2024
# have in target, but don't try to check for existence where we know
2025
# we do not have a revision as that would be pointless.
2026
target_ids = set(self.target._all_possible_ids())
2027
possibly_present_revisions = target_ids.intersection(source_ids_set)
2028
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2029
required_revisions = source_ids_set.difference(actually_present_revisions)
2030
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2031
if revision_id is not None:
2032
# we used get_ancestry to determine source_ids then we are assured all
2033
# revisions referenced are present as they are installed in topological order.
2034
# and the tip revision was validated by get_ancestry.
2035
return required_topo_revisions
2037
# if we just grabbed the possibly available ids, then
2038
# we only have an estimate of whats available and need to validate
2039
# that against the revision records.
2040
return self.source._eliminate_revisions_not_present(required_topo_revisions)
2043
class InterModel1and2(InterRepository):
2045
_matching_repo_format = None
2048
def is_compatible(source, target):
2049
if not isinstance(source, Repository):
2051
if not isinstance(target, Repository):
2053
if not source._format.rich_root_data and target._format.rich_root_data:
2059
def fetch(self, revision_id=None, pb=None):
2060
"""See InterRepository.fetch()."""
2061
from bzrlib.fetch import Model1toKnit2Fetcher
2062
f = Model1toKnit2Fetcher(to_repository=self.target,
2063
from_repository=self.source,
2064
last_revision=revision_id,
2066
return f.count_copied, f.failed_revisions
2069
def copy_content(self, revision_id=None, basis=None):
2070
"""Make a complete copy of the content in self into destination.
2072
This is a destructive operation! Do not use it on existing
2075
:param revision_id: Only copy the content needed to construct
2076
revision_id and its parents.
2077
:param basis: Copy the needed data preferentially from basis.
2080
self.target.set_make_working_trees(self.source.make_working_trees())
2081
except NotImplementedError:
2083
# grab the basis available data
2084
if basis is not None:
2085
self.target.fetch(basis, revision_id=revision_id)
2086
# but don't bother fetching if we have the needed data now.
2087
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
2088
self.target.has_revision(revision_id)):
2090
self.target.fetch(self.source, revision_id=revision_id)
2093
class InterKnit1and2(InterKnitRepo):
2095
_matching_repo_format = None
2098
def is_compatible(source, target):
2099
"""Be compatible with Knit1 source and Knit2 target"""
2101
return (isinstance(source._format, (RepositoryFormatKnit1)) and
2102
isinstance(target._format, (RepositoryFormatKnit2)))
2103
except AttributeError:
2107
def fetch(self, revision_id=None, pb=None):
2108
"""See InterRepository.fetch()."""
2109
from bzrlib.fetch import Knit1to2Fetcher
2110
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2111
self.source, self.source._format, self.target,
2112
self.target._format)
2113
f = Knit1to2Fetcher(to_repository=self.target,
2114
from_repository=self.source,
2115
last_revision=revision_id,
2117
return f.count_copied, f.failed_revisions
2120
InterRepository.register_optimiser(InterSameDataRepository)
2121
InterRepository.register_optimiser(InterWeaveRepo)
2122
InterRepository.register_optimiser(InterKnitRepo)
2123
InterRepository.register_optimiser(InterModel1and2)
2124
InterRepository.register_optimiser(InterKnit1and2)
2127
class RepositoryTestProviderAdapter(object):
2128
"""A tool to generate a suite testing multiple repository formats at once.
2130
This is done by copying the test once for each transport and injecting
2131
the transport_server, transport_readonly_server, and bzrdir_format and
2132
repository_format classes into each copy. Each copy is also given a new id()
2133
to make it easy to identify.
2136
def __init__(self, transport_server, transport_readonly_server, formats):
2137
self._transport_server = transport_server
2138
self._transport_readonly_server = transport_readonly_server
2139
self._formats = formats
2141
def adapt(self, test):
2142
result = unittest.TestSuite()
2143
for repository_format, bzrdir_format in self._formats:
2144
new_test = deepcopy(test)
2145
new_test.transport_server = self._transport_server
2146
new_test.transport_readonly_server = self._transport_readonly_server
2147
new_test.bzrdir_format = bzrdir_format
2148
new_test.repository_format = repository_format
2149
def make_new_test_id():
2150
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
2151
return lambda: new_id
2152
new_test.id = make_new_test_id()
2153
result.addTest(new_test)
2157
class InterRepositoryTestProviderAdapter(object):
2158
"""A tool to generate a suite testing multiple inter repository formats.
2160
This is done by copying the test once for each interrepo provider and injecting
2161
the transport_server, transport_readonly_server, repository_format and
2162
repository_to_format classes into each copy.
2163
Each copy is also given a new id() to make it easy to identify.
2166
def __init__(self, transport_server, transport_readonly_server, formats):
2167
self._transport_server = transport_server
2168
self._transport_readonly_server = transport_readonly_server
2169
self._formats = formats
2171
def adapt(self, test):
2172
result = unittest.TestSuite()
2173
for interrepo_class, repository_format, repository_format_to in self._formats:
2174
new_test = deepcopy(test)
2175
new_test.transport_server = self._transport_server
2176
new_test.transport_readonly_server = self._transport_readonly_server
2177
new_test.interrepo_class = interrepo_class
2178
new_test.repository_format = repository_format
2179
new_test.repository_format_to = repository_format_to
2180
def make_new_test_id():
2181
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
2182
return lambda: new_id
2183
new_test.id = make_new_test_id()
2184
result.addTest(new_test)
2188
def default_test_list():
2189
"""Generate the default list of interrepo permutations to test."""
2191
# test the default InterRepository between format 6 and the current
2193
# XXX: robertc 20060220 reinstate this when there are two supported
2194
# formats which do not have an optimal code path between them.
2195
#result.append((InterRepository,
2196
# RepositoryFormat6(),
2197
# RepositoryFormatKnit1()))
2198
for optimiser in InterRepository._optimisers:
2199
if optimiser._matching_repo_format is not None:
2200
result.append((optimiser,
2201
optimiser._matching_repo_format,
2202
optimiser._matching_repo_format
2204
# if there are specific combinations we want to use, we can add them
2206
result.append((InterModel1and2, RepositoryFormat5(),
2207
RepositoryFormatKnit2()))
2208
result.append((InterKnit1and2, RepositoryFormatKnit1(),
2209
RepositoryFormatKnit2()))
2213
class CopyConverter(object):
2214
"""A repository conversion tool which just performs a copy of the content.
2216
This is slow but quite reliable.
2219
def __init__(self, target_format):
2220
"""Create a CopyConverter.
2222
:param target_format: The format the resulting repository should be.
2224
self.target_format = target_format
2226
def convert(self, repo, pb):
2227
"""Perform the conversion of to_convert, giving feedback via pb.
2229
:param to_convert: The disk object to convert.
2230
:param pb: a progress bar to use for progress information.
2235
# this is only useful with metadir layouts - separated repo content.
2236
# trigger an assertion if not such
2237
repo._format.get_format_string()
2238
self.repo_dir = repo.bzrdir
2239
self.step('Moving repository to repository.backup')
2240
self.repo_dir.transport.move('repository', 'repository.backup')
2241
backup_transport = self.repo_dir.transport.clone('repository.backup')
2242
repo._format.check_conversion_target(self.target_format)
2243
self.source_repo = repo._format.open(self.repo_dir,
2245
_override_transport=backup_transport)
2246
self.step('Creating new repository')
2247
converted = self.target_format.initialize(self.repo_dir,
2248
self.source_repo.is_shared())
2249
converted.lock_write()
2251
self.step('Copying content into repository.')
2252
self.source_repo.copy_content_into(converted)
2255
self.step('Deleting old repository content.')
2256
self.repo_dir.transport.delete_tree('repository.backup')
2257
self.pb.note('repository converted')
2259
def step(self, message):
2260
"""Update the pb by a step."""
2262
self.pb.update(message, self.count, self.total)
2265
class CommitBuilder(object):
2266
"""Provides an interface to build up a commit.
2268
This allows describing a tree to be committed without needing to
2269
know the internals of the format of the repository.
2272
record_root_entry = False
2273
def __init__(self, repository, parents, config, timestamp=None,
2274
timezone=None, committer=None, revprops=None,
2276
"""Initiate a CommitBuilder.
2278
:param repository: Repository to commit to.
2279
:param parents: Revision ids of the parents of the new revision.
2280
:param config: Configuration to use.
2281
:param timestamp: Optional timestamp recorded for commit.
2282
:param timezone: Optional timezone for timestamp.
2283
:param committer: Optional committer to set for commit.
2284
:param revprops: Optional dictionary of revision properties.
2285
:param revision_id: Optional revision id.
2287
self._config = config
2289
if committer is None:
2290
self._committer = self._config.username()
2292
assert isinstance(committer, basestring), type(committer)
2293
self._committer = committer
2295
self.new_inventory = Inventory(None)
2296
self._new_revision_id = revision_id
2297
self.parents = parents
2298
self.repository = repository
2301
if revprops is not None:
2302
self._revprops.update(revprops)
2304
if timestamp is None:
2305
timestamp = time.time()
2306
# Restrict resolution to 1ms
2307
self._timestamp = round(timestamp, 3)
2309
if timezone is None:
2310
self._timezone = local_time_offset()
2312
self._timezone = int(timezone)
2314
self._generate_revision_if_needed()
2316
def commit(self, message):
2317
"""Make the actual commit.
2319
:return: The revision id of the recorded revision.
2321
rev = _mod_revision.Revision(
2322
timestamp=self._timestamp,
2323
timezone=self._timezone,
2324
committer=self._committer,
2326
inventory_sha1=self.inv_sha1,
2327
revision_id=self._new_revision_id,
2328
properties=self._revprops)
2329
rev.parent_ids = self.parents
2330
self.repository.add_revision(self._new_revision_id, rev,
2331
self.new_inventory, self._config)
2332
return self._new_revision_id
2334
def revision_tree(self):
2335
"""Return the tree that was just committed.
2337
After calling commit() this can be called to get a RevisionTree
2338
representing the newly committed tree. This is preferred to
2339
calling Repository.revision_tree() because that may require
2340
deserializing the inventory, while we already have a copy in
2343
return RevisionTree(self.repository, self.new_inventory,
2344
self._new_revision_id)
2346
def finish_inventory(self):
2347
"""Tell the builder that the inventory is finished."""
2348
if self.new_inventory.root is None:
2349
symbol_versioning.warn('Root entry should be supplied to'
2350
' record_entry_contents, as of bzr 0.10.',
2351
DeprecationWarning, stacklevel=2)
2352
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
2353
self.new_inventory.revision_id = self._new_revision_id
2354
self.inv_sha1 = self.repository.add_inventory(
2355
self._new_revision_id,
2360
def _gen_revision_id(self):
2361
"""Return new revision-id."""
2362
s = '%s-%s-' % (self._config.user_email(),
2363
compact_date(self._timestamp))
2364
s += hexlify(rand_bytes(8))
2367
def _generate_revision_if_needed(self):
2368
"""Create a revision id if None was supplied.
2370
If the repository can not support user-specified revision ids
2371
they should override this function and raise UnsupportedOperation
2372
if _new_revision_id is not None.
2374
:raises: UnsupportedOperation
2376
if self._new_revision_id is None:
2377
self._new_revision_id = self._gen_revision_id()
2379
def record_entry_contents(self, ie, parent_invs, path, tree):
2380
"""Record the content of ie from tree into the commit if needed.
2382
Side effect: sets ie.revision when unchanged
2384
:param ie: An inventory entry present in the commit.
2385
:param parent_invs: The inventories of the parent revisions of the
2387
:param path: The path the entry is at in the tree.
2388
:param tree: The tree which contains this entry and should be used to
2391
if self.new_inventory.root is None and ie.parent_id is not None:
2392
symbol_versioning.warn('Root entry should be supplied to'
2393
' record_entry_contents, as of bzr 0.10.',
2394
DeprecationWarning, stacklevel=2)
2395
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2397
self.new_inventory.add(ie)
2399
# ie.revision is always None if the InventoryEntry is considered
2400
# for committing. ie.snapshot will record the correct revision
2401
# which may be the sole parent if it is untouched.
2402
if ie.revision is not None:
2405
# In this revision format, root entries have no knit or weave
2406
if ie is self.new_inventory.root:
2407
# When serializing out to disk and back in
2408
# root.revision is always _new_revision_id
2409
ie.revision = self._new_revision_id
2411
previous_entries = ie.find_previous_heads(
2413
self.repository.weave_store,
2414
self.repository.get_transaction())
2415
# we are creating a new revision for ie in the history store
2417
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2419
def modified_directory(self, file_id, file_parents):
2420
"""Record the presence of a symbolic link.
2422
:param file_id: The file_id of the link to record.
2423
:param file_parents: The per-file parent revision ids.
2425
self._add_text_to_weave(file_id, [], file_parents.keys())
2427
def modified_file_text(self, file_id, file_parents,
2428
get_content_byte_lines, text_sha1=None,
2430
"""Record the text of file file_id
2432
:param file_id: The file_id of the file to record the text of.
2433
:param file_parents: The per-file parent revision ids.
2434
:param get_content_byte_lines: A callable which will return the byte
2436
:param text_sha1: Optional SHA1 of the file contents.
2437
:param text_size: Optional size of the file contents.
2439
# mutter('storing text of file {%s} in revision {%s} into %r',
2440
# file_id, self._new_revision_id, self.repository.weave_store)
2441
# special case to avoid diffing on renames or
2443
if (len(file_parents) == 1
2444
and text_sha1 == file_parents.values()[0].text_sha1
2445
and text_size == file_parents.values()[0].text_size):
2446
previous_ie = file_parents.values()[0]
2447
versionedfile = self.repository.weave_store.get_weave(file_id,
2448
self.repository.get_transaction())
2449
versionedfile.clone_text(self._new_revision_id,
2450
previous_ie.revision, file_parents.keys())
2451
return text_sha1, text_size
2453
new_lines = get_content_byte_lines()
2454
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2455
# should return the SHA1 and size
2456
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2457
return osutils.sha_strings(new_lines), \
2458
sum(map(len, new_lines))
2460
def modified_link(self, file_id, file_parents, link_target):
2461
"""Record the presence of a symbolic link.
2463
:param file_id: The file_id of the link to record.
2464
:param file_parents: The per-file parent revision ids.
2465
:param link_target: Target location of this link.
2467
self._add_text_to_weave(file_id, [], file_parents.keys())
2469
def _add_text_to_weave(self, file_id, new_lines, parents):
2470
versionedfile = self.repository.weave_store.get_weave_or_empty(
2471
file_id, self.repository.get_transaction())
2472
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2473
versionedfile.clear_cache()
2476
class _CommitBuilder(CommitBuilder):
2477
"""Temporary class so old CommitBuilders are detected properly
2479
Note: CommitBuilder works whether or not root entry is recorded.
2482
record_root_entry = True
2485
class RootCommitBuilder(CommitBuilder):
2486
"""This commitbuilder actually records the root id"""
2488
record_root_entry = True
2490
def record_entry_contents(self, ie, parent_invs, path, tree):
2491
"""Record the content of ie from tree into the commit if needed.
2493
Side effect: sets ie.revision when unchanged
2495
:param ie: An inventory entry present in the commit.
2496
:param parent_invs: The inventories of the parent revisions of the
2498
:param path: The path the entry is at in the tree.
2499
:param tree: The tree which contains this entry and should be used to
2502
assert self.new_inventory.root is not None or ie.parent_id is None
2503
self.new_inventory.add(ie)
2505
# ie.revision is always None if the InventoryEntry is considered
2506
# for committing. ie.snapshot will record the correct revision
2507
# which may be the sole parent if it is untouched.
2508
if ie.revision is not None:
2511
previous_entries = ie.find_previous_heads(
2513
self.repository.weave_store,
2514
self.repository.get_transaction())
2515
# we are creating a new revision for ie in the history store
2517
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2529
def _unescaper(match, _map=_unescape_map):
2530
return _map[match.group(1)]
2536
def _unescape_xml(data):
2537
"""Unescape predefined XML entities in a string of data."""
2539
if _unescape_re is None:
2540
_unescape_re = re.compile('\&([^;]*);')
2541
return _unescape_re.sub(_unescaper, data)