/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/branchbuilder.py

  • Committer: Vincent Ladeuil
  • Date: 2007-11-24 14:20:59 UTC
  • mto: (3928.1.1 bzr.integration)
  • mto: This revision was merged to the branch mainline in revision 3929.
  • Revision ID: v.ladeuil+lp@free.fr-20071124142059-2114qtsgfdv8g9p1
Ssl files needed for the test https server.

* bzrlib/tests/ssl_certs/create_ssls.py: 
Script to create the ssl keys and certificates.

* bzrlib/tests/ssl_certs/server.crt: 
Server certificate signed by the certificate authority.

* bzrlib/tests/ssl_certs/server.csr: 
Server certificate signing request.

* bzrlib/tests/ssl_certs/server_without_pass.key: 
Server key usable without password.

* bzrlib/tests/ssl_certs/server_with_pass.key: 
Server key.

* bzrlib/tests/ssl_certs/ca.key: 
Certificate authority private key.

* bzrlib/tests/ssl_certs/ca.crt: 
Certificate authority certificate.

* bzrlib/tests/ssl_certs/__init__.py: 
Provide access to ssl files (keys and certificates). 

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2007 Canonical Ltd
2
2
#
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
12
12
#
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
16
16
 
17
17
"""Utility for create branches with particular contents."""
18
18
 
19
 
from __future__ import absolute_import
20
 
 
21
 
from . import (
22
 
    controldir,
23
 
    commit,
24
 
    errors,
25
 
    memorytree,
26
 
    revision,
27
 
    )
28
 
from .sixish import (
29
 
    viewitems,
30
 
    )
 
19
from bzrlib import bzrdir, errors, memorytree
31
20
 
32
21
 
33
22
class BranchBuilder(object):
34
 
    r"""A BranchBuilder aids creating Branches with particular shapes.
35
 
 
 
23
    """A BranchBuilder aids creating Branches with particular shapes.
 
24
    
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.
39
28
 
40
 
    This is meant as a helper for the test suite, not as a general class for
41
 
    real data.
42
 
 
43
29
    For instance:
44
 
 
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')
52
 
    'rev-id'
53
 
    >>> builder.build_snapshot([b'rev-id'],
54
 
    ...     [('modify', (b'f-id', 'new-content\n'))],
55
 
    ...     revision_id=b'rev2-id')
56
 
    'rev2-id'
57
 
    >>> builder.finish_series()
58
 
    >>> branch = builder.get_branch()
59
 
 
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()
65
35
    """
66
36
 
67
 
    def __init__(self, transport=None, format=None, branch=None):
 
37
    def __init__(self, transport, format=None):
68
38
        """Construct a BranchBuilder on transport.
69
 
 
 
39
        
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.
77
 
        """
78
 
        if branch is not None:
79
 
            if format is not None:
80
 
                raise AssertionError(
81
 
                    "branch and format kwargs are mutually exclusive")
82
 
            if transport is not None:
83
 
                raise AssertionError(
84
 
                    "branch and transport kwargs are mutually exclusive")
85
 
            self._branch = branch
86
 
        else:
87
 
            if not transport.has('.'):
88
 
                transport.mkdir('.')
89
 
            if format is None:
90
 
                format = 'default'
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)
95
 
        self._tree = None
96
 
 
97
 
    def build_commit(self, parent_ids=None, allow_leftmost_as_ghost=False,
98
 
                     **commit_kwargs):
99
 
        """Build a commit on the branch.
100
 
 
101
 
        This makes a commit with no real file content for when you only want
102
 
        to look at the revision graph structure.
103
 
 
104
 
        :param commit_kwargs: Arguments to pass through to commit, such as
105
 
             timestamp.
106
 
        """
107
 
        if parent_ids is not None:
108
 
            if len(parent_ids) == 0:
109
 
                base_id = revision.NULL_REVISION
110
 
            else:
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.
 
45
        """
 
46
        if not transport.has('.'):
 
47
            transport.mkdir('.')
 
48
        if format is None:
 
49
            format = 'default'
 
50
        self._branch = bzrdir.BzrDir.create_branch_convenience(transport.base,
 
51
            format=bzrdir.format_registry.make_bzrdir(format))
 
52
 
 
53
    def build_commit(self):
 
54
        """Build a commit on the branch."""
 
55
        tree = memorytree.MemoryTree.create_on_branch(self._branch)
 
56
        tree.lock_write()
 
57
        try:
120
58
            tree.add('')
121
 
            return self._do_commit(tree, **commit_kwargs)
122
 
 
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,
128
 
            reporter=reporter,
129
 
            **kwargs)
130
 
 
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
136
 
            # implement it here.
137
 
            cur_revno, cur_revision_id = self._branch.last_revision_info()
138
 
            try:
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:
145
 
                    raise
146
 
                new_revno = 1
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
153
 
            # locked throughout.
154
 
            new_tree = self._branch.create_memorytree()
155
 
            new_tree.lock_write()
156
 
            self._tree.unlock()
157
 
            self._tree = new_tree
158
 
 
159
 
    def start_series(self):
160
 
        """We will be creating a series of commits.
161
 
 
162
 
        This allows us to hold open the locks while we are processing.
163
 
 
164
 
        Make sure to call 'finish_series' when you are done.
165
 
        """
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()
171
 
 
172
 
    def finish_series(self):
173
 
        """Call this after start_series to unlock the various objects."""
174
 
        self._tree.unlock()
175
 
        self._tree = None
176
 
 
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.
181
 
 
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.
186
 
 
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'))
194
 
            ('flush', None)
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
200
 
            value.
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
207
 
        """
208
 
        if parent_ids is not None:
209
 
            if len(parent_ids) == 0:
210
 
                base_id = revision.NULL_REVISION
211
 
            else:
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)
216
 
 
217
 
        if self._tree is not None:
218
 
            tree = self._tree
219
 
        else:
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:
231
 
                if action == 'add':
232
 
                    path, file_id, kind, content = info
233
 
                    if kind == 'directory':
234
 
                        pending.to_add_directories.append((path, file_id))
235
 
                    else:
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':
242
 
                    path, content = info
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()
252
 
                else:
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)
258
 
 
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:
262
 
            if path == '':
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'])
268
 
            else:
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))
 
60
        finally:
 
61
            tree.unlock()
277
62
 
278
63
    def get_branch(self):
279
64
        """Return the branch created by the builder."""
280
65
        return self._branch
281
 
 
282
 
 
283
 
class _PendingActions(object):
284
 
    """Pending actions for build_snapshot to take.
285
 
 
286
 
    This is just a simple class to hold a bunch of the intermediate state of
287
 
    build_snapshot in single object.
288
 
    """
289
 
 
290
 
    def __init__(self):
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()
297
 
        self.to_rename = []
298