/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: 2019-07-07 20:43:57 UTC
  • mfrom: (7370 work)
  • mto: This revision was merged to the branch mainline in revision 7378.
  • Revision ID: jelmer@jelmer.uk-20190707204357-82bayabtwikhoi0i
merge trunk.

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  # noqa: F401
 
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
        from .. import (
 
75
            controldir,
 
76
            trace,
 
77
            ui,
 
78
            urlutils,
 
79
            )
 
80
        from ..controldir import (
 
81
            ControlDir,
 
82
            )
 
83
        from ..errors import (
 
84
            BzrError,
 
85
            BzrCommandError,
 
86
            NoRepositoryPresent,
 
87
            NotBranchError,
 
88
            )
 
89
        from ..i18n 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 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(
 
115
                gettext("%r is not a git repository") % src_location)
 
116
        try:
 
117
            target_controldir = ControlDir.open_from_transport(dest_transport)
 
118
        except NotBranchError:
 
119
            target_controldir = dest_format.initialize_on_transport_ex(
 
120
                dest_transport, shared_repo=True)[1]
 
121
        try:
 
122
            target_repo = target_controldir.find_repository()
 
123
        except NoRepositoryPresent:
 
124
            target_repo = target_controldir.create_repository(shared=True)
 
125
 
 
126
        if not target_repo.supports_rich_root():
 
127
            raise BzrCommandError(
 
128
                gettext("Target repository doesn't support rich roots"))
 
129
 
 
130
        interrepo = InterRepository.get(source_repo, target_repo)
 
131
        mapping = source_repo.get_mapping()
 
132
        refs = interrepo.fetch()
 
133
        with ui.ui_factory.nested_progress_bar() as pb:
 
134
            for i, (name, sha) in enumerate(viewitems(refs)):
 
135
                try:
 
136
                    branch_name = ref_to_branch_name(name)
 
137
                except ValueError:
 
138
                    # Not a branch, ignore
 
139
                    continue
 
140
                pb.update(gettext("creating branches"), i, len(refs))
 
141
                if (getattr(target_controldir._format, "colocated_branches",
 
142
                            False) and colocated):
 
143
                    if name == "HEAD":
 
144
                        branch_name = None
 
145
                    head_branch = self._get_colocated_branch(
 
146
                        target_controldir, branch_name)
 
147
                else:
 
148
                    head_branch = self._get_nested_branch(
 
149
                        dest_transport, dest_format, branch_name)
 
150
                revid = mapping.revision_id_foreign_to_bzr(sha)
 
151
                source_branch = LocalGitBranch(
 
152
                    source_repo.controldir, source_repo, sha)
 
153
                if head_branch.last_revision() != revid:
 
154
                    head_branch.generate_revision_history(revid)
 
155
                source_branch.tags.merge_to(head_branch.tags)
 
156
                if not head_branch.get_parent():
 
157
                    url = urlutils.join_segment_parameters(
 
158
                        source_branch.base,
 
159
                        {"branch": urlutils.escape(branch_name)})
 
160
                    head_branch.set_parent(url)
 
161
        trace.note(gettext(
 
162
            "Use 'bzr checkout' to create a working tree in "
 
163
            "the newly created branches."))
 
164
 
 
165
 
 
166
class cmd_git_object(Command):
 
167
    """List or display Git objects by SHA.
 
168
 
 
169
    Cat a particular object's Git representation if a SHA is specified.
 
170
    List all available SHAs otherwise.
 
171
    """
 
172
 
 
173
    hidden = True
 
174
 
 
175
    aliases = ["git-objects", "git-cat"]
 
176
    takes_args = ["sha1?"]
 
177
    takes_options = [Option('directory',
 
178
                            short_name='d',
 
179
                            help='Location of repository.', type=text_type),
 
180
                     Option('pretty', help='Pretty-print objects.')]
 
181
    encoding_type = 'exact'
 
182
 
 
183
    @display_command
 
184
    def run(self, sha1=None, directory=".", pretty=False):
 
185
        from ..errors import (
 
186
            BzrCommandError,
 
187
            )
 
188
        from ..controldir import (
 
189
            ControlDir,
 
190
            )
 
191
        from .object_store import (
 
192
            get_object_store,
 
193
            )
 
194
        from ..i18n import gettext
 
195
        controldir, _ = ControlDir.open_containing(directory)
 
196
        repo = controldir.find_repository()
 
197
        object_store = get_object_store(repo)
 
198
        with object_store.lock_read():
 
199
            if sha1 is not None:
 
200
                try:
 
201
                    obj = object_store[sha1.encode('ascii')]
 
202
                except KeyError:
 
203
                    raise BzrCommandError(
 
204
                        gettext("Object not found: %s") % sha1)
 
205
                if pretty:
 
206
                    text = obj.as_pretty_string()
 
207
                else:
 
208
                    text = obj.as_raw_string()
 
209
                self.outf.write(text)
 
210
            else:
 
211
                for sha1 in object_store:
 
212
                    self.outf.write("%s\n" % sha1.decode('ascii'))
 
213
 
 
214
 
 
215
class cmd_git_refs(Command):
 
216
    """Output all of the virtual refs for a repository.
 
217
 
 
218
    """
 
219
 
 
220
    hidden = True
 
221
 
 
222
    takes_args = ["location?"]
 
