1
# Copyright (C) 2007, 2008, 2009 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Utility for create branches with particular contents."""
27
class BranchBuilder(object):
28
r"""A BranchBuilder aids creating Branches with particular shapes.
30
The expected way to use BranchBuilder is to construct a
31
BranchBuilder on the transport you want your branch on, and then call
32
appropriate build_ methods on it to get the shape of history you want.
34
This is meant as a helper for the test suite, not as a general class for
39
>>> from breezy.transport.memory import MemoryTransport
40
>>> builder = BranchBuilder(MemoryTransport("memory:///"))
41
>>> builder.start_series()
42
>>> builder.build_snapshot(None, [
43
... ('add', ('', b'root-id', 'directory', '')),
44
... ('add', ('filename', b'f-id', 'file', b'content\n'))],
45
... revision_id=b'rev-id')
47
>>> builder.build_snapshot([b'rev-id'],
48
... [('modify', ('filename', b'new-content\n'))],
49
... revision_id=b'rev2-id')
51
>>> builder.finish_series()
52
>>> branch = builder.get_branch()
54
:ivar _tree: This is a private member which is not meant to be modified by
55
users of this class. While a 'series' is in progress, it should hold a
56
MemoryTree with the contents of the last commit (ready to be modified
57
by the next build_snapshot command) with a held write lock. Outside of
58
a series in progress, it should be None.
61
def __init__(self, transport=None, format=None, branch=None):
62
"""Construct a BranchBuilder on transport.
64
:param transport: The transport the branch should be created on.
65
If the path of the transport does not exist but its parent does
67
:param format: Either a BzrDirFormat, or the name of a format in the
68
controldir format registry for the branch to be built.
69
:param branch: An already constructed branch to use. This param is
70
mutually exclusive with the transport and format params.
72
if branch is not None:
73
if format is not None:
75
"branch and format kwargs are mutually exclusive")
76
if transport is not None:
78
"branch and transport kwargs are mutually exclusive")
81
if not transport.has('.'):
85
if isinstance(format, str):
86
format = controldir.format_registry.make_controldir(format)
87
self._branch = controldir.ControlDir.create_branch_convenience(
88
transport.base, format=format, force_new_tree=False)
91
def build_commit(self, parent_ids=None, allow_leftmost_as_ghost=False,
93
"""Build a commit on the branch.
95
This makes a commit with no real file content for when you only want
96
to look at the revision graph structure.
98
:param commit_kwargs: Arguments to pass through to commit, such as
101
if parent_ids is not None:
102
if len(parent_ids) == 0:
103
base_id = revision.NULL_REVISION
105
base_id = parent_ids[0]
106
if base_id != self._branch.last_revision():
107
self._move_branch_pointer(
108
base_id, allow_leftmost_as_ghost=allow_leftmost_as_ghost)
109
tree = self._branch.create_memorytree()
110
with tree.lock_write():
111
if parent_ids is not None:
114
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
116
return self._do_commit(tree, **commit_kwargs)
118
def _do_commit(self, tree, message=None, message_callback=None, **kwargs):
119
reporter = commit.NullCommitReporter()
120
if message is None and message_callback is None:
121
message = u'commit %d' % (self._branch.revno() + 1,)
122
return tree.commit(message, message_callback=message_callback,
123
reporter=reporter, **kwargs)
125
def _move_branch_pointer(self, new_revision_id,
126
allow_leftmost_as_ghost=False):
127
"""Point self._branch to a different revision id."""
128
with self._branch.lock_write():
129
# We don't seem to have a simple set_last_revision(), so we
131
cur_revno, cur_revision_id = self._branch.last_revision_info()
133
g = self._branch.repository.get_graph()
134
new_revno = g.find_distance_to_null(
135
new_revision_id, [(cur_revision_id, cur_revno)])
136
self._branch.set_last_revision_info(new_revno, new_revision_id)
137
except errors.GhostRevisionsHaveNoRevno:
138
if not allow_leftmost_as_ghost:
141
if self._tree is not None:
142
# We are currently processing a series, but when switching branch
143
# pointers, it is easiest to just create a new memory tree.
144
# That way we are sure to have the right files-on-disk
145
# We are cheating a little bit here, and locking the new tree
146
# before the old tree is unlocked. But that way the branch stays
148
new_tree = self._branch.create_memorytree()
149
new_tree.lock_write()
151
self._tree = new_tree
153
def start_series(self):
154
"""We will be creating a series of commits.
156
This allows us to hold open the locks while we are processing.
158
Make sure to call 'finish_series' when you are done.
160
if self._tree is not None:
161
raise AssertionError('You cannot start a new series while a'
162
' series is already going.')
163
self._tree = self._branch.create_memorytree()
164
self._tree.lock_write()
166
def finish_series(self):
167
"""Call this after start_series to unlock the various objects."""
171
def build_snapshot(self, parent_ids, actions, message=None, timestamp=None,
172
allow_leftmost_as_ghost=False, committer=None,
173
timezone=None, message_callback=None, revision_id=None):
174
"""Build a commit, shaped in a specific way.
176
Most of the actions are self-explanatory. 'flush' is special action to
177
break a series of actions into discrete steps so that complex changes
178
(such as unversioning a file-id and re-adding it with a different kind)
179
can be expressed in a way that will clearly work.
181
:param parent_ids: A list of parent_ids to use for the commit.
182
It can be None, which indicates to use the last commit.
183
:param actions: A list of actions to perform. Supported actions are:
184
('add', ('path', b'file-id', 'kind', b'content' or None))
185
('modify', ('path', b'new-content'))
186
('unversion', 'path')
187
('rename', ('orig-path', 'new-path'))
189
:param message: An optional commit message, if not supplied, a default
190
commit message will be written.
191
:param message_callback: A message callback to use for the commit, as
192
per mutabletree.commit.
193
:param timestamp: If non-None, set the timestamp of the commit to this
195
:param timezone: An optional timezone for timestamp.
196
:param committer: An optional username to use for commit
197
:param allow_leftmost_as_ghost: True if the leftmost parent should be
198
permitted to be a ghost.
199
:param revision_id: The handle for the new commit, can be None
200
:return: The revision_id of the new commit
202
if parent_ids is not None:
203
if len(parent_ids) == 0:
204
base_id = revision.NULL_REVISION
206
base_id = parent_ids[0]
207
if base_id != self._branch.last_revision():
208
self._move_branch_pointer(
209
base_id, allow_leftmost_as_ghost=allow_leftmost_as_ghost)
211
if self._tree is not None:
214
tree = self._branch.create_memorytree()
215
with tree.lock_write():
216
if parent_ids is not None:
219
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
220
# Unfortunately, MemoryTree.add(directory) just creates an
221
# inventory entry. And the only public function to create a
222
# directory is MemoryTree.mkdir() which creates the directory, but
223
# also always adds it. So we have to use a multi-pass setup.
224
pending = _PendingActions()
225
for action, info in actions:
227
path, file_id, kind, content = info
228
if kind == 'directory':
229
pending.to_add_directories.append((path, file_id))
231
pending.to_add_files.append(path)
232
pending.to_add_file_ids.append(file_id)
233
pending.to_add_kinds.append(kind)
234
if content is not None:
235
pending.new_contents[path] = content
236
elif action == 'modify':
238
pending.new_contents[path] = content
239
elif action == 'unversion':
240
pending.to_unversion_paths.add(info)
241
elif action == 'rename':
242
from_relpath, to_relpath = info
243
pending.to_rename.append((from_relpath, to_relpath))
244
elif action == 'flush':
245
self._flush_pending(tree, pending)
246
pending = _PendingActions()
248
raise ValueError('Unknown build action: "%s"' % (action,))
249
self._flush_pending(tree, pending)
250
return self._do_commit(
251
tree, message=message, rev_id=revision_id,
252
timestamp=timestamp, timezone=timezone, committer=committer,
253
message_callback=message_callback)
255
def _flush_pending(self, tree, pending):
256
"""Flush the pending actions in 'pending', i.e. apply them to tree."""
257
for path, file_id in pending.to_add_directories:
259
if tree.has_filename(path) \
260
and path in pending.to_unversion_paths:
261
# We're overwriting this path, no need to unversion
262
pending.to_unversion_paths.discard(path)
263
# Special case, because the path already exists
264
tree.add([path], [file_id], ['directory'])
266
tree.mkdir(path, file_id)
267
for from_relpath, to_relpath in pending.to_rename:
268
tree.rename_one(from_relpath, to_relpath)
269
if pending.to_unversion_paths:
270
tree.unversion(pending.to_unversion_paths)
271
tree.add(pending.to_add_files, pending.to_add_file_ids,
272
pending.to_add_kinds)
273
for path, content in pending.new_contents.items():
274
tree.put_file_bytes_non_atomic(path, content)
276
def get_branch(self):
277
"""Return the branch created by the builder."""
281
class _PendingActions(object):
282
"""Pending actions for build_snapshot to take.
284
This is just a simple class to hold a bunch of the intermediate state of
285
build_snapshot in single object.
289
self.to_add_directories = []
290
self.to_add_files = []
291
self.to_add_file_ids = []
292
self.to_add_kinds = []
293
self.new_contents = {}
294
self.to_unversion_paths = set()