/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: Canonical.com Patch Queue Manager
  • Date: 2006-04-24 10:31:28 UTC
  • mfrom: (1684.1.2 bzr.mbp.integration)
  • Revision ID: pqm@pqm.ubuntu.com-20060424103128-a637f56a7c529bad
(mbp) tutorial improvements

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