/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 commands.py

  • Committer: Jelmer Vernooij
  • Date: 2018-03-17 17:54:17 UTC
  • mto: (0.200.1859 work)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180317175417-4ag21da38udunec9
Add tests for memorytree.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2009 Canonical Ltd
 
2
 
 
3
# Authors: Robert Collins <robert.collins@canonical.com>
 
4
#          Jelmer Vernooij <jelmer@samba.org>
 
5
#          John Carr <john.carr@unrouted.co.uk>
 
6
#
 
7
# This program is free software; you can redistribute it and/or modify
 
8
# it under the terms of the GNU General Public License as published by
 
9
# the Free Software Foundation; either version 2 of the License, or
 
10
# (at your option) any later version.
 
11
#
 
12
# This program is distributed in the hope that it will be useful,
 
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
15
# GNU General Public License for more details.
 
16
#
 
17
# You should have received a copy of the GNU General Public License
 
18
# along with this program; if not, write to the Free Software
 
19
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
20
 
 
21
"""Git-specific subcommands for Bazaar."""
 
22
 
 
23
from __future__ import absolute_import
 
24
 
 
25
import breezy.bzr.bzrdir
 
26
from ...commands import (
 
27
    Command,
 
28
    display_command,
 
29
    )
 
30
from ...option import (
 
31
    Option,
 
32
    )
 
33
 
 
34
 
 
35
class cmd_git_import(Command):
 
36
    """Import all branches from a git repository.
 
37
 
 
38
    """
 
39
 
 
40
    takes_args = ["src_location", "dest_location?"]
 
41
 
 
42
    takes_options = [
 
43
                     Option('colocated', help='Create colocated branches.'),
 
44
                     ]
 
45
 
 
46
    def _get_colocated_branch(self, target_controldir, name):
 
47
        from ...errors import NotBranchError
 
48
        try:
 
49
            return target_controldir.open_branch(name=name)
 
50
        except NotBranchError:
 
51
            return target_controldir.create_branch(name=name)
 
52
 
 
53
    def _get_nested_branch(self, dest_transport, dest_format, name):
 
54
        from ...controldir import ControlDir
 
55
        from ...errors import NotBranchError
 
56
        head_transport = dest_transport.clone(name)
 
57
        try:
 
58
            head_controldir = ControlDir.open_from_transport(head_transport)
 
59
        except NotBranchError:
 
60
            head_controldir = dest_format.initialize_on_transport_ex(
 
61
                head_transport, create_prefix=True)[1]
 
62
        try:
 
63
            return head_controldir.open_branch()
 
64
        except NotBranchError:
 
65
            return head_controldir.create_branch()
 
66
 
 
67
    def run(self, src_location, dest_location=None, colocated=False):
 
68
        import os
 
69
        import urllib
 
70
        from ... import (
 
71
            controldir,
 
72
            trace,
 
73
            ui,
 
74
            urlutils,
 
75
            )
 
76
        from ...controldir import (
 
77
            ControlDir,
 
78
            )
 
79
        from ...errors import (
 
80
            BzrCommandError,
 
81
            NoRepositoryPresent,
 
82
            NotBranchError,
 
83
            )
 
84
        from . import gettext
 
85
        from ...repository import (
 
86
            InterRepository,
 
87
            Repository,
 
88
            )
 
89
        from ...transport import get_transport
 
90
        from .branch import (
 
91
            LocalGitBranch,
 
92
            )
 
93
        from .refs import (
 
94
            ref_to_branch_name,
 
95
            )
 
96
        from .repository import GitRepository
 
97
 
 
98
        dest_format = controldir.ControlDirFormat.get_default_format()
 
99
        assert dest_format is not None
 
100
 
 
101
        if dest_location is None:
 
102
            dest_location = os.path.basename(src_location.rstrip("/\\"))
 
103
 
 
104
        dest_transport = get_transport(dest_location)
 
105
 
 
106
        source_repo = Repository.open(src_location)
 
107
        if not isinstance(source_repo, GitRepository):
 
108
            raise BzrCommandError(gettext("%r is not a git repository") % src_location)
 
109
        try:
 
110
            target_controldir = ControlDir.open_from_transport(dest_transport)
 
111
        except NotBranchError:
 
112
            target_controldir = dest_format.initialize_on_transport_ex(
 
113
                dest_transport, shared_repo=True)[1]
 
114
        try:
 
115
            target_repo = target_controldir.find_repository()
 
116
        except NoRepositoryPresent:
 
117
            target_repo = target_controldir.create_repository(shared=True)
 
118
 
 
119
        if not target_repo.supports_rich_root():
 
120
            raise BzrCommandError(gettext("Target repository doesn't support rich roots"))
 
