169
83
"""Construct the current default format repository in a_bzrdir."""
170
84
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__()
86
def __init__(self, transport, branch_format, _format=None, a_bzrdir=None):
88
if transport is not None:
89
warn("Repository.__init__(..., transport=XXX): The transport parameter is "
90
"deprecated and was never in a supported release. Please use "
91
"bzrdir.open_repository() or bzrdir.open_branch().repository.",
94
self.control_files = LockableFiles(transport.clone(bzrlib.BZRDIR), 'README')
96
# TODO: clone into repository if needed
97
self.control_files = LockableFiles(a_bzrdir.get_repository_transport(None), 'README')
99
dir_mode = self.control_files._dir_mode
100
file_mode = self.control_files._file_mode
183
101
self._format = _format
184
# the following are part of the public API for Repository:
185
102
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()
104
def get_weave(name, prefixed=False):
106
name = safe_unicode(name)
109
relpath = self.control_files._escape(name)
110
weave_transport = self.control_files._transport.clone(relpath)
111
ws = WeaveStore(weave_transport, prefixed=prefixed,
114
if self.control_files._transport.should_cache():
115
ws.enable_cache = True
119
def get_store(name, compressed=True, prefixed=False):
120
# FIXME: This approach of assuming stores are all entirely compressed
121
# or entirely uncompressed is tidy, but breaks upgrade from
122
# some existing branches where there's a mixture; we probably
123
# still want the option to look for both.
125
name = safe_unicode(name)
128
relpath = self.control_files._escape(name)
129
store = TextStore(self.control_files._transport.clone(relpath),
130
prefixed=prefixed, compressed=compressed,
133
#if self._transport.should_cache():
134
# cache_path = os.path.join(self.cache_root, name)
135
# os.mkdir(cache_path)
136
# store = bzrlib.store.CachedStore(store, cache_path)
139
if branch_format is not None:
140
# circular dependencies:
141
from bzrlib.branch import (BzrBranchFormat4,
145
if isinstance(branch_format, BzrBranchFormat4):
146
self._format = RepositoryFormat4()
147
elif isinstance(branch_format, BzrBranchFormat5):
148
self._format = RepositoryFormat5()
149
elif isinstance(branch_format, BzrBranchFormat6):
150
self._format = RepositoryFormat6()
153
if isinstance(self._format, RepositoryFormat4):
154
self.inventory_store = get_store('inventory-store')
155
self.text_store = get_store('text-store')
156
self.revision_store = get_store('revision-store')
157
elif isinstance(self._format, RepositoryFormat5):
158
self.control_weaves = get_weave('')
159
self.weave_store = get_weave('weaves')
160
self.revision_store = get_store('revision-store', compressed=False)
161
elif isinstance(self._format, RepositoryFormat6):
162
self.control_weaves = get_weave('')
163
self.weave_store = get_weave('weaves', prefixed=True)
164
self.revision_store = get_store('revision-store', compressed=False,
166
elif isinstance(self._format, RepositoryFormat7):
167
self.control_weaves = get_weave('')
168
self.weave_store = get_weave('weaves', prefixed=True)
169
self.revision_store = get_store('revision-store', compressed=False,
171
self.revision_store.register_suffix('sig')
206
173
def lock_write(self):
207
174
self.control_files.lock_write()
285
321
bzrdir.BzrDirFormat6)):
286
322
result = a_bzrdir.open_repository()
288
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
324
result = self._format.initialize(a_bzrdir)
289
325
self.copy_content_into(result, revision_id, basis)
293
328
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())
329
"""True if this branch has a copy of the revision.
331
This does not necessarily imply the revision is merge
332
or on the mainline."""
333
return (revision_id is None
334
or self.revision_store.has_id(revision_id))
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.
337
def get_revision_xml_file(self, revision_id):
338
"""Return XML file object for revision object."""
307
339
if not revision_id or not isinstance(revision_id, basestring):
308
340
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())
342
return self.revision_store.get(revision_id)
343
except (IndexError, KeyError):
344
raise bzrlib.errors.NoSuchRevision(self, revision_id)
317
347
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()
348
return self.get_revision_xml_file(revision_id).read()
326
351
def get_revision(self, revision_id):
327
352
"""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)
353
xml_file = self.get_revision_xml_file(revision_id)
356
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
357
except SyntaxError, e:
358
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
362
assert r.revision_id == revision_id
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)
366
def get_revision_sha1(self, revision_id):
367
"""Hash the stored value of a revision, and return it."""
368
# In the future, revision entries will be signed. At that
369
# point, it is probably best *not* to include the signature
370
# in the revision hash. Because that lets you re-sign
371
# the revision, (add signatures/remove signatures) and still
372
# have all hash pointers stay consistent.
373
# But for now, just hash the contents.
374
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
387
376
@needs_write_lock
388
377
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.
378
self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)),
381
def fileid_involved_between_revs(self, from_revid, to_revid):
382
"""Find file_id(s) which are involved in the changes between revisions.
384
This determines the set of revisions which are involved, and then
385
finds all file ids affected by those revisions.
387
# TODO: jam 20060119 This code assumes that w.inclusions will
388
# always be correct. But because of the presence of ghosts
389
# it is possible to be wrong.
390
# One specific example from Robert Collins:
391
# Two branches, with revisions ABC, and AD
392
# C is a ghost merge of D.
393
# Inclusions doesn't recognize D as an ancestor.
394
# If D is ever merged in the future, the weave
395
# won't be fixed, because AD never saw revision C
396
# to cause a conflict which would force a reweave.
397
w = self.get_inventory_weave()
398
from_set = set(w.inclusions([w.lookup(from_revid)]))
399
to_set = set(w.inclusions([w.lookup(to_revid)]))
400
included = to_set.difference(from_set)
401
changed = map(w.idx_to_name, included)
402
return self._fileid_involved_by_set(changed)
404
def fileid_involved(self, last_revid=None):
405
"""Find all file_ids modified in the ancestry of last_revid.
407
:param last_revid: If None, last_revision() will be used.
409
w = self.get_inventory_weave()
411
changed = set(w._names)
413
included = w.inclusions([w.lookup(last_revid)])
414
changed = map(w.idx_to_name, included)
415
return self._fileid_involved_by_set(changed)
417
def fileid_involved_by_set(self, changes):
418
"""Find all file_ids modified by the set of revisions passed in.
420
:param changes: A set() of revision ids
422
# TODO: jam 20060119 This line does *nothing*, remove it.
423
# or better yet, change _fileid_involved_by_set so
424
# that it takes the inventory weave, rather than
425
# pulling it out by itself.
426
return self._fileid_involved_by_set(changes)
428
def _fileid_involved_by_set(self, changes):
429
"""Find the set of file-ids affected by the set of revisions.
431
:param changes: A set() of revision ids.
432
:return: A set() of file ids.
434
This peaks at the Weave, interpreting each line, looking to
435
see if it mentions one of the revisions. And if so, includes
436
the file id mentioned.
437
This expects both the Weave format, and the serialization
438
to have a single line per file/directory, and to have
439
fileid="" and revision="" on that line.
402
441
assert isinstance(self._format, (RepositoryFormat5,
403
442
RepositoryFormat6,
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)
443
RepositoryFormat7)), \
444
"fileid_involved only supported for branches which store inventory as unnested xml"
409
446
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):
448
for line in w._weave:
450
# it is ugly, but it is due to the weave structure
451
if not isinstance(line, basestring): continue
421
453
start = line.find('file_id="')+9
422
454
if start < 9: continue
423
455
end = line.find('"', start)
425
file_id = _unescape_xml(line[start:end])
457
file_id = xml.sax.saxutils.unescape(line[start:end])
459
# check if file_id is already present
460
if file_id in file_ids: continue
427
462
start = line.find('revision="')+10
428
463
if start < 10: continue
429
464
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)
466
revision_id = xml.sax.saxutils.unescape(line[start:end])
468
if revision_id in changes:
469
file_ids.add(file_id)
437
473
def get_inventory_weave(self):
625
552
# use inventory as it was in that revision
626
553
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))
555
raise BzrError("%r is not present in revision %s" % (file, revno))
557
revno = self.revision_id_to_revno(revision_id)
558
except errors.NoSuchRevision:
559
# TODO: This should not be BzrError,
560
# but NoSuchFile doesn't fit either
561
raise BzrError('%r is not present in revision %s'
562
% (file, revision_id))
564
raise BzrError('%r is not present in revision %s'
632
566
tree.print_file(file_id)
634
568
def get_transaction(self):
635
569
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)
656
571
@needs_write_lock
657
572
def sign_revision(self, revision_id, gpg_strategy):
658
573
plaintext = Testament.from_revision(self, revision_id).as_short_text()
659
574
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
577
class RepositoryFormat(object):
993
578
"""A repository format.
1306
756
super(RepositoryFormat6, self).__init__()
1307
757
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1309
def get_format_description(self):
1310
"""See RepositoryFormat.get_format_description()."""
1311
return "Weave repository format 6"
1313
def _get_revision_store(self, repo_transport, control_files):
1314
"""See RepositoryFormat._get_revision_store()."""
1315
return self._get_text_rev_store(repo_transport,
1321
def _get_text_store(self, transport, control_files):
1322
"""See RepositoryFormat._get_text_store()."""
1323
return self._get_versioned_file_store('weaves', transport, control_files)
1326
class MetaDirRepositoryFormat(RepositoryFormat):
1327
"""Common base class for the new repositories using the metadir layout."""
1330
super(MetaDirRepositoryFormat, self).__init__()
1331
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1333
def _create_control_files(self, a_bzrdir):
1334
"""Create the required files and the initial control_files object."""
1335
# FIXME: RBC 20060125 don't peek under the covers
760
class RepositoryFormat7(RepositoryFormat):
763
This repository format has:
764
- weaves for file texts and inventory
765
- hash subdirectory based stores.
766
- TextStores for revisions and signatures.
767
- a format marker of its own
770
def get_format_string(self):
771
"""See RepositoryFormat.get_format_string()."""
772
return "Bazaar-NG Repository format 7"
774
def initialize(self, a_bzrdir):
775
"""Create a weave repository.
777
from bzrlib.weavefile import write_weave_v5
778
from bzrlib.weave import Weave
780
# Create an empty weave
782
bzrlib.weavefile.write_weave_v5(Weave(), sio)
783
empty_weave = sio.getvalue()
785
mutter('creating repository in %s.', a_bzrdir.transport.base)
786
dirs = ['revision-store', 'weaves']
787
files = [('inventory.weave', StringIO(empty_weave)),
789
utf8_files = [('format', self.get_format_string())]
791
# FIXME: RBC 20060125 dont peek under the covers
1336
792
# NB: no need to escape relative paths that are url safe.
1337
794
repository_transport = a_bzrdir.get_repository_transport(self)
1338
control_files = LockableFiles(repository_transport, 'lock', LockDir)
1339
control_files.create_lock()
1340
return control_files
1342
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1343
"""Upload the initial blank content."""
1344
control_files = self._create_control_files(a_bzrdir)
795
repository_transport.put(lock_file, StringIO()) # TODO get the file mode from the bzrdir lock files., mode=file_mode)
796
control_files = LockableFiles(repository_transport, 'lock')
1345
797
control_files.lock_write()
798
control_files._transport.mkdir_multi(dirs,
799
mode=control_files._dir_mode)
1347
control_files._transport.mkdir_multi(dirs,
1348
mode=control_files._dir_mode)
1349
801
for file, content in files:
1350
802
control_files.put(file, content)
1351
803
for file, content in utf8_files:
1352
804
control_files.put_utf8(file, content)
1354
control_files.put_utf8('shared-storage', '')
1356
806
control_files.unlock()
1359
class RepositoryFormat7(MetaDirRepositoryFormat):
1360
"""Bzr repository 7.
1362
This repository format has:
1363
- weaves for file texts and inventory
1364
- hash subdirectory based stores.
1365
- TextStores for revisions and signatures.
1366
- a format marker of its own
1367
- an optional 'shared-storage' flag
1368
- an optional 'no-working-trees' flag
1371
def _get_control_store(self, repo_transport, control_files):
1372
"""Return the control store for this repository."""
1373
return self._get_versioned_file_store('',
1378
def get_format_string(self):
1379
"""See RepositoryFormat.get_format_string()."""
1380
return "Bazaar-NG Repository format 7"
1382
def get_format_description(self):
1383
"""See RepositoryFormat.get_format_description()."""
1384
return "Weave repository format 7"
1386
def _get_revision_store(self, repo_transport, control_files):
1387
"""See RepositoryFormat._get_revision_store()."""
1388
return self._get_text_rev_store(repo_transport,
1395
def _get_text_store(self, transport, control_files):
1396
"""See RepositoryFormat._get_text_store()."""
1397
return self._get_versioned_file_store('weaves',
1401
def initialize(self, a_bzrdir, shared=False):
1402
"""Create a weave repository.
1404
:param shared: If true the repository will be initialized as a shared
1407
from bzrlib.weavefile import write_weave_v5
1408
from bzrlib.weave import Weave
1410
# Create an empty weave
1412
write_weave_v5(Weave(), sio)
1413
empty_weave = sio.getvalue()
1415
mutter('creating repository in %s.', a_bzrdir.transport.base)
1416
dirs = ['revision-store', 'weaves']
1417
files = [('inventory.weave', StringIO(empty_weave)),
1419
utf8_files = [('format', self.get_format_string())]
1421
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1422
return self.open(a_bzrdir=a_bzrdir, _found=True)
1424
def open(self, a_bzrdir, _found=False, _override_transport=None):
1425
"""See RepositoryFormat.open().
1427
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1428
repository at a slightly different url
1429
than normal. I.e. during 'upgrade'.
1432
format = RepositoryFormat.find_format(a_bzrdir)
1433
assert format.__class__ == self.__class__
1434
if _override_transport is not None:
1435
repo_transport = _override_transport
1437
repo_transport = a_bzrdir.get_repository_transport(None)
1438
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1439
text_store = self._get_text_store(repo_transport, control_files)
1440
control_store = self._get_control_store(repo_transport, control_files)
1441
_revision_store = self._get_revision_store(repo_transport, control_files)
1442
return MetaDirRepository(_format=self,
1444
control_files=control_files,
1445
_revision_store=_revision_store,
1446
control_store=control_store,
1447
text_store=text_store)
1450
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1451
"""Bzr repository knit format 1.
1453
This repository format has:
1454
- knits for file texts and inventory
1455
- hash subdirectory based stores.
1456
- knits for revisions and signatures
1457
- TextStores for revisions and signatures.
1458
- a format marker of its own
1459
- an optional 'shared-storage' flag
1460
- an optional 'no-working-trees' flag
1463
This format was introduced in bzr 0.8.
1466
def _get_control_store(self, repo_transport, control_files):
1467
"""Return the control store for this repository."""
1468
return VersionedFileStore(
1471
file_mode=control_files._file_mode,
1472
versionedfile_class=KnitVersionedFile,
1473
versionedfile_kwargs={'factory':KnitPlainFactory()},
1476
def get_format_string(self):
1477
"""See RepositoryFormat.get_format_string()."""
1478
return "Bazaar-NG Knit Repository Format 1"
1480
def get_format_description(self):
1481
"""See RepositoryFormat.get_format_description()."""
1482
return "Knit repository format 1"
1484
def _get_revision_store(self, repo_transport, control_files):
1485
"""See RepositoryFormat._get_revision_store()."""
1486
from bzrlib.store.revision.knit import KnitRevisionStore
1487
versioned_file_store = VersionedFileStore(
1489
file_mode=control_files._file_mode,
1492
versionedfile_class=KnitVersionedFile,
1493
versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory()},
1496
return KnitRevisionStore(versioned_file_store)
1498
def _get_text_store(self, transport, control_files):
1499
"""See RepositoryFormat._get_text_store()."""
1500
return self._get_versioned_file_store('knits',
1503
versionedfile_class=KnitVersionedFile,
1506
def initialize(self, a_bzrdir, shared=False):
1507
"""Create a knit format 1 repository.
1509
:param a_bzrdir: bzrdir to contain the new repository; must already
1511
:param shared: If true the repository will be initialized as a shared
1514
mutter('creating repository in %s.', a_bzrdir.transport.base)
1515
dirs = ['revision-store', 'knits']
1517
utf8_files = [('format', self.get_format_string())]
1519
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1520
repo_transport = a_bzrdir.get_repository_transport(None)
1521
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1522
control_store = self._get_control_store(repo_transport, control_files)
1523
transaction = transactions.WriteTransaction()
1524
# trigger a write of the inventory store.
1525
control_store.get_weave_or_empty('inventory', transaction)
1526
_revision_store = self._get_revision_store(repo_transport, control_files)
1527
_revision_store.has_revision_id('A', transaction)
1528
_revision_store.get_signature_file(transaction)
1529
return self.open(a_bzrdir=a_bzrdir, _found=True)
1531
def open(self, a_bzrdir, _found=False, _override_transport=None):
1532
"""See RepositoryFormat.open().
1534
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1535
repository at a slightly different url
1536
than normal. I.e. during 'upgrade'.
1539
format = RepositoryFormat.find_format(a_bzrdir)
1540
assert format.__class__ == self.__class__
1541
if _override_transport is not None:
1542
repo_transport = _override_transport
1544
repo_transport = a_bzrdir.get_repository_transport(None)
1545
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1546
text_store = self._get_text_store(repo_transport, control_files)
1547
control_store = self._get_control_store(repo_transport, control_files)
1548
_revision_store = self._get_revision_store(repo_transport, control_files)
1549
return KnitRepository(_format=self,
1551
control_files=control_files,
1552
_revision_store=_revision_store,
1553
control_store=control_store,
1554
text_store=text_store)
807
return Repository(None, branch_format=None, _format=self, a_bzrdir=a_bzrdir)
810
super(RepositoryFormat7, self).__init__()
811
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1557
814
# formats which have no format string are not discoverable
1558
815
# and not independently creatable, so are not registered.
1559
RepositoryFormat.register_format(RepositoryFormat7())
1560
_default_format = RepositoryFormatKnit1()
1561
RepositoryFormat.register_format(_default_format)
1562
RepositoryFormat.set_default_format(_default_format)
816
__default_format = RepositoryFormat7()
817
RepositoryFormat.register_format(__default_format)
818
RepositoryFormat.set_default_format(__default_format)
1563
819
_legacy_formats = [RepositoryFormat4(),
1564
820
RepositoryFormat5(),
1565
821
RepositoryFormat6()]
1568
class InterRepository(InterObject):
1569
"""This class represents operations taking place between two repositories.
1571
Its instances have methods like copy_content and fetch, and contain
1572
references to the source and target repositories these operations can be
1575
Often we will provide convenience methods on 'repository' which carry out
1576
operations with another repository - they will always forward to
1577
InterRepository.get(other).method_name(parameters).
1581
"""The available optimised InterRepository types."""
1584
def copy_content(self, revision_id=None, basis=None):
1585
"""Make a complete copy of the content in self into destination.
1587
This is a destructive operation! Do not use it on existing
1590
:param revision_id: Only copy the content needed to construct
1591
revision_id and its parents.
1592
:param basis: Copy the needed data preferentially from basis.
1595
self.target.set_make_working_trees(self.source.make_working_trees())
1596
except NotImplementedError:
1598
# grab the basis available data
1599
if basis is not None:
1600
self.target.fetch(basis, revision_id=revision_id)
1601
# but don't bother fetching if we have the needed data now.
1602
if (revision_id not in (None, NULL_REVISION) and
1603
self.target.has_revision(revision_id)):
1605
self.target.fetch(self.source, revision_id=revision_id)
1608
def fetch(self, revision_id=None, pb=None):
1609
"""Fetch the content required to construct revision_id.
1611
The content is copied from source to target.
1613
:param revision_id: if None all content is copied, if NULL_REVISION no
1615
:param pb: optional progress bar to use for progress reports. If not
1616
provided a default one will be created.
1618
Returns the copied revision count and the failed revisions in a tuple:
1621
from bzrlib.fetch import GenericRepoFetcher
1622
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1623
self.source, self.source._format, self.target, self.target._format)
1624
f = GenericRepoFetcher(to_repository=self.target,
1625
from_repository=self.source,
1626
last_revision=revision_id,
1628
return f.count_copied, f.failed_revisions
1631
def missing_revision_ids(self, revision_id=None):
1632
"""Return the revision ids that source has that target does not.
1634
These are returned in topological order.
1636
:param revision_id: only return revision ids included by this
1639
# generic, possibly worst case, slow code path.
1640
target_ids = set(self.target.all_revision_ids())
1641
if revision_id is not None:
1642
source_ids = self.source.get_ancestry(revision_id)
1643
assert source_ids[0] == None
1646
source_ids = self.source.all_revision_ids()
1647
result_set = set(source_ids).difference(target_ids)
1648
# this may look like a no-op: its not. It preserves the ordering
1649
# other_ids had while only returning the members from other_ids
1650
# that we've decided we need.
1651
return [rev_id for rev_id in source_ids if rev_id in result_set]
1654
class InterWeaveRepo(InterRepository):
1655
"""Optimised code paths between Weave based repositories."""
1657
_matching_repo_format = RepositoryFormat7()
1658
"""Repository format for testing with."""
1661
def is_compatible(source, target):
1662
"""Be compatible with known Weave formats.
1664
We don't test for the stores being of specific types because that
1665
could lead to confusing results, and there is no need to be
1669
return (isinstance(source._format, (RepositoryFormat5,
1671
RepositoryFormat7)) and
1672
isinstance(target._format, (RepositoryFormat5,
1674
RepositoryFormat7)))
1675
except AttributeError:
1679
def copy_content(self, revision_id=None, basis=None):
1680
"""See InterRepository.copy_content()."""
1681
# weave specific optimised path:
1682
if basis is not None:
1683
# copy the basis in, then fetch remaining data.
1684
basis.copy_content_into(self.target, revision_id)
1685
# the basis copy_content_into could miss-set this.
1687
self.target.set_make_working_trees(self.source.make_working_trees())
1688
except NotImplementedError:
1690
self.target.fetch(self.source, revision_id=revision_id)
1693
self.target.set_make_working_trees(self.source.make_working_trees())
1694
except NotImplementedError:
1696
# FIXME do not peek!
1697
if self.source.control_files._transport.listable():
1698
pb = ui.ui_factory.nested_progress_bar()
1700
self.target.weave_store.copy_all_ids(
1701
self.source.weave_store,
1703
from_transaction=self.source.get_transaction(),
1704
to_transaction=self.target.get_transaction())
1705
pb.update('copying inventory', 0, 1)
1706
self.target.control_weaves.copy_multi(
1707
self.source.control_weaves, ['inventory'],
1708
from_transaction=self.source.get_transaction(),
1709
to_transaction=self.target.get_transaction())
1710
self.target._revision_store.text_store.copy_all_ids(
1711
self.source._revision_store.text_store,
1716
self.target.fetch(self.source, revision_id=revision_id)
1719
def fetch(self, revision_id=None, pb=None):
1720
"""See InterRepository.fetch()."""
1721
from bzrlib.fetch import GenericRepoFetcher
1722
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1723
self.source, self.source._format, self.target, self.target._format)
1724
f = GenericRepoFetcher(to_repository=self.target,
1725
from_repository=self.source,
1726
last_revision=revision_id,
1728
return f.count_copied, f.failed_revisions
1731
def missing_revision_ids(self, revision_id=None):
1732
"""See InterRepository.missing_revision_ids()."""
1733
# we want all revisions to satisfy revision_id in source.
1734
# but we don't want to stat every file here and there.
1735
# we want then, all revisions other needs to satisfy revision_id
1736
# checked, but not those that we have locally.
1737
# so the first thing is to get a subset of the revisions to
1738
# satisfy revision_id in source, and then eliminate those that
1739
# we do already have.
1740
# this is slow on high latency connection to self, but as as this
1741
# disk format scales terribly for push anyway due to rewriting
1742
# inventory.weave, this is considered acceptable.
1744
if revision_id is not None:
1745
source_ids = self.source.get_ancestry(revision_id)
1746
assert source_ids[0] == None
1749
source_ids = self.source._all_possible_ids()
1750
source_ids_set = set(source_ids)
1751
# source_ids is the worst possible case we may need to pull.
1752
# now we want to filter source_ids against what we actually
1753
# have in target, but don't try to check for existence where we know
1754
# we do not have a revision as that would be pointless.
1755
target_ids = set(self.target._all_possible_ids())
1756
possibly_present_revisions = target_ids.intersection(source_ids_set)
1757
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1758
required_revisions = source_ids_set.difference(actually_present_revisions)
1759
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1760
if revision_id is not None:
1761
# we used get_ancestry to determine source_ids then we are assured all
1762
# revisions referenced are present as they are installed in topological order.
1763
# and the tip revision was validated by get_ancestry.
1764
return required_topo_revisions
1766
# if we just grabbed the possibly available ids, then
1767
# we only have an estimate of whats available and need to validate
1768
# that against the revision records.
1769
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1772
class InterKnitRepo(InterRepository):
1773
"""Optimised code paths between Knit based repositories."""
1775
_matching_repo_format = RepositoryFormatKnit1()
1776
"""Repository format for testing with."""
1779
def is_compatible(source, target):
1780
"""Be compatible with known Knit formats.
1782
We don't test for the stores being of specific types because that
1783
could lead to confusing results, and there is no need to be
1787
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1788
isinstance(target._format, (RepositoryFormatKnit1)))
1789
except AttributeError:
1793
def fetch(self, revision_id=None, pb=None):
1794
"""See InterRepository.fetch()."""
1795
from bzrlib.fetch import KnitRepoFetcher
1796
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1797
self.source, self.source._format, self.target, self.target._format)
1798
f = KnitRepoFetcher(to_repository=self.target,
1799
from_repository=self.source,
1800
last_revision=revision_id,
1802
return f.count_copied, f.failed_revisions
1805
def missing_revision_ids(self, revision_id=None):
1806
"""See InterRepository.missing_revision_ids()."""
1807
if revision_id is not None:
1808
source_ids = self.source.get_ancestry(revision_id)
1809
assert source_ids[0] == None
1812
source_ids = self.source._all_possible_ids()
1813
source_ids_set = set(source_ids)
1814
# source_ids is the worst possible case we may need to pull.
1815
# now we want to filter source_ids against what we actually
1816
# have in target, but don't try to check for existence where we know
1817
# we do not have a revision as that would be pointless.
1818
target_ids = set(self.target._all_possible_ids())
1819
possibly_present_revisions = target_ids.intersection(source_ids_set)
1820
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1821
required_revisions = source_ids_set.difference(actually_present_revisions)
1822
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1823
if revision_id is not None:
1824
# we used get_ancestry to determine source_ids then we are assured all
1825
# revisions referenced are present as they are installed in topological order.
1826
# and the tip revision was validated by get_ancestry.
1827
return required_topo_revisions
1829
# if we just grabbed the possibly available ids, then
1830
# we only have an estimate of whats available and need to validate
1831
# that against the revision records.
1832
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1834
InterRepository.register_optimiser(InterWeaveRepo)
1835
InterRepository.register_optimiser(InterKnitRepo)
824
# TODO: jam 20060108 Create a new branch format, and as part of upgrade
825
# make sure that ancestry.weave is deleted (it is never used, but
826
# used to be created)
1838
828
class RepositoryTestProviderAdapter(object):
1839
829
"""A tool to generate a suite testing multiple repository formats at once.
1863
853
new_test.id = make_new_test_id()
1864
854
result.addTest(new_test)
1868
class InterRepositoryTestProviderAdapter(object):
1869
"""A tool to generate a suite testing multiple inter repository formats.
1871
This is done by copying the test once for each interrepo provider and injecting
1872
the transport_server, transport_readonly_server, repository_format and
1873
repository_to_format classes into each copy.
1874
Each copy is also given a new id() to make it easy to identify.
1877
def __init__(self, transport_server, transport_readonly_server, formats):
1878
self._transport_server = transport_server
1879
self._transport_readonly_server = transport_readonly_server
1880
self._formats = formats
1882
def adapt(self, test):
1883
result = TestSuite()
1884
for interrepo_class, repository_format, repository_format_to in self._formats:
1885
new_test = deepcopy(test)
1886
new_test.transport_server = self._transport_server
1887
new_test.transport_readonly_server = self._transport_readonly_server
1888
new_test.interrepo_class = interrepo_class
1889
new_test.repository_format = repository_format
1890
new_test.repository_format_to = repository_format_to
1891
def make_new_test_id():
1892
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1893
return lambda: new_id
1894
new_test.id = make_new_test_id()
1895
result.addTest(new_test)
1899
def default_test_list():
1900
"""Generate the default list of interrepo permutations to test."""
1902
# test the default InterRepository between format 6 and the current
1904
# XXX: robertc 20060220 reinstate this when there are two supported
1905
# formats which do not have an optimal code path between them.
1906
result.append((InterRepository,
1907
RepositoryFormat6(),
1908
RepositoryFormatKnit1()))
1909
for optimiser in InterRepository._optimisers:
1910
result.append((optimiser,
1911
optimiser._matching_repo_format,
1912
optimiser._matching_repo_format
1914
# if there are specific combinations we want to use, we can add them
1919
class CopyConverter(object):
1920
"""A repository conversion tool which just performs a copy of the content.
1922
This is slow but quite reliable.
1925
def __init__(self, target_format):
1926
"""Create a CopyConverter.
1928
:param target_format: The format the resulting repository should be.
1930
self.target_format = target_format
1932
def convert(self, repo, pb):
1933
"""Perform the conversion of to_convert, giving feedback via pb.
1935
:param to_convert: The disk object to convert.
1936
:param pb: a progress bar to use for progress information.
1941
# this is only useful with metadir layouts - separated repo content.
1942
# trigger an assertion if not such
1943
repo._format.get_format_string()
1944
self.repo_dir = repo.bzrdir
1945
self.step('Moving repository to repository.backup')
1946
self.repo_dir.transport.move('repository', 'repository.backup')
1947
backup_transport = self.repo_dir.transport.clone('repository.backup')
1948
self.source_repo = repo._format.open(self.repo_dir,
1950
_override_transport=backup_transport)
1951
self.step('Creating new repository')
1952
converted = self.target_format.initialize(self.repo_dir,
1953
self.source_repo.is_shared())
1954
converted.lock_write()
1956
self.step('Copying content into repository.')
1957
self.source_repo.copy_content_into(converted)
1960
self.step('Deleting old repository content.')
1961
self.repo_dir.transport.delete_tree('repository.backup')
1962
self.pb.note('repository converted')
1964
def step(self, message):
1965
"""Update the pb by a step."""
1967
self.pb.update(message, self.count, self.total)
1970
class CommitBuilder(object):
1971
"""Provides an interface to build up a commit.
1973
This allows describing a tree to be committed without needing to
1974
know the internals of the format of the repository.
1977
record_root_entry = False
1978
def __init__(self, repository, parents, config, timestamp=None,
1979
timezone=None, committer=None, revprops=None,
1981
"""Initiate a CommitBuilder.
1983
:param repository: Repository to commit to.
1984
:param parents: Revision ids of the parents of the new revision.
1985
:param config: Configuration to use.
1986
:param timestamp: Optional timestamp recorded for commit.
1987
:param timezone: Optional timezone for timestamp.
1988
:param committer: Optional committer to set for commit.
1989
:param revprops: Optional dictionary of revision properties.
1990
:param revision_id: Optional revision id.
1992
self._config = config
1994
if committer is None:
1995
self._committer = self._config.username()
1997
assert isinstance(committer, basestring), type(committer)
1998
self._committer = committer
2000
self.new_inventory = Inventory(None)
2001
self._new_revision_id = revision_id
2002
self.parents = parents
2003
self.repository = repository
2006
if revprops is not None:
2007
self._revprops.update(revprops)
2009
if timestamp is None:
2010
timestamp = time.time()
2011
# Restrict resolution to 1ms
2012
self._timestamp = round(timestamp, 3)
2014
if timezone is None:
2015
self._timezone = local_time_offset()
2017
self._timezone = int(timezone)
2019
self._generate_revision_if_needed()
2021
def commit(self, message):
2022
"""Make the actual commit.
2024
:return: The revision id of the recorded revision.
2026
rev = Revision(timestamp=self._timestamp,
2027
timezone=self._timezone,
2028
committer=self._committer,
2030
inventory_sha1=self.inv_sha1,
2031
revision_id=self._new_revision_id,
2032
properties=self._revprops)
2033
rev.parent_ids = self.parents
2034
self.repository.add_revision(self._new_revision_id, rev,
2035
self.new_inventory, self._config)
2036
return self._new_revision_id
2038
def finish_inventory(self):
2039
"""Tell the builder that the inventory is finished."""
2040
if self.new_inventory.root is None:
2041
symbol_versioning.warn('Root entry should be supplied to'
2042
' record_entry_contents, as of bzr 0.10.',
2043
DeprecationWarning, stacklevel=2)
2044
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
2045
self.new_inventory.revision_id = self._new_revision_id
2046
self.inv_sha1 = self.repository.add_inventory(
2047
self._new_revision_id,
2052
def _gen_revision_id(self):
2053
"""Return new revision-id."""
2054
s = '%s-%s-' % (self._config.user_email(),
2055
compact_date(self._timestamp))
2056
s += hexlify(rand_bytes(8))
2059
def _generate_revision_if_needed(self):
2060
"""Create a revision id if None was supplied.
2062
If the repository can not support user-specified revision ids
2063
they should override this function and raise UnsupportedOperation
2064
if _new_revision_id is not None.
2066
:raises: UnsupportedOperation
2068
if self._new_revision_id is None:
2069
self._new_revision_id = self._gen_revision_id()
2071
def record_entry_contents(self, ie, parent_invs, path, tree):
2072
"""Record the content of ie from tree into the commit if needed.
2074
Side effect: sets ie.revision when unchanged
2076
:param ie: An inventory entry present in the commit.
2077
:param parent_invs: The inventories of the parent revisions of the
2079
:param path: The path the entry is at in the tree.
2080
:param tree: The tree which contains this entry and should be used to
2083
if self.new_inventory.root is None and ie.parent_id is not None:
2084
symbol_versioning.warn('Root entry should be supplied to'
2085
' record_entry_contents, as of bzr 0.10.',
2086
DeprecationWarning, stacklevel=2)
2087
self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2089
self.new_inventory.add(ie)
2091
# ie.revision is always None if the InventoryEntry is considered
2092
# for committing. ie.snapshot will record the correct revision
2093
# which may be the sole parent if it is untouched.
2094
if ie.revision is not None:
2097
# In this revision format, root entries have no knit or weave
2098
if ie is self.new_inventory.root:
2099
if len(parent_invs):
2100
ie.revision = parent_invs[0].root.revision
2104
previous_entries = ie.find_previous_heads(
2106
self.repository.weave_store,
2107
self.repository.get_transaction())
2108
# we are creating a new revision for ie in the history store
2110
ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2112
def modified_directory(self, file_id, file_parents):
2113
"""Record the presence of a symbolic link.
2115
:param file_id: The file_id of the link to record.
2116
:param file_parents: The per-file parent revision ids.
2118
self._add_text_to_weave(file_id, [], file_parents.keys())
2120
def modified_file_text(self, file_id, file_parents,
2121
get_content_byte_lines, text_sha1=None,
2123
"""Record the text of file file_id
2125
:param file_id: The file_id of the file to record the text of.
2126
:param file_parents: The per-file parent revision ids.
2127
:param get_content_byte_lines: A callable which will return the byte
2129
:param text_sha1: Optional SHA1 of the file contents.
2130
:param text_size: Optional size of the file contents.
2132
# mutter('storing text of file {%s} in revision {%s} into %r',
2133
# file_id, self._new_revision_id, self.repository.weave_store)
2134
# special case to avoid diffing on renames or
2136
if (len(file_parents) == 1
2137
and text_sha1 == file_parents.values()[0].text_sha1
2138
and text_size == file_parents.values()[0].text_size):
2139
previous_ie = file_parents.values()[0]
2140
versionedfile = self.repository.weave_store.get_weave(file_id,
2141
self.repository.get_transaction())
2142
versionedfile.clone_text(self._new_revision_id,
2143
previous_ie.revision, file_parents.keys())
2144
return text_sha1, text_size
2146
new_lines = get_content_byte_lines()
2147
# TODO: Rather than invoking sha_strings here, _add_text_to_weave
2148
# should return the SHA1 and size
2149
self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2150
return osutils.sha_strings(new_lines), \
2151
sum(map(len, new_lines))
2153
def modified_link(self, file_id, file_parents, link_target):
2154
"""Record the presence of a symbolic link.
2156
:param file_id: The file_id of the link to record.
2157
:param file_parents: The per-file parent revision ids.
2158
:param link_target: Target location of this link.
2160
self._add_text_to_weave(file_id, [], file_parents.keys())
2162
def _add_text_to_weave(self, file_id, new_lines, parents):
2163
versionedfile = self.repository.weave_store.get_weave_or_empty(
2164
file_id, self.repository.get_transaction())
2165
versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2166
versionedfile.clear_cache()
2169
class _CommitBuilder(CommitBuilder):
2170
"""Temporary class so old CommitBuilders are detected properly
2172
Note: CommitBuilder works whether or not root entry is recorded.
2175
record_root_entry = True
2187
def _unescaper(match, _map=_unescape_map):
2188
return _map[match.group(1)]
2194
def _unescape_xml(data):
2195
"""Unescape predefined XML entities in a string of data."""
2197
if _unescape_re is None:
2198
_unescape_re = re.compile('\&([^;]*);')
2199
return _unescape_re.sub(_unescaper, data)