/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-06-14 17:59:16 UTC
  • mto: This revision was merged to the branch mainline in revision 7065.
  • Revision ID: jelmer@jelmer.uk-20180614175916-a2e2xh5k533guq1x
Move breezy.plugins.git to breezy.git.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
 
22
22
"""Git-specific subcommands for Bazaar."""
23
23
 
24
 
import breezy.bzr  # noqa: F401
25
 
from breezy import controldir
 
24
from __future__ import absolute_import
 
25
 
 
26
import breezy.bzr.bzrdir
26
27
from ..commands import (
27
28
    Command,
28
29
    display_command,
29
30
    )
30
31
from ..option import (
31
32
    Option,
32
 
    RegistryOption,
 
33
    )
 
34
from ..sixish import (
 
35
    text_type,
33
36
    )
34
37
 
35
38
 
41
44
    takes_args = ["src_location", "dest_location?"]
42
45
 
43
46
    takes_options = [
44
 
        Option('colocated', help='Create colocated branches.'),
45
 
        RegistryOption('dest-format',
46
 
                       help='Specify a format for this branch. '
47
 
                       'See "help formats" for a full list.',
48
 
                       lazy_registry=('breezy.controldir', 'format_registry'),
49
 
                       converter=lambda name: controldir.format_registry.make_controldir(
50
 
                            name),
51
 
                       value_switches=True,
52
 
                       title="Branch format",
53
 
                       ),
54
 
        ]
 
47
                     Option('colocated', help='Create colocated branches.'),
 
48
                     ]
55
49
 
56
50
    def _get_colocated_branch(self, target_controldir, name):
57
51
        from ..errors import NotBranchError
74
68
        except NotBranchError:
75
69
            return head_controldir.create_branch()
76
70
 
77
 
    def run(self, src_location, dest_location=None, colocated=False, dest_format=None):
 
71
    def run(self, src_location, dest_location=None, colocated=False):
78
72
        import os
 
73
        import urllib
79
74
        from .. import (
80
75
            controldir,
81
76
            trace,
86
81
            ControlDir,
87
82
            )
88
83
        from ..errors import (
89
 
            BzrError,
90
 
            CommandError,
 
84
            BzrCommandError,
91
85
            NoRepositoryPresent,
92
86
            NotBranchError,
93
87
            )
94
 
        from ..i18n import gettext
 
88
        from . import gettext
95
89
        from ..repository import (
96
90
            InterRepository,
97
91
            Repository,
105
99
            )
106
100
        from .repository import GitRepository
107
101
 
 
102
        dest_format = controldir.ControlDirFormat.get_default_format()
108
103
        if dest_format is None:
109
 
            dest_format = controldir.format_registry.make_controldir('default')
 
104
            raise errors.BzrError('no default format')
110
105
 
111
106
        if dest_location is None:
112
107
            dest_location = os.path.basename(src_location.rstrip("/\\"))
115
110
 
116
111
        source_repo = Repository.open(src_location)
117
112
        if not isinstance(source_repo, GitRepository):
118
 
            raise CommandError(
119
 
                gettext("%r is not a git repository") % src_location)
 
113
            raise BzrCommandError(gettext("%r is not a git repository") % src_location)
120
114
        try:
121
115
            target_controldir = ControlDir.open_from_transport(dest_transport)
122
116
        except NotBranchError:
128
122
            target_repo = target_controldir.create_repository(shared=True)
129
123
 
130
124
        if not target_repo.supports_rich_root():
131
 
            raise CommandError(
132
 
                gettext("Target repository doesn't support rich roots"))
 
125
            raise BzrCommandError(gettext("Target repository doesn't support rich roots"))
133
126
 
134
127
        interrepo = InterRepository.get(source_repo, target_repo)
135
128
        mapping = source_repo.get_mapping()
136
 
        result = interrepo.fetch()
137
 
        with ui.ui_factory.nested_progress_bar() as pb:
138
 
            for i, (name, sha) in enumerate(result.refs.items()):
 
129
        refs = interrepo.fetch()
 
130
        pb = ui.ui_factory.nested_progress_bar()
 
131
        try:
 
132
            for i, (name, sha) in enumerate(refs.iteritems()):
139
133
                try:
140
134
                    branch_name = ref_to_branch_name(name)
141
135
                except ValueError:
142
136
                    # Not a branch, ignore
143
137
                    continue
144
 
                pb.update(gettext("creating branches"), i, len(result.refs))