121
 
 
122
        interrepo = InterRepository.get(source_repo, target_repo)
 
123
        mapping = source_repo.get_mapping()
 
124
        refs = interrepo.fetch()
 
125
        refs_dict = refs.as_dict()
 
126
        pb = ui.ui_factory.nested_progress_bar()
 
127
        try:
 
128
            for i, (name, sha) in enumerate(refs_dict.iteritems()):
 
129
                try:
 
130
                    branch_name = ref_to_branch_name(name)
 
131
                except ValueError:
 
132
                    # Not a branch, ignore
 
133
                    continue
 
134
                pb.update(gettext("creating branches"), i, len(refs_dict))
 
135
                if getattr(target_controldir._format, "colocated_branches", False) and colocated:
 
136
                    if name == "HEAD":
 
137
                        branch_name = None
 
138
                    head_branch = self._get_colocated_branch(target_controldir, branch_name)
 
139
                else:
 
140
                    head_branch = self._get_nested_branch(dest_transport, dest_format, branch_name)
 
141
                revid = mapping.revision_id_foreign_to_bzr(sha)
 
142
                source_branch = LocalGitBranch(source_repo.controldir, source_repo,
 
143
                    sha)
 
144
                if head_branch.last_revision() != revid:
 
145
                    head_branch.generate_revision_history(revid)
 
146
                source_branch.tags.merge_to(head_branch.tags)
 
147
                if not head_branch.get_parent():
 
148
                    url = urlutils.join_segment_parameters(
 
149
                        source_branch.base, {"ref": urllib.quote(name, '')})
 
150
                    head_branch.set_parent(url)
 
151
        finally:
 
152
            pb.finished()
 
153
        trace.note(gettext(
 
154
            "Use 'bzr checkout' to create a working tree in "
 
155
            "the newly created branches."))
 
156
 
 
157
 
 
158
class cmd_git_object(Command):
 
159
    """List or display Git objects by SHA.
 
160
 
 
161
    Cat a particular object's Git representation if a SHA is specified.
 
162
    List all available SHAs otherwise.
 
163
    """
 
164
 
 
165
    hidden = True
 
166
 
 
167
    aliases = ["git-objects", "git-cat"]
 
168
    takes_args = ["sha1?"]
 
169
    takes_options = [Option('directory',
 
170
        short_name='d',
 
171
        help='Location of repository.', type=unicode),
 
172
        Option('pretty', help='Pretty-print objects.')]
 
173
    encoding_type = 'exact'
 
174
 
 
175
    @display_command
 
176
    def run(self, sha1=None, directory=".", pretty=False):
 
177
        from ...errors import (
 
178
            BzrCommandError,
 
179
            )
 
180
        from ...controldir import (
 
181
            ControlDir,
 
182
            )
 
183
        from .object_store import (
 
184
            get_object_store,
 
185
            )
 
186
        from . import gettext
 
187
        controldir, _ = ControlDir.open_containing(directory)
 
188
        repo = controldir.find_repository()
 
189
        object_store = get_object_store(repo)
 
190
        with object_store.lock_read():
 
191
            if sha1 is not None:
 
192
                try:
 
193
                    obj = object_store[str(sha1)]
 
194
                except KeyError:
 
195
                    raise BzrCommandError(gettext("Object not found: %s") % sha1)
 
196
                if pretty:
 
197
                    text = obj.as_pretty_string()
 
198
                else:
 
199
                    text = obj.as_raw_string()
 
200
                self.outf.write(text)
 
201
            else:
 
202
                for sha1 in object_store:
 
203
                    self.outf.write("%s\n" % sha1)
 
204
 
 
205
 
 
206
class cmd_git_refs(Command):
 
207
    """Output all of the virtual refs for a repository.
 
208
 
 
209
    """
 
210
 
 
211
    hidden = True
 
212
 
 
213
    takes_args = ["location?"]
 
214
 
 
215
    @display_command
 
216
    def run(self, location="."):
 
217
        from ...controldir import (
 
218
            ControlDir,
 
219
            )
 
220
        from .refs import (
 
221
            get_refs_container,
 
222
            )
 
223
        from .object_store import (
 
224
            get_object_store,
 
225
            )
 
226
        controldir, _ = ControlDir.open_containing(location)
 
227
        repo = controldir.find_repository()
 
228
        object_store = get_object_store(repo)
 
229
        with object_store.lock_read():
 
230
            refs = get_refs_container(controldir, object_store)
 
231
            for k, v in refs.as_dict().iteritems():
 
232
                self.outf.write("%s -> %s\n" % (k, v))
 
233
 
 
234
 
 
235
class cmd_git_apply(Command):
 
