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 binascii import hexlify
18
from copy import deepcopy
19
from cStringIO import StringIO
22
from unittest import TestSuite
24
from bzrlib import bzrdir, check, delta, gpg, errors, xml5, ui, transactions, osutils
25
from bzrlib.decorators import needs_read_lock, needs_write_lock
26
from bzrlib.errors import InvalidRevisionId
27
from bzrlib.graph import Graph
28
from bzrlib.inter import InterObject
29
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
30
from bzrlib.knit import KnitVersionedFile, KnitPlainFactory
31
from bzrlib.lockable_files import LockableFiles, TransportLock
32
from bzrlib.lockdir import LockDir
33
from bzrlib.osutils import (safe_unicode, rand_bytes, compact_date,
35
from bzrlib.revision import NULL_REVISION, Revision
36
from bzrlib.revisiontree import RevisionTree
37
from bzrlib.store.versioned import VersionedFileStore, WeaveStore
38
from bzrlib.store.text import TextStore
39
from bzrlib import symbol_versioning
40
from bzrlib.symbol_versioning import (deprecated_method,
43
from bzrlib.testament import Testament
44
from bzrlib.trace import mutter, note, warning
45
from bzrlib.tsort import topo_sort
46
from bzrlib.weave import WeaveFile
49
# Old formats display a warning, but only once
50
_deprecation_warning_done = False
53
class Repository(object):
54
"""Repository holding history for one or more branches.
56
The repository holds and retrieves historical information including
57
revisions and file history. It's normally accessed only by the Branch,
58
which views a particular line of development through that history.
60
The Repository builds on top of Stores and a Transport, which respectively
61
describe the disk data format and the way of accessing the (possibly
66
def add_inventory(self, revid, inv, parents):
67
"""Add the inventory inv to the repository as revid.
69
:param parents: The revision ids of the parents that revid
70
is known to have and are in the repository already.
72
returns the sha1 of the serialized inventory.
74
assert inv.revision_id is None or inv.revision_id == revid, \
75
"Mismatch between inventory revision" \
76
" id and insertion revid (%r, %r)" % (inv.revision_id, revid)
77
assert inv.root is not None
78
inv_text = xml5.serializer_v5.write_inventory_to_string(inv)
79
inv_sha1 = osutils.sha_string(inv_text)
80
inv_vf = self.control_weaves.get_weave('inventory',
81
self.get_transaction())
82
self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
85
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
87
for parent in parents:
89
final_parents.append(parent)
91
inv_vf.add_lines(revid, final_parents, lines)
94
def add_revision(self, rev_id, rev, inv=None, config=None):
95
"""Add rev to the revision store as rev_id.
97
:param rev_id: the revision id to use.
98
:param rev: The revision object.
99
:param inv: The inventory for the revision. if None, it will be looked
100
up in the inventory storer
101
:param config: If None no digital signature will be created.
102
If supplied its signature_needed method will be used
103
to determine if a signature should be made.
105
if config is not None and config.signature_needed():
107
inv = self.get_inventory(rev_id)
108
plaintext = Testament(rev, inv).as_short_text()
109
self.store_revision_signature(
110
gpg.GPGStrategy(config), plaintext, rev_id)
111
if not rev_id in self.get_inventory_weave():
113
raise errors.WeaveRevisionNotPresent(rev_id,
114
self.get_inventory_weave())
116
# yes, this is not suitable for adding with ghosts.
117
self.add_inventory(rev_id, inv, rev.parent_ids)
118
self._revision_store.add_revision(rev, self.get_transaction())
121
def _all_possible_ids(self):
122
"""Return all the possible revisions that we could find."""
123
return self.get_inventory_weave().versions()
125
def all_revision_ids(self):
126
"""Returns a list of all the revision ids in the repository.
128
This is deprecated because code should generally work on the graph
129
reachable from a particular revision, and ignore any other revisions
130
that might be present. There is no direct replacement method.
132
return self._all_revision_ids()
135
def _all_revision_ids(self):
136
"""Returns a list of all the revision ids in the repository.
138
These are in as much topological order as the underlying store can
139
present: for weaves ghosts may lead to a lack of correctness until
140
the reweave updates the parents list.
142
if self._revision_store.text_store.listable():
143
return self._revision_store.all_revision_ids(self.get_transaction())
144
result = self._all_possible_ids()
145
return self._eliminate_revisions_not_present(result)
147
def break_lock(self):
148
"""Break a lock if one is present from another instance.
150
Uses the ui factory to ask for confirmation if the lock may be from
153
self.control_files.break_lock()
156
def _eliminate_revisions_not_present(self, revision_ids):
157
"""Check every revision id in revision_ids to see if we have it.
159
Returns a set of the present revisions.
162
for id in revision_ids:
163
if self.has_revision(id):
168
def create(a_bzrdir):
169
"""Construct the current default format repository in a_bzrdir."""
170
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
172
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
173
"""instantiate a Repository.
175
:param _format: The format of the repository on disk.
176
:param a_bzrdir: The BzrDir of the repository.
178
In the future we will have a single api for all stores for
179
getting file texts, inventories and revisions, then
180
this construct will accept instances of those things.
182
super(Repository, self).__init__()
183
self._format = _format
184
# the following are part of the public API for Repository:
185
self.bzrdir = a_bzrdir
186
self.control_files = control_files
187
self._revision_store = _revision_store
188
self.text_store = text_store
189
# backwards compatibility
190
self.weave_store = text_store
191
# not right yet - should be more semantically clear ?
193
self.control_store = control_store
194
self.control_weaves = control_store
195
# TODO: make sure to construct the right store classes, etc, depending
196
# on whether escaping is required.
197
self._warn_if_deprecated()
200
return '%s(%r)' % (self.__class__.__name__,
201
self.bzrdir.transport.base)
204
return self.control_files.is_locked()
206
def lock_write(self):
207
self.control_files.lock_write()
210
self.control_files.lock_read()
212
def get_physical_lock_status(self):
213
return self.control_files.get_physical_lock_status()
216
def missing_revision_ids(self, other, revision_id=None):
217
"""Return the revision ids that other has that this does not.
219
These are returned in topological order.
221
revision_id: only return revision ids included by revision_id.
223
return InterRepository.get(other, self).missing_revision_ids(revision_id)
227
"""Open the repository rooted at base.
229
For instance, if the repository is at URL/.bzr/repository,
230
Repository.open(URL) -> a Repository instance.
232
control = bzrdir.BzrDir.open(base)
233
return control.open_repository()
235
def copy_content_into(self, destination, revision_id=None, basis=None):
236
"""Make a complete copy of the content in self into destination.
238
This is a destructive operation! Do not use it on existing
241
return InterRepository.get(self, destination).copy_content(revision_id, basis)
243
def fetch(self, source, revision_id=None, pb=None):
244
"""Fetch the content required to construct revision_id from source.
246
If revision_id is None all content is copied.
248
return InterRepository.get(source, self).fetch(revision_id=revision_id,
251
def get_commit_builder(self, branch, parents, config, timestamp=None,
252
timezone=None, committer=None, revprops=None,
254
"""Obtain a CommitBuilder for this repository.
256
:param branch: Branch to commit to.
257
:param parents: Revision ids of the parents of the new revision.
258
:param config: Configuration to use.
259
:param timestamp: Optional timestamp recorded for commit.
260
:param timezone: Optional timezone for timestamp.
261
:param committer: Optional committer to set for commit.
262
:param revprops: Optional dictionary of revision properties.
263
:param revision_id: Optional revision id.
265
return _CommitBuilder(self, parents, config, timestamp, timezone,
266
committer, revprops, revision_id)
269
self.control_files.unlock()
272
def clone(self, a_bzrdir, revision_id=None, basis=None):
273
"""Clone this repository into a_bzrdir using the current format.
275
Currently no check is made that the format of this repository and
276
the bzrdir format are compatible. FIXME RBC 20060201.
278
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
279
# use target default format.
280
result = a_bzrdir.create_repository()
281
# FIXME RBC 20060209 split out the repository type to avoid this check ?
282
elif isinstance(a_bzrdir._format,
283
(bzrdir.BzrDirFormat4,
284
bzrdir.BzrDirFormat5,
285
bzrdir.BzrDirFormat6)):
286
result = a_bzrdir.open_repository()
288
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
289
self.copy_content_into(result, revision_id, basis)
293
def has_revision(self, revision_id):
294
"""True if this repository has a copy of the revision."""
295
return self._revision_store.has_revision_id(revision_id,
296
self.get_transaction())
299
def get_revision_reconcile(self, revision_id):
300
"""'reconcile' helper routine that allows access to a revision always.
302
This variant of get_revision does not cross check the weave graph
303
against the revision one as get_revision does: but it should only
304
be used by reconcile, or reconcile-alike commands that are correcting
305
or testing the revision graph.
307
if not revision_id or not isinstance(revision_id, basestring):
308
raise InvalidRevisionId(revision_id=revision_id, branch=self)
309
return self._revision_store.get_revisions([revision_id],
310
self.get_transaction())[0]
312
def get_revisions(self, revision_ids):
313
return self._revision_store.get_revisions(revision_ids,
314
self.get_transaction())
317
def get_revision_xml(self, revision_id):
318
rev = self.get_revision(revision_id)
320
# the current serializer..
321
self._revision_store._serializer.write_revision(rev, rev_tmp)
323
return rev_tmp.getvalue()
326
def get_revision(self, revision_id):
327
"""Return the Revision object for a named revision"""
328
r = self.get_revision_reconcile(revision_id)
329
# weave corruption can lead to absent revision markers that should be
331
# the following test is reasonably cheap (it needs a single weave read)
332
# and the weave is cached in read transactions. In write transactions
333
# it is not cached but typically we only read a small number of
334
# revisions. For knits when they are introduced we will probably want
335
# to ensure that caching write transactions are in use.
336
inv = self.get_inventory_weave()
337
self._check_revision_parents(r, inv)
341
def get_deltas_for_revisions(self, revisions):
342
"""Produce a generator of revision deltas.
344
Note that the input is a sequence of REVISIONS, not revision_ids.
345
Trees will be held in memory until the generator exits.
346
Each delta is relative to the revision's lefthand predecessor.
348
required_trees = set()
349
for revision in revisions:
350
required_trees.add(revision.revision_id)
351
required_trees.update(revision.parent_ids[:1])
352
trees = dict((t.get_revision_id(), t) for
353
t in self.revision_trees(required_trees))
354
for revision in revisions:
355
if not revision.parent_ids:
356
old_tree = self.revision_tree(None)
358
old_tree = trees[revision.parent_ids[0]]
359
yield trees[revision.revision_id].changes_from(old_tree)
362
def get_revision_delta(self, revision_id):
363
"""Return the delta for one revision.
365
The delta is relative to the left-hand predecessor of the
368
r = self.get_revision(revision_id)
369
return list(self.get_deltas_for_revisions([r]))[0]
371
def _check_revision_parents(self, revision, inventory):
372
"""Private to Repository and Fetch.
374
This checks the parentage of revision in an inventory weave for
375
consistency and is only applicable to inventory-weave-for-ancestry
376
using repository formats & fetchers.
378
weave_parents = inventory.get_parents(revision.revision_id)
379
weave_names = inventory.versions()
380
for parent_id in revision.parent_ids:
381
if parent_id in weave_names:
382
# this parent must not be a ghost.
383
if not parent_id in weave_parents:
385
raise errors.CorruptRepository(self)
388
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
389
signature = gpg_strategy.sign(plaintext)
390
self._revision_store.add_revision_signature_text(revision_id,
392
self.get_transaction())
394
def fileids_altered_by_revision_ids(self, revision_ids):
395
"""Find the file ids and versions affected by revisions.
397
:param revisions: an iterable containing revision ids.
398
:return: a dictionary mapping altered file-ids to an iterable of
399
revision_ids. Each altered file-ids has the exact revision_ids that
400
altered it listed explicitly.
402
assert isinstance(self._format, (RepositoryFormat5,
405
RepositoryFormatKnit1)), \
406
("fileids_altered_by_revision_ids only supported for branches "
407
"which store inventory as unnested xml, not on %r" % self)
408
selected_revision_ids = set(revision_ids)
409
w = self.get_inventory_weave()
412
# this code needs to read every new line in every inventory for the
413
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
414
# not present in one of those inventories is unnecessary but not
415
# harmful because we are filtering by the revision id marker in the
416
# inventory lines : we only select file ids altered in one of those
417
# revisions. We don't need to see all lines in the inventory because
418
# only those added in an inventory in rev X can contain a revision=X
420
for line in w.iter_lines_added_or_present_in_versions(selected_revision_ids):
421
start = line.find('file_id="')+9
422
if start < 9: continue
423
end = line.find('"', start)
425
file_id = _unescape_xml(line[start:end])
427
start = line.find('revision="')+10
428
if start < 10: continue
429
end = line.find('"', start)
431
revision_id = _unescape_xml(line[start:end])
432
if revision_id in selected_revision_ids:
433
result.setdefault(file_id, set()).add(revision_id)
437
def get_inventory_weave(self):
438
return self.control_weaves.get_weave('inventory',
439
self.get_transaction())
442
def get_inventory(self, revision_id):
443
"""Get Inventory object by hash."""
444
return self.deserialise_inventory(
445
revision_id, self.get_inventory_xml(revision_id))
447
def deserialise_inventory(self, revision_id, xml):
448
"""Transform the xml into an inventory object.
450
:param revision_id: The expected revision id of the inventory.
451
:param xml: A serialised inventory.
453
result = xml5.serializer_v5.read_inventory_from_string(xml)
454
result.root.revision = revision_id
458
def get_inventory_xml(self, revision_id):
459
"""Get inventory XML as a file object."""
461
assert isinstance(revision_id, basestring), type(revision_id)
462
iw = self.get_inventory_weave()
463
return iw.get_text(revision_id)
465
raise errors.HistoryMissing(self, 'inventory', revision_id)
468
def get_inventory_sha1(self, revision_id):
469
"""Return the sha1 hash of the inventory entry
471
return self.get_revision(revision_id).inventory_sha1
474
def get_revision_graph(self, revision_id=None):
475
"""Return a dictionary containing the revision graph.
477
:param revision_id: The revision_id to get a graph from. If None, then
478
the entire revision graph is returned. This is a deprecated mode of
479
operation and will be removed in the future.
480
:return: a dictionary of revision_id->revision_parents_list.
482
# special case NULL_REVISION
483
if revision_id == NULL_REVISION:
485
weave = self.get_inventory_weave()
486
all_revisions = self._eliminate_revisions_not_present(weave.versions())
487
entire_graph = dict([(node, weave.get_parents(node)) for
488
node in all_revisions])
489
if revision_id is None:
491
elif revision_id not in entire_graph:
492
raise errors.NoSuchRevision(self, revision_id)
494
# add what can be reached from revision_id
496
pending = set([revision_id])
497
while len(pending) > 0:
499
result[node] = entire_graph[node]
500
for revision_id in result[node]:
501
if revision_id not in result:
502
pending.add(revision_id)
506
def get_revision_graph_with_ghosts(self, revision_ids=None):
507
"""Return a graph of the revisions with ghosts marked as applicable.
509
:param revision_ids: an iterable of revisions to graph or None for all.
510
:return: a Graph object with the graph reachable from revision_ids.
514
pending = set(self.all_revision_ids())
517
pending = set(revision_ids)
518
# special case NULL_REVISION
519
if NULL_REVISION in pending:
520
pending.remove(NULL_REVISION)
521
required = set(pending)
524
revision_id = pending.pop()
526
rev = self.get_revision(revision_id)
527
except errors.NoSuchRevision:
528
if revision_id in required:
531
result.add_ghost(revision_id)
533
for parent_id in rev.parent_ids:
534
# is this queued or done ?
535
if (parent_id not in pending and
536
parent_id not in done):
538
pending.add(parent_id)
539
result.add_node(revision_id, rev.parent_ids)
540
done.add(revision_id)
544
def get_revision_inventory(self, revision_id):
545
"""Return inventory of a past revision."""
546
# TODO: Unify this with get_inventory()
547
# bzr 0.0.6 and later imposes the constraint that the inventory_id
548
# must be the same as its revision, so this is trivial.
549
if revision_id is None:
550
# This does not make sense: if there is no revision,
551
# then it is the current tree inventory surely ?!
552
# and thus get_root_id() is something that looks at the last
553
# commit on the branch, and the get_root_id is an inventory check.
554
raise NotImplementedError
555
# return Inventory(self.get_root_id())
557
return self.get_inventory(revision_id)
561
"""Return True if this repository is flagged as a shared repository."""
562
raise NotImplementedError(self.is_shared)
565
def reconcile(self, other=None, thorough=False):
566
"""Reconcile this repository."""
567
from bzrlib.reconcile import RepoReconciler
568
reconciler = RepoReconciler(self, thorough=thorough)
569
reconciler.reconcile()
573
def revision_tree(self, revision_id):
574
"""Return Tree for a revision on this branch.
576
`revision_id` may be None for the empty tree revision.
578
# TODO: refactor this to use an existing revision object
579
# so we don't need to read it in twice.
580
if revision_id is None or revision_id == NULL_REVISION:
581
return RevisionTree(self, Inventory(), NULL_REVISION)
583
inv = self.get_revision_inventory(revision_id)
584
return RevisionTree(self, inv, revision_id)
587
def revision_trees(self, revision_ids):
588
"""Return Tree for a revision on this branch.
590
`revision_id` may not be None or 'null:'"""
591
assert None not in revision_ids
592
assert NULL_REVISION not in revision_ids
593
texts = self.get_inventory_weave().get_texts(revision_ids)
594
for text, revision_id in zip(texts, revision_ids):
595
inv = self.deserialise_inventory(revision_id, text)
596
yield RevisionTree(self, inv, revision_id)
599
def get_ancestry(self, revision_id):
600
"""Return a list of revision-ids integrated by a revision.
602
The first element of the list is always None, indicating the origin
603
revision. This might change when we have history horizons, or
604
perhaps we should have a new API.
606
This is topologically sorted.
608
if revision_id is None:
610
if not self.has_revision(revision_id):
611
raise errors.NoSuchRevision(self, revision_id)
612
w = self.get_inventory_weave()
613
candidates = w.get_ancestry(revision_id)
614
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
617
def print_file(self, file, revision_id):
618
"""Print `file` to stdout.
620
FIXME RBC 20060125 as John Meinel points out this is a bad api
621
- it writes to stdout, it assumes that that is valid etc. Fix
622
by creating a new more flexible convenience function.
624
tree = self.revision_tree(revision_id)
625
# use inventory as it was in that revision
626
file_id = tree.inventory.path2id(file)
628
# TODO: jam 20060427 Write a test for this code path
629
# it had a bug in it, and was raising the wrong
631
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
632
tree.print_file(file_id)
634
def get_transaction(self):
635
return self.control_files.get_transaction()
637
def revision_parents(self, revid):
638
return self.get_inventory_weave().parent_names(revid)
641
def set_make_working_trees(self, new_value):
642
"""Set the policy flag for making working trees when creating branches.
644
This only applies to branches that use this repository.
646
The default is 'True'.
647
:param new_value: True to restore the default, False to disable making
650
raise NotImplementedError(self.set_make_working_trees)
652
def make_working_trees(self):
653
"""Returns the policy for making working trees on new branches."""
654
raise NotImplementedError(self.make_working_trees)
657
def sign_revision(self, revision_id, gpg_strategy):
658
plaintext = Testament.from_revision(self, revision_id).as_short_text()
659
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
662
def has_signature_for_revision_id(self, revision_id):
663
"""Query for a revision signature for revision_id in the repository."""
664
return self._revision_store.has_signature(revision_id,
665
self.get_transaction())
668
def get_signature_text(self, revision_id):
669
"""Return the text for a signature."""
670
return self._revision_store.get_signature_text(revision_id,
671
self.get_transaction())
674
def check(self, revision_ids):
675
"""Check consistency of all history of given revision_ids.
677
Different repository implementations should override _check().
679
:param revision_ids: A non-empty list of revision_ids whose ancestry
680
will be checked. Typically the last revision_id of a branch.
683
raise ValueError("revision_ids must be non-empty in %s.check"
685
return self._check(revision_ids)
687
def _check(self, revision_ids):
688
result = check.Check(self)
692
def _warn_if_deprecated(self):
693
global _deprecation_warning_done
694
if _deprecation_warning_done:
696
_deprecation_warning_done = True
697
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
698
% (self._format, self.bzrdir.transport.base))
701
class AllInOneRepository(Repository):
702
"""Legacy support - the repository behaviour for all-in-one branches."""
704
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
705
# we reuse one control files instance.
706
dir_mode = a_bzrdir._control_files._dir_mode
707
file_mode = a_bzrdir._control_files._file_mode
709
def get_store(name, compressed=True, prefixed=False):
710
# FIXME: This approach of assuming stores are all entirely compressed
711
# or entirely uncompressed is tidy, but breaks upgrade from
712
# some existing branches where there's a mixture; we probably
713
# still want the option to look for both.
714
relpath = a_bzrdir._control_files._escape(name)
715
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
716
prefixed=prefixed, compressed=compressed,
719
#if self._transport.should_cache():
720
# cache_path = os.path.join(self.cache_root, name)
721
# os.mkdir(cache_path)
722
# store = bzrlib.store.CachedStore(store, cache_path)
725
# not broken out yet because the controlweaves|inventory_store
726
# and text_store | weave_store bits are still different.
727
if isinstance(_format, RepositoryFormat4):
728
# cannot remove these - there is still no consistent api
729
# which allows access to this old info.
730
self.inventory_store = get_store('inventory-store')
731
text_store = get_store('text-store')
732
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
736
"""AllInOne repositories cannot be shared."""
740
def set_make_working_trees(self, new_value):
741
"""Set the policy flag for making working trees when creating branches.
743
This only applies to branches that use this repository.
745
The default is 'True'.
746
:param new_value: True to restore the default, False to disable making
749
raise NotImplementedError(self.set_make_working_trees)
751
def make_working_trees(self):
752
"""Returns the policy for making working trees on new branches."""
756
def install_revision(repository, rev, revision_tree):
757
"""Install all revision data into a repository."""
760
for p_id in rev.parent_ids:
761
if repository.has_revision(p_id):
762
present_parents.append(p_id)
763
parent_trees[p_id] = repository.revision_tree(p_id)
765
parent_trees[p_id] = repository.revision_tree(None)
767
inv = revision_tree.inventory
769
# backwards compatability hack: skip the root id.
770
entries = inv.iter_entries()
772
# Add the texts that are not already present
773
for path, ie in entries:
774
w = repository.weave_store.get_weave_or_empty(ie.file_id,
775
repository.get_transaction())
776
if ie.revision not in w:
778
# FIXME: TODO: The following loop *may* be overlapping/duplicate
779
# with InventoryEntry.find_previous_heads(). if it is, then there
780
# is a latent bug here where the parents may have ancestors of each
782
for revision, tree in parent_trees.iteritems():
783
if ie.file_id not in tree:
785
parent_id = tree.inventory[ie.file_id].revision
786
if parent_id in text_parents:
788
text_parents.append(parent_id)
790
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
791
repository.get_transaction())
792
lines = revision_tree.get_file(ie.file_id).readlines()
793
vfile.add_lines(rev.revision_id, text_parents, lines)
795
# install the inventory
796
repository.add_inventory(rev.revision_id, inv, present_parents)
797
except errors.RevisionAlreadyPresent:
799
repository.add_revision(rev.revision_id, rev, inv)
802
class MetaDirRepository(Repository):
803
"""Repositories in the new meta-dir layout."""
805
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
806
super(MetaDirRepository, self).__init__(_format,
812
dir_mode = self.control_files._dir_mode
813
file_mode = self.control_files._file_mode
817
"""Return True if this repository is flagged as a shared repository."""
818
return self.control_files._transport.has('shared-storage')
821
def set_make_working_trees(self, new_value):
822
"""Set the policy flag for making working trees when creating branches.
824
This only applies to branches that use this repository.
826
The default is 'True'.
827
:param new_value: True to restore the default, False to disable making
832
self.control_files._transport.delete('no-working-trees')
833
except errors.NoSuchFile:
836
self.control_files.put_utf8('no-working-trees', '')
838
def make_working_trees(self):
839
"""Returns the policy for making working trees on new branches."""
840
return not self.control_files._transport.has('no-working-trees')
843
class KnitRepository(MetaDirRepository):
844
"""Knit format repository."""
846
def _warn_if_deprecated(self):
847
# This class isn't deprecated
850
def _inventory_add_lines(self, inv_vf, revid, parents, lines):
851
inv_vf.add_lines_with_ghosts(revid, parents, lines)
854
def _all_revision_ids(self):
855
"""See Repository.all_revision_ids()."""
856
# Knits get the revision graph from the index of the revision knit, so
857
# it's always possible even if they're on an unlistable transport.
858
return self._revision_store.all_revision_ids(self.get_transaction())
860
def fileid_involved_between_revs(self, from_revid, to_revid):
861
"""Find file_id(s) which are involved in the changes between revisions.
863
This determines the set of revisions which are involved, and then
864
finds all file ids affected by those revisions.
866
vf = self._get_revision_vf()
867
from_set = set(vf.get_ancestry(from_revid))
868
to_set = set(vf.get_ancestry(to_revid))
869
changed = to_set.difference(from_set)
870
return self._fileid_involved_by_set(changed)
872
def fileid_involved(self, last_revid=None):
873
"""Find all file_ids modified in the ancestry of last_revid.
875
:param last_revid: If None, last_revision() will be used.
878
changed = set(self.all_revision_ids())
880
changed = set(self.get_ancestry(last_revid))
883
return self._fileid_involved_by_set(changed)
886
def get_ancestry(self, revision_id):
887
"""Return a list of revision-ids integrated by a revision.
889
This is topologically sorted.
891
if revision_id is None:
893
vf = self._get_revision_vf()
895
return [None] + vf.get_ancestry(revision_id)
896
except errors.RevisionNotPresent:
897
raise errors.NoSuchRevision(self, revision_id)
900
def get_revision(self, revision_id):
901
"""Return the Revision object for a named revision"""
902
return self.get_revision_reconcile(revision_id)
905
def get_revision_graph(self, revision_id=None):
906
"""Return a dictionary containing the revision graph.
908
:param revision_id: The revision_id to get a graph from. If None, then
909
the entire revision graph is returned. This is a deprecated mode of
910
operation and will be removed in the future.
911
:return: a dictionary of revision_id->revision_parents_list.
913
# special case NULL_REVISION
914
if revision_id == NULL_REVISION:
916
weave = self._get_revision_vf()
917
entire_graph = weave.get_graph()
918
if revision_id is None:
919
return weave.get_graph()
920
elif revision_id not in weave:
921
raise errors.NoSuchRevision(self, revision_id)
923
# add what can be reached from revision_id
925
pending = set([revision_id])
926
while len(pending) > 0:
928
result[node] = weave.get_parents(node)
929
for revision_id in result[node]:
930
if revision_id not in result:
931
pending.add(revision_id)
935
def get_revision_graph_with_ghosts(self, revision_ids=None):
936
"""Return a graph of the revisions with ghosts marked as applicable.
938
:param revision_ids: an iterable of revisions to graph or None for all.
939
:return: a Graph object with the graph reachable from revision_ids.
942
vf = self._get_revision_vf()
943
versions = set(vf.versions())
945
pending = set(self.all_revision_ids())
948
pending = set(revision_ids)
949
# special case NULL_REVISION
950
if NULL_REVISION in pending:
951
pending.remove(NULL_REVISION)
952
required = set(pending)
955
revision_id = pending.pop()
956
if not revision_id in versions:
957
if revision_id in required:
958
raise errors.NoSuchRevision(self, revision_id)
960
result.add_ghost(revision_id)
961
# mark it as done so we don't try for it again.
962
done.add(revision_id)
964
parent_ids = vf.get_parents_with_ghosts(revision_id)
965
for parent_id in parent_ids:
966
# is this queued or done ?
967
if (parent_id not in pending and
968
parent_id not in done):
970
pending.add(parent_id)
971
result.add_node(revision_id, parent_ids)
972
done.add(revision_id)
975
def _get_revision_vf(self):
976
""":return: a versioned file containing the revisions."""
977
vf = self._revision_store.get_revision_file(self.get_transaction())
981
def reconcile(self, other=None, thorough=False):
982
"""Reconcile this repository."""
983
from bzrlib.reconcile import KnitReconciler
984
reconciler = KnitReconciler(self, thorough=thorough)
985
reconciler.reconcile()
988
def revision_parents(self, revision_id):
989
return self._get_revision_vf().get_parents(revision_id)
992
class RepositoryFormat(object):
993
"""A repository format.
995
Formats provide three things:
996
* An initialization routine to construct repository data on disk.
997
* a format string which is used when the BzrDir supports versioned
999
* an open routine which returns a Repository instance.
1001
Formats are placed in an dict by their format string for reference
1002
during opening. These should be subclasses of RepositoryFormat
1005
Once a format is deprecated, just deprecate the initialize and open
1006
methods on the format class. Do not deprecate the object, as the
1007
object will be created every system load.
1009
Common instance attributes:
1010
_matchingbzrdir - the bzrdir format that the repository format was
1011
originally written to work with. This can be used if manually
1012
constructing a bzrdir and repository, or more commonly for test suite
1016
_default_format = None
1017
"""The default format used for new repositories."""
1020
"""The known formats."""
1023
return "<%s>" % self.__class__.__name__
1026
def find_format(klass, a_bzrdir):
1027
"""Return the format for the repository object in a_bzrdir."""
1029
transport = a_bzrdir.get_repository_transport(None)
1030
format_string = transport.get("format").read()
1031
return klass._formats[format_string]
1032
except errors.NoSuchFile:
1033
raise errors.NoRepositoryPresent(a_bzrdir)
1035
raise errors.UnknownFormatError(format=format_string)
1037
def _get_control_store(self, repo_transport, control_files):
1038
"""Return the control store for this repository."""
1039
raise NotImplementedError(self._get_control_store)
1042
def get_default_format(klass):
1043
"""Return the current default format."""
1044
return klass._default_format
1046
def get_format_string(self):
1047
"""Return the ASCII format string that identifies this format.
1049
Note that in pre format ?? repositories the format string is
1050
not permitted nor written to disk.
1052
raise NotImplementedError(self.get_format_string)
1054
def get_format_description(self):
1055
"""Return the short description for this format."""
1056
raise NotImplementedError(self.get_format_description)
1058
def _get_revision_store(self, repo_transport, control_files):
1059
"""Return the revision store object for this a_bzrdir."""
1060
raise NotImplementedError(self._get_revision_store)
1062
def _get_text_rev_store(self,
1069
"""Common logic for getting a revision store for a repository.
1071
see self._get_revision_store for the subclass-overridable method to
1072
get the store for a repository.
1074
from bzrlib.store.revision.text import TextRevisionStore
1075
dir_mode = control_files._dir_mode
1076
file_mode = control_files._file_mode
1077
text_store =TextStore(transport.clone(name),
1079
compressed=compressed,
1081
file_mode=file_mode)
1082
_revision_store = TextRevisionStore(text_store, serializer)
1083
return _revision_store
1085
def _get_versioned_file_store(self,
1090
versionedfile_class=WeaveFile,
1091
versionedfile_kwargs={},
1093
weave_transport = control_files._transport.clone(name)
1094
dir_mode = control_files._dir_mode
1095
file_mode = control_files._file_mode
1096
return VersionedFileStore(weave_transport, prefixed=prefixed,
1098
file_mode=file_mode,
1099
versionedfile_class=versionedfile_class,
1100
versionedfile_kwargs=versionedfile_kwargs,
1103
def initialize(self, a_bzrdir, shared=False):
1104
"""Initialize a repository of this format in a_bzrdir.
1106
:param a_bzrdir: The bzrdir to put the new repository in it.
1107
:param shared: The repository should be initialized as a sharable one.
1109
This may raise UninitializableFormat if shared repository are not
1110
compatible the a_bzrdir.
1113
def is_supported(self):
1114
"""Is this format supported?
1116
Supported formats must be initializable and openable.
1117
Unsupported formats may not support initialization or committing or
1118
some other features depending on the reason for not being supported.
1122
def open(self, a_bzrdir, _found=False):
1123
"""Return an instance of this format for the bzrdir a_bzrdir.
1125
_found is a private parameter, do not use it.
1127
raise NotImplementedError(self.open)
1130
def register_format(klass, format):
1131
klass._formats[format.get_format_string()] = format
1134
def set_default_format(klass, format):
1135
klass._default_format = format
1138
def unregister_format(klass, format):
1139
assert klass._formats[format.get_format_string()] is format
1140
del klass._formats[format.get_format_string()]
1143
class PreSplitOutRepositoryFormat(RepositoryFormat):
1144
"""Base class for the pre split out repository formats."""
1146
def initialize(self, a_bzrdir, shared=False, _internal=False):
1147
"""Create a weave repository.
1149
TODO: when creating split out bzr branch formats, move this to a common
1150
base for Format5, Format6. or something like that.
1152
from bzrlib.weavefile import write_weave_v5
1153
from bzrlib.weave import Weave
1156
raise errors.IncompatibleFormat(self, a_bzrdir._format)
1159
# always initialized when the bzrdir is.
1160
return self.open(a_bzrdir, _found=True)
1162
# Create an empty weave
1164
write_weave_v5(Weave(), sio)
1165
empty_weave = sio.getvalue()
1167
mutter('creating repository in %s.', a_bzrdir.transport.base)
1168
dirs = ['revision-store', 'weaves']
1169
files = [('inventory.weave', StringIO(empty_weave)),
1172
# FIXME: RBC 20060125 don't peek under the covers
1173
# NB: no need to escape relative paths that are url safe.
1174
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock',
1176
control_files.create_lock()
1177
control_files.lock_write()
1178
control_files._transport.mkdir_multi(dirs,
1179
mode=control_files._dir_mode)
1181
for file, content in files:
1182
control_files.put(file, content)
1184
control_files.unlock()
1185
return self.open(a_bzrdir, _found=True)
1187
def _get_control_store(self, repo_transport, control_files):
1188
"""Return the control store for this repository."""
1189
return self._get_versioned_file_store('',
1194
def _get_text_store(self, transport, control_files):
1195
"""Get a store for file texts for this format."""
1196
raise NotImplementedError(self._get_text_store)
1198
def open(self, a_bzrdir, _found=False):
1199
"""See RepositoryFormat.open()."""
1201
# we are being called directly and must probe.
1202
raise NotImplementedError
1204
repo_transport = a_bzrdir.get_repository_transport(None)
1205
control_files = a_bzrdir._control_files
1206
text_store = self._get_text_store(repo_transport, control_files)
1207
control_store = self._get_control_store(repo_transport, control_files)
1208
_revision_store = self._get_revision_store(repo_transport, control_files)
1209
return AllInOneRepository(_format=self,
1211
_revision_store=_revision_store,
1212
control_store=control_store,
1213
text_store=text_store)
1216
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1217
"""Bzr repository format 4.
1219
This repository format has:
1221
- TextStores for texts, inventories,revisions.
1223
This format is deprecated: it indexes texts using a text id which is
1224
removed in format 5; initialization and write support for this format
1229
super(RepositoryFormat4, self).__init__()
1230
self._matchingbzrdir = bzrdir.BzrDirFormat4()
1232
def get_format_description(self):
1233
"""See RepositoryFormat.get_format_description()."""
1234
return "Repository format 4"
1236
def initialize(self, url, shared=False, _internal=False):
1237
"""Format 4 branches cannot be created."""
1238
raise errors.UninitializableFormat(self)
1240
def is_supported(self):
1241
"""Format 4 is not supported.
1243
It is not supported because the model changed from 4 to 5 and the
1244
conversion logic is expensive - so doing it on the fly was not
1249
def _get_control_store(self, repo_transport, control_files):
1250
"""Format 4 repositories have no formal control store at this point.
1252
This will cause any control-file-needing apis to fail - this is desired.
1256
def _get_revision_store(self, repo_transport, control_files):
1257
"""See RepositoryFormat._get_revision_store()."""
1258
from bzrlib.xml4 import serializer_v4
1259
return self._get_text_rev_store(repo_transport,
1262
serializer=serializer_v4)
1264
def _get_text_store(self, transport, control_files):
1265
"""See RepositoryFormat._get_text_store()."""
1268
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1269
"""Bzr control format 5.
1271
This repository format has:
1272
- weaves for file texts and inventory
1274
- TextStores for revisions and signatures.
1278
super(RepositoryFormat5, self).__init__()
1279
self._matchingbzrdir = bzrdir.BzrDirFormat5()
1281
def get_format_description(self):
1282
"""See RepositoryFormat.get_format_description()."""
1283
return "Weave repository format 5"
1285
def _get_revision_store(self, repo_transport, control_files):
1286
"""See RepositoryFormat._get_revision_store()."""
1287
"""Return the revision store object for this a_bzrdir."""
1288
return self._get_text_rev_store(repo_transport,
1293
def _get_text_store(self, transport, control_files):
1294
"""See RepositoryFormat._get_text_store()."""
1295
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1298
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1299
"""Bzr control format 6.
1301
This repository format has:
1302
- weaves for file texts and inventory
1303
- hash subdirectory based stores.
1304
- TextStores for revisions and signatures.
1308
super(RepositoryFormat6, self).__init__()
1309
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1311
def get_format_description(self):
1312
"""See RepositoryFormat.get_format_description()."""
1313
return "Weave repository format 6"
1315
def _get_revision_store(self, repo_transport, control_files):
1316
"""See RepositoryFormat._get_revision_store()."""
1317
return self._get_text_rev_store(repo_transport,
1323
def _get_text_store(self, transport, control_files):
1324
"""See RepositoryFormat._get_text_store()."""
1325
return self._get_versioned_file_store('weaves', transport, control_files)
1328
class MetaDirRepositoryFormat(RepositoryFormat):
1329
"""Common base class for the new repositories using the metadir layout."""
1332
super(MetaDirRepositoryFormat, self).__init__()
1333
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1335
def _create_control_files(self, a_bzrdir):
1336
"""Create the required files and the initial control_files object."""
1337
# FIXME: RBC 20060125 don't peek under the covers
1338
# NB: no need to escape relative paths that are url safe.
1339
repository_transport = a_bzrdir.get_repository_transport(self)
1340
control_files = LockableFiles(repository_transport, 'lock', LockDir)
1341
control_files.create_lock()
1342
return control_files
1344
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1345
"""Upload the initial blank content."""
1346
control_files = self._create_control_files(a_bzrdir)
1347
control_files.lock_write()
1349
control_files._transport.mkdir_multi(dirs,
1350
mode=control_files._dir_mode)
1351
for file, content in files:
1352
control_files.put(file, content)
1353
for file, content in utf8_files:
1354
control_files.put_utf8(file, content)
1356
control_files.put_utf8('shared-storage', '')
1358
control_files.unlock()
1361
class RepositoryFormat7(MetaDirRepositoryFormat):
1362
"""Bzr repository 7.
1364
This repository format has:
1365
- weaves for file texts and inventory
1366
- hash subdirectory based stores.
1367
- TextStores for revisions and signatures.
1368
- a format marker of its own
1369
- an optional 'shared-storage' flag
1370
- an optional 'no-working-trees' flag
1373
def _get_control_store(self, repo_transport, control_files):
1374
"""Return the control store for this repository."""
1375
return self._get_versioned_file_store('',
1380
def get_format_string(self):
1381
"""See RepositoryFormat.get_format_string()."""
1382
return "Bazaar-NG Repository format 7"
1384
def get_format_description(self):
1385
"""See RepositoryFormat.get_format_description()."""
1386
return "Weave repository format 7"
1388
def _get_revision_store(self, repo_transport, control_files):
1389
"""See RepositoryFormat._get_revision_store()."""
1390
return self._get_text_rev_store(repo_transport,
1397
def _get_text_store(self, transport, control_files):
1398
"""See RepositoryFormat._get_text_store()."""
1399
return self._get_versioned_file_store('weaves',
1403
def initialize(self, a_bzrdir, shared=False):
1404
"""Create a weave repository.
1406
:param shared: If true the repository will be initialized as a shared
1409
from bzrlib.weavefile import write_weave_v5
1410
from bzrlib.weave import Weave
1412
# Create an empty weave
1414
write_weave_v5(Weave(), sio)
1415
empty_weave = sio.getvalue()
1417
mutter('creating repository in %s.', a_bzrdir.transport.base)
1418
dirs = ['revision-store', 'weaves']
1419
files = [('inventory.weave', StringIO(empty_weave)),
1421
utf8_files = [('format', self.get_format_string())]
1423
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1424
return self.open(a_bzrdir=a_bzrdir, _found=True)
1426
def open(self, a_bzrdir, _found=False, _override_transport=None):
1427
"""See RepositoryFormat.open().
1429
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1430
repository at a slightly different url
1431
than normal. I.e. during 'upgrade'.
1434
format = RepositoryFormat.find_format(a_bzrdir)
1435
assert format.__class__ == self.__class__
1436
if _override_transport is not None:
1437
repo_transport = _override_transport
1439
repo_transport = a_bzrdir.get_repository_transport(None)
1440
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1441
text_store = self._get_text_store(repo_transport, control_files)
1442
control_store = self._get_control_store(repo_transport, control_files)
1443
_revision_store = self._get_revision_store(repo_transport, control_files)
1444
return MetaDirRepository(_format=self,
1446
control_files=control_files,
1447
_revision_store=_revision_store,
1448
control_store=control_store,
1449
text_store=text_store)
1452
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1453
"""Bzr repository knit format 1.
1455
This repository format has:
1456
- knits for file texts and inventory
1457
- hash subdirectory based stores.
1458
- knits for revisions and signatures
1459
- TextStores for revisions and signatures.
1460
- a format marker of its own
1461
- an optional 'shared-storage' flag
1462
- an optional 'no-working-trees' flag
1465
This format was introduced in bzr 0.8.
1468
def _get_control_store(self, repo_transport, control_files):
1469
"""Return the control store for this repository."""
1470
return VersionedFileStore(
1473
file_mode=control_files._file_mode,
1474
versionedfile_class=KnitVersionedFile,
1475
versionedfile_kwargs={'factory':KnitPlainFactory()},
1478
def get_format_string(self):
1479
"""See RepositoryFormat.get_format_string()."""
1480
return "Bazaar-NG Knit Repository Format 1"
1482
def get_format_description(self):
1483
"""See RepositoryFormat.get_format_description()."""
1484
return "Knit repository format 1"
1486
def _get_revision_store(self, repo_transport, control_files):
1487
"""See RepositoryFormat._get_revision_store()."""
1488
from bzrlib.store.revision.knit import KnitRevisionStore
1489
versioned_file_store = VersionedFileStore(
1491
file_mode=control_files._file_mode,
1494
versionedfile_class=KnitVersionedFile,
1495
versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory(),},
1498
return KnitRevisionStore(versioned_file_store)
1500
def _get_text_store(self, transport, control_files):
1501
"""See RepositoryFormat._get_text_store()."""
1502
return self._get_versioned_file_store('knits',
1505
versionedfile_class=KnitVersionedFile,
1506
versionedfile_kwargs={
1507
'create_parent_dir':True,
1508
'delay_create':True,
1509
'dir_mode':control_files._dir_mode,
1513
def initialize(self, a_bzrdir, shared=False):
1514
"""Create a knit format 1 repository.
1516
:param a_bzrdir: bzrdir to contain the new repository; must already
1518
:param shared: If true the repository will be initialized as a shared
1521
mutter('creating repository in %s.', a_bzrdir.transport.base)
1522
dirs = ['revision-store', 'knits']
1524
utf8_files = [('format', self.get_format_string())]
1526
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1527
repo_transport = a_bzrdir.get_repository_transport(None)
1528
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1529
control_store = self._get_control_store(repo_transport, control_files)
1530
transaction = transactions.WriteTransaction()
1531
# trigger a write of the inventory store.
1532
control_store.get_weave_or_empty('inventory', transaction)
1533
_revision_store = self._get_revision_store(repo_transport, control_files)
1534
_revision_store.has_revision_id('A', transaction)
1535
_revision_store.get_signature_file(transaction)
1536
return self.open(a_bzrdir=a_bzrdir, _found=True)
1538
def open(self, a_bzrdir, _found=False, _override_transport=None):
1539
"""See RepositoryFormat.open().
1541
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1542
repository at a slightly different url
1543
than normal. I.e. during 'upgrade'.
1546
format = RepositoryFormat.find_format(a_bzrdir)
1547
assert format.__class__ == self.__class__
1548
if _override_transport is not None:
1549
repo_transport = _override_transport
1551
repo_transport = a_bzrdir.get_repository_transport(None)
1552
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1553
text_store = self._get_text_store(repo_transport, control_files)
1554
control_store = self._get_control_store(repo_transport, control_files)
1555
_revision_store = self._get_revision_store(repo_transport, control_files)
1556
return KnitRepository(_format=self,
1558
control_files=control_files,
1559
_revision_store=_revision_store,
1560
control_store=control_store,
1561
text_store=text_store)
1564
# formats which have no format string are not discoverable
1565
# and not independently creatable, so are not registered.
1566
RepositoryFormat.register_format(RepositoryFormat7())
1567
_default_format = RepositoryFormatKnit1()
1568
RepositoryFormat.register_format(_default_format)
1569
RepositoryFormat.set_default_format(_default_format)
1570
_legacy_formats = [RepositoryFormat4(),
1571
RepositoryFormat5(),
1572
RepositoryFormat6()]
1575
class InterRepository(InterObject):
1576
"""This class represents operations taking place between two repositories.
1578
Its instances have methods like copy_content and fetch, and contain
1579
references to the source and target repositories these operations can be
1582
Often we will provide convenience methods on 'repository' which carry out
1583
operations with another repository - they will always forward to
1584
InterRepository.get(other).method_name(parameters).
1588
"""The available optimised InterRepository types."""
1591
def copy_content(self, revision_id=None, basis=None):
1592
"""Make a complete copy of the content in self into destination.
1594
This is a destructive operation! Do not use it on existing
1597
:param revision_id: Only copy the content needed to construct
1598
revision_id and its parents.
1599
:param basis: Copy the needed data preferentially from basis.
1602
self.target.set_make_working_trees(self.source.make_working_trees())
1603
except NotImplementedError:
1605
# grab the basis available data
1606
if basis is not None:
1607
self.target.fetch(basis, revision_id=revision_id)
1608
# but don't bother fetching if we have the needed data now.
1609
if (revision_id not in (None, NULL_REVISION) and
1610
self.target.has_revision(revision_id)):
1612
self.target.fetch(self.source, revision_id=revision_id)
1615
def fetch(self, revision_id=None, pb=None):
1616
"""Fetch the content required to construct revision_id.
1618
The content is copied from source to target.
1620
:param revision_id: if None all content is copied, if NULL_REVISION no
1622
:param pb: optional progress bar to use for progress reports. If not
1623
provided a default one will be created.
1625
Returns the copied revision count and the failed revisions in a tuple:
1628
from bzrlib.fetch import GenericRepoFetcher
1629
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1630
self.source, self.source._format, self.target, self.target._format)
1631
f = GenericRepoFetcher(to_repository=self.target,
1632
from_repository=self.source,
1633
last_revision=revision_id,
1635
return f.count_copied, f.failed_revisions
1638
def missing_revision_ids(self, revision_id=None):
1639
"""Return the revision ids that source has that target does not.
1641
These are returned in topological order.
1643
:param revision_id: only return revision ids included by this
1646
# generic, possibly worst case, slow code path.
1647
target_ids = set(self.target.all_revision_ids())
1648
if revision_id is not None:
1649
source_ids = self.source.get_ancestry(revision_id)
1650
assert source_ids[0] is None
1653
source_ids = self.source.all_revision_ids()
1654
result_set = set(source_ids).difference(target_ids)
1655
# this may look like a no-op: its not. It preserves the ordering
1656
# other_ids had while only returning the members from other_ids
1657
# that we've decided we need.
1658
return [rev_id for rev_id in source_ids if rev_id in result_set]
1661
class InterWeaveRepo(InterRepository):
1662
"""Optimised code paths between Weave based repositories."""
1664
_matching_repo_format = RepositoryFormat7()
1665
"""Repository format for testing with."""
1668
def is_compatible(source, target):
1669
"""Be compatible with known Weave formats.
1671
We don't test for the stores being of specific types because that
1672
could lead to confusing results, and there is no need to be
1676
return (isinstance(source._format, (RepositoryFormat5,
1678
RepositoryFormat7)) and
1679
isinstance(target._format, (RepositoryFormat5,
1681
RepositoryFormat7)))
1682
except AttributeError:
1686
def copy_content(self, revision_id=None, basis=None):
1687
"""See InterRepository.copy_content()."""
1688
# weave specific optimised path:
1689
if basis is not None:
1690
# copy the basis in, then fetch remaining data.
1691
basis.copy_content_into(self.target, revision_id)
1692
# the basis copy_content_into could miss-set this.
1694
self.target.set_make_working_trees(self.source.make_working_trees())
1695
except NotImplementedError:
1697
self.target.fetch(self.source, revision_id=revision_id)
1700
self.target.set_make_working_trees(self.source.make_working_trees())
1701
except NotImplementedError:
1703
# FIXME do not peek!
1704
if self.source.control_files._transport.listable():
1705
pb = ui.ui_factory.nested_progress_bar()
1707
self.target.weave_store.copy_all_ids(
1708
self.source.weave_store,
1710
from_transaction=self.source.get_transaction(),
1711
to_transaction=self.target.get_transaction())
1712
pb.update('copying inventory', 0, 1)
1713
self.target.control_weaves.copy_multi(
1714
self.source.control_weaves, ['inventory'],
1715
from_transaction=self.source.get_transaction(),
1716
to_transaction=self.target.get_transaction())
1717
self.target._revision_store.text_store.copy_all_ids(
1718
self.source._revision_store.text_store,
1723
self.target.fetch(self.source, revision_id=revision_id)
1726
def fetch(self, revision_id=None, pb=None):
1727
"""See InterRepository.fetch()."""
1728
from bzrlib.fetch import GenericRepoFetcher
1729
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1730
self.source, self.source._format, self.target, self.target._format)
1731
f = GenericRepoFetcher(to_repository=self.target,
1732
from_repository=self.source,
1733
last_revision=revision_id,
1735
return f.count_copied, f.failed_revisions
1738
def missing_revision_ids(self, revision_id=None):
1739
"""See InterRepository.missing_revision_ids()."""
1740
# we want all revisions to satisfy revision_id in source.
1741
# but we don't want to stat every file here and there.
1742
# we want then, all revisions other needs to satisfy revision_id
1743
# checked, but not those that we have locally.
1744
# so the first thing is to get a subset of the revisions to
1745
# satisfy revision_id in source, and then eliminate those that
1746
# we do already have.
1747
# this is slow on high latency connection to self, but as as this
1748
# disk format scales terribly for push anyway due to rewriting
1749
# inventory.weave, this is considered acceptable.
1751
if revision_id is not None:
1752
source_ids = self.source.get_ancestry(revision_id)
1753
assert source_ids[0] is None
1756
source_ids = self.source._all_possible_ids()
1757
source_ids_set = set(source_ids)
1758
# source_ids is the worst possible case we may need to pull.
1759
# now we want to filter source_ids against what we actually
1760
# have in target, but don't try to check for existence where we know
1761
# we do not have a revision as that would be pointless.
1762
target_ids = set(self.target._all_possible_ids())
1763
possibly_present_revisions = target_ids.intersection(source_ids_set)
1764
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1765
required_revisions = source_ids_set.difference(actually_present_revisions)
1766
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1767
if revision_id is not None:
1768
# we used get_ancestry to determine source_ids then we are assured all
1769
# revisions referenced are present as they are installed in topological order.
1770
# and the tip revision was validated by get_ancestry.
1771
return required_topo_revisions
1773
# if we just grabbed the possibly available ids, then
1774
# we only have an estimate of whats available and need to validate
1775
# that against the revision records.
1776
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1779
class InterKnitRepo(InterRepository):
1780
"""Optimised code paths between Knit based repositories."""
1782
_matching_repo_format = RepositoryFormatKnit1()
1783
"""Repository format for testing with."""
1786
def is_compatible(source, target):
1787
"""Be compatible with known Knit formats.
1789
We don't test for the stores being of specific types because that
1790
could lead to confusing results, and there is no need to be
1794
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1795
isinstance(target._format, (RepositoryFormatKnit1)))
1796
except AttributeError:
1800
def fetch(self, revision_id=None, pb=None):
1801
"""See InterRepository.fetch()."""
1802
from bzrlib.fetch import KnitRepoFetcher
1803
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1804
self.source, self.source._format, self.target, self.target._format)
1805
f = KnitRepoFetcher(to_repository=self.target,
1806
from_repository=self.source,
1807
last_revision=revision_id,
1809
return f.count_copied, f.failed_revisions
1812
def missing_revision_ids(self, revision_id=None):
1813
"""See InterRepository.missing_revision_ids()."""
1814
if revision_id is not None:
1815
source_ids = self.source.get_ancestry(revision_id)
1816
assert source_ids[0] is None
1819
source_ids = self.source._all_possible_ids()
1820
source_ids_set = set(source_ids)
1821
# source_ids is the worst possible case we may need to pull.
1822
# now we want to filter source_ids against what we actually
1823
# have in target, but don't try to check for existence where we know
1824
# we do not have a revision as that would be pointless.
1825
target_ids = set(self.target._all_possible_ids())
1826
possibly_present_revisions = target_ids.intersection(source_ids_set)
1827
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1828
required_revisions = source_ids_set.difference(actually_present_revisions)
1829
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1830
if revision_id is not None:
1831
# we used get_ancestry to determine source_ids then we are assured all
1832
# revisions referenced are present as they are installed in topological order.
1833
# and the tip revision was validated by get_ancestry.
1834
return required_topo_revisions
1836
# if we just grabbed the possibly available ids, then
1837
# we only have an estimate of whats available and need to validate
1838
# that against the revision records.
1839
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1841
InterRepository.register_optimiser(InterWeaveRepo)
1842
InterRepository.register_optimiser(InterKnitRepo)
1845
class RepositoryTestProviderAdapter(object):
1846
"""A tool to generate a suite testing multiple repository formats at once.
1848
This is done by copying the test once for each transport and injecting
1849
the transport_server, transport_readonly_server, and bzrdir_format and
1850
repository_format classes into each copy. Each copy is also given a new id()
1851
to make it easy to identify.
1854
def __init__(self, transport_server, transport_readonly_server, formats):
1855
self._transport_server = transport_server
1856
self._transport_readonly_server = transport_readonly_server
1857
self._formats = formats
1859
def adapt(self, test):
1860
result = TestSuite()
1861
for repository_format, bzrdir_format in self._formats:
1862
new_test = deepcopy(test)
1863
new_test.transport_server = self._transport_server
1864
new_test.transport_readonly_server = self._transport_readonly_server
1865
new_test.bzrdir_format = bzrdir_format
1866
new_test.repository_format = repository_format
1867
def make_new_test_id():
1868
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1869
return lambda: new_id
1870
new_test.id = make_new_test_id()
1871
result.addTest(new_test)
1875
class InterRepositoryTestProviderAdapter(object):
1876
"""A tool to generate a suite testing multiple inter repository formats.
1878
This is done by copying the test once for each interrepo provider and injecting
1879
the transport_server, transport_readonly_server, repository_format and
1880
repository_to_format classes into each copy.
1881
Each copy is also given a new id() to make it easy to identify.
1884
def __init__(self, transport_server, transport_readonly_server, formats):
1885
self._transport_server = transport_server
1886
self._transport_readonly_server = transport_readonly_server
1887
self._formats = formats
1889
def adapt(self, test):
1890
result = TestSuite()
1891
for interrepo_class, repository_format, repository_format_to in self._formats:
1892
new_test = deepcopy(test)
1893
new_test.transport_server = self._transport_server
1894
new_test.transport_readonly_server = self._transport_readonly_server
1895
new_test.interrepo_class = interrepo_class
1896
new_test.repository_format = repository_format
1897
new_test.repository_format_to = repository_format_to
1898
def make_new_test_id():
1899
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1900
return lambda: new_id
1901
new_test.id = make_new_test_id()
1902
result.addTest(new_test)
1906
def default_test_list():
1907
"""Generate the default list of interrepo permutations to test."""
1909
# test the default InterRepository between format 6 and the current
1911
# XXX: robertc 20060220 reinstate this when there are two supported
1912
# formats which do not have an optimal code path between them.
1913
result.append((InterRepository,
1914
RepositoryFormat6(),
1915
RepositoryFormatKnit1()))
1916
for optimiser in InterRepository._optimisers:
1917
result.append((optimiser,
1918
optimiser._matching_repo_format,
1919
optimiser._matching_repo_format
1921
# if there are specific combinations we want to use, we can add them
1926
class CopyConverter(object):
1927
"""A repository conversion tool which just performs a copy of the content.
1929
This is slow but quite reliable.
1932
def __init__(self, target_format):
1933
"""Create a CopyConverter.
1935
:param target_format: The format the resulting repository should be.
1937
self.target_format = target_format
1939
def convert(self, repo, pb):
1940
"""Perform the conversion of to_convert, giving feedback via pb.
1942
:param to_convert: The disk object to convert.
1943
:param pb: a progress bar to use for progress information.
1948
# this is only useful with metadir layouts - separated repo content.
1949
# trigger an assertion if not such
1950
repo._format.get_format_string()
1951
self.repo_dir = repo.bzrdir
1952
self.step('Moving repository to repository.backup')
1953
self.repo_dir.transport.move('repository', 'repository.backup')
1954
backup_transport = self.repo_dir.transport.clone('repository.backup')
1955
self.source_repo = repo._format.open(self.repo_dir,
1957
_override_transport=backup_transport)
1958
self.step('Creating new repository')
1959
converted = self.target_format.initialize(self.repo_dir,
1960
self.source_repo.is_shared())
1961
converted.lock_write()
1963
self.step('Copying content into repository.')
1964
self.source_repo.copy_content_into(converted)
1967
self.step('Deleting old repository content.')
1968
self.repo_dir.transport.delete_tree('repository.backup')
1969
self.pb.note('repository converted')
1971
def step(self, message):
1972
"""Update the pb by a step."""
1974
self.pb.update(message, self.count, self.total)
1977
class CommitBuilder(object):
1978
"""Provides an interface to build up a commit.
1980
This allows describing a tree to be committed without needing to
1981
know the internals of the format of the repository.
1984
record_root_entry = False
1985
def __init__(self, repository, parents, config, timestamp=None,
1986
timezone=None, committer=None, revprops=None,
1988
"""Initiate a CommitBuilder.
1990
:param repository: Repository to commit to.
1991
:param parents: Revision ids of the parents of the new revision.
1992
:param config: Configuration to use.
1993
:param timestamp: Optional timestamp recorded for commit.
1994
:param timezone: Optional timezone for timestamp.
1995
:param committer: Optional committer to set for commit.
1996
:param revprops: Optional dictionary of revision properties.
1997
:param revision_id: Optional revision id.
1999
self._config = config
2001
if committer is None:
2002
self._committer = self._config.username()
2004
assert isinstance(committer, basestring), type(committer)
2005
self._committer = committer
2007
self.new_inventory = Inventory(None)
2008
self._new_revision_id = revision_id
2009
self.parents = parents
2010
self.repository = repository
2013
if revprops is not None:
2014
self._revprops.update(revprops)
2016
if timestamp is None:
2017
timestamp = time.time()
2018
# Restrict resolution to 1ms
2019
self._timestamp = round(timestamp, 3)
2021
if timezone is None:
2022
self._timezone = local_time_offset()
2024
self._timezone = int(timezone)
2026
self._generate_revision_if_needed()
2028
def commit(self, message):
2029
"""Make the actual commit.
2031
:return: The revision id of the recorded revision.
2033
rev = Revision(timestamp=self._timestamp,
2034
timezone=self._timezone,
2035
committer=self._committer,
2037
inventory_sha1=self.inv_sha1,
2038
revision_id=self._new_revision_id,
2039
properties=self._revprops)
2040
rev.parent_ids = self.parents
2041
self.repository.add_revision(self._new_revision_id, rev,
2042
self.new_inventory, self._config)
2043
return 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
s = '%s-%s-' % (self._config.user_email(),
2062
compact_date(self._timestamp))
2063
s += hexlify(rand_bytes(8))
2066
def _generate_revision_if_needed(self):
2067
"""Create a revision id if None was supplied.
2069
If the repository can not support user-specified revision ids
2070
they should override this function and raise UnsupportedOperation
2071
if _new_revision_id is not None.
2073
:raises: UnsupportedOperation
2075
if self._new_revision_id is None:
2076
self._new_revision_id = self._gen_revision_id()
2078
def record_entry_contents(self, ie, parent_invs, path, tree):
2079
"""Record the content of ie from tree into the commit if needed.
2081
Side effect: sets ie.revision when unchanged
2083
:param ie: An inventory entry present in the commit.
2084
:param parent_invs: The inventories of the parent revisions of the
2086
:param path: The path the entry is at in the tree.
2087
:param tree: The tree which contains this entry and should be used to
2090
if self.new_inventory.root is None and ie.parent_id is not None:
2091
symbol_versioning.warn('Root entry should be supplied to'
2092
' record_entry_contents, as of bzr 0.10.',
2093
DeprecationWarning, stacklevel=2)
2094
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2096
self.new_inventory.add(ie)
2098
# ie.revision is always None if the InventoryEntry is considered
2099
# for committing. ie.snapshot will record the correct revision
2100
# which may be the sole parent if it is untouched.
2101
if ie.revision is not None:
2104
# In this revision format, root entries have no knit or weave
2105
if ie is self.new_inventory.root:
2106
if len(parent_invs):
2107
ie.revision = parent_invs[0].root.revision
2111
previous_entries = ie.find_previous_heads(
2113
self.repository.weave_store,
2114
self.repository.get_transaction())
2115
# we are creating a new revision for ie in the history store
2117
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2119
def modified_directory(self, file_id, file_parents):
2120
"""Record the presence of a symbolic link.
2122
:param file_id: The file_id of the link to record.
2123
:param file_parents: The per-file parent revision ids.
2125
self._add_text_to_weave(file_id, [], file_parents.keys())
2127
def modified_file_text(self, file_id, file_parents,
2128
get_content_byte_lines, text_sha1=None,
2130
"""Record the text of file file_id
2132
:param file_id: The file_id of the file to record the text of.
2133
:param file_parents: The per-file parent revision ids.
2134
:param get_content_byte_lines: A callable which will return the byte
2136
:param text_sha1: Optional SHA1 of the file contents.
2137
:param text_size: Optional size of the file contents.
2139
# mutter('storing text of file {%s} in revision {%s} into %r',
2140
# file_id, self._new_revision_id, self.repository.weave_store)
2141
# special case to avoid diffing on renames or
2143
if (len(file_parents) == 1
2144
and text_sha1 == file_parents.values()[0].text_sha1
2145
and text_size == file_parents.values()[0].text_size):
2146
previous_ie = file_parents.values()[0]
2147
versionedfile = self.repository.weave_store.get_weave(file_id,
2148
self.repository.get_transaction())
2149
versionedfile.clone_text(self._new_revision_id,
2150
previous_ie.revision, file_parents.keys())
2151
return text_sha1, text_size
2153
new_lines = get_content_byte_lines()
2154
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2155
# should return the SHA1 and size
2156
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2157
return osutils.sha_strings(new_lines), \
2158
sum(map(len, new_lines))
2160
def modified_link(self, file_id, file_parents, link_target):
2161
"""Record the presence of a symbolic link.
2163
:param file_id: The file_id of the link to record.
2164
:param file_parents: The per-file parent revision ids.
2165
:param link_target: Target location of this link.
2167
self._add_text_to_weave(file_id, [], file_parents.keys())
2169
def _add_text_to_weave(self, file_id, new_lines, parents):
2170
versionedfile = self.repository.weave_store.get_weave_or_empty(
2171
file_id, self.repository.get_transaction())
2172
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2173
versionedfile.clear_cache()
2176
class _CommitBuilder(CommitBuilder):
2177
"""Temporary class so old CommitBuilders are detected properly
2179
Note: CommitBuilder works whether or not root entry is recorded.
2182
record_root_entry = True
2194
def _unescaper(match, _map=_unescape_map):
2195
return _map[match.group(1)]
2201
def _unescape_xml(data):
2202
"""Unescape predefined XML entities in a string of data."""
2204
if _unescape_re is None:
2205
_unescape_re = re.compile('\&([^;]*);')
2206
return _unescape_re.sub(_unescaper, data)