223
 
 
224
    @display_command
 
225
    def run(self, location="."):
 
226
        from ..controldir import (
 
227
            ControlDir,
 
228
            )
 
229
        from .refs import (
 
230
            get_refs_container,
 
231
            )
 
232
        from .object_store import (
 
233
            get_object_store,
 
234
            )
 
235
        controldir, _ = ControlDir.open_containing(location)
 
236
        repo = controldir.find_repository()
 
237
        object_store = get_object_store(repo)
 
238
        with object_store.lock_read():
 
239
            refs = get_refs_container(controldir, object_store)
 
240
            for k, v in sorted(viewitems(refs.as_dict())):
 
241
                self.outf.write("%s -> %s\n" %
 
242
                                (k.decode('utf-8'), v.decode('utf-8')))
 
243
 
 
244
 
 
245
class cmd_git_apply(Command):
 
246
    """Apply a series of git-am style patches.
 
247
 
 
248
    This command will in the future probably be integrated into "bzr pull".
 
249
    """
 
250
 
 
251
    takes_options = [
 
252
        Option('signoff', short_name='s', help='Add a Signed-off-by line.'),
 
253
        Option('force',
 
254
               help='Apply patches even if tree has uncommitted changes.')
 
255
        ]
 
256
    takes_args = ["patches*"]
 
257
 
 
258
    def _apply_patch(self, wt, f, signoff):
 
259
        """Apply a patch.
 
260
 
 
261
        :param wt: A Bazaar working tree object.
 
262
        :param f: Patch file to read.
 
263
        :param signoff: Add Signed-Off-By flag.
 
264
        """
 
265
        from dulwich.patch import git_am_patch_split
 
266
        from breezy.patch import patch_tree
 
267
        (c, diff, version) = git_am_patch_split(f)
 
268
        # FIXME: Cope with git-specific bits in patch
 
269
        # FIXME: Add new files to working tree
 
270
        patch_tree(wt, [diff], strip=1, out=self.outf)
 
271
        message = c.message.decode('utf-8')
 
272
        if signoff:
 
273
            signed_off_by = wt.branch.get_config().username()
 
274
            message += "Signed-off-by: %s\n" % (signed_off_by, )
 
275
        wt.commit(authors=[c.author.decode('utf-8')], message=message)
 
276
 
 
277
    def run(self, patches_list=None, signoff=False, force=False):
 
278
        from ..errors import UncommittedChanges
 
279
        from ..workingtree import WorkingTree
 
280
        if patches_list is None:
 
281
            patches_list = []
 
282
 
 
283
        tree, _ = WorkingTree.open_containing(".")
 
284
        if tree.basis_tree().changes_from(tree).has_changed() and not force:
 
285
            raise UncommittedChanges(tree)
 
286
        with tree.lock_write():
 
287
            for patch in patches_list:
 
288
                with open(patch, 'r') as f:
 
289
                    self._apply_patch(tree, f, signoff=signoff)
 
290
 
 
291
 
 
292
class cmd_git_push_pristine_tar_deltas(Command):
 
293
    """Push pristine tar deltas to a git repository."""
 
294
 
 
295
    takes_options = [Option('directory',
 
296
                            short_name='d',
 
297
                            help='Location of repository.', type=text_type)]
 
298
    takes_args = ['target', 'package']
 
299
 
 
300
    def run(self, target, package, directory='.'):
 
301
        from ..branch import Branch
 
302
        from ..errors import (
 
303
            BzrCommandError,
 
304
            NoSuchRevision,
 
305
            )
 
306
        from ..trace import warning
 
307
        from ..repository import Repository
 
308
        from .object_store import get_object_store
 
309
        from .pristine_tar import (
 
310
            revision_pristine_tar_data,
 
311
            store_git_pristine_tar_data,
 
312
            )
 
313
        source = Branch.open_containing(directory)[0]
 
314
        target_bzr = Repository.open(target)
 
315
        target = getattr(target_bzr, '_git', None)
 
316
        if target is None:
 
317
            raise BzrCommandError("Target not a git repository")
 
318
        git_store = get_object_store(source.repository)
 
319
        with git_store.lock_read():
 
320
            tag_dict = source.tags.get_tag_dict()
 
321
            for name, revid in tag_dict.iteritems():
 
322
                try:
 
323
                    rev = source.repository.get_revision(revid)
 
324
                except NoSuchRevision:
 
325
                    continue
 
326
                try:
 
327
                    delta, kind = revision_pristine_tar_data(rev)
 
328
                except KeyError:
 
329
                    continue
 
330
                gitid = git_store._lookup_revision_sha1(revid)
 
331
                if (not (name.startswith('upstream/') or
 
332
                         name.startswith('upstream-'))):
 
333
                    warning(
 
334
                        "Unexpected pristine tar revision tagged %s. "
 
335
                        "Ignoring.", name)
 
336
                    continue
 
337
                upstream_version = name[len("upstream/"):]
 
338
                filename = '%s_%s.orig.tar.%s' % (
 
339
                    package, upstream_version, kind)
 
340
                if gitid not in target:
 
341
                    warning(
 
342
                        "base git id %s for %s missing in target repository",
 
343
                        gitid, filename)
 
344
                store_git_pristine_tar_data(target, filename.encode('utf-8'),
 
345
                                            delta, gitid)