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

  • Committer: Jelmer Vernooij
  • Date: 2018-09-30 00:33:53 UTC
  • mto: This revision was merged to the branch mainline in revision 7134.
  • Revision ID: jelmer@jelmer.uk-20180930003353-2z5sugalbxfxfiru
When opening working trees with .git files, open the right control transport.

Show diffs side-by-side

added added

removed removed

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