145
 
                if (getattr(target_controldir._format, "colocated_branches",
146
 
                            False) and colocated):
 
138
                pb.update(gettext("creating branches"), i, len(refs))
 
139
                if getattr(target_controldir._format, "colocated_branches", False) and colocated:
147
140
                    if name == "HEAD":
148
141
                        branch_name = None
149
 
                    head_branch = self._get_colocated_branch(
150
 
                        target_controldir, branch_name)
 
142
                    head_branch = self._get_colocated_branch(target_controldir, branch_name)
151
143
                else:
152
 
                    head_branch = self._get_nested_branch(
153
 
                        dest_transport, dest_format, branch_name)
 
144
                    head_branch = self._get_nested_branch(dest_transport, dest_format, branch_name)
154
145
                revid = mapping.revision_id_foreign_to_bzr(sha)
155
 
                source_branch = LocalGitBranch(
156
 
                    source_repo.controldir, source_repo, sha)
 
146
                source_branch = LocalGitBranch(source_repo.controldir, source_repo,
 
147
                    sha)
157
148
                if head_branch.last_revision() != revid:
158
149
                    head_branch.generate_revision_history(revid)
159
150
                source_branch.tags.merge_to(head_branch.tags)
160
151
                if not head_branch.get_parent():
161
152
                    url = urlutils.join_segment_parameters(
162
 
                        source_branch.base,
163
 
                        {"branch": urlutils.escape(branch_name)})
 
153
                        source_branch.base, {"branch": urllib.quote(branch_name.encode('utf-8'), '')})
164
154
                    head_branch.set_parent(url)
 
155
        finally:
 
156
            pb.finished()
165
157
        trace.note(gettext(
166
158
            "Use 'bzr checkout' to create a working tree in "
167
159
            "the newly created branches."))
179
171
    aliases = ["git-objects", "git-cat"]
180
172
    takes_args = ["sha1?"]
181
173
    takes_options = [Option('directory',
182
 
                            short_name='d',
183
 
                            help='Location of repository.', type=str),
184
 
                     Option('pretty', help='Pretty-print objects.')]
 
174
        short_name='d',
 
175
        help='Location of repository.', type=text_type),
 
176
        Option('pretty', help='Pretty-print objects.')]
185
177
    encoding_type = 'exact'
186
178
 
187
179
    @display_command
188
180
    def run(self, sha1=None, directory=".", pretty=False):
189
181
        from ..errors import (
190
 
            CommandError,
 
182
            BzrCommandError,
191
183
            )
192
184
        from ..controldir import (
193
185
            ControlDir,
195
187
        from .object_store import (
196
188
            get_object_store,
197
189
            )
198
 
        from ..i18n import gettext
 
190
        from . import gettext
199
191
        controldir, _ = ControlDir.open_containing(directory)
200
192
        repo = controldir.find_repository()
201
193
        object_store = get_object_store(repo)
202
194
        with object_store.lock_read():
203
195
            if sha1 is not None:
204
196
                try:
205
 
                    obj = object_store[sha1.encode('ascii')]
 
197
                    obj = object_store[str(sha1)]
206
198
                except KeyError:
207
 
                    raise CommandError(
208
 
                        gettext("Object not found: %s") % sha1)
 
199
                    raise BzrCommandError(gettext("Object not found: %s") % sha1)
209
200
                if pretty:
210
201
                    text = obj.as_pretty_string()
211
202
                else:
213
204
                self.outf.write(text)
214
205
            else:
215
206
                for sha1 in object_store:
216
 
                    self.outf.write("%s\n" % sha1.decode('ascii'))
 
207
                    self.outf.write("%s\n" % sha1)
217
208
 
218
209
 
219
210
class cmd_git_refs(Command):
241
232
        object_store = get_object_store(repo)
242
233
        with object_store.lock_read():
243
234
            refs = get_refs_container(controldir, object_store)
244
 
            for k, v in sorted(refs.as_dict().items()):
245
 
                self.outf.write("%s -> %s\n" %
246
 
                                (k.decode('utf-8'), v.decode('utf-8')))
 
235
            for k, v in refs.as_dict().iteritems():
 
236
                self.outf.write("%s -> %s\n" % (k, v))
247
237
 
248
238
 
249
239
class cmd_git_apply(Command):
250
240
    """Apply a series of git-am style patches.
251
241
 
252
 
    This command will in the future probably be integrated into "bzr pull".
 
242
    This command will in the future probably be integrated into 
 
243
    "bzr pull".
253
244
    """
254
245
 
255
246
    takes_options = [
256
247
        Option('signoff', short_name='s', help='Add a Signed-off-by line.'),
257
248
        Option('force',
258
 
               help='Apply patches even if tree has uncommitted changes.')
 
249
            help='Apply patches even if tree has uncommitted changes.')
259
250
        ]