236
    """Apply a series of git-am style patches.
 
237
 
 
238
    This command will in the future probably be integrated into 
 
239
    "bzr pull".
 
240
    """
 
241
 
 
242
    takes_options = [
 
243
        Option('signoff', short_name='s', help='Add a Signed-off-by line.'),
 
244
        Option('force',
 
245
            help='Apply patches even if tree has uncommitted changes.')
 
246
        ]
 
247
    takes_args = ["patches*"]
 
248
 
 
249
    def _apply_patch(self, wt, f, signoff):
 
250
        """Apply a patch.
 
251
 
 
252
        :param wt: A Bazaar working tree object.
 
253
        :param f: Patch file to read.
 
254
        :param signoff: Add Signed-Off-By flag.
 
255
        """
 
256
        from . import gettext
 
257
        from ...errors import BzrCommandError
 
258
        from dulwich.patch import git_am_patch_split
 
259
        import subprocess
 
260
        (c, diff, version) = git_am_patch_split(f)
 
261
        # FIXME: Cope with git-specific bits in patch
 
262
        # FIXME: Add new files to working tree
 
263
        p = subprocess.Popen(["patch", "-p1"], stdin=subprocess.PIPE,
 
264
            cwd=wt.basedir)
 
265
        p.communicate(diff)
 
266
        exitcode = p.wait()
 
267
        if exitcode != 0:
 
268
            raise BzrCommandError(gettext("error running patch"))
 
269
        message = c.message
 
270
        if signoff:
 
271
            signed_off_by = wt.branch.get_config().username()
 
272
            message += "Signed-off-by: %s\n" % signed_off_by.encode('utf-8')
 
273
        wt.commit(authors=[c.author], message=message)
 
274
 
 
275
    def run(self, patches_list=None, signoff=False, force=False):
 
276
        from ...errors import UncommittedChanges
 
277
        from ...workingtree import WorkingTree
 
278
        if patches_list is None:
 
279
            patches_list = []
 
280
 
 
281
        tree, _ = WorkingTree.open_containing(".")
 
282
        if tree.basis_tree().changes_from(tree).has_changed() and not force:
 
283
            raise UncommittedChanges(tree)
 
284
        with tree.lock_write():
 
285
            for patch in patches_list:
 
286
                with open(patch, 'r') as f:
 
287
                    self._apply_patch(tree, f, signoff=signoff)
 
288
 
 
289
 
 
290
class cmd_git_push_pristine_tar_deltas(Command):
 
291
    """Push pristine tar deltas to a git repository."""
 
292
 
 
293
    takes_options = [Option('directory',
 
294
        short_name='d',
 
295
        help='Location of repository.', type=unicode)]
 
296
    takes_args = ['target', 'package']
 
297
 
 
298
    def run(self, target, package, directory='.'):
 
299
        from ...branch import Branch
 
300
        from ...errors import (
 
301
            BzrCommandError,
 
302
            NoSuchRevision,
 
303
            )
 
304
        from ...trace import warning
 
305
        from ...repository import Repository
 
306
        from .object_store import get_object_store
 
307
        from .pristine_tar import (
 
308
            revision_pristine_tar_data,
 
309
            store_git_pristine_tar_data,
 
310
            )
 
311
        source = Branch.open_containing(directory)[0]
 
312
        target_bzr = Repository.open(target)
 
313
        target = getattr(target_bzr, '_git', None)
 
314
        if target is None:
 
315
            raise BzrCommandError("Target not a git repository")
 
316
        git_store = get_object_store(source.repository)
 
317
        with git_store.lock_read():
 
318
            tag_dict = source.tags.get_tag_dict()
 
319
            for name, revid in tag_dict.iteritems():
 
320
                try:
 
321
                    rev = source.repository.get_revision(revid)
 
322
                except NoSuchRevision:
 
323
                    continue
 
324
                try:
 
325
                    delta, kind = revision_pristine_tar_data(rev)
 
326
                except KeyError:
 
327
                    continue
 
328
                gitid = git_store._lookup_revision_sha1(revid)
 
329
                if not (name.startswith('upstream/') or name.startswith('upstream-')):
 
330
                    warning("Unexpected pristine tar revision tagged %s. Ignoring.",
 
331
                         name)
 
332
                    continue
 
333
                upstream_version = name[len("upstream/"):]
 
334
                filename = '%s_%s.orig.tar.%s' % (package, upstream_version, kind)
 
335
                if not gitid in target:
 
336
                    warning("base git id %s for %s missing in target repository",
 
337
                            gitid, filename)
 
338
                store_git_pristine_tar_data(target, filename.encode('utf-8'),
 
339
                    delta, gitid)