/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: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

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