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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
17
"""Utility for create branches with particular contents."""
19
from __future__ import absolute_import
19
from bzrlib import bzrdir, errors, memorytree
33
22
class BranchBuilder(object):
34
r"""A BranchBuilder aids creating Branches with particular shapes.
23
"""A BranchBuilder aids creating Branches with particular shapes.
36
25
The expected way to use BranchBuilder is to construct a
37
26
BranchBuilder on the transport you want your branch on, and then call
38
27
appropriate build_ methods on it to get the shape of history you want.
40
This is meant as a helper for the test suite, not as a general class for
45
>>> from breezy.transport.memory import MemoryTransport
46
>>> builder = BranchBuilder(MemoryTransport("memory:///"))
47
>>> builder.start_series()
48
>>> builder.build_snapshot(None, [
49
... ('add', ('', b'root-id', 'directory', '')),
50
... ('add', ('filename', b'f-id', 'file', 'content\n'))],
51
... revision_id=b'rev-id')
53
>>> builder.build_snapshot([b'rev-id'],
54
... [('modify', (b'f-id', 'new-content\n'))],
55
... revision_id=b'rev2-id')
57
>>> builder.finish_series()
58
>>> branch = builder.get_branch()
60
:ivar _tree: This is a private member which is not meant to be modified by
61
users of this class. While a 'series' is in progress, it should hold a
62
MemoryTree with the contents of the last commit (ready to be modified
63
by the next build_snapshot command) with a held write lock. Outside of
64
a series in progress, it should be None.
30
builder = BranchBuilder(self.get_transport().clone('relpath'))
31
builder.build_commit()
32
builder.build_commit()
33
builder.build_commit()
34
branch = builder.get_branch()
67
def __init__(self, transport=None, format=None, branch=None):
37
def __init__(self, transport, format=None):
68
38
"""Construct a BranchBuilder on transport.
70
40
:param transport: The transport the branch should be created on.
71
41
If the path of the transport does not exist but its parent does
72
42
it will be created.
73
:param format: Either a BzrDirFormat, or the name of a format in the
74
controldir format registry for the branch to be built.
75
:param branch: An already constructed branch to use. This param is
76
mutually exclusive with the transport and format params.
78
if branch is not None:
79
if format is not None:
81
"branch and format kwargs are mutually exclusive")
82
if transport is not None:
84
"branch and transport kwargs are mutually exclusive")
87
if not transport.has('.'):
91
if isinstance(format, str):
92
format = controldir.format_registry.make_controldir(format)
93
self._branch = controldir.ControlDir.create_branch_convenience(
94
transport.base, format=format, force_new_tree=False)
97
def build_commit(self, parent_ids=None, allow_leftmost_as_ghost=False,
99
"""Build a commit on the branch.
101
This makes a commit with no real file content for when you only want
102
to look at the revision graph structure.
104
:param commit_kwargs: Arguments to pass through to commit, such as
107
if parent_ids is not None:
108
if len(parent_ids) == 0:
109
base_id = revision.NULL_REVISION
111
base_id = parent_ids[0]
112
if base_id != self._branch.last_revision():
113
self._move_branch_pointer(base_id,
114
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
115
tree = self._branch.create_memorytree()
116
with tree.lock_write():
117
if parent_ids is not None:
118
tree.set_parent_ids(parent_ids,
119
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
43
:param format: The name of a format in the bzrdir format registry
44
for the branch to be built.
46
if not transport.has('.'):
50
self._branch = bzrdir.BzrDir.create_branch_convenience(transport.base,
51
format=bzrdir.format_registry.make_bzrdir(format))
53
def build_commit(self):
54
"""Build a commit on the branch."""
55
tree = memorytree.MemoryTree.create_on_branch(self._branch)
121
return self._do_commit(tree, **commit_kwargs)
123
def _do_commit(self, tree, message=None, message_callback=None, **kwargs):
124
reporter = commit.NullCommitReporter()
125
if message is None and message_callback is None:
126
message = u'commit %d' % (self._branch.revno() + 1,)
127
return tree.commit(message, message_callback=message_callback,
131
def _move_branch_pointer(self, new_revision_id,
132
allow_leftmost_as_ghost=False):
133
"""Point self._branch to a different revision id."""
134
with self._branch.lock_write():
135
# We don't seem to have a simple set_last_revision(), so we
137
cur_revno, cur_revision_id = self._branch.last_revision_info()
139
g = self._branch.repository.get_graph()
140
new_revno = g.find_distance_to_null(new_revision_id,
141
[(cur_revision_id, cur_revno)])
142
self._branch.set_last_revision_info(new_revno, new_revision_id)
143
except errors.GhostRevisionsHaveNoRevno:
144
if not allow_leftmost_as_ghost:
147
if self._tree is not None:
148
# We are currently processing a series, but when switching branch
149
# pointers, it is easiest to just create a new memory tree.
150
# That way we are sure to have the right files-on-disk
151
# We are cheating a little bit here, and locking the new tree
152
# before the old tree is unlocked. But that way the branch stays
154
new_tree = self._branch.create_memorytree()
155
new_tree.lock_write()
157
self._tree = new_tree
159
def start_series(self):
160
"""We will be creating a series of commits.
162
This allows us to hold open the locks while we are processing.
164
Make sure to call 'finish_series' when you are done.
166
if self._tree is not None:
167
raise AssertionError('You cannot start a new series while a'
168
' series is already going.')
169
self._tree = self._branch.create_memorytree()
170
self._tree.lock_write()
172
def finish_series(self):
173
"""Call this after start_series to unlock the various objects."""
177
def build_snapshot(self, parent_ids, actions, message=None, timestamp=None,
178
allow_leftmost_as_ghost=False, committer=None, timezone=None,
179
message_callback=None, revision_id=None):
180
"""Build a commit, shaped in a specific way.
182
Most of the actions are self-explanatory. 'flush' is special action to
183
break a series of actions into discrete steps so that complex changes
184
(such as unversioning a file-id and re-adding it with a different kind)
185
can be expressed in a way that will clearly work.
187
:param parent_ids: A list of parent_ids to use for the commit.
188
It can be None, which indicates to use the last commit.
189
:param actions: A list of actions to perform. Supported actions are:
190
('add', ('path', b'file-id', 'kind', 'content' or None))
191
('modify', ('path', 'new-content'))
192
('unversion', 'path')
193
('rename', ('orig-path', 'new-path'))
195
:param message: An optional commit message, if not supplied, a default
196
commit message will be written.
197
:param message_callback: A message callback to use for the commit, as
198
per mutabletree.commit.
199
:param timestamp: If non-None, set the timestamp of the commit to this
201
:param timezone: An optional timezone for timestamp.
202
:param committer: An optional username to use for commit
203
:param allow_leftmost_as_ghost: True if the leftmost parent should be
204
permitted to be a ghost.
205
:param revision_id: The handle for the new commit, can be None
206
:return: The revision_id of the new commit
208
if parent_ids is not None:
209
if len(parent_ids) == 0:
210
base_id = revision.NULL_REVISION
212
base_id = parent_ids[0]
213
if base_id != self._branch.last_revision():
214
self._move_branch_pointer(base_id,
215
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
217
if self._tree is not None:
220
tree = self._branch.create_memorytree()
221
with tree.lock_write():
222
if parent_ids is not None:
223
tree.set_parent_ids(parent_ids,
224
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
225
# Unfortunately, MemoryTree.add(directory) just creates an
226
# inventory entry. And the only public function to create a
227
# directory is MemoryTree.mkdir() which creates the directory, but
228
# also always adds it. So we have to use a multi-pass setup.
229
pending = _PendingActions()
230
for action, info in actions:
232
path, file_id, kind, content = info
233
if kind == 'directory':
234
pending.to_add_directories.append((path, file_id))
236
pending.to_add_files.append(path)
237
pending.to_add_file_ids.append(file_id)
238
pending.to_add_kinds.append(kind)
239
if content is not None:
240
pending.new_contents[path] = content
241
elif action == 'modify':
243
pending.new_contents[path] = content
244
elif action == 'unversion':
245
pending.to_unversion_paths.add(info)
246
elif action == 'rename':
247
from_relpath, to_relpath = info
248
pending.to_rename.append((from_relpath, to_relpath))
249
elif action == 'flush':
250
self._flush_pending(tree, pending)
251
pending = _PendingActions()
253
raise ValueError('Unknown build action: "%s"' % (action,))
254
self._flush_pending(tree, pending)
255
return self._do_commit(tree, message=message, rev_id=revision_id,
256
timestamp=timestamp, timezone=timezone, committer=committer,
257
message_callback=message_callback)
259
def _flush_pending(self, tree, pending):
260
"""Flush the pending actions in 'pending', i.e. apply them to 'tree'."""
261
for path, file_id in pending.to_add_directories:
263
if tree.has_filename(path) and path in pending.to_unversion_paths:
264
# We're overwriting this path, no need to unversion
265
pending.to_unversion_paths.discard(path)
266
# Special case, because the path already exists
267
tree.add([path], [file_id], ['directory'])
269
tree.mkdir(path, file_id)
270
for from_relpath, to_relpath in pending.to_rename:
271
tree.rename_one(from_relpath, to_relpath)
272
if pending.to_unversion_paths:
273
tree.unversion(pending.to_unversion_paths)
274
tree.add(pending.to_add_files, pending.to_add_file_ids, pending.to_add_kinds)
275
for path, content in viewitems(pending.new_contents):
276
tree.put_file_bytes_non_atomic(path, content)
59
return tree.commit('commit %d' % (self._branch.revno() + 1))
278
63
def get_branch(self):
279
64
"""Return the branch created by the builder."""
280
65
return self._branch
283
class _PendingActions(object):
284
"""Pending actions for build_snapshot to take.
286
This is just a simple class to hold a bunch of the intermediate state of
287
build_snapshot in single object.
291
self.to_add_directories = []
292
self.to_add_files = []
293
self.to_add_file_ids = []
294
self.to_add_kinds = []
295
self.new_contents = {}
296
self.to_unversion_paths = set()