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(), """
38
revision as _mod_revision,
43
from bzrlib.bundle import serializer
44
from bzrlib.revisiontree import RevisionTree
45
from bzrlib.store.versioned import VersionedFileStore
46
from bzrlib.store.text import TextStore
47
from bzrlib.testament import Testament
51
from bzrlib.decorators import needs_read_lock, needs_write_lock
52
from bzrlib.inter import InterObject
53
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
54
from bzrlib.symbol_versioning import (
58
from bzrlib.trace import mutter, note, warning
61
# Old formats display a warning, but only once
62
_deprecation_warning_done = False
65
######################################################################
68
class Repository(object):
69
"""Repository holding history for one or more branches.
71
The repository holds and retrieves historical information including
72
revisions and file history. It's normally accessed only by the Branch,
73
which views a particular line of development through that history.
75
The Repository builds on top of Stores and a Transport, which respectively
76
describe the disk data format and the way of accessing the (possibly
80
_file_ids_altered_regex = lazy_regex.lazy_compile(
81
r'file_id="(?P<file_id>[^"]+)"'
82
r'.*revision="(?P<revision_id>[^"]+)"'
85
def abort_write_group(self):
86
"""Commit the contents accrued within the current write group.
88
:seealso: start_write_group.
90
if self._write_group is not self.get_transaction():
91
# has an unlock or relock occured ?
92
raise errors.BzrError('mismatched lock context and write group.')
93
self._abort_write_group()
94
self._write_group = None
96
def _abort_write_group(self):
97
"""Template method for per-repository write group cleanup.
99
This is called during abort before the write group is considered to be
100
finished and should cleanup any internal state accrued during the write
101
group. There is no requirement that data handed to the repository be
102
*not* made available - this is not a rollback - but neither should any
103
attempt be made to ensure that data added is fully commited. Abort is
104
invoked when an error has occured so futher disk or network operations
105
may not be possible or may error and if possible should not be
110
def add_inventory(self, revision_id, inv, parents):
111
"""Add the inventory inv to the repository as revision_id.
113
:param parents: The revision ids of the parents that revision_id
114
is known to have and are in the repository already.
116
returns the sha1 of the serialized inventory.
118
revision_id = osutils.safe_revision_id(revision_id)
119
_mod_revision.check_not_reserved_id(revision_id)
120
assert inv.revision_id is None or inv.revision_id == revision_id, \
121
"Mismatch between inventory revision" \
122
" id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
123
assert inv.root is not None
124
inv_text = self.serialise_inventory(inv)
125
inv_sha1 = osutils.sha_string(inv_text)
126
inv_vf = self.control_weaves.get_weave('inventory',
127
self.get_transaction())
128
self._inventory_add_lines(inv_vf, revision_id, parents,
129
osutils.split_lines(inv_text))
132
def _inventory_add_lines(self, inv_vf, revision_id, parents, lines):
134
for parent in parents:
136
final_parents.append(parent)
138
inv_vf.add_lines(revision_id, final_parents, lines)
141
def add_revision(self, revision_id, rev, inv=None, config=None):
142
"""Add rev to the revision store as revision_id.
144
:param revision_id: the revision id to use.
145
:param rev: The revision object.
146
:param inv: The inventory for the revision. if None, it will be looked
147
up in the inventory storer
148
:param config: If None no digital signature will be created.
149
If supplied its signature_needed method will be used
150
to determine if a signature should be made.
152
revision_id = osutils.safe_revision_id(revision_id)
153
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
155
_mod_revision.check_not_reserved_id(revision_id)
156
if config is not None and config.signature_needed():
158
inv = self.get_inventory(revision_id)
159
plaintext = Testament(rev, inv).as_short_text()
160
self.store_revision_signature(
161
gpg.GPGStrategy(config), plaintext, revision_id)
162
if not revision_id in self.get_inventory_weave():
164
raise errors.WeaveRevisionNotPresent(revision_id,
165
self.get_inventory_weave())
167
# yes, this is not suitable for adding with ghosts.
168
self.add_inventory(revision_id, inv, rev.parent_ids)
169
self._revision_store.add_revision(rev, self.get_transaction())
171
def _add_revision_text(self, revision_id, text):
172
revision = self._revision_store._serializer.read_revision_from_string(
174
self._revision_store._add_revision(revision, StringIO(text),
175
self.get_transaction())
178
def _all_possible_ids(self):
179
"""Return all the possible revisions that we could find."""
180
return self.get_inventory_weave().versions()
182
def all_revision_ids(self):
183
"""Returns a list of all the revision ids in the repository.
185
This is deprecated because code should generally work on the graph
186
reachable from a particular revision, and ignore any other revisions
187
that might be present. There is no direct replacement method.
189
return self._all_revision_ids()
192
def _all_revision_ids(self):
193
"""Returns a list of all the revision ids in the repository.
195
These are in as much topological order as the underlying store can
196
present: for weaves ghosts may lead to a lack of correctness until
197
the reweave updates the parents list.
199
if self._revision_store.text_store.listable():
200
return self._revision_store.all_revision_ids(self.get_transaction())
201
result = self._all_possible_ids()
202
# TODO: jam 20070210 Ensure that _all_possible_ids returns non-unicode
203
# ids. (It should, since _revision_store's API should change to
204
# return utf8 revision_ids)
205
return self._eliminate_revisions_not_present(result)
207
def break_lock(self):
208
"""Break a lock if one is present from another instance.
210
Uses the ui factory to ask for confirmation if the lock may be from
213
self.control_files.break_lock()
216
def _eliminate_revisions_not_present(self, revision_ids):
217
"""Check every revision id in revision_ids to see if we have it.
219
Returns a set of the present revisions.
222
for id in revision_ids:
223
if self.has_revision(id):
228
def create(a_bzrdir):
229
"""Construct the current default format repository in a_bzrdir."""
230
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
232
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
233
"""instantiate a Repository.
235
:param _format: The format of the repository on disk.
236
:param a_bzrdir: The BzrDir of the repository.
238
In the future we will have a single api for all stores for
239
getting file texts, inventories and revisions, then
240
this construct will accept instances of those things.
242
super(Repository, self).__init__()
243
self._format = _format
244
# the following are part of the public API for Repository:
245
self.bzrdir = a_bzrdir
246
self.control_files = control_files
247
self._revision_store = _revision_store
248
self.text_store = text_store
249
# backwards compatibility
250
self.weave_store = text_store
251
# not right yet - should be more semantically clear ?
253
self.control_store = control_store
254
self.control_weaves = control_store
255
# TODO: make sure to construct the right store classes, etc, depending
256
# on whether escaping is required.
257
self._warn_if_deprecated()
258
self._write_group = None
261
return '%s(%r)' % (self.__class__.__name__,
262
self.bzrdir.transport.base)
264
def is_in_write_group(self):
265
"""Return True if there is an open write group.
267
:seealso: start_write_group.
269
return self._write_group is not None
272
return self.control_files.is_locked()
274
def lock_write(self, token=None):
275
"""Lock this repository for writing.
277
:param token: if this is already locked, then lock_write will fail
278
unless the token matches the existing lock.
279
:returns: a token if this instance supports tokens, otherwise None.
280
:raises TokenLockingNotSupported: when a token is given but this
281
instance doesn't support using token locks.
282
:raises MismatchedToken: if the specified token doesn't match the token
283
of the existing lock.
285
A token should be passed in if you know that you have locked the object
286
some other way, and need to synchronise this object's state with that
289
XXX: this docstring is duplicated in many places, e.g. lockable_files.py
291
result = self.control_files.lock_write(token=token)
296
self.control_files.lock_read()
299
def get_physical_lock_status(self):
300
return self.control_files.get_physical_lock_status()
302
def leave_lock_in_place(self):
303
"""Tell this repository not to release the physical lock when this
306
If lock_write doesn't return a token, then this method is not supported.
308
self.control_files.leave_in_place()
310
def dont_leave_lock_in_place(self):
311
"""Tell this repository to release the physical lock when this
312
object is unlocked, even if it didn't originally acquire it.
314
If lock_write doesn't return a token, then this method is not supported.
316
self.control_files.dont_leave_in_place()
319
def gather_stats(self, revid=None, committers=None):
320
"""Gather statistics from a revision id.
322
:param revid: The revision id to gather statistics from, if None, then
323
no revision specific statistics are gathered.
324
:param committers: Optional parameter controlling whether to grab
325
a count of committers from the revision specific statistics.
326
:return: A dictionary of statistics. Currently this contains:
327
committers: The number of committers if requested.
328
firstrev: A tuple with timestamp, timezone for the penultimate left
329
most ancestor of revid, if revid is not the NULL_REVISION.
330
latestrev: A tuple with timestamp, timezone for revid, if revid is
331
not the NULL_REVISION.
332
revisions: The total revision count in the repository.
333
size: An estimate disk size of the repository in bytes.
336
if revid and committers:
337
result['committers'] = 0
338
if revid and revid != _mod_revision.NULL_REVISION:
340
all_committers = set()
341
revisions = self.get_ancestry(revid)
342
# pop the leading None
344
first_revision = None
346
# ignore the revisions in the middle - just grab first and last
347
revisions = revisions[0], revisions[-1]
348
for revision in self.get_revisions(revisions):
349
if not first_revision:
350
first_revision = revision
352
all_committers.add(revision.committer)
353
last_revision = revision
355
result['committers'] = len(all_committers)
356
result['firstrev'] = (first_revision.timestamp,
357
first_revision.timezone)
358
result['latestrev'] = (last_revision.timestamp,
359
last_revision.timezone)
361
# now gather global repository information
362
if self.bzrdir.root_transport.listable():
363
c, t = self._revision_store.total_size(self.get_transaction())
364
result['revisions'] = c
369
def missing_revision_ids(self, other, revision_id=None):
370
"""Return the revision ids that other has that this does not.
372
These are returned in topological order.
374
revision_id: only return revision ids included by revision_id.
376
revision_id = osutils.safe_revision_id(revision_id)
377
return InterRepository.get(other, self).missing_revision_ids(revision_id)
381
"""Open the repository rooted at base.
383
For instance, if the repository is at URL/.bzr/repository,
384
Repository.open(URL) -> a Repository instance.
386
control = bzrdir.BzrDir.open(base)
387
return control.open_repository()
389
def copy_content_into(self, destination, revision_id=None):
390
"""Make a complete copy of the content in self into destination.
392
This is a destructive operation! Do not use it on existing
395
revision_id = osutils.safe_revision_id(revision_id)
396
return InterRepository.get(self, destination).copy_content(revision_id)
398
def commit_write_group(self):
399
"""Commit the contents accrued within the current write group.
401
:seealso: start_write_group.
403
if self._write_group is not self.get_transaction():
404
# has an unlock or relock occured ?
405
raise errors.BzrError('mismatched lock context and write group.')
406
self._commit_write_group()
407
self._write_group = None
409
def _commit_write_group(self):
410
"""Template method for per-repository write group cleanup.
412
This is called before the write group is considered to be
413
finished and should ensure that all data handed to the repository
414
for writing during the write group is safely committed (to the
415
extent possible considering file system caching etc).
418
def fetch(self, source, revision_id=None, pb=None):
419
"""Fetch the content required to construct revision_id from source.
421
If revision_id is None all content is copied.
423
revision_id = osutils.safe_revision_id(revision_id)
424
inter = InterRepository.get(source, self)
426
return inter.fetch(revision_id=revision_id, pb=pb)
427
except NotImplementedError:
428
raise errors.IncompatibleRepositories(source, self)
430
def create_bundle(self, target, base, fileobj, format=None):
431
return serializer.write_bundle(self, target, base, fileobj, format)
433
def get_commit_builder(self, branch, parents, config, timestamp=None,
434
timezone=None, committer=None, revprops=None,
436
"""Obtain a CommitBuilder for this repository.
438
:param branch: Branch to commit to.
439
:param parents: Revision ids of the parents of the new revision.
440
:param config: Configuration to use.
441
:param timestamp: Optional timestamp recorded for commit.
442
:param timezone: Optional timezone for timestamp.
443
:param committer: Optional committer to set for commit.
444
:param revprops: Optional dictionary of revision properties.
445
:param revision_id: Optional revision id.
447
revision_id = osutils.safe_revision_id(revision_id)
448
result =_CommitBuilder(self, parents, config, timestamp, timezone,
449
committer, revprops, revision_id)
450
self.start_write_group()
454
if (self.control_files._lock_count == 1 and
455
self.control_files._lock_mode == 'w'):
456
if self._write_group is not None:
457
raise errors.BzrError(
458
'Must end write groups before releasing write locks.')
459
self.control_files.unlock()
462
def clone(self, a_bzrdir, revision_id=None):
463
"""Clone this repository into a_bzrdir using the current format.
465
Currently no check is made that the format of this repository and
466
the bzrdir format are compatible. FIXME RBC 20060201.
468
:return: The newly created destination repository.
470
# TODO: deprecate after 0.16; cloning this with all its settings is
471
# probably not very useful -- mbp 20070423
472
dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
473
self.copy_content_into(dest_repo, revision_id)
476
def start_write_group(self):
477
"""Start a write group in the repository.
479
Write groups are used by repositories which do not have a 1:1 mapping
480
between file ids and backend store to manage the insertion of data from
481
both fetch and commit operations.
483
A write lock is required around the start_write_group/commit_write_group
484
for the support of lock-requiring repository formats.
487
if not self.is_locked() or self.control_files._lock_mode != 'w':
488
raise errors.NotWriteLocked(self)
489
if self._write_group:
490
raise errors.BzrError('already in a write group')
491
self._start_write_group()
492
# so we can detect unlock/relock - the write group is now entered.
493
self._write_group = self.get_transaction()
495
def _start_write_group(self):
496
"""Template method for per-repository write group startup.
498
This is called before the write group is considered to be
503
def sprout(self, to_bzrdir, revision_id=None):
504
"""Create a descendent repository for new development.
506
Unlike clone, this does not copy the settings of the repository.
508
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
509
dest_repo.fetch(self, revision_id=revision_id)
512
def _create_sprouting_repo(self, a_bzrdir, shared):
513
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
514
# use target default format.
515
dest_repo = a_bzrdir.create_repository()
517
# Most control formats need the repository to be specifically
518
# created, but on some old all-in-one formats it's not needed
520
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
521
except errors.UninitializableFormat:
522
dest_repo = a_bzrdir.open_repository()
526
def has_revision(self, revision_id):
527
"""True if this repository has a copy of the revision."""
528
revision_id = osutils.safe_revision_id(revision_id)
529
return self._revision_store.has_revision_id(revision_id,
530
self.get_transaction())
533
def get_revision_reconcile(self, revision_id):
534
"""'reconcile' helper routine that allows access to a revision always.
536
This variant of get_revision does not cross check the weave graph
537
against the revision one as get_revision does: but it should only
538
be used by reconcile, or reconcile-alike commands that are correcting
539
or testing the revision graph.
541
if not revision_id or not isinstance(revision_id, basestring):
542
raise errors.InvalidRevisionId(revision_id=revision_id,
544
return self.get_revisions([revision_id])[0]
547
def get_revisions(self, revision_ids):
548
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
549
revs = self._revision_store.get_revisions(revision_ids,
550
self.get_transaction())
552
assert not isinstance(rev.revision_id, unicode)
553
for parent_id in rev.parent_ids:
554
assert not isinstance(parent_id, unicode)
558
def get_revision_xml(self, revision_id):
559
# TODO: jam 20070210 This shouldn't be necessary since get_revision
560
# would have already do it.
561
# TODO: jam 20070210 Just use _serializer.write_revision_to_string()
562
revision_id = osutils.safe_revision_id(revision_id)
563
rev = self.get_revision(revision_id)
565
# the current serializer..
566
self._revision_store._serializer.write_revision(rev, rev_tmp)
568
return rev_tmp.getvalue()
571
def get_revision(self, revision_id):
572
"""Return the Revision object for a named revision"""
573
# TODO: jam 20070210 get_revision_reconcile should do this for us
574
revision_id = osutils.safe_revision_id(revision_id)
575
r = self.get_revision_reconcile(revision_id)
576
# weave corruption can lead to absent revision markers that should be
578
# the following test is reasonably cheap (it needs a single weave read)
579
# and the weave is cached in read transactions. In write transactions
580
# it is not cached but typically we only read a small number of
581
# revisions. For knits when they are introduced we will probably want
582
# to ensure that caching write transactions are in use.
583
inv = self.get_inventory_weave()
584
self._check_revision_parents(r, inv)
588
def get_deltas_for_revisions(self, revisions):
589
"""Produce a generator of revision deltas.
591
Note that the input is a sequence of REVISIONS, not revision_ids.
592
Trees will be held in memory until the generator exits.
593
Each delta is relative to the revision's lefthand predecessor.
595
required_trees = set()
596
for revision in revisions:
597
required_trees.add(revision.revision_id)
598
required_trees.update(revision.parent_ids[:1])
599
trees = dict((t.get_revision_id(), t) for
600
t in self.revision_trees(required_trees))
601
for revision in revisions:
602
if not revision.parent_ids:
603
old_tree = self.revision_tree(None)
605
old_tree = trees[revision.parent_ids[0]]
606
yield trees[revision.revision_id].changes_from(old_tree)
609
def get_revision_delta(self, revision_id):
610
"""Return the delta for one revision.
612
The delta is relative to the left-hand predecessor of the
615
r = self.get_revision(revision_id)
616
return list(self.get_deltas_for_revisions([r]))[0]
618
def _check_revision_parents(self, revision, inventory):
619
"""Private to Repository and Fetch.
621
This checks the parentage of revision in an inventory weave for
622
consistency and is only applicable to inventory-weave-for-ancestry
623
using repository formats & fetchers.
625
weave_parents = inventory.get_parents(revision.revision_id)
626
weave_names = inventory.versions()
627
for parent_id in revision.parent_ids:
628
if parent_id in weave_names:
629
# this parent must not be a ghost.
630
if not parent_id in weave_parents:
632
raise errors.CorruptRepository(self)
635
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
636
revision_id = osutils.safe_revision_id(revision_id)
637
signature = gpg_strategy.sign(plaintext)
638
self._revision_store.add_revision_signature_text(revision_id,
640
self.get_transaction())
642
def fileids_altered_by_revision_ids(self, revision_ids):
643
"""Find the file ids and versions affected by revisions.
645
:param revisions: an iterable containing revision ids.
646
:return: a dictionary mapping altered file-ids to an iterable of
647
revision_ids. Each altered file-ids has the exact revision_ids that
648
altered it listed explicitly.
650
assert self._serializer.support_altered_by_hack, \
651
("fileids_altered_by_revision_ids only supported for branches "
652
"which store inventory as unnested xml, not on %r" % self)
653
selected_revision_ids = set(osutils.safe_revision_id(r)
654
for r in revision_ids)
655
w = self.get_inventory_weave()
658
# this code needs to read every new line in every inventory for the
659
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
660
# not present in one of those inventories is unnecessary but not
661
# harmful because we are filtering by the revision id marker in the
662
# inventory lines : we only select file ids altered in one of those
663
# revisions. We don't need to see all lines in the inventory because
664
# only those added in an inventory in rev X can contain a revision=X
666
unescape_revid_cache = {}
667
unescape_fileid_cache = {}
669
# jam 20061218 In a big fetch, this handles hundreds of thousands
670
# of lines, so it has had a lot of inlining and optimizing done.
671
# Sorry that it is a little bit messy.
672
# Move several functions to be local variables, since this is a long
674
search = self._file_ids_altered_regex.search
675
unescape = _unescape_xml
676
setdefault = result.setdefault
677
pb = ui.ui_factory.nested_progress_bar()
679
for line in w.iter_lines_added_or_present_in_versions(
680
selected_revision_ids, pb=pb):
684
# One call to match.group() returning multiple items is quite a
685
# bit faster than 2 calls to match.group() each returning 1
686
file_id, revision_id = match.group('file_id', 'revision_id')
688
# Inlining the cache lookups helps a lot when you make 170,000
689
# lines and 350k ids, versus 8.4 unique ids.
690
# Using a cache helps in 2 ways:
691
# 1) Avoids unnecessary decoding calls
692
# 2) Re-uses cached strings, which helps in future set and
694
# (2) is enough that removing encoding entirely along with
695
# the cache (so we are using plain strings) results in no
696
# performance improvement.
698
revision_id = unescape_revid_cache[revision_id]
700
unescaped = unescape(revision_id)
701
unescape_revid_cache[revision_id] = unescaped
702
revision_id = unescaped
704
if revision_id in selected_revision_ids:
706
file_id = unescape_fileid_cache[file_id]
708
unescaped = unescape(file_id)
709
unescape_fileid_cache[file_id] = unescaped
711
setdefault(file_id, set()).add(revision_id)
717
def get_inventory_weave(self):
718
return self.control_weaves.get_weave('inventory',
719
self.get_transaction())
722
def get_inventory(self, revision_id):
723
"""Get Inventory object by hash."""
724
# TODO: jam 20070210 Technically we don't need to sanitize, since all
725
# called functions must sanitize.
726
revision_id = osutils.safe_revision_id(revision_id)
727
return self.deserialise_inventory(
728
revision_id, self.get_inventory_xml(revision_id))
730
def deserialise_inventory(self, revision_id, xml):
731
"""Transform the xml into an inventory object.
733
:param revision_id: The expected revision id of the inventory.
734
:param xml: A serialised inventory.
736
revision_id = osutils.safe_revision_id(revision_id)
737
result = self._serializer.read_inventory_from_string(xml)
738
result.root.revision = revision_id
741
def serialise_inventory(self, inv):
742
return self._serializer.write_inventory_to_string(inv)
744
def get_serializer_format(self):
745
return self._serializer.format_num
748
def get_inventory_xml(self, revision_id):
749
"""Get inventory XML as a file object."""
750
revision_id = osutils.safe_revision_id(revision_id)
752
assert isinstance(revision_id, str), type(revision_id)
753
iw = self.get_inventory_weave()
754
return iw.get_text(revision_id)
756
raise errors.HistoryMissing(self, 'inventory', revision_id)
759
def get_inventory_sha1(self, revision_id):
760
"""Return the sha1 hash of the inventory entry
762
# TODO: jam 20070210 Shouldn't this be deprecated / removed?
763
revision_id = osutils.safe_revision_id(revision_id)
764
return self.get_revision(revision_id).inventory_sha1
767
def get_revision_graph(self, revision_id=None):
768
"""Return a dictionary containing the revision graph.
770
:param revision_id: The revision_id to get a graph from. If None, then
771
the entire revision graph is returned. This is a deprecated mode of
772
operation and will be removed in the future.
773
:return: a dictionary of revision_id->revision_parents_list.
775
# special case NULL_REVISION
776
if revision_id == _mod_revision.NULL_REVISION:
778
revision_id = osutils.safe_revision_id(revision_id)
779
a_weave = self.get_inventory_weave()
780
all_revisions = self._eliminate_revisions_not_present(
782
entire_graph = dict([(node, a_weave.get_parents(node)) for
783
node in all_revisions])
784
if revision_id is None:
786
elif revision_id not in entire_graph:
787
raise errors.NoSuchRevision(self, revision_id)
789
# add what can be reached from revision_id
791
pending = set([revision_id])
792
while len(pending) > 0:
794
result[node] = entire_graph[node]
795
for revision_id in result[node]:
796
if revision_id not in result:
797
pending.add(revision_id)
801
def get_revision_graph_with_ghosts(self, revision_ids=None):
802
"""Return a graph of the revisions with ghosts marked as applicable.
804
:param revision_ids: an iterable of revisions to graph or None for all.
805
:return: a Graph object with the graph reachable from revision_ids.
807
result = deprecated_graph.Graph()
809
pending = set(self.all_revision_ids())
812
pending = set(osutils.safe_revision_id(r) for r in revision_ids)
813
# special case NULL_REVISION
814
if _mod_revision.NULL_REVISION in pending:
815
pending.remove(_mod_revision.NULL_REVISION)
816
required = set(pending)
819
revision_id = pending.pop()
821
rev = self.get_revision(revision_id)
822
except errors.NoSuchRevision:
823
if revision_id in required:
826
result.add_ghost(revision_id)
828
for parent_id in rev.parent_ids:
829
# is this queued or done ?
830
if (parent_id not in pending and
831
parent_id not in done):
833
pending.add(parent_id)
834
result.add_node(revision_id, rev.parent_ids)
835
done.add(revision_id)
838
def _get_history_vf(self):
839
"""Get a versionedfile whose history graph reflects all revisions.
841
For weave repositories, this is the inventory weave.
843
return self.get_inventory_weave()
845
def iter_reverse_revision_history(self, revision_id):
846
"""Iterate backwards through revision ids in the lefthand history
848
:param revision_id: The revision id to start with. All its lefthand
849
ancestors will be traversed.
851
revision_id = osutils.safe_revision_id(revision_id)
852
if revision_id in (None, _mod_revision.NULL_REVISION):
854
next_id = revision_id
855
versionedfile = self._get_history_vf()
858
parents = versionedfile.get_parents(next_id)
859
if len(parents) == 0:
865
def get_revision_inventory(self, revision_id):
866
"""Return inventory of a past revision."""
867
# TODO: Unify this with get_inventory()
868
# bzr 0.0.6 and later imposes the constraint that the inventory_id
869
# must be the same as its revision, so this is trivial.
870
if revision_id is None:
871
# This does not make sense: if there is no revision,
872
# then it is the current tree inventory surely ?!
873
# and thus get_root_id() is something that looks at the last
874
# commit on the branch, and the get_root_id is an inventory check.
875
raise NotImplementedError
876
# return Inventory(self.get_root_id())
878
return self.get_inventory(revision_id)
882
"""Return True if this repository is flagged as a shared repository."""
883
raise NotImplementedError(self.is_shared)
886
def reconcile(self, other=None, thorough=False):
887
"""Reconcile this repository."""
888
from bzrlib.reconcile import RepoReconciler
889
reconciler = RepoReconciler(self, thorough=thorough)
890
reconciler.reconcile()
893
def _refresh_data(self):
894
"""Helper called from lock_* to ensure coherency with disk.
896
The default implementation does nothing; it is however possible
897
for repositories to maintain loaded indices across multiple locks
898
by checking inside their implementation of this method to see
899
whether their indices are still valid. This depends of course on
900
the disk format being validatable in this manner.
904
def revision_tree(self, revision_id):
905
"""Return Tree for a revision on this branch.
907
`revision_id` may be None for the empty tree revision.
909
# TODO: refactor this to use an existing revision object
910
# so we don't need to read it in twice.
911
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
912
return RevisionTree(self, Inventory(root_id=None),
913
_mod_revision.NULL_REVISION)
915
revision_id = osutils.safe_revision_id(revision_id)
916
inv = self.get_revision_inventory(revision_id)
917
return RevisionTree(self, inv, revision_id)
920
def revision_trees(self, revision_ids):
921
"""Return Tree for a revision on this branch.
923
`revision_id` may not be None or 'null:'"""
924
assert None not in revision_ids
925
assert _mod_revision.NULL_REVISION not in revision_ids
926
texts = self.get_inventory_weave().get_texts(revision_ids)
927
for text, revision_id in zip(texts, revision_ids):
928
inv = self.deserialise_inventory(revision_id, text)
929
yield RevisionTree(self, inv, revision_id)
932
def get_ancestry(self, revision_id, topo_sorted=True):
933
"""Return a list of revision-ids integrated by a revision.
935
The first element of the list is always None, indicating the origin
936
revision. This might change when we have history horizons, or
937
perhaps we should have a new API.
939
This is topologically sorted.
941
if _mod_revision.is_null(revision_id):
943
revision_id = osutils.safe_revision_id(revision_id)
944
if not self.has_revision(revision_id):
945
raise errors.NoSuchRevision(self, revision_id)
946
w = self.get_inventory_weave()
947
candidates = w.get_ancestry(revision_id, topo_sorted)
948
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
951
"""Compress the data within the repository.
953
This operation only makes sense for some repository types. For other
954
types it should be a no-op that just returns.
956
This stub method does not require a lock, but subclasses should use
957
@needs_write_lock as this is a long running call its reasonable to
958
implicitly lock for the user.
962
def print_file(self, file, revision_id):
963
"""Print `file` to stdout.
965
FIXME RBC 20060125 as John Meinel points out this is a bad api
966
- it writes to stdout, it assumes that that is valid etc. Fix
967
by creating a new more flexible convenience function.
969
revision_id = osutils.safe_revision_id(revision_id)
970
tree = self.revision_tree(revision_id)
971
# use inventory as it was in that revision
972
file_id = tree.inventory.path2id(file)
974
# TODO: jam 20060427 Write a test for this code path
975
# it had a bug in it, and was raising the wrong
977
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
978
tree.print_file(file_id)
980
def get_transaction(self):
981
return self.control_files.get_transaction()
983
def revision_parents(self, revision_id):
984
revision_id = osutils.safe_revision_id(revision_id)
985
return self.get_inventory_weave().parent_names(revision_id)
987
def get_parents(self, revision_ids):
988
"""See StackedParentsProvider.get_parents"""
990
for revision_id in revision_ids:
991
if revision_id == _mod_revision.NULL_REVISION:
995
parents = self.get_revision(revision_id).parent_ids
996
except errors.NoSuchRevision:
999
if len(parents) == 0:
1000
parents = [_mod_revision.NULL_REVISION]
1001
parents_list.append(parents)
1004
def _make_parents_provider(self):
1007
def get_graph(self, other_repository=None):
1008
"""Return the graph walker for this repository format"""
1009
parents_provider = self._make_parents_provider()
1010
if (other_repository is not None and
1011
other_repository.bzrdir.transport.base !=
1012
self.bzrdir.transport.base):
1013
parents_provider = graph._StackedParentsProvider(
1014
[parents_provider, other_repository._make_parents_provider()])
1015
return graph.Graph(parents_provider)
1018
def set_make_working_trees(self, new_value):
1019
"""Set the policy flag for making working trees when creating branches.
1021
This only applies to branches that use this repository.
1023
The default is 'True'.
1024
:param new_value: True to restore the default, False to disable making
1027
raise NotImplementedError(self.set_make_working_trees)
1029
def make_working_trees(self):
1030
"""Returns the policy for making working trees on new branches."""
1031
raise NotImplementedError(self.make_working_trees)
1034
def sign_revision(self, revision_id, gpg_strategy):
1035
revision_id = osutils.safe_revision_id(revision_id)
1036
plaintext = Testament.from_revision(self, revision_id).as_short_text()
1037
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1040
def has_signature_for_revision_id(self, revision_id):
1041
"""Query for a revision signature for revision_id in the repository."""
1042
revision_id = osutils.safe_revision_id(revision_id)
1043
return self._revision_store.has_signature(revision_id,
1044
self.get_transaction())
1047
def get_signature_text(self, revision_id):
1048
"""Return the text for a signature."""
1049
revision_id = osutils.safe_revision_id(revision_id)
1050
return self._revision_store.get_signature_text(revision_id,
1051
self.get_transaction())
1054
def check(self, revision_ids):
1055
"""Check consistency of all history of given revision_ids.
1057
Different repository implementations should override _check().
1059
:param revision_ids: A non-empty list of revision_ids whose ancestry
1060
will be checked. Typically the last revision_id of a branch.
1062
if not revision_ids:
1063
raise ValueError("revision_ids must be non-empty in %s.check"
1065
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1066
return self._check(revision_ids)
1068
def _check(self, revision_ids):
1069
result = check.Check(self)
1073
def _warn_if_deprecated(self):
1074
global _deprecation_warning_done
1075
if _deprecation_warning_done:
1077
_deprecation_warning_done = True
1078
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
1079
% (self._format, self.bzrdir.transport.base))
1081
def supports_rich_root(self):
1082
return self._format.rich_root_data
1084
def _check_ascii_revisionid(self, revision_id, method):
1085
"""Private helper for ascii-only repositories."""
1086
# weave repositories refuse to store revisionids that are non-ascii.
1087
if revision_id is not None:
1088
# weaves require ascii revision ids.
1089
if isinstance(revision_id, unicode):
1091
revision_id.encode('ascii')
1092
except UnicodeEncodeError:
1093
raise errors.NonAsciiRevisionId(method, self)
1096
revision_id.decode('ascii')
1097
except UnicodeDecodeError:
1098
raise errors.NonAsciiRevisionId(method, self)
1102
# remove these delegates a while after bzr 0.15
1103
def __make_delegated(name, from_module):
1104
def _deprecated_repository_forwarder():
1105
symbol_versioning.warn('%s moved to %s in bzr 0.15'
1106
% (name, from_module),
1109
m = __import__(from_module, globals(), locals(), [name])
1111
return getattr(m, name)
1112
except AttributeError:
1113
raise AttributeError('module %s has no name %s'
1115
globals()[name] = _deprecated_repository_forwarder
1118
'AllInOneRepository',
1119
'WeaveMetaDirRepository',
1120
'PreSplitOutRepositoryFormat',
1121
'RepositoryFormat4',
1122
'RepositoryFormat5',
1123
'RepositoryFormat6',
1124
'RepositoryFormat7',
1126
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
1130
'RepositoryFormatKnit',
1131
'RepositoryFormatKnit1',
1133
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
1136
def install_revision(repository, rev, revision_tree):
1137
"""Install all revision data into a repository."""
1138
present_parents = []
1140
for p_id in rev.parent_ids:
1141
if repository.has_revision(p_id):
1142
present_parents.append(p_id)
1143
parent_trees[p_id] = repository.revision_tree(p_id)
1145
parent_trees[p_id] = repository.revision_tree(None)
1147
inv = revision_tree.inventory
1148
entries = inv.iter_entries()
1149
# backwards compatibility hack: skip the root id.
1150
if not repository.supports_rich_root():
1151
path, root = entries.next()
1152
if root.revision != rev.revision_id:
1153
raise errors.IncompatibleRevision(repr(repository))
1154
# Add the texts that are not already present
1155
for path, ie in entries:
1156
w = repository.weave_store.get_weave_or_empty(ie.file_id,
1157
repository.get_transaction())
1158
if ie.revision not in w:
1160
# FIXME: TODO: The following loop *may* be overlapping/duplicate
1161
# with InventoryEntry.find_previous_heads(). if it is, then there
1162
# is a latent bug here where the parents may have ancestors of each
1164
for revision, tree in parent_trees.iteritems():
1165
if ie.file_id not in tree:
1167
parent_id = tree.inventory[ie.file_id].revision
1168
if parent_id in text_parents:
1170
text_parents.append(parent_id)
1172
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
1173
repository.get_transaction())
1174
lines = revision_tree.get_file(ie.file_id).readlines()
1175
vfile.add_lines(rev.revision_id, text_parents, lines)
1177
# install the inventory
1178
repository.add_inventory(rev.revision_id, inv, present_parents)
1179
except errors.RevisionAlreadyPresent:
1181
repository.add_revision(rev.revision_id, rev, inv)
1184
class MetaDirRepository(Repository):
1185
"""Repositories in the new meta-dir layout."""
1187
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
1188
super(MetaDirRepository, self).__init__(_format,
1194
dir_mode = self.control_files._dir_mode
1195
file_mode = self.control_files._file_mode
1198
def is_shared(self):
1199
"""Return True if this repository is flagged as a shared repository."""
1200
return self.control_files._transport.has('shared-storage')
1203
def set_make_working_trees(self, new_value):
1204
"""Set the policy flag for making working trees when creating branches.
1206
This only applies to branches that use this repository.
1208
The default is 'True'.
1209
:param new_value: True to restore the default, False to disable making
1214
self.control_files._transport.delete('no-working-trees')
1215
except errors.NoSuchFile:
1218
self.control_files.put_utf8('no-working-trees', '')
1220
def make_working_trees(self):
1221
"""Returns the policy for making working trees on new branches."""
1222
return not self.control_files._transport.has('no-working-trees')
1225
class RepositoryFormatRegistry(registry.Registry):
1226
"""Registry of RepositoryFormats.
1229
def get(self, format_string):
1230
r = registry.Registry.get(self, format_string)
1236
format_registry = RepositoryFormatRegistry()
1237
"""Registry of formats, indexed by their identifying format string.
1239
This can contain either format instances themselves, or classes/factories that
1240
can be called to obtain one.
1244
#####################################################################
1245
# Repository Formats
1247
class RepositoryFormat(object):
1248
"""A repository format.
1250
Formats provide three things:
1251
* An initialization routine to construct repository data on disk.
1252
* a format string which is used when the BzrDir supports versioned
1254
* an open routine which returns a Repository instance.
1256
Formats are placed in an dict by their format string for reference
1257
during opening. These should be subclasses of RepositoryFormat
1260
Once a format is deprecated, just deprecate the initialize and open
1261
methods on the format class. Do not deprecate the object, as the
1262
object will be created every system load.
1264
Common instance attributes:
1265
_matchingbzrdir - the bzrdir format that the repository format was
1266
originally written to work with. This can be used if manually
1267
constructing a bzrdir and repository, or more commonly for test suite
1272
return "<%s>" % self.__class__.__name__
1274
def __eq__(self, other):
1275
# format objects are generally stateless
1276
return isinstance(other, self.__class__)
1278
def __ne__(self, other):
1279
return not self == other
1282
def find_format(klass, a_bzrdir):
1283
"""Return the format for the repository object in a_bzrdir.
1285
This is used by bzr native formats that have a "format" file in
1286
the repository. Other methods may be used by different types of
1290
transport = a_bzrdir.get_repository_transport(None)
1291
format_string = transport.get("format").read()
1292
return format_registry.get(format_string)
1293
except errors.NoSuchFile:
1294
raise errors.NoRepositoryPresent(a_bzrdir)
1296
raise errors.UnknownFormatError(format=format_string)
1299
def register_format(klass, format):
1300
format_registry.register(format.get_format_string(), format)
1303
def unregister_format(klass, format):
1304
format_registry.remove(format.get_format_string())
1307
def get_default_format(klass):
1308
"""Return the current default format."""
1309
from bzrlib import bzrdir
1310
return bzrdir.format_registry.make_bzrdir('default').repository_format
1312
def _get_control_store(self, repo_transport, control_files):
1313
"""Return the control store for this repository."""
1314
raise NotImplementedError(self._get_control_store)
1316
def get_format_string(self):
1317
"""Return the ASCII format string that identifies this format.
1319
Note that in pre format ?? repositories the format string is
1320
not permitted nor written to disk.
1322
raise NotImplementedError(self.get_format_string)
1324
def get_format_description(self):
1325
"""Return the short description for this format."""
1326
raise NotImplementedError(self.get_format_description)
1328
def _get_revision_store(self, repo_transport, control_files):
1329
"""Return the revision store object for this a_bzrdir."""
1330
raise NotImplementedError(self._get_revision_store)
1332
def _get_text_rev_store(self,
1339
"""Common logic for getting a revision store for a repository.
1341
see self._get_revision_store for the subclass-overridable method to
1342
get the store for a repository.
1344
from bzrlib.store.revision.text import TextRevisionStore
1345
dir_mode = control_files._dir_mode
1346
file_mode = control_files._file_mode
1347
text_store = TextStore(transport.clone(name),
1349
compressed=compressed,
1351
file_mode=file_mode)
1352
_revision_store = TextRevisionStore(text_store, serializer)
1353
return _revision_store
1355
# TODO: this shouldn't be in the base class, it's specific to things that
1356
# use weaves or knits -- mbp 20070207
1357
def _get_versioned_file_store(self,
1362
versionedfile_class=None,
1363
versionedfile_kwargs={},
1365
if versionedfile_class is None:
1366
versionedfile_class = self._versionedfile_class
1367
weave_transport = control_files._transport.clone(name)
1368
dir_mode = control_files._dir_mode
1369
file_mode = control_files._file_mode
1370
return VersionedFileStore(weave_transport, prefixed=prefixed,
1372
file_mode=file_mode,
1373
versionedfile_class=versionedfile_class,
1374
versionedfile_kwargs=versionedfile_kwargs,
1377
def initialize(self, a_bzrdir, shared=False):
1378
"""Initialize a repository of this format in a_bzrdir.
1380
:param a_bzrdir: The bzrdir to put the new repository in it.
1381
:param shared: The repository should be initialized as a sharable one.
1382
:returns: The new repository object.
1384
This may raise UninitializableFormat if shared repository are not
1385
compatible the a_bzrdir.
1387
raise NotImplementedError(self.initialize)
1389
def is_supported(self):
1390
"""Is this format supported?
1392
Supported formats must be initializable and openable.
1393
Unsupported formats may not support initialization or committing or
1394
some other features depending on the reason for not being supported.
1398
def check_conversion_target(self, target_format):
1399
raise NotImplementedError(self.check_conversion_target)
1401
def open(self, a_bzrdir, _found=False):
1402
"""Return an instance of this format for the bzrdir a_bzrdir.
1404
_found is a private parameter, do not use it.
1406
raise NotImplementedError(self.open)
1409
class MetaDirRepositoryFormat(RepositoryFormat):
1410
"""Common base class for the new repositories using the metadir layout."""
1412
rich_root_data = False
1413
supports_tree_reference = False
1414
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1417
super(MetaDirRepositoryFormat, self).__init__()
1419
def _create_control_files(self, a_bzrdir):
1420
"""Create the required files and the initial control_files object."""
1421
# FIXME: RBC 20060125 don't peek under the covers
1422
# NB: no need to escape relative paths that are url safe.
1423
repository_transport = a_bzrdir.get_repository_transport(self)
1424
control_files = lockable_files.LockableFiles(repository_transport,
1425
'lock', lockdir.LockDir)
1426
control_files.create_lock()
1427
return control_files
1429
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1430
"""Upload the initial blank content."""
1431
control_files = self._create_control_files(a_bzrdir)
1432
control_files.lock_write()
1434
control_files._transport.mkdir_multi(dirs,
1435
mode=control_files._dir_mode)
1436
for file, content in files:
1437
control_files.put(file, content)
1438
for file, content in utf8_files:
1439
control_files.put_utf8(file, content)
1441
control_files.put_utf8('shared-storage', '')
1443
control_files.unlock()
1446
# formats which have no format string are not discoverable
1447
# and not independently creatable, so are not registered. They're
1448
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
1449
# needed, it's constructed directly by the BzrDir. Non-native formats where
1450
# the repository is not separately opened are similar.
1452
format_registry.register_lazy(
1453
'Bazaar-NG Repository format 7',
1454
'bzrlib.repofmt.weaverepo',
1457
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1458
# default control directory format
1460
format_registry.register_lazy(
1461
'Bazaar-NG Knit Repository Format 1',
1462
'bzrlib.repofmt.knitrepo',
1463
'RepositoryFormatKnit1',
1465
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1467
format_registry.register_lazy(
1468
'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
1469
'bzrlib.repofmt.knitrepo',
1470
'RepositoryFormatKnit3',
1474
class InterRepository(InterObject):
1475
"""This class represents operations taking place between two repositories.
1477
Its instances have methods like copy_content and fetch, and contain
1478
references to the source and target repositories these operations can be
1481
Often we will provide convenience methods on 'repository' which carry out
1482
operations with another repository - they will always forward to
1483
InterRepository.get(other).method_name(parameters).
1487
"""The available optimised InterRepository types."""
1489
def copy_content(self, revision_id=None):
1490
raise NotImplementedError(self.copy_content)
1492
def fetch(self, revision_id=None, pb=None):
1493
"""Fetch the content required to construct revision_id.
1495
The content is copied from self.source to self.target.
1497
:param revision_id: if None all content is copied, if NULL_REVISION no
1499
:param pb: optional progress bar to use for progress reports. If not
1500
provided a default one will be created.
1502
Returns the copied revision count and the failed revisions in a tuple:
1505
raise NotImplementedError(self.fetch)
1508
def missing_revision_ids(self, revision_id=None):
1509
"""Return the revision ids that source has that target does not.
1511
These are returned in topological order.
1513
:param revision_id: only return revision ids included by this
1516
# generic, possibly worst case, slow code path.
1517
target_ids = set(self.target.all_revision_ids())
1518
if revision_id is not None:
1519
# TODO: jam 20070210 InterRepository is internal enough that it
1520
# should assume revision_ids are already utf-8
1521
revision_id = osutils.safe_revision_id(revision_id)
1522
source_ids = self.source.get_ancestry(revision_id)
1523
assert source_ids[0] is None
1526
source_ids = self.source.all_revision_ids()
1527
result_set = set(source_ids).difference(target_ids)
1528
# this may look like a no-op: its not. It preserves the ordering
1529
# other_ids had while only returning the members from other_ids
1530
# that we've decided we need.
1531
return [rev_id for rev_id in source_ids if rev_id in result_set]
1534
class InterSameDataRepository(InterRepository):
1535
"""Code for converting between repositories that represent the same data.
1537
Data format and model must match for this to work.
1541
def _get_repo_format_to_test(self):
1542
"""Repository format for testing with."""
1543
return RepositoryFormat.get_default_format()
1546
def is_compatible(source, target):
1547
if source.supports_rich_root() != target.supports_rich_root():
1549
if source._serializer != target._serializer:
1554
def copy_content(self, revision_id=None):
1555
"""Make a complete copy of the content in self into destination.
1557
This copies both the repository's revision data, and configuration information
1558
such as the make_working_trees setting.
1560
This is a destructive operation! Do not use it on existing
1563
:param revision_id: Only copy the content needed to construct
1564
revision_id and its parents.
1567
self.target.set_make_working_trees(self.source.make_working_trees())
1568
except NotImplementedError:
1570
# TODO: jam 20070210 This is fairly internal, so we should probably
1571
# just assert that revision_id is not unicode.
1572
revision_id = osutils.safe_revision_id(revision_id)
1573
# but don't bother fetching if we have the needed data now.
1574
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1575
self.target.has_revision(revision_id)):
1577
self.target.fetch(self.source, revision_id=revision_id)
1580
def fetch(self, revision_id=None, pb=None):
1581
"""See InterRepository.fetch()."""
1582
from bzrlib.fetch import GenericRepoFetcher
1583
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1584
self.source, self.source._format, self.target,
1585
self.target._format)
1586
# TODO: jam 20070210 This should be an assert, not a translate
1587
revision_id = osutils.safe_revision_id(revision_id)
1588
f = GenericRepoFetcher(to_repository=self.target,
1589
from_repository=self.source,
1590
last_revision=revision_id,
1592
return f.count_copied, f.failed_revisions
1595
class InterWeaveRepo(InterSameDataRepository):
1596
"""Optimised code paths between Weave based repositories."""
1599
def _get_repo_format_to_test(self):
1600
from bzrlib.repofmt import weaverepo
1601
return weaverepo.RepositoryFormat7()
1604
def is_compatible(source, target):
1605
"""Be compatible with known Weave formats.
1607
We don't test for the stores being of specific types because that
1608
could lead to confusing results, and there is no need to be
1611
from bzrlib.repofmt.weaverepo import (
1617
return (isinstance(source._format, (RepositoryFormat5,
1619
RepositoryFormat7)) and
1620
isinstance(target._format, (RepositoryFormat5,
1622
RepositoryFormat7)))
1623
except AttributeError:
1627
def copy_content(self, revision_id=None):
1628
"""See InterRepository.copy_content()."""
1629
# weave specific optimised path:
1630
# TODO: jam 20070210 Internal, should be an assert, not translate
1631
revision_id = osutils.safe_revision_id(revision_id)
1633
self.target.set_make_working_trees(self.source.make_working_trees())
1634
except NotImplementedError:
1636
# FIXME do not peek!
1637
if self.source.control_files._transport.listable():
1638
pb = ui.ui_factory.nested_progress_bar()
1640
self.target.weave_store.copy_all_ids(
1641
self.source.weave_store,
1643
from_transaction=self.source.get_transaction(),
1644
to_transaction=self.target.get_transaction())
1645
pb.update('copying inventory', 0, 1)
1646
self.target.control_weaves.copy_multi(
1647
self.source.control_weaves, ['inventory'],
1648
from_transaction=self.source.get_transaction(),
1649
to_transaction=self.target.get_transaction())
1650
self.target._revision_store.text_store.copy_all_ids(
1651
self.source._revision_store.text_store,
1656
self.target.fetch(self.source, revision_id=revision_id)
1659
def fetch(self, revision_id=None, pb=None):
1660
"""See InterRepository.fetch()."""
1661
from bzrlib.fetch import GenericRepoFetcher
1662
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1663
self.source, self.source._format, self.target, self.target._format)
1664
# TODO: jam 20070210 This should be an assert, not a translate
1665
revision_id = osutils.safe_revision_id(revision_id)
1666
f = GenericRepoFetcher(to_repository=self.target,
1667
from_repository=self.source,
1668
last_revision=revision_id,
1670
return f.count_copied, f.failed_revisions
1673
def missing_revision_ids(self, revision_id=None):
1674
"""See InterRepository.missing_revision_ids()."""
1675
# we want all revisions to satisfy revision_id in source.
1676
# but we don't want to stat every file here and there.
1677
# we want then, all revisions other needs to satisfy revision_id
1678
# checked, but not those that we have locally.
1679
# so the first thing is to get a subset of the revisions to
1680
# satisfy revision_id in source, and then eliminate those that
1681
# we do already have.
1682
# this is slow on high latency connection to self, but as as this
1683
# disk format scales terribly for push anyway due to rewriting
1684
# inventory.weave, this is considered acceptable.
1686
if revision_id is not None:
1687
source_ids = self.source.get_ancestry(revision_id)
1688
assert source_ids[0] is None
1691
source_ids = self.source._all_possible_ids()
1692
source_ids_set = set(source_ids)
1693
# source_ids is the worst possible case we may need to pull.
1694
# now we want to filter source_ids against what we actually
1695
# have in target, but don't try to check for existence where we know
1696
# we do not have a revision as that would be pointless.
1697
target_ids = set(self.target._all_possible_ids())
1698
possibly_present_revisions = target_ids.intersection(source_ids_set)
1699
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1700
required_revisions = source_ids_set.difference(actually_present_revisions)
1701
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1702
if revision_id is not None:
1703
# we used get_ancestry to determine source_ids then we are assured all
1704
# revisions referenced are present as they are installed in topological order.
1705
# and the tip revision was validated by get_ancestry.
1706
return required_topo_revisions
1708
# if we just grabbed the possibly available ids, then
1709
# we only have an estimate of whats available and need to validate
1710
# that against the revision records.
1711
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1714
class InterKnitRepo(InterSameDataRepository):
1715
"""Optimised code paths between Knit based repositories."""
1718
def _get_repo_format_to_test(self):
1719
from bzrlib.repofmt import knitrepo
1720
return knitrepo.RepositoryFormatKnit1()
1723
def is_compatible(source, target):
1724
"""Be compatible with known Knit formats.
1726
We don't test for the stores being of specific types because that
1727
could lead to confusing results, and there is no need to be
1730
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
1732
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1733
isinstance(target._format, (RepositoryFormatKnit1)))
1734
except AttributeError:
1738
def fetch(self, revision_id=None, pb=None):
1739
"""See InterRepository.fetch()."""
1740
from bzrlib.fetch import KnitRepoFetcher
1741
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1742
self.source, self.source._format, self.target, self.target._format)
1743
# TODO: jam 20070210 This should be an assert, not a translate
1744
revision_id = osutils.safe_revision_id(revision_id)
1745
f = KnitRepoFetcher(to_repository=self.target,
1746
from_repository=self.source,
1747
last_revision=revision_id,
1749
return f.count_copied, f.failed_revisions
1752
def missing_revision_ids(self, revision_id=None):
1753
"""See InterRepository.missing_revision_ids()."""
1754
if revision_id is not None:
1755
source_ids = self.source.get_ancestry(revision_id)
1756
assert source_ids[0] is None
1759
source_ids = self.source._all_possible_ids()
1760
source_ids_set = set(source_ids)
1761
# source_ids is the worst possible case we may need to pull.
1762
# now we want to filter source_ids against what we actually
1763
# have in target, but don't try to check for existence where we know
1764
# we do not have a revision as that would be pointless.
1765
target_ids = set(self.target._all_possible_ids())
1766
possibly_present_revisions = target_ids.intersection(source_ids_set)
1767
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1768
required_revisions = source_ids_set.difference(actually_present_revisions)
1769
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1770
if revision_id is not None:
1771
# we used get_ancestry to determine source_ids then we are assured all
1772
# revisions referenced are present as they are installed in topological order.
1773
# and the tip revision was validated by get_ancestry.
1774
return required_topo_revisions
1776
# if we just grabbed the possibly available ids, then
1777
# we only have an estimate of whats available and need to validate
1778
# that against the revision records.
1779
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1782
class InterModel1and2(InterRepository):
1785
def _get_repo_format_to_test(self):
1789
def is_compatible(source, target):
1790
if not source.supports_rich_root() and target.supports_rich_root():
1796
def fetch(self, revision_id=None, pb=None):
1797
"""See InterRepository.fetch()."""
1798
from bzrlib.fetch import Model1toKnit2Fetcher
1799
# TODO: jam 20070210 This should be an assert, not a translate
1800
revision_id = osutils.safe_revision_id(revision_id)
1801
f = Model1toKnit2Fetcher(to_repository=self.target,
1802
from_repository=self.source,
1803
last_revision=revision_id,
1805
return f.count_copied, f.failed_revisions
1808
def copy_content(self, revision_id=None):
1809
"""Make a complete copy of the content in self into destination.
1811
This is a destructive operation! Do not use it on existing
1814
:param revision_id: Only copy the content needed to construct
1815
revision_id and its parents.
1818
self.target.set_make_working_trees(self.source.make_working_trees())
1819
except NotImplementedError:
1821
# TODO: jam 20070210 Internal, assert, don't translate
1822
revision_id = osutils.safe_revision_id(revision_id)
1823
# but don't bother fetching if we have the needed data now.
1824
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1825
self.target.has_revision(revision_id)):
1827
self.target.fetch(self.source, revision_id=revision_id)
1830
class InterKnit1and2(InterKnitRepo):
1833
def _get_repo_format_to_test(self):
1837
def is_compatible(source, target):
1838
"""Be compatible with Knit1 source and Knit3 target"""
1839
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
1841
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1842
RepositoryFormatKnit3
1843
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1844
isinstance(target._format, (RepositoryFormatKnit3)))
1845
except AttributeError:
1849
def fetch(self, revision_id=None, pb=None):
1850
"""See InterRepository.fetch()."""
1851
from bzrlib.fetch import Knit1to2Fetcher
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
# TODO: jam 20070210 This should be an assert, not a translate
1856
revision_id = osutils.safe_revision_id(revision_id)
1857
f = Knit1to2Fetcher(to_repository=self.target,
1858
from_repository=self.source,
1859
last_revision=revision_id,
1861
return f.count_copied, f.failed_revisions
1864
class InterRemoteRepository(InterRepository):
1865
"""Code for converting between RemoteRepository objects.
1867
This just gets an non-remote repository from the RemoteRepository, and calls
1868
InterRepository.get again.
1871
def __init__(self, source, target):
1872
if isinstance(source, remote.RemoteRepository):
1873
source._ensure_real()
1874
real_source = source._real_repository
1876
real_source = source
1877
if isinstance(target, remote.RemoteRepository):
1878
target._ensure_real()
1879
real_target = target._real_repository
1881
real_target = target
1882
self.real_inter = InterRepository.get(real_source, real_target)
1885
def is_compatible(source, target):
1886
if isinstance(source, remote.RemoteRepository):
1888
if isinstance(target, remote.RemoteRepository):
1892
def copy_content(self, revision_id=None):
1893
self.real_inter.copy_content(revision_id=revision_id)
1895
def fetch(self, revision_id=None, pb=None):
1896
self.real_inter.fetch(revision_id=revision_id, pb=pb)
1899
def _get_repo_format_to_test(self):
1903
InterRepository.register_optimiser(InterSameDataRepository)
1904
InterRepository.register_optimiser(InterWeaveRepo)
1905
InterRepository.register_optimiser(InterKnitRepo)
1906
InterRepository.register_optimiser(InterModel1and2)
1907
InterRepository.register_optimiser(InterKnit1and2)
1908
InterRepository.register_optimiser(InterRemoteRepository)
1911
class CopyConverter(object):
1912
"""A repository conversion tool which just performs a copy of the content.
1914
This is slow but quite reliable.
1917
def __init__(self, target_format):
1918
"""Create a CopyConverter.
1920
:param target_format: The format the resulting repository should be.
1922
self.target_format = target_format
1924
def convert(self, repo, pb):
1925
"""Perform the conversion of to_convert, giving feedback via pb.
1927
:param to_convert: The disk object to convert.
1928
:param pb: a progress bar to use for progress information.
1933
# this is only useful with metadir layouts - separated repo content.
1934
# trigger an assertion if not such
1935
repo._format.get_format_string()
1936
self.repo_dir = repo.bzrdir
1937
self.step('Moving repository to repository.backup')
1938
self.repo_dir.transport.move('repository', 'repository.backup')
1939
backup_transport = self.repo_dir.transport.clone('repository.backup')
1940
repo._format.check_conversion_target(self.target_format)
1941
self.source_repo = repo._format.open(self.repo_dir,
1943
_override_transport=backup_transport)
1944
self.step('Creating new repository')
1945
converted = self.target_format.initialize(self.repo_dir,
1946
self.source_repo.is_shared())
1947
converted.lock_write()
1949
self.step('Copying content into repository.')
1950
self.source_repo.copy_content_into(converted)
1953
self.step('Deleting old repository content.')
1954
self.repo_dir.transport.delete_tree('repository.backup')
1955
self.pb.note('repository converted')
1957
def step(self, message):
1958
"""Update the pb by a step."""
1960
self.pb.update(message, self.count, self.total)
1963
class CommitBuilder(object):
1964
"""Provides an interface to build up a commit.
1966
This allows describing a tree to be committed without needing to
1967
know the internals of the format of the repository.
1970
record_root_entry = False
1971
def __init__(self, repository, parents, config, timestamp=None,
1972
timezone=None, committer=None, revprops=None,
1974
"""Initiate a CommitBuilder.
1976
:param repository: Repository to commit to.
1977
:param parents: Revision ids of the parents of the new revision.
1978
:param config: Configuration to use.
1979
:param timestamp: Optional timestamp recorded for commit.
1980
:param timezone: Optional timezone for timestamp.
1981
:param committer: Optional committer to set for commit.
1982
:param revprops: Optional dictionary of revision properties.
1983
:param revision_id: Optional revision id.
1985
self._config = config
1987
if committer is None:
1988
self._committer = self._config.username()
1990
assert isinstance(committer, basestring), type(committer)
1991
self._committer = committer
1993
self.new_inventory = Inventory(None)
1994
self._new_revision_id = osutils.safe_revision_id(revision_id)
1995
self.parents = parents
1996
self.repository = repository
1999
if revprops is not None:
2000
self._revprops.update(revprops)
2002
if timestamp is None:
2003
timestamp = time.time()
2004
# Restrict resolution to 1ms
2005
self._timestamp = round(timestamp, 3)
2007
if timezone is None:
2008
self._timezone = osutils.local_time_offset()
2010
self._timezone = int(timezone)
2012
self._generate_revision_if_needed()
2014
def commit(self, message):
2015
"""Make the actual commit.
2017
:return: The revision id of the recorded revision.
2019
rev = _mod_revision.Revision(
2020
timestamp=self._timestamp,
2021
timezone=self._timezone,
2022
committer=self._committer,
2024
inventory_sha1=self.inv_sha1,
2025
revision_id=self._new_revision_id,
2026
properties=self._revprops)
2027
rev.parent_ids = self.parents
2028
self.repository.add_revision(self._new_revision_id, rev,
2029
self.new_inventory, self._config)
2030
self.repository.commit_write_group()
2031
return self._new_revision_id
2033
def revision_tree(self):
2034
"""Return the tree that was just committed.
2036
After calling commit() this can be called to get a RevisionTree
2037
representing the newly committed tree. This is preferred to
2038
calling Repository.revision_tree() because that may require
2039
deserializing the inventory, while we already have a copy in
2042
return RevisionTree(self.repository, self.new_inventory,
2043
self._new_revision_id)
2045
def finish_inventory(self):
2046
"""Tell the builder that the inventory is finished."""
2047
if self.new_inventory.root is None:
2048
symbol_versioning.warn('Root entry should be supplied to'
2049
' record_entry_contents, as of bzr 0.10.',
2050
DeprecationWarning, stacklevel=2)
2051
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
2052
self.new_inventory.revision_id = self._new_revision_id
2053
self.inv_sha1 = self.repository.add_inventory(
2054
self._new_revision_id,
2059
def _gen_revision_id(self):
2060
"""Return new revision-id."""
2061
return generate_ids.gen_revision_id(self._config.username(),
2064
def _generate_revision_if_needed(self):
2065
"""Create a revision id if None was supplied.
2067
If the repository can not support user-specified revision ids
2068
they should override this function and raise CannotSetRevisionId
2069
if _new_revision_id is not None.
2071
:raises: CannotSetRevisionId
2073
if self._new_revision_id is None:
2074
self._new_revision_id = self._gen_revision_id()
2076
def record_entry_contents(self, ie, parent_invs, path, tree):
2077
"""Record the content of ie from tree into the commit if needed.
2079
Side effect: sets ie.revision when unchanged
2081
:param ie: An inventory entry present in the commit.
2082
:param parent_invs: The inventories of the parent revisions of the
2084
:param path: The path the entry is at in the tree.
2085
:param tree: The tree which contains this entry and should be used to
2088
if self.new_inventory.root is None and ie.parent_id is not None:
2089
symbol_versioning.warn('Root entry should be supplied to'
2090
' record_entry_contents, as of bzr 0.10.',
2091
DeprecationWarning, stacklevel=2)
2092
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2094
self.new_inventory.add(ie)
2096
# ie.revision is always None if the InventoryEntry is considered
2097
# for committing. ie.snapshot will record the correct revision
2098
# which may be the sole parent if it is untouched.
2099
if ie.revision is not None:
2102
# In this revision format, root entries have no knit or weave
2103
if ie is self.new_inventory.root:
2104
# When serializing out to disk and back in
2105
# root.revision is always _new_revision_id
2106
ie.revision = self._new_revision_id
2108
previous_entries = ie.find_previous_heads(
2110
self.repository.weave_store,
2111
self.repository.get_transaction())
2112
# we are creating a new revision for ie in the history store
2114
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2116
def modified_directory(self, file_id, file_parents):
2117
"""Record the presence of a symbolic link.
2119
:param file_id: The file_id of the link to record.
2120
:param file_parents: The per-file parent revision ids.
2122
self._add_text_to_weave(file_id, [], file_parents.keys())
2124
def modified_reference(self, file_id, file_parents):
2125
"""Record the modification of a reference.
2127
:param file_id: The file_id of the link to record.
2128
:param file_parents: The per-file parent revision ids.
2130
self._add_text_to_weave(file_id, [], file_parents.keys())
2132
def modified_file_text(self, file_id, file_parents,
2133
get_content_byte_lines, text_sha1=None,
2135
"""Record the text of file file_id
2137
:param file_id: The file_id of the file to record the text of.
2138
:param file_parents: The per-file parent revision ids.
2139
:param get_content_byte_lines: A callable which will return the byte
2141
:param text_sha1: Optional SHA1 of the file contents.
2142
:param text_size: Optional size of the file contents.
2144
# mutter('storing text of file {%s} in revision {%s} into %r',
2145
# file_id, self._new_revision_id, self.repository.weave_store)
2146
# special case to avoid diffing on renames or
2148
if (len(file_parents) == 1
2149
and text_sha1 == file_parents.values()[0].text_sha1
2150
and text_size == file_parents.values()[0].text_size):
2151
previous_ie = file_parents.values()[0]
2152
versionedfile = self.repository.weave_store.get_weave(file_id,
2153
self.repository.get_transaction())
2154
versionedfile.clone_text(self._new_revision_id,
2155
previous_ie.revision, file_parents.keys())
2156
return text_sha1, text_size
2158
new_lines = get_content_byte_lines()
2159
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2160
# should return the SHA1 and size
2161
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2162
return osutils.sha_strings(new_lines), \
2163
sum(map(len, new_lines))
2165
def modified_link(self, file_id, file_parents, link_target):
2166
"""Record the presence of a symbolic link.
2168
:param file_id: The file_id of the link to record.
2169
:param file_parents: The per-file parent revision ids.
2170
:param link_target: Target location of this link.
2172
self._add_text_to_weave(file_id, [], file_parents.keys())
2174
def _add_text_to_weave(self, file_id, new_lines, parents):
2175
versionedfile = self.repository.weave_store.get_weave_or_empty(
2176
file_id, self.repository.get_transaction())
2177
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2178
versionedfile.clear_cache()
2181
class _CommitBuilder(CommitBuilder):
2182
"""Temporary class so old CommitBuilders are detected properly
2184
Note: CommitBuilder works whether or not root entry is recorded.
2187
record_root_entry = True
2190
class RootCommitBuilder(CommitBuilder):
2191
"""This commitbuilder actually records the root id"""
2193
record_root_entry = True
2195
def record_entry_contents(self, ie, parent_invs, path, tree):
2196
"""Record the content of ie from tree into the commit if needed.
2198
Side effect: sets ie.revision when unchanged
2200
:param ie: An inventory entry present in the commit.
2201
:param parent_invs: The inventories of the parent revisions of the
2203
:param path: The path the entry is at in the tree.
2204
:param tree: The tree which contains this entry and should be used to
2207
assert self.new_inventory.root is not None or ie.parent_id is None
2208
self.new_inventory.add(ie)
2210
# ie.revision is always None if the InventoryEntry is considered
2211
# for committing. ie.snapshot will record the correct revision
2212
# which may be the sole parent if it is untouched.
2213
if ie.revision is not None:
2216
previous_entries = ie.find_previous_heads(
2218
self.repository.weave_store,
2219
self.repository.get_transaction())
2220
# we are creating a new revision for ie in the history store
2222
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2234
def _unescaper(match, _map=_unescape_map):
2235
code = match.group(1)
2239
if not code.startswith('#'):
2241
return unichr(int(code[1:])).encode('utf8')
2247
def _unescape_xml(data):
2248
"""Unescape predefined XML entities in a string of data."""
2250
if _unescape_re is None:
2251
_unescape_re = re.compile('\&([^;]*);')
2252
return _unescape_re.sub(_unescaper, data)