260
251
    takes_args = ["patches*"]
261
252
 
266
257
        :param f: Patch file to read.
267
258
        :param signoff: Add Signed-Off-By flag.
268
259
        """
 
260
        from . import gettext
 
261
        from ..errors import BzrCommandError
269
262
        from dulwich.patch import git_am_patch_split
270
 
        from breezy.patch import patch_tree
 
263
        import subprocess
271
264
        (c, diff, version) = git_am_patch_split(f)
272
265
        # FIXME: Cope with git-specific bits in patch
273
266
        # FIXME: Add new files to working tree
274
 
        patch_tree(wt, [diff], strip=1, out=self.outf)
275
 
        message = c.message.decode('utf-8')
 
267
        p = subprocess.Popen(["patch", "-p1"], stdin=subprocess.PIPE,
 
268
            cwd=wt.basedir)
 
269
        p.communicate(diff)
 
270
        exitcode = p.wait()
 
271
        if exitcode != 0:
 
272
            raise BzrCommandError(gettext("error running patch"))
 
273
        message = c.message
276
274
        if signoff:
277
275
            signed_off_by = wt.branch.get_config().username()
278
 
            message += "Signed-off-by: %s\n" % (signed_off_by, )
279
 
        wt.commit(authors=[c.author.decode('utf-8')], message=message)
 
276
            message += "Signed-off-by: %s\n" % signed_off_by.encode('utf-8')
 
277
        wt.commit(authors=[c.author], message=message)
280
278
 
281
279
    def run(self, patches_list=None, signoff=False, force=False):
282
280
        from ..errors import UncommittedChanges
297
295
    """Push pristine tar deltas to a git repository."""
298
296
 
299
297
    takes_options = [Option('directory',
300
 
                            short_name='d',
301
 
                            help='Location of repository.', type=str)]
 
298
        short_name='d',
 
299
        help='Location of repository.', type=text_type)]
302
300
    takes_args = ['target', 'package']
303
301
 
304
302
    def run(self, target, package, directory='.'):
305
303
        from ..branch import Branch
306
304
        from ..errors import (
307
 
            CommandError,
 
305
            BzrCommandError,
308
306
            NoSuchRevision,
309
307
            )
310
308
        from ..trace import warning
311
309
        from ..repository import Repository
312
 
        from .mapping import encode_git_path
313
310
        from .object_store import get_object_store
314
311
        from .pristine_tar import (
315
312
            revision_pristine_tar_data,
319
316
        target_bzr = Repository.open(target)
320
317
        target = getattr(target_bzr, '_git', None)
321
318
        if target is None:
322
 
            raise CommandError("Target not a git repository")
 
319
            raise BzrCommandError("Target not a git repository")
323
320
        git_store = get_object_store(source.repository)
324
321
        with git_store.lock_read():
325
322
            tag_dict = source.tags.get_tag_dict()
333
330
                except KeyError:
334
331
                    continue
335
332
                gitid = git_store._lookup_revision_sha1(revid)
336
 
                if (not (name.startswith('upstream/') or
337
 
                         name.startswith('upstream-'))):
338
 
                    warning(
339
 
                        "Unexpected pristine tar revision tagged %s. "
340
 
                        "Ignoring.", name)
 
333
                if not (name.startswith('upstream/') or name.startswith('upstream-')):
 
334
                    warning("Unexpected pristine tar revision tagged %s. Ignoring.",
 
335
                         name)
341
336
                    continue
342
337
                upstream_version = name[len("upstream/"):]
343
 
                filename = '%s_%s.orig.tar.%s' % (
344
 
                    package, upstream_version, kind)
345
 
                if gitid not in target:
346
 
                    warning(
347
 
                        "base git id %s for %s missing in target repository",
348
 
                        gitid, filename)
349
 
                store_git_pristine_tar_data(target, encode_git_path(filename),
350
 
                                            delta, gitid)
 
338
                filename = '%s_%s.orig.tar.%s' % (package, upstream_version, kind)
 
339
                if not gitid in target:
 
340
                    warning("base git id %s for %s missing in target repository",
 
341
                            gitid, filename)
 
342
                store_git_pristine_tar_data(target, filename.encode('utf-8'),
 
343
                    delta, gitid)