1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1
# Copyright (C) 2005, 2006 Canonical Ltd
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
from copy import deepcopy
17
18
from cStringIO import StringIO
19
from bzrlib.lazy_import import lazy_import
20
lazy_import(globals(), """
38
revision as _mod_revision,
43
from bzrlib.revisiontree import RevisionTree
44
from bzrlib.store.versioned import VersionedFileStore
19
from unittest import TestSuite
21
import bzrlib.bzrdir as bzrdir
22
from bzrlib.decorators import needs_read_lock, needs_write_lock
23
import bzrlib.errors as errors
24
from bzrlib.errors import InvalidRevisionId
25
import bzrlib.gpg as gpg
26
from bzrlib.graph import Graph
27
from bzrlib.inter import InterObject
28
from bzrlib.knit import KnitVersionedFile
29
from bzrlib.lockable_files import LockableFiles, TransportLock
30
from bzrlib.lockdir import LockDir
31
from bzrlib.osutils import safe_unicode
32
from bzrlib.revision import NULL_REVISION
33
from bzrlib.store.versioned import VersionedFileStore, WeaveStore
45
34
from bzrlib.store.text import TextStore
35
from bzrlib.symbol_versioning import *
36
from bzrlib.trace import mutter
37
from bzrlib.tree import RevisionTree
38
from bzrlib.tsort import topo_sort
46
39
from bzrlib.testament import Testament
50
from bzrlib.decorators import needs_read_lock, needs_write_lock
51
from bzrlib.inter import InterObject
52
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
53
from bzrlib.symbol_versioning import (
57
from bzrlib.trace import mutter, note, warning
60
# Old formats display a warning, but only once
61
_deprecation_warning_done = False
64
######################################################################
40
from bzrlib.tree import EmptyTree
42
from bzrlib.weave import WeaveFile
67
46
class Repository(object):
68
47
"""Repository holding history for one or more branches.
79
_file_ids_altered_regex = lazy_regex.lazy_compile(
80
r'file_id="(?P<file_id>[^"]+)"'
81
r'.*revision="(?P<revision_id>[^"]+)"'
85
def add_inventory(self, revision_id, inv, parents):
86
"""Add the inventory inv to the repository as revision_id.
59
def add_inventory(self, revid, inv, parents):
60
"""Add the inventory inv to the repository as revid.
88
:param parents: The revision ids of the parents that revision_id
62
:param parents: The revision ids of the parents that revid
89
63
is known to have and are in the repository already.
91
65
returns the sha1 of the serialized inventory.
93
revision_id = osutils.safe_revision_id(revision_id)
94
_mod_revision.check_not_reserved_id(revision_id)
95
assert inv.revision_id is None or inv.revision_id == revision_id, \
96
"Mismatch between inventory revision" \
97
" id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
98
assert inv.root is not None
99
inv_text = self.serialise_inventory(inv)
100
inv_sha1 = osutils.sha_string(inv_text)
67
inv_text = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
68
inv_sha1 = bzrlib.osutils.sha_string(inv_text)
101
69
inv_vf = self.control_weaves.get_weave('inventory',
102
70
self.get_transaction())
103
self._inventory_add_lines(inv_vf, revision_id, parents,
104
osutils.split_lines(inv_text))
71
inv_vf.add_lines(revid, parents, bzrlib.osutils.split_lines(inv_text))
107
def _inventory_add_lines(self, inv_vf, revision_id, parents, lines):
109
for parent in parents:
111
final_parents.append(parent)
113
inv_vf.add_lines(revision_id, final_parents, lines)
116
def add_revision(self, revision_id, rev, inv=None, config=None):
117
"""Add rev to the revision store as revision_id.
75
def add_revision(self, rev_id, rev, inv=None, config=None):
76
"""Add rev to the revision store as rev_id.
119
:param revision_id: the revision id to use.
78
:param rev_id: the revision id to use.
120
79
:param rev: The revision object.
121
80
:param inv: The inventory for the revision. if None, it will be looked
122
81
up in the inventory storer
124
83
If supplied its signature_needed method will be used
125
84
to determine if a signature should be made.
127
revision_id = osutils.safe_revision_id(revision_id)
128
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
130
_mod_revision.check_not_reserved_id(revision_id)
131
86
if config is not None and config.signature_needed():
133
inv = self.get_inventory(revision_id)
88
inv = self.get_inventory(rev_id)
134
89
plaintext = Testament(rev, inv).as_short_text()
135
90
self.store_revision_signature(
136
gpg.GPGStrategy(config), plaintext, revision_id)
137
if not revision_id in self.get_inventory_weave():
91
gpg.GPGStrategy(config), plaintext, rev_id)
92
if not rev_id in self.get_inventory_weave():
139
raise errors.WeaveRevisionNotPresent(revision_id,
94
raise errors.WeaveRevisionNotPresent(rev_id,
140
95
self.get_inventory_weave())
142
97
# yes, this is not suitable for adding with ghosts.
143
self.add_inventory(revision_id, inv, rev.parent_ids)
144
self._revision_store.add_revision(rev, self.get_transaction())
98
self.add_inventory(rev_id, inv, rev.parent_ids)
99
self._revision_store.add_revision(rev, self.get_transaction())
147
102
def _all_possible_ids(self):
148
103
"""Return all the possible revisions that we could find."""
149
104
return self.get_inventory_weave().versions()
151
107
def all_revision_ids(self):
152
108
"""Returns a list of all the revision ids in the repository.
154
This is deprecated because code should generally work on the graph
155
reachable from a particular revision, and ignore any other revisions
156
that might be present. There is no direct replacement method.
158
return self._all_revision_ids()
161
def _all_revision_ids(self):
162
"""Returns a list of all the revision ids in the repository.
164
110
These are in as much topological order as the underlying store can
165
111
present: for weaves ghosts may lead to a lack of correctness until
166
112
the reweave updates the parents list.
208
143
getting file texts, inventories and revisions, then
209
144
this construct will accept instances of those things.
211
super(Repository, self).__init__()
146
object.__init__(self)
212
147
self._format = _format
213
148
# the following are part of the public API for Repository:
214
149
self.bzrdir = a_bzrdir
215
150
self.control_files = control_files
216
151
self._revision_store = _revision_store
217
152
self.text_store = text_store
218
# backwards compatibility
153
# backwards compatability
219
154
self.weave_store = text_store
220
155
# not right yet - should be more semantically clear ?
222
157
self.control_store = control_store
223
158
self.control_weaves = control_store
224
# TODO: make sure to construct the right store classes, etc, depending
225
# on whether escaping is required.
226
self._warn_if_deprecated()
229
return '%s(%r)' % (self.__class__.__name__,
230
self.bzrdir.transport.base)
160
def lock_write(self):
161
self.control_files.lock_write()
164
self.control_files.lock_read()
232
166
def is_locked(self):
233
167
return self.control_files.is_locked()
235
def lock_write(self, token=None):
236
"""Lock this repository for writing.
238
:param token: if this is already locked, then lock_write will fail
239
unless the token matches the existing lock.
240
:returns: a token if this instance supports tokens, otherwise None.
241
:raises TokenLockingNotSupported: when a token is given but this
242
instance doesn't support using token locks.
243
:raises MismatchedToken: if the specified token doesn't match the token
244
of the existing lock.
246
A token should be passed in if you know that you have locked the object
247
some other way, and need to synchronise this object's state with that
250
XXX: this docstring is duplicated in many places, e.g. lockable_files.py
252
return self.control_files.lock_write(token=token)
255
self.control_files.lock_read()
257
def get_physical_lock_status(self):
258
return self.control_files.get_physical_lock_status()
260
def leave_lock_in_place(self):
261
"""Tell this repository not to release the physical lock when this
264
If lock_write doesn't return a token, then this method is not supported.
266
self.control_files.leave_in_place()
268
def dont_leave_lock_in_place(self):
269
"""Tell this repository to release the physical lock when this
270
object is unlocked, even if it didn't originally acquire it.
272
If lock_write doesn't return a token, then this method is not supported.
274
self.control_files.dont_leave_in_place()
277
def gather_stats(self, revid=None, committers=None):
278
"""Gather statistics from a revision id.
280
:param revid: The revision id to gather statistics from, if None, then
281
no revision specific statistics are gathered.
282
:param committers: Optional parameter controlling whether to grab
283
a count of committers from the revision specific statistics.
284
:return: A dictionary of statistics. Currently this contains:
285
committers: The number of committers if requested.
286
firstrev: A tuple with timestamp, timezone for the penultimate left
287
most ancestor of revid, if revid is not the NULL_REVISION.
288
latestrev: A tuple with timestamp, timezone for revid, if revid is
289
not the NULL_REVISION.
290
revisions: The total revision count in the repository.
291
size: An estimate disk size of the repository in bytes.
294
if revid and committers:
295
result['committers'] = 0
296
if revid and revid != _mod_revision.NULL_REVISION:
298
all_committers = set()
299
revisions = self.get_ancestry(revid)
300
# pop the leading None
302
first_revision = None
304
# ignore the revisions in the middle - just grab first and last
305
revisions = revisions[0], revisions[-1]
306
for revision in self.get_revisions(revisions):
307
if not first_revision:
308
first_revision = revision
310
all_committers.add(revision.committer)
311
last_revision = revision
313
result['committers'] = len(all_committers)
314
result['firstrev'] = (first_revision.timestamp,
315
first_revision.timezone)
316
result['latestrev'] = (last_revision.timestamp,
317
last_revision.timezone)
319
# now gather global repository information
320
if self.bzrdir.root_transport.listable():
321
c, t = self._revision_store.total_size(self.get_transaction())
322
result['revisions'] = c
327
170
def missing_revision_ids(self, other, revision_id=None):
328
171
"""Return the revision ids that other has that this does not.
341
183
For instance, if the repository is at URL/.bzr/repository,
342
184
Repository.open(URL) -> a Repository instance.
344
control = bzrdir.BzrDir.open(base)
186
control = bzrlib.bzrdir.BzrDir.open(base)
345
187
return control.open_repository()
347
def copy_content_into(self, destination, revision_id=None):
189
def copy_content_into(self, destination, revision_id=None, basis=None):
348
190
"""Make a complete copy of the content in self into destination.
350
192
This is a destructive operation! Do not use it on existing
353
revision_id = osutils.safe_revision_id(revision_id)
354
return InterRepository.get(self, destination).copy_content(revision_id)
195
return InterRepository.get(self, destination).copy_content(revision_id, basis)
356
197
def fetch(self, source, revision_id=None, pb=None):
357
198
"""Fetch the content required to construct revision_id from source.
359
200
If revision_id is None all content is copied.
361
revision_id = osutils.safe_revision_id(revision_id)
362
inter = InterRepository.get(source, self)
364
return inter.fetch(revision_id=revision_id, pb=pb)
365
except NotImplementedError:
366
raise errors.IncompatibleRepositories(source, self)
368
def get_commit_builder(self, branch, parents, config, timestamp=None,
369
timezone=None, committer=None, revprops=None,
371
"""Obtain a CommitBuilder for this repository.
373
:param branch: Branch to commit to.
374
:param parents: Revision ids of the parents of the new revision.
375
:param config: Configuration to use.
376
:param timestamp: Optional timestamp recorded for commit.
377
:param timezone: Optional timezone for timestamp.
378
:param committer: Optional committer to set for commit.
379
:param revprops: Optional dictionary of revision properties.
380
:param revision_id: Optional revision id.
382
revision_id = osutils.safe_revision_id(revision_id)
383
return _CommitBuilder(self, parents, config, timestamp, timezone,
384
committer, revprops, revision_id)
202
return InterRepository.get(source, self).fetch(revision_id=revision_id,
386
205
def unlock(self):
387
206
self.control_files.unlock()
390
def clone(self, a_bzrdir, revision_id=None):
209
def clone(self, a_bzrdir, revision_id=None, basis=None):
391
210
"""Clone this repository into a_bzrdir using the current format.
393
212
Currently no check is made that the format of this repository and
394
213
the bzrdir format are compatible. FIXME RBC 20060201.
396
:return: The newly created destination repository.
398
# TODO: deprecate after 0.16; cloning this with all its settings is
399
# probably not very useful -- mbp 20070423
400
dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
401
self.copy_content_into(dest_repo, revision_id)
405
def sprout(self, to_bzrdir, revision_id=None):
406
"""Create a descendent repository for new development.
408
Unlike clone, this does not copy the settings of the repository.
410
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
411
dest_repo.fetch(self, revision_id=revision_id)
414
def _create_sprouting_repo(self, a_bzrdir, shared):
415
215
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
416
216
# use target default format.
417
dest_repo = a_bzrdir.create_repository()
217
result = a_bzrdir.create_repository()
218
# FIXME RBC 20060209 split out the repository type to avoid this check ?
219
elif isinstance(a_bzrdir._format,
220
(bzrlib.bzrdir.BzrDirFormat4,
221
bzrlib.bzrdir.BzrDirFormat5,
222
bzrlib.bzrdir.BzrDirFormat6)):
223
result = a_bzrdir.open_repository()
419
# Most control formats need the repository to be specifically
420
# created, but on some old all-in-one formats it's not needed
422
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
423
except errors.UninitializableFormat:
424
dest_repo = a_bzrdir.open_repository()
225
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
226
self.copy_content_into(result, revision_id, basis)
428
230
def has_revision(self, revision_id):
429
231
"""True if this repository has a copy of the revision."""
430
revision_id = osutils.safe_revision_id(revision_id)
431
232
return self._revision_store.has_revision_id(revision_id,
432
233
self.get_transaction())
536
289
@needs_write_lock
537
290
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
538
revision_id = osutils.safe_revision_id(revision_id)
539
291
signature = gpg_strategy.sign(plaintext)
540
292
self._revision_store.add_revision_signature_text(revision_id,
542
294
self.get_transaction())
544
def fileids_altered_by_revision_ids(self, revision_ids):
545
"""Find the file ids and versions affected by revisions.
547
:param revisions: an iterable containing revision ids.
548
:return: a dictionary mapping altered file-ids to an iterable of
549
revision_ids. Each altered file-ids has the exact revision_ids that
550
altered it listed explicitly.
552
assert self._serializer.support_altered_by_hack, \
553
("fileids_altered_by_revision_ids only supported for branches "
554
"which store inventory as unnested xml, not on %r" % self)
555
selected_revision_ids = set(osutils.safe_revision_id(r)
556
for r in revision_ids)
557
w = self.get_inventory_weave()
560
# this code needs to read every new line in every inventory for the
561
# inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
562
# not present in one of those inventories is unnecessary but not
296
def fileid_involved_between_revs(self, from_revid, to_revid):
297
"""Find file_id(s) which are involved in the changes between revisions.
299
This determines the set of revisions which are involved, and then
300
finds all file ids affected by those revisions.
302
w = self.get_inventory_weave()
303
from_set = set(w.get_ancestry(from_revid))
304
to_set = set(w.get_ancestry(to_revid))
305
changed = to_set.difference(from_set)
306
return self._fileid_involved_by_set(changed)
308
def fileid_involved(self, last_revid=None):
309
"""Find all file_ids modified in the ancestry of last_revid.
311
:param last_revid: If None, last_revision() will be used.
313
w = self.get_inventory_weave()
315
changed = set(w.versions())
317
changed = set(w.get_ancestry(last_revid))
318
return self._fileid_involved_by_set(changed)
320
def fileid_involved_by_set(self, changes):
321
"""Find all file_ids modified by the set of revisions passed in.
323
:param changes: A set() of revision ids
325
# TODO: jam 20060119 This line does *nothing*, remove it.
326
# or better yet, change _fileid_involved_by_set so
327
# that it takes the inventory weave, rather than
328
# pulling it out by itself.
329
return self._fileid_involved_by_set(changes)
331
def _fileid_involved_by_set(self, changes):
332
"""Find the set of file-ids affected by the set of revisions.
334
:param changes: A set() of revision ids.
335
:return: A set() of file ids.
337
This peaks at the Weave, interpreting each line, looking to
338
see if it mentions one of the revisions. And if so, includes
339
the file id mentioned.
340
This expects both the Weave format, and the serialization
341
to have a single line per file/directory, and to have
342
fileid="" and revision="" on that line.
344
assert isinstance(self._format, (RepositoryFormat5,
347
RepositoryFormatKnit1)), \
348
"fileid_involved only supported for branches which store inventory as unnested xml"
350
w = self.get_inventory_weave()
353
# this code needs to read every line in every inventory for the
354
# inventories [changes]. Seeing a line twice is ok. Seeing a line
355
# not pesent in one of those inventories is unnecessary and not
563
356
# harmful because we are filtering by the revision id marker in the
564
# inventory lines : we only select file ids altered in one of those
565
# revisions. We don't need to see all lines in the inventory because
357
# inventory lines to only select file ids altered in one of those
358
# revisions. We dont need to see all lines in the inventory because
566
359
# only those added in an inventory in rev X can contain a revision=X
568
unescape_revid_cache = {}
569
unescape_fileid_cache = {}
571
# jam 20061218 In a big fetch, this handles hundreds of thousands
572
# of lines, so it has had a lot of inlining and optimizing done.
573
# Sorry that it is a little bit messy.
574
# Move several functions to be local variables, since this is a long
576
search = self._file_ids_altered_regex.search
577
unescape = _unescape_xml
578
setdefault = result.setdefault
579
pb = ui.ui_factory.nested_progress_bar()
581
for line in w.iter_lines_added_or_present_in_versions(
582
selected_revision_ids, pb=pb):
586
# One call to match.group() returning multiple items is quite a
587
# bit faster than 2 calls to match.group() each returning 1
588
file_id, revision_id = match.group('file_id', 'revision_id')
590
# Inlining the cache lookups helps a lot when you make 170,000
591
# lines and 350k ids, versus 8.4 unique ids.
592
# Using a cache helps in 2 ways:
593
# 1) Avoids unnecessary decoding calls
594
# 2) Re-uses cached strings, which helps in future set and
596
# (2) is enough that removing encoding entirely along with
597
# the cache (so we are using plain strings) results in no
598
# performance improvement.
600
revision_id = unescape_revid_cache[revision_id]
602
unescaped = unescape(revision_id)
603
unescape_revid_cache[revision_id] = unescaped
604
revision_id = unescaped
606
if revision_id in selected_revision_ids:
608
file_id = unescape_fileid_cache[file_id]
610
unescaped = unescape(file_id)
611
unescape_fileid_cache[file_id] = unescaped
613
setdefault(file_id, set()).add(revision_id)
361
for line in w.iter_lines_added_or_present_in_versions(changes):
362
start = line.find('file_id="')+9
363
if start < 9: continue
364
end = line.find('"', start)
366
file_id = _unescape_xml(line[start:end])
368
# check if file_id is already present
369
if file_id in file_ids: continue
371
start = line.find('revision="')+10
372
if start < 10: continue
373
end = line.find('"', start)
375
revision_id = _unescape_xml(line[start:end])
376
if revision_id in changes:
377
file_ids.add(file_id)
619
381
def get_inventory_weave(self):
624
386
def get_inventory(self, revision_id):
625
387
"""Get Inventory object by hash."""
626
# TODO: jam 20070210 Technically we don't need to sanitize, since all
627
# called functions must sanitize.
628
revision_id = osutils.safe_revision_id(revision_id)
629
return self.deserialise_inventory(
630
revision_id, self.get_inventory_xml(revision_id))
632
def deserialise_inventory(self, revision_id, xml):
633
"""Transform the xml into an inventory object.
635
:param revision_id: The expected revision id of the inventory.
636
:param xml: A serialised inventory.
638
revision_id = osutils.safe_revision_id(revision_id)
639
result = self._serializer.read_inventory_from_string(xml)
640
result.root.revision = revision_id
643
def serialise_inventory(self, inv):
644
return self._serializer.write_inventory_to_string(inv)
388
xml = self.get_inventory_xml(revision_id)
389
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
647
392
def get_inventory_xml(self, revision_id):
648
393
"""Get inventory XML as a file object."""
649
revision_id = osutils.safe_revision_id(revision_id)
651
assert isinstance(revision_id, str), type(revision_id)
395
assert isinstance(revision_id, basestring), type(revision_id)
652
396
iw = self.get_inventory_weave()
653
397
return iw.get_text(revision_id)
654
398
except IndexError:
655
raise errors.HistoryMissing(self, 'inventory', revision_id)
399
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
658
402
def get_inventory_sha1(self, revision_id):
659
403
"""Return the sha1 hash of the inventory entry
661
# TODO: jam 20070210 Shouldn't this be deprecated / removed?
662
revision_id = osutils.safe_revision_id(revision_id)
663
405
return self.get_revision(revision_id).inventory_sha1
666
408
def get_revision_graph(self, revision_id=None):
667
409
"""Return a dictionary containing the revision graph.
669
:param revision_id: The revision_id to get a graph from. If None, then
670
the entire revision graph is returned. This is a deprecated mode of
671
operation and will be removed in the future.
672
411
:return: a dictionary of revision_id->revision_parents_list.
674
# special case NULL_REVISION
675
if revision_id == _mod_revision.NULL_REVISION:
677
revision_id = osutils.safe_revision_id(revision_id)
678
a_weave = self.get_inventory_weave()
679
all_revisions = self._eliminate_revisions_not_present(
681
entire_graph = dict([(node, a_weave.get_parents(node)) for
413
weave = self.get_inventory_weave()
414
all_revisions = self._eliminate_revisions_not_present(weave.versions())
415
entire_graph = dict([(node, weave.get_parents(node)) for
682
416
node in all_revisions])
683
417
if revision_id is None:
684
418
return entire_graph
782
487
raise NotImplementedError(self.is_shared)
784
489
@needs_write_lock
785
def reconcile(self, other=None, thorough=False):
786
491
"""Reconcile this repository."""
787
492
from bzrlib.reconcile import RepoReconciler
788
reconciler = RepoReconciler(self, thorough=thorough)
493
reconciler = RepoReconciler(self)
789
494
reconciler.reconcile()
790
495
return reconciler
793
498
def revision_tree(self, revision_id):
794
499
"""Return Tree for a revision on this branch.
796
`revision_id` may be None for the empty tree revision.
501
`revision_id` may be None for the null revision, in which case
502
an `EmptyTree` is returned."""
798
503
# TODO: refactor this to use an existing revision object
799
504
# so we don't need to read it in twice.
800
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
801
return RevisionTree(self, Inventory(root_id=None),
802
_mod_revision.NULL_REVISION)
505
if revision_id is None or revision_id == NULL_REVISION:
804
revision_id = osutils.safe_revision_id(revision_id)
805
508
inv = self.get_revision_inventory(revision_id)
806
509
return RevisionTree(self, inv, revision_id)
809
def revision_trees(self, revision_ids):
810
"""Return Tree for a revision on this branch.
812
`revision_id` may not be None or 'null:'"""
813
assert None not in revision_ids
814
assert _mod_revision.NULL_REVISION not in revision_ids
815
texts = self.get_inventory_weave().get_texts(revision_ids)
816
for text, revision_id in zip(texts, revision_ids):
817
inv = self.deserialise_inventory(revision_id, text)
818
yield RevisionTree(self, inv, revision_id)
821
def get_ancestry(self, revision_id, topo_sorted=True):
512
def get_ancestry(self, revision_id):
822
513
"""Return a list of revision-ids integrated by a revision.
824
The first element of the list is always None, indicating the origin
825
revision. This might change when we have history horizons, or
826
perhaps we should have a new API.
828
515
This is topologically sorted.
830
517
if revision_id is None:
832
revision_id = osutils.safe_revision_id(revision_id)
833
519
if not self.has_revision(revision_id):
834
520
raise errors.NoSuchRevision(self, revision_id)
835
521
w = self.get_inventory_weave()
836
candidates = w.get_ancestry(revision_id, topo_sorted)
522
candidates = w.get_ancestry(revision_id)
837
523
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
844
530
- it writes to stdout, it assumes that that is valid etc. Fix
845
531
by creating a new more flexible convenience function.
847
revision_id = osutils.safe_revision_id(revision_id)
848
533
tree = self.revision_tree(revision_id)
849
534
# use inventory as it was in that revision
850
535
file_id = tree.inventory.path2id(file)
852
# TODO: jam 20060427 Write a test for this code path
853
# it had a bug in it, and was raising the wrong
855
raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
537
raise BzrError("%r is not present in revision %s" % (file, revno))
539
revno = self.revision_id_to_revno(revision_id)
540
except errors.NoSuchRevision:
541
# TODO: This should not be BzrError,
542
# but NoSuchFile doesn't fit either
543
raise BzrError('%r is not present in revision %s'
544
% (file, revision_id))
546
raise BzrError('%r is not present in revision %s'
856
548
tree.print_file(file_id)
858
550
def get_transaction(self):
859
551
return self.control_files.get_transaction()
861
def revision_parents(self, revision_id):
862
revision_id = osutils.safe_revision_id(revision_id)
863
return self.get_inventory_weave().parent_names(revision_id)
865
def get_parents(self, revision_ids):
866
"""See StackedParentsProvider.get_parents"""
868
for revision_id in revision_ids:
869
if revision_id == _mod_revision.NULL_REVISION:
873
parents = self.get_revision(revision_id).parent_ids
874
except errors.NoSuchRevision:
877
if len(parents) == 0:
878
parents = [_mod_revision.NULL_REVISION]
879
parents_list.append(parents)
882
def _make_parents_provider(self):
885
def get_graph(self, other_repository=None):
886
"""Return the graph walker for this repository format"""
887
parents_provider = self._make_parents_provider()
888
if (other_repository is not None and
889
other_repository.bzrdir.transport.base !=
890
self.bzrdir.transport.base):
891
parents_provider = graph._StackedParentsProvider(
892
[parents_provider, other_repository._make_parents_provider()])
893
return graph.Graph(parents_provider)
553
def revision_parents(self, revid):
554
return self.get_inventory_weave().parent_names(revid)
895
556
@needs_write_lock
896
557
def set_make_working_trees(self, new_value):
911
572
@needs_write_lock
912
573
def sign_revision(self, revision_id, gpg_strategy):
913
revision_id = osutils.safe_revision_id(revision_id)
914
574
plaintext = Testament.from_revision(self, revision_id).as_short_text()
915
575
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
918
578
def has_signature_for_revision_id(self, revision_id):
919
579
"""Query for a revision signature for revision_id in the repository."""
920
revision_id = osutils.safe_revision_id(revision_id)
921
580
return self._revision_store.has_signature(revision_id,
922
581
self.get_transaction())
925
584
def get_signature_text(self, revision_id):
926
585
"""Return the text for a signature."""
927
revision_id = osutils.safe_revision_id(revision_id)
928
586
return self._revision_store.get_signature_text(revision_id,
929
587
self.get_transaction())
590
class AllInOneRepository(Repository):
591
"""Legacy support - the repository behaviour for all-in-one branches."""
593
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
594
# we reuse one control files instance.
595
dir_mode = a_bzrdir._control_files._dir_mode
596
file_mode = a_bzrdir._control_files._file_mode
598
def get_store(name, compressed=True, prefixed=False):
599
# FIXME: This approach of assuming stores are all entirely compressed
600
# or entirely uncompressed is tidy, but breaks upgrade from
601
# some existing branches where there's a mixture; we probably
602
# still want the option to look for both.
603
relpath = a_bzrdir._control_files._escape(name)
604
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
605
prefixed=prefixed, compressed=compressed,
608
#if self._transport.should_cache():
609
# cache_path = os.path.join(self.cache_root, name)
610
# os.mkdir(cache_path)
611
# store = bzrlib.store.CachedStore(store, cache_path)
614
# not broken out yet because the controlweaves|inventory_store
615
# and text_store | weave_store bits are still different.
616
if isinstance(_format, RepositoryFormat4):
617
# cannot remove these - there is still no consistent api
618
# which allows access to this old info.
619
self.inventory_store = get_store('inventory-store')
620
text_store = get_store('text-store')
621
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
932
def check(self, revision_ids):
933
"""Check consistency of all history of given revision_ids.
935
Different repository implementations should override _check().
937
:param revision_ids: A non-empty list of revision_ids whose ancestry
938
will be checked. Typically the last revision_id of a branch.
625
"""AllInOne repositories cannot be shared."""
629
def set_make_working_trees(self, new_value):
630
"""Set the policy flag for making working trees when creating branches.
632
This only applies to branches that use this repository.
634
The default is 'True'.
635
:param new_value: True to restore the default, False to disable making
941
raise ValueError("revision_ids must be non-empty in %s.check"
943
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
944
return self._check(revision_ids)
946
def _check(self, revision_ids):
947
result = check.Check(self)
951
def _warn_if_deprecated(self):
952
global _deprecation_warning_done
953
if _deprecation_warning_done:
955
_deprecation_warning_done = True
956
warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
957
% (self._format, self.bzrdir.transport.base))
959
def supports_rich_root(self):
960
return self._format.rich_root_data
962
def _check_ascii_revisionid(self, revision_id, method):
963
"""Private helper for ascii-only repositories."""
964
# weave repositories refuse to store revisionids that are non-ascii.
965
if revision_id is not None:
966
# weaves require ascii revision ids.
967
if isinstance(revision_id, unicode):
969
revision_id.encode('ascii')
970
except UnicodeEncodeError:
971
raise errors.NonAsciiRevisionId(method, self)
974
revision_id.decode('ascii')
975
except UnicodeDecodeError:
976
raise errors.NonAsciiRevisionId(method, self)
980
# remove these delegates a while after bzr 0.15
981
def __make_delegated(name, from_module):
982
def _deprecated_repository_forwarder():
983
symbol_versioning.warn('%s moved to %s in bzr 0.15'
984
% (name, from_module),
987
m = __import__(from_module, globals(), locals(), [name])
989
return getattr(m, name)
990
except AttributeError:
991
raise AttributeError('module %s has no name %s'
993
globals()[name] = _deprecated_repository_forwarder
996
'AllInOneRepository',
997
'WeaveMetaDirRepository',
998
'PreSplitOutRepositoryFormat',
1000
'RepositoryFormat5',
1001
'RepositoryFormat6',
1002
'RepositoryFormat7',
1004
__make_delegated(_name, 'bzrlib.repofmt.weaverepo')
1008
'RepositoryFormatKnit',
1009
'RepositoryFormatKnit1',
1011
__make_delegated(_name, 'bzrlib.repofmt.knitrepo')
1014
def install_revision(repository, rev, revision_tree):
1015
"""Install all revision data into a repository."""
1016
present_parents = []
1018
for p_id in rev.parent_ids:
1019
if repository.has_revision(p_id):
1020
present_parents.append(p_id)
1021
parent_trees[p_id] = repository.revision_tree(p_id)
1023
parent_trees[p_id] = repository.revision_tree(None)
1025
inv = revision_tree.inventory
1026
entries = inv.iter_entries()
1027
# backwards compatability hack: skip the root id.
1028
if not repository.supports_rich_root():
1029
path, root = entries.next()
1030
if root.revision != rev.revision_id:
1031
raise errors.IncompatibleRevision(repr(repository))
1032
# Add the texts that are not already present
1033
for path, ie in entries:
1034
w = repository.weave_store.get_weave_or_empty(ie.file_id,
1035
repository.get_transaction())
1036
if ie.revision not in w:
1038
# FIXME: TODO: The following loop *may* be overlapping/duplicate
1039
# with InventoryEntry.find_previous_heads(). if it is, then there
1040
# is a latent bug here where the parents may have ancestors of each
1042
for revision, tree in parent_trees.iteritems():
1043
if ie.file_id not in tree:
1045
parent_id = tree.inventory[ie.file_id].revision
1046
if parent_id in text_parents:
1048
text_parents.append(parent_id)
1050
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
1051
repository.get_transaction())
1052
lines = revision_tree.get_file(ie.file_id).readlines()
1053
vfile.add_lines(rev.revision_id, text_parents, lines)
1055
# install the inventory
1056
repository.add_inventory(rev.revision_id, inv, present_parents)
1057
except errors.RevisionAlreadyPresent:
1059
repository.add_revision(rev.revision_id, rev, inv)
638
raise NotImplementedError(self.set_make_working_trees)
640
def make_working_trees(self):
641
"""Returns the policy for making working trees on new branches."""
1062
645
class MetaDirRepository(Repository):
1100
684
return not self.control_files._transport.has('no-working-trees')
1103
class RepositoryFormatRegistry(registry.Registry):
1104
"""Registry of RepositoryFormats.
1107
def get(self, format_string):
1108
r = registry.Registry.get(self, format_string)
687
class KnitRepository(MetaDirRepository):
688
"""Knit format repository."""
691
def all_revision_ids(self):
692
"""See Repository.all_revision_ids()."""
693
return self._revision_store.all_revision_ids(self.get_transaction())
695
def fileid_involved_between_revs(self, from_revid, to_revid):
696
"""Find file_id(s) which are involved in the changes between revisions.
698
This determines the set of revisions which are involved, and then
699
finds all file ids affected by those revisions.
701
vf = self._get_revision_vf()
702
from_set = set(vf.get_ancestry(from_revid))
703
to_set = set(vf.get_ancestry(to_revid))
704
changed = to_set.difference(from_set)
705
return self._fileid_involved_by_set(changed)
707
def fileid_involved(self, last_revid=None):
708
"""Find all file_ids modified in the ancestry of last_revid.
710
:param last_revid: If None, last_revision() will be used.
713
changed = set(self.all_revision_ids())
715
changed = set(self.get_ancestry(last_revid))
718
return self._fileid_involved_by_set(changed)
721
def get_ancestry(self, revision_id):
722
"""Return a list of revision-ids integrated by a revision.
724
This is topologically sorted.
726
if revision_id is None:
728
vf = self._get_revision_vf()
730
return [None] + vf.get_ancestry(revision_id)
731
except errors.RevisionNotPresent:
732
raise errors.NoSuchRevision(self, revision_id)
735
def get_revision(self, revision_id):
736
"""Return the Revision object for a named revision"""
737
return self.get_revision_reconcile(revision_id)
740
def get_revision_graph(self, revision_id=None):
741
"""Return a dictionary containing the revision graph.
743
:return: a dictionary of revision_id->revision_parents_list.
745
weave = self._get_revision_vf()
746
entire_graph = weave.get_graph()
747
if revision_id is None:
748
return weave.get_graph()
749
elif revision_id not in weave:
750
raise errors.NoSuchRevision(self, revision_id)
752
# add what can be reached from revision_id
754
pending = set([revision_id])
755
while len(pending) > 0:
757
result[node] = weave.get_parents(node)
758
for revision_id in result[node]:
759
if revision_id not in result:
760
pending.add(revision_id)
764
def get_revision_graph_with_ghosts(self, revision_ids=None):
765
"""Return a graph of the revisions with ghosts marked as applicable.
767
:param revision_ids: an iterable of revisions to graph or None for all.
768
:return: a Graph object with the graph reachable from revision_ids.
771
vf = self._get_revision_vf()
772
versions = vf.versions()
774
pending = set(self.all_revision_ids())
777
pending = set(revision_ids)
778
required = set(revision_ids)
781
revision_id = pending.pop()
782
if not revision_id in versions:
783
if revision_id in required:
784
raise errors.NoSuchRevision(self, revision_id)
786
result.add_ghost(revision_id)
788
parent_ids = vf.get_parents_with_ghosts(revision_id)
789
for parent_id in parent_ids:
790
# is this queued or done ?
791
if (parent_id not in pending and
792
parent_id not in done):
794
pending.add(parent_id)
795
result.add_node(revision_id, parent_ids)
799
def _get_revision_vf(self):
800
""":return: a versioned file containing the revisions."""
801
vf = self._revision_store.get_revision_file(self.get_transaction())
806
"""Reconcile this repository."""
807
from bzrlib.reconcile import KnitReconciler
808
reconciler = KnitReconciler(self)
809
reconciler.reconcile()
1114
format_registry = RepositoryFormatRegistry()
1115
"""Registry of formats, indexed by their identifying format string.
1117
This can contain either format instances themselves, or classes/factories that
1118
can be called to obtain one.
1122
#####################################################################
1123
# Repository Formats
812
def revision_parents(self, revid):
813
return self._get_revision_vf().get_parents(rev_id)
1125
815
class RepositoryFormat(object):
1126
816
"""A repository format.
1284
939
raise NotImplementedError(self.open)
942
def register_format(klass, format):
943
klass._formats[format.get_format_string()] = format
946
def set_default_format(klass, format):
947
klass._default_format = format
950
def unregister_format(klass, format):
951
assert klass._formats[format.get_format_string()] is format
952
del klass._formats[format.get_format_string()]
955
class PreSplitOutRepositoryFormat(RepositoryFormat):
956
"""Base class for the pre split out repository formats."""
958
def initialize(self, a_bzrdir, shared=False, _internal=False):
959
"""Create a weave repository.
961
TODO: when creating split out bzr branch formats, move this to a common
962
base for Format5, Format6. or something like that.
964
from bzrlib.weavefile import write_weave_v5
965
from bzrlib.weave import Weave
968
raise errors.IncompatibleFormat(self, a_bzrdir._format)
971
# always initialized when the bzrdir is.
972
return self.open(a_bzrdir, _found=True)
974
# Create an empty weave
976
bzrlib.weavefile.write_weave_v5(Weave(), sio)
977
empty_weave = sio.getvalue()
979
mutter('creating repository in %s.', a_bzrdir.transport.base)
980
dirs = ['revision-store', 'weaves']
981
files = [('inventory.weave', StringIO(empty_weave)),
984
# FIXME: RBC 20060125 dont peek under the covers
985
# NB: no need to escape relative paths that are url safe.
986
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock',
988
control_files.create_lock()
989
control_files.lock_write()
990
control_files._transport.mkdir_multi(dirs,
991
mode=control_files._dir_mode)
993
for file, content in files:
994
control_files.put(file, content)
996
control_files.unlock()
997
return self.open(a_bzrdir, _found=True)
999
def _get_control_store(self, repo_transport, control_files):
1000
"""Return the control store for this repository."""
1001
return self._get_versioned_file_store('',
1006
def _get_text_store(self, transport, control_files):
1007
"""Get a store for file texts for this format."""
1008
raise NotImplementedError(self._get_text_store)
1010
def open(self, a_bzrdir, _found=False):
1011
"""See RepositoryFormat.open()."""
1013
# we are being called directly and must probe.
1014
raise NotImplementedError
1016
repo_transport = a_bzrdir.get_repository_transport(None)
1017
control_files = a_bzrdir._control_files
1018
text_store = self._get_text_store(repo_transport, control_files)
1019
control_store = self._get_control_store(repo_transport, control_files)
1020
_revision_store = self._get_revision_store(repo_transport, control_files)
1021
return AllInOneRepository(_format=self,
1023
_revision_store=_revision_store,
1024
control_store=control_store,
1025
text_store=text_store)
1028
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1029
"""Bzr repository format 4.
1031
This repository format has:
1033
- TextStores for texts, inventories,revisions.
1035
This format is deprecated: it indexes texts using a text id which is
1036
removed in format 5; initializationa and write support for this format
1041
super(RepositoryFormat4, self).__init__()
1042
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
1044
def initialize(self, url, shared=False, _internal=False):
1045
"""Format 4 branches cannot be created."""
1046
raise errors.UninitializableFormat(self)
1048
def is_supported(self):
1049
"""Format 4 is not supported.
1051
It is not supported because the model changed from 4 to 5 and the
1052
conversion logic is expensive - so doing it on the fly was not
1057
def _get_control_store(self, repo_transport, control_files):
1058
"""Format 4 repositories have no formal control store at this point.
1060
This will cause any control-file-needing apis to fail - this is desired.
1064
def _get_revision_store(self, repo_transport, control_files):
1065
"""See RepositoryFormat._get_revision_store()."""
1066
from bzrlib.xml4 import serializer_v4
1067
return self._get_text_rev_store(repo_transport,
1070
serializer=serializer_v4)
1072
def _get_text_store(self, transport, control_files):
1073
"""See RepositoryFormat._get_text_store()."""
1076
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1077
"""Bzr control format 5.
1079
This repository format has:
1080
- weaves for file texts and inventory
1082
- TextStores for revisions and signatures.
1086
super(RepositoryFormat5, self).__init__()
1087
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
1089
def _get_revision_store(self, repo_transport, control_files):
1090
"""See RepositoryFormat._get_revision_store()."""
1091
"""Return the revision store object for this a_bzrdir."""
1092
return self._get_text_rev_store(repo_transport,
1097
def _get_text_store(self, transport, control_files):
1098
"""See RepositoryFormat._get_text_store()."""
1099
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1102
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1103
"""Bzr control format 6.
1105
This repository format has:
1106
- weaves for file texts and inventory
1107
- hash subdirectory based stores.
1108
- TextStores for revisions and signatures.
1112
super(RepositoryFormat6, self).__init__()
1113
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
1115
def _get_revision_store(self, repo_transport, control_files):
1116
"""See RepositoryFormat._get_revision_store()."""
1117
return self._get_text_rev_store(repo_transport,
1123
def _get_text_store(self, transport, control_files):
1124
"""See RepositoryFormat._get_text_store()."""
1125
return self._get_versioned_file_store('weaves', transport, control_files)
1287
1128
class MetaDirRepositoryFormat(RepositoryFormat):
1288
"""Common base class for the new repositories using the metadir layout."""
1290
rich_root_data = False
1291
supports_tree_reference = False
1292
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1129
"""Common base class for the new repositories using the metadir layour."""
1294
1131
def __init__(self):
1295
1132
super(MetaDirRepositoryFormat, self).__init__()
1133
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
1297
1135
def _create_control_files(self, a_bzrdir):
1298
1136
"""Create the required files and the initial control_files object."""
1299
# FIXME: RBC 20060125 don't peek under the covers
1137
# FIXME: RBC 20060125 dont peek under the covers
1300
1138
# NB: no need to escape relative paths that are url safe.
1301
1139
repository_transport = a_bzrdir.get_repository_transport(self)
1302
control_files = lockable_files.LockableFiles(repository_transport,
1303
'lock', lockdir.LockDir)
1140
control_files = LockableFiles(repository_transport, 'lock', LockDir)
1304
1141
control_files.create_lock()
1305
1142
return control_files
1321
1158
control_files.unlock()
1161
class RepositoryFormat7(MetaDirRepositoryFormat):
1162
"""Bzr repository 7.
1164
This repository format has:
1165
- weaves for file texts and inventory
1166
- hash subdirectory based stores.
1167
- TextStores for revisions and signatures.
1168
- a format marker of its own
1169
- an optional 'shared-storage' flag
1170
- an optional 'no-working-trees' flag
1173
def _get_control_store(self, repo_transport, control_files):
1174
"""Return the control store for this repository."""
1175
return self._get_versioned_file_store('',
1180
def get_format_string(self):
1181
"""See RepositoryFormat.get_format_string()."""
1182
return "Bazaar-NG Repository format 7"
1184
def _get_revision_store(self, repo_transport, control_files):
1185
"""See RepositoryFormat._get_revision_store()."""
1186
return self._get_text_rev_store(repo_transport,
1193
def _get_text_store(self, transport, control_files):
1194
"""See RepositoryFormat._get_text_store()."""
1195
return self._get_versioned_file_store('weaves',
1199
def initialize(self, a_bzrdir, shared=False):
1200
"""Create a weave repository.
1202
:param shared: If true the repository will be initialized as a shared
1205
from bzrlib.weavefile import write_weave_v5
1206
from bzrlib.weave import Weave
1208
# Create an empty weave
1210
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1211
empty_weave = sio.getvalue()
1213
mutter('creating repository in %s.', a_bzrdir.transport.base)
1214
dirs = ['revision-store', 'weaves']
1215
files = [('inventory.weave', StringIO(empty_weave)),
1217
utf8_files = [('format', self.get_format_string())]
1219
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1220
return self.open(a_bzrdir=a_bzrdir, _found=True)
1222
def open(self, a_bzrdir, _found=False, _override_transport=None):
1223
"""See RepositoryFormat.open().
1225
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1226
repository at a slightly different url
1227
than normal. I.e. during 'upgrade'.
1230
format = RepositoryFormat.find_format(a_bzrdir)
1231
assert format.__class__ == self.__class__
1232
if _override_transport is not None:
1233
repo_transport = _override_transport
1235
repo_transport = a_bzrdir.get_repository_transport(None)
1236
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1237
text_store = self._get_text_store(repo_transport, control_files)
1238
control_store = self._get_control_store(repo_transport, control_files)
1239
_revision_store = self._get_revision_store(repo_transport, control_files)
1240
return MetaDirRepository(_format=self,
1242
control_files=control_files,
1243
_revision_store=_revision_store,
1244
control_store=control_store,
1245
text_store=text_store)
1248
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1249
"""Bzr repository knit format 1.
1251
This repository format has:
1252
- knits for file texts and inventory
1253
- hash subdirectory based stores.
1254
- knits for revisions and signatures
1255
- TextStores for revisions and signatures.
1256
- a format marker of its own
1257
- an optional 'shared-storage' flag
1258
- an optional 'no-working-trees' flag
1262
def _get_control_store(self, repo_transport, control_files):
1263
"""Return the control store for this repository."""
1264
return self._get_versioned_file_store('',
1268
versionedfile_class=KnitVersionedFile)
1270
def get_format_string(self):
1271
"""See RepositoryFormat.get_format_string()."""
1272
return "Bazaar-NG Knit Repository Format 1"
1274
def _get_revision_store(self, repo_transport, control_files):
1275
"""See RepositoryFormat._get_revision_store()."""
1276
from bzrlib.store.revision.knit import KnitRevisionStore
1277
versioned_file_store = VersionedFileStore(
1279
file_mode = control_files._file_mode,
1282
versionedfile_class=KnitVersionedFile)
1283
return KnitRevisionStore(versioned_file_store)
1285
def _get_text_store(self, transport, control_files):
1286
"""See RepositoryFormat._get_text_store()."""
1287
return self._get_versioned_file_store('knits',
1290
versionedfile_class=KnitVersionedFile)
1292
def initialize(self, a_bzrdir, shared=False):
1293
"""Create a knit format 1 repository.
1295
:param shared: If true the repository will be initialized as a shared
1297
XXX NOTE that this current uses a Weave for testing and will become
1298
A Knit in due course.
1300
from bzrlib.weavefile import write_weave_v5
1301
from bzrlib.weave import Weave
1303
# Create an empty weave
1305
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1306
empty_weave = sio.getvalue()
1308
mutter('creating repository in %s.', a_bzrdir.transport.base)
1309
dirs = ['revision-store', 'knits', 'control']
1310
files = [('control/inventory.weave', StringIO(empty_weave)),
1312
utf8_files = [('format', self.get_format_string())]
1314
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1315
repo_transport = a_bzrdir.get_repository_transport(None)
1316
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1317
control_store = self._get_control_store(repo_transport, control_files)
1318
transaction = bzrlib.transactions.WriteTransaction()
1319
# trigger a write of the inventory store.
1320
control_store.get_weave_or_empty('inventory', transaction)
1321
_revision_store = self._get_revision_store(repo_transport, control_files)
1322
_revision_store.has_revision_id('A', transaction)
1323
_revision_store.get_signature_file(transaction)
1324
return self.open(a_bzrdir=a_bzrdir, _found=True)
1326
def open(self, a_bzrdir, _found=False, _override_transport=None):
1327
"""See RepositoryFormat.open().
1329
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1330
repository at a slightly different url
1331
than normal. I.e. during 'upgrade'.
1334
format = RepositoryFormat.find_format(a_bzrdir)
1335
assert format.__class__ == self.__class__
1336
if _override_transport is not None:
1337
repo_transport = _override_transport
1339
repo_transport = a_bzrdir.get_repository_transport(None)
1340
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1341
text_store = self._get_text_store(repo_transport, control_files)
1342
control_store = self._get_control_store(repo_transport, control_files)
1343
_revision_store = self._get_revision_store(repo_transport, control_files)
1344
return KnitRepository(_format=self,
1346
control_files=control_files,
1347
_revision_store=_revision_store,
1348
control_store=control_store,
1349
text_store=text_store)
1324
1352
# formats which have no format string are not discoverable
1325
# and not independently creatable, so are not registered. They're
1326
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
1327
# needed, it's constructed directly by the BzrDir. Non-native formats where
1328
# the repository is not separately opened are similar.
1330
format_registry.register_lazy(
1331
'Bazaar-NG Repository format 7',
1332
'bzrlib.repofmt.weaverepo',
1335
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1336
# default control directory format
1338
format_registry.register_lazy(
1339
'Bazaar-NG Knit Repository Format 1',
1340
'bzrlib.repofmt.knitrepo',
1341
'RepositoryFormatKnit1',
1343
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1345
format_registry.register_lazy(
1346
'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
1347
'bzrlib.repofmt.knitrepo',
1348
'RepositoryFormatKnit3',
1353
# and not independently creatable, so are not registered.
1354
_default_format = RepositoryFormat7()
1355
RepositoryFormat.register_format(_default_format)
1356
RepositoryFormat.register_format(RepositoryFormatKnit1())
1357
RepositoryFormat.set_default_format(_default_format)
1358
_legacy_formats = [RepositoryFormat4(),
1359
RepositoryFormat5(),
1360
RepositoryFormat6()]
1352
1363
class InterRepository(InterObject):
1408
1471
# that we've decided we need.
1409
1472
return [rev_id for rev_id in source_ids if rev_id in result_set]
1412
class InterSameDataRepository(InterRepository):
1413
"""Code for converting between repositories that represent the same data.
1415
Data format and model must match for this to work.
1419
def _get_repo_format_to_test(self):
1420
"""Repository format for testing with."""
1421
return RepositoryFormat.get_default_format()
1424
def is_compatible(source, target):
1425
if source.supports_rich_root() != target.supports_rich_root():
1427
if source._serializer != target._serializer:
1432
def copy_content(self, revision_id=None):
1433
"""Make a complete copy of the content in self into destination.
1435
This copies both the repository's revision data, and configuration information
1436
such as the make_working_trees setting.
1438
This is a destructive operation! Do not use it on existing
1441
:param revision_id: Only copy the content needed to construct
1442
revision_id and its parents.
1475
"""Release the locks on source and target."""
1445
self.target.set_make_working_trees(self.source.make_working_trees())
1446
except NotImplementedError:
1448
# TODO: jam 20070210 This is fairly internal, so we should probably
1449
# just assert that revision_id is not unicode.
1450
revision_id = osutils.safe_revision_id(revision_id)
1451
# but don't bother fetching if we have the needed data now.
1452
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1453
self.target.has_revision(revision_id)):
1455
self.target.fetch(self.source, revision_id=revision_id)
1458
def fetch(self, revision_id=None, pb=None):
1459
"""See InterRepository.fetch()."""
1460
from bzrlib.fetch import GenericRepoFetcher
1461
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1462
self.source, self.source._format, self.target,
1463
self.target._format)
1464
# TODO: jam 20070210 This should be an assert, not a translate
1465
revision_id = osutils.safe_revision_id(revision_id)
1466
f = GenericRepoFetcher(to_repository=self.target,
1467
from_repository=self.source,
1468
last_revision=revision_id,
1470
return f.count_copied, f.failed_revisions
1473
class InterWeaveRepo(InterSameDataRepository):
1477
self.target.unlock()
1479
self.source.unlock()
1482
class InterWeaveRepo(InterRepository):
1474
1483
"""Optimised code paths between Weave based repositories."""
1477
def _get_repo_format_to_test(self):
1478
from bzrlib.repofmt import weaverepo
1479
return weaverepo.RepositoryFormat7()
1485
_matching_repo_format = _default_format
1486
"""Repository format for testing with."""
1482
1489
def is_compatible(source, target):
1483
1490
"""Be compatible with known Weave formats.
1485
We don't test for the stores being of specific types because that
1492
We dont test for the stores being of specific types becase that
1486
1493
could lead to confusing results, and there is no need to be
1487
1494
overly general.
1489
from bzrlib.repofmt.weaverepo import (
1495
1497
return (isinstance(source._format, (RepositoryFormat5,
1496
1498
RepositoryFormat6,
1504
1506
@needs_write_lock
1505
def copy_content(self, revision_id=None):
1507
def copy_content(self, revision_id=None, basis=None):
1506
1508
"""See InterRepository.copy_content()."""
1507
1509
# weave specific optimised path:
1508
# TODO: jam 20070210 Internal, should be an assert, not translate
1509
revision_id = osutils.safe_revision_id(revision_id)
1511
self.target.set_make_working_trees(self.source.make_working_trees())
1512
except NotImplementedError:
1514
# FIXME do not peek!
1515
if self.source.control_files._transport.listable():
1516
pb = ui.ui_factory.nested_progress_bar()
1510
if basis is not None:
1511
# copy the basis in, then fetch remaining data.
1512
basis.copy_content_into(self.target, revision_id)
1513
# the basis copy_content_into could misset this.
1518
self.target.weave_store.copy_all_ids(
1519
self.source.weave_store,
1521
from_transaction=self.source.get_transaction(),
1522
to_transaction=self.target.get_transaction())
1523
pb.update('copying inventory', 0, 1)
1524
self.target.control_weaves.copy_multi(
1525
self.source.control_weaves, ['inventory'],
1526
from_transaction=self.source.get_transaction(),
1527
to_transaction=self.target.get_transaction())
1528
self.target._revision_store.text_store.copy_all_ids(
1529
self.source._revision_store.text_store,
1515
self.target.set_make_working_trees(self.source.make_working_trees())
1516
except NotImplementedError:
1534
1518
self.target.fetch(self.source, revision_id=revision_id)
1521
self.target.set_make_working_trees(self.source.make_working_trees())
1522
except NotImplementedError:
1524
# FIXME do not peek!
1525
if self.source.control_files._transport.listable():
1526
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1528
self.target.weave_store.copy_all_ids(
1529
self.source.weave_store,
1531
from_transaction=self.source.get_transaction(),
1532
to_transaction=self.target.get_transaction())
1533
pb.update('copying inventory', 0, 1)
1534
self.target.control_weaves.copy_multi(
1535
self.source.control_weaves, ['inventory'],
1536
from_transaction=self.source.get_transaction(),
1537
to_transaction=self.target.get_transaction())
1538
self.target._revision_store.text_store.copy_all_ids(
1539
self.source._revision_store.text_store,
1544
self.target.fetch(self.source, revision_id=revision_id)
1536
1546
@needs_write_lock
1537
1547
def fetch(self, revision_id=None, pb=None):
1656
1657
# that against the revision records.
1657
1658
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1660
class InterModel1and2(InterRepository):
1663
def _get_repo_format_to_test(self):
1667
def is_compatible(source, target):
1668
if not source.supports_rich_root() and target.supports_rich_root():
1674
def fetch(self, revision_id=None, pb=None):
1675
"""See InterRepository.fetch()."""
1676
from bzrlib.fetch import Model1toKnit2Fetcher
1677
# TODO: jam 20070210 This should be an assert, not a translate
1678
revision_id = osutils.safe_revision_id(revision_id)
1679
f = Model1toKnit2Fetcher(to_repository=self.target,
1680
from_repository=self.source,
1681
last_revision=revision_id,
1683
return f.count_copied, f.failed_revisions
1686
def copy_content(self, revision_id=None):
1687
"""Make a complete copy of the content in self into destination.
1689
This is a destructive operation! Do not use it on existing
1692
:param revision_id: Only copy the content needed to construct
1693
revision_id and its parents.
1696
self.target.set_make_working_trees(self.source.make_working_trees())
1697
except NotImplementedError:
1699
# TODO: jam 20070210 Internal, assert, don't translate
1700
revision_id = osutils.safe_revision_id(revision_id)
1701
# but don't bother fetching if we have the needed data now.
1702
if (revision_id not in (None, _mod_revision.NULL_REVISION) and
1703
self.target.has_revision(revision_id)):
1705
self.target.fetch(self.source, revision_id=revision_id)
1708
class InterKnit1and2(InterKnitRepo):
1711
def _get_repo_format_to_test(self):
1715
def is_compatible(source, target):
1716
"""Be compatible with Knit1 source and Knit3 target"""
1717
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
1719
from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1720
RepositoryFormatKnit3
1721
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1722
isinstance(target._format, (RepositoryFormatKnit3)))
1723
except AttributeError:
1727
def fetch(self, revision_id=None, pb=None):
1728
"""See InterRepository.fetch()."""
1729
from bzrlib.fetch import Knit1to2Fetcher
1730
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1731
self.source, self.source._format, self.target,
1732
self.target._format)
1733
# TODO: jam 20070210 This should be an assert, not a translate
1734
revision_id = osutils.safe_revision_id(revision_id)
1735
f = Knit1to2Fetcher(to_repository=self.target,
1736
from_repository=self.source,
1737
last_revision=revision_id,
1739
return f.count_copied, f.failed_revisions
1742
class InterRemoteRepository(InterRepository):
1743
"""Code for converting between RemoteRepository objects.
1745
This just gets an non-remote repository from the RemoteRepository, and calls
1746
InterRepository.get again.
1749
def __init__(self, source, target):
1750
if isinstance(source, remote.RemoteRepository):
1751
source._ensure_real()
1752
real_source = source._real_repository
1754
real_source = source
1755
if isinstance(target, remote.RemoteRepository):
1756
target._ensure_real()
1757
real_target = target._real_repository
1759
real_target = target
1760
self.real_inter = InterRepository.get(real_source, real_target)
1763
def is_compatible(source, target):
1764
if isinstance(source, remote.RemoteRepository):
1766
if isinstance(target, remote.RemoteRepository):
1770
def copy_content(self, revision_id=None):
1771
self.real_inter.copy_content(revision_id=revision_id)
1773
def fetch(self, revision_id=None, pb=None):
1774
self.real_inter.fetch(revision_id=revision_id, pb=pb)
1777
def _get_repo_format_to_test(self):
1781
InterRepository.register_optimiser(InterSameDataRepository)
1782
1660
InterRepository.register_optimiser(InterWeaveRepo)
1783
1661
InterRepository.register_optimiser(InterKnitRepo)
1784
InterRepository.register_optimiser(InterModel1and2)
1785
InterRepository.register_optimiser(InterKnit1and2)
1786
InterRepository.register_optimiser(InterRemoteRepository)
1664
class RepositoryTestProviderAdapter(object):
1665
"""A tool to generate a suite testing multiple repository formats at once.
1667
This is done by copying the test once for each transport and injecting
1668
the transport_server, transport_readonly_server, and bzrdir_format and
1669
repository_format classes into each copy. Each copy is also given a new id()
1670
to make it easy to identify.
1673
def __init__(self, transport_server, transport_readonly_server, formats):
1674
self._transport_server = transport_server
1675
self._transport_readonly_server = transport_readonly_server
1676
self._formats = formats
1678
def adapt(self, test):
1679
result = TestSuite()
1680
for repository_format, bzrdir_format in self._formats:
1681
new_test = deepcopy(test)
1682
new_test.transport_server = self._transport_server
1683
new_test.transport_readonly_server = self._transport_readonly_server
1684
new_test.bzrdir_format = bzrdir_format
1685
new_test.repository_format = repository_format
1686
def make_new_test_id():
1687
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1688
return lambda: new_id
1689
new_test.id = make_new_test_id()
1690
result.addTest(new_test)
1694
class InterRepositoryTestProviderAdapter(object):
1695
"""A tool to generate a suite testing multiple inter repository formats.
1697
This is done by copying the test once for each interrepo provider and injecting
1698
the transport_server, transport_readonly_server, repository_format and
1699
repository_to_format classes into each copy.
1700
Each copy is also given a new id() to make it easy to identify.
1703
def __init__(self, transport_server, transport_readonly_server, formats):
1704
self._transport_server = transport_server
1705
self._transport_readonly_server = transport_readonly_server
1706
self._formats = formats
1708
def adapt(self, test):
1709
result = TestSuite()
1710
for interrepo_class, repository_format, repository_format_to in self._formats:
1711
new_test = deepcopy(test)
1712
new_test.transport_server = self._transport_server
1713
new_test.transport_readonly_server = self._transport_readonly_server
1714
new_test.interrepo_class = interrepo_class
1715
new_test.repository_format = repository_format
1716
new_test.repository_format_to = repository_format_to
1717
def make_new_test_id():
1718
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1719
return lambda: new_id
1720
new_test.id = make_new_test_id()
1721
result.addTest(new_test)
1725
def default_test_list():
1726
"""Generate the default list of interrepo permutations to test."""
1728
# test the default InterRepository between format 6 and the current
1730
# XXX: robertc 20060220 reinstate this when there are two supported
1731
# formats which do not have an optimal code path between them.
1732
result.append((InterRepository,
1733
RepositoryFormat6(),
1734
RepositoryFormatKnit1()))
1735
for optimiser in InterRepository._optimisers:
1736
result.append((optimiser,
1737
optimiser._matching_repo_format,
1738
optimiser._matching_repo_format
1740
# if there are specific combinations we want to use, we can add them
1789
1745
class CopyConverter(object):
1838
1793
self.pb.update(message, self.count, self.total)
1841
class CommitBuilder(object):
1842
"""Provides an interface to build up a commit.
1844
This allows describing a tree to be committed without needing to
1845
know the internals of the format of the repository.
1848
record_root_entry = False
1849
def __init__(self, repository, parents, config, timestamp=None,
1850
timezone=None, committer=None, revprops=None,
1852
"""Initiate a CommitBuilder.
1854
:param repository: Repository to commit to.
1855
:param parents: Revision ids of the parents of the new revision.
1856
:param config: Configuration to use.
1857
:param timestamp: Optional timestamp recorded for commit.
1858
:param timezone: Optional timezone for timestamp.
1859
:param committer: Optional committer to set for commit.
1860
:param revprops: Optional dictionary of revision properties.
1861
:param revision_id: Optional revision id.
1863
self._config = config
1865
if committer is None:
1866
self._committer = self._config.username()
1868
assert isinstance(committer, basestring), type(committer)
1869
self._committer = committer
1871
self.new_inventory = Inventory(None)
1872
self._new_revision_id = osutils.safe_revision_id(revision_id)
1873
self.parents = parents
1874
self.repository = repository
1877
if revprops is not None:
1878
self._revprops.update(revprops)
1880
if timestamp is None:
1881
timestamp = time.time()
1882
# Restrict resolution to 1ms
1883
self._timestamp = round(timestamp, 3)
1885
if timezone is None:
1886
self._timezone = osutils.local_time_offset()
1888
self._timezone = int(timezone)
1890
self._generate_revision_if_needed()
1892
def commit(self, message):
1893
"""Make the actual commit.
1895
:return: The revision id of the recorded revision.
1897
rev = _mod_revision.Revision(
1898
timestamp=self._timestamp,
1899
timezone=self._timezone,
1900
committer=self._committer,
1902
inventory_sha1=self.inv_sha1,
1903
revision_id=self._new_revision_id,
1904
properties=self._revprops)
1905
rev.parent_ids = self.parents
1906
self.repository.add_revision(self._new_revision_id, rev,
1907
self.new_inventory, self._config)
1908
return self._new_revision_id
1910
def revision_tree(self):
1911
"""Return the tree that was just committed.
1913
After calling commit() this can be called to get a RevisionTree
1914
representing the newly committed tree. This is preferred to
1915
calling Repository.revision_tree() because that may require
1916
deserializing the inventory, while we already have a copy in
1919
return RevisionTree(self.repository, self.new_inventory,
1920
self._new_revision_id)
1922
def finish_inventory(self):
1923
"""Tell the builder that the inventory is finished."""
1924
if self.new_inventory.root is None:
1925
symbol_versioning.warn('Root entry should be supplied to'
1926
' record_entry_contents, as of bzr 0.10.',
1927
DeprecationWarning, stacklevel=2)
1928
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1929
self.new_inventory.revision_id = self._new_revision_id
1930
self.inv_sha1 = self.repository.add_inventory(
1931
self._new_revision_id,
1936
def _gen_revision_id(self):
1937
"""Return new revision-id."""
1938
return generate_ids.gen_revision_id(self._config.username(),
1941
def _generate_revision_if_needed(self):
1942
"""Create a revision id if None was supplied.
1944
If the repository can not support user-specified revision ids
1945
they should override this function and raise CannotSetRevisionId
1946
if _new_revision_id is not None.
1948
:raises: CannotSetRevisionId
1950
if self._new_revision_id is None:
1951
self._new_revision_id = self._gen_revision_id()
1953
def record_entry_contents(self, ie, parent_invs, path, tree):
1954
"""Record the content of ie from tree into the commit if needed.
1956
Side effect: sets ie.revision when unchanged
1958
:param ie: An inventory entry present in the commit.
1959
:param parent_invs: The inventories of the parent revisions of the
1961
:param path: The path the entry is at in the tree.
1962
:param tree: The tree which contains this entry and should be used to
1965
if self.new_inventory.root is None and ie.parent_id is not None:
1966
symbol_versioning.warn('Root entry should be supplied to'
1967
' record_entry_contents, as of bzr 0.10.',
1968
DeprecationWarning, stacklevel=2)
1969
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
1971
self.new_inventory.add(ie)
1973
# ie.revision is always None if the InventoryEntry is considered
1974
# for committing. ie.snapshot will record the correct revision
1975
# which may be the sole parent if it is untouched.
1976
if ie.revision is not None:
1979
# In this revision format, root entries have no knit or weave
1980
if ie is self.new_inventory.root:
1981
# When serializing out to disk and back in
1982
# root.revision is always _new_revision_id
1983
ie.revision = self._new_revision_id
1985
previous_entries = ie.find_previous_heads(
1987
self.repository.weave_store,
1988
self.repository.get_transaction())
1989
# we are creating a new revision for ie in the history store
1991
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
1993
def modified_directory(self, file_id, file_parents):
1994
"""Record the presence of a symbolic link.
1996
:param file_id: The file_id of the link to record.
1997
:param file_parents: The per-file parent revision ids.
1999
self._add_text_to_weave(file_id, [], file_parents.keys())
2001
def modified_reference(self, file_id, file_parents):
2002
"""Record the modification of a reference.
2004
:param file_id: The file_id of the link to record.
2005
:param file_parents: The per-file parent revision ids.
2007
self._add_text_to_weave(file_id, [], file_parents.keys())
2009
def modified_file_text(self, file_id, file_parents,
2010
get_content_byte_lines, text_sha1=None,
2012
"""Record the text of file file_id
2014
:param file_id: The file_id of the file to record the text of.
2015
:param file_parents: The per-file parent revision ids.
2016
:param get_content_byte_lines: A callable which will return the byte
2018
:param text_sha1: Optional SHA1 of the file contents.
2019
:param text_size: Optional size of the file contents.
2021
# mutter('storing text of file {%s} in revision {%s} into %r',
2022
# file_id, self._new_revision_id, self.repository.weave_store)
2023
# special case to avoid diffing on renames or
2025
if (len(file_parents) == 1
2026
and text_sha1 == file_parents.values()[0].text_sha1
2027
and text_size == file_parents.values()[0].text_size):
2028
previous_ie = file_parents.values()[0]
2029
versionedfile = self.repository.weave_store.get_weave(file_id,
2030
self.repository.get_transaction())
2031
versionedfile.clone_text(self._new_revision_id,
2032
previous_ie.revision, file_parents.keys())
2033
return text_sha1, text_size
2035
new_lines = get_content_byte_lines()
2036
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2037
# should return the SHA1 and size
2038
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2039
return osutils.sha_strings(new_lines), \
2040
sum(map(len, new_lines))
2042
def modified_link(self, file_id, file_parents, link_target):
2043
"""Record the presence of a symbolic link.
2045
:param file_id: The file_id of the link to record.
2046
:param file_parents: The per-file parent revision ids.
2047
:param link_target: Target location of this link.
2049
self._add_text_to_weave(file_id, [], file_parents.keys())
2051
def _add_text_to_weave(self, file_id, new_lines, parents):
2052
versionedfile = self.repository.weave_store.get_weave_or_empty(
2053
file_id, self.repository.get_transaction())
2054
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2055
versionedfile.clear_cache()
2058
class _CommitBuilder(CommitBuilder):
2059
"""Temporary class so old CommitBuilders are detected properly
2061
Note: CommitBuilder works whether or not root entry is recorded.
2064
record_root_entry = True
2067
class RootCommitBuilder(CommitBuilder):
2068
"""This commitbuilder actually records the root id"""
2070
record_root_entry = True
2072
def record_entry_contents(self, ie, parent_invs, path, tree):
2073
"""Record the content of ie from tree into the commit if needed.
2075
Side effect: sets ie.revision when unchanged
2077
:param ie: An inventory entry present in the commit.
2078
:param parent_invs: The inventories of the parent revisions of the
2080
:param path: The path the entry is at in the tree.
2081
:param tree: The tree which contains this entry and should be used to
2084
assert self.new_inventory.root is not None or ie.parent_id is None
2085
self.new_inventory.add(ie)
2087
# ie.revision is always None if the InventoryEntry is considered
2088
# for committing. ie.snapshot will record the correct revision
2089
# which may be the sole parent if it is untouched.
2090
if ie.revision is not None:
2093
previous_entries = ie.find_previous_heads(
2095
self.repository.weave_store,
2096
self.repository.get_transaction())
2097
# we are creating a new revision for ie in the history store
2099
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2111
def _unescaper(match, _map=_unescape_map):
2112
code = match.group(1)
2116
if not code.startswith('#'):
2118
return unichr(int(code[1:])).encode('utf8')
1796
# Copied from xml.sax.saxutils
2124
1797
def _unescape_xml(data):
2125
"""Unescape predefined XML entities in a string of data."""
2127
if _unescape_re is None:
2128
_unescape_re = re.compile('\&([^;]*);')
2129
return _unescape_re.sub(_unescaper, data)
1798
"""Unescape &, <, and > in a string of data.
1800
data = data.replace("<", "<")
1801
data = data.replace(">", ">")
1802
# must do ampersand last
1803
return data.replace("&", "&")