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

In .testr.conf; run all git-relevant tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2009 Canonical Ltd
 
2
 
 
3
# Authors: Robert Collins <robert.collins@canonical.com>
 
4
#          Jelmer Vernooij <jelmer@samba.org>
 
5
#          John Carr <john.carr@unrouted.co.uk>
 
6
#
 
7
# This program is free software; you can redistribute it and/or modify
 
8
# it under the terms of the GNU General Public License as published by
 
9
# the Free Software Foundation; either version 2 of the License, or
 
10
# (at your option) any later version.
 
11
#
 
12
# This program is distributed in the hope that it will be useful,
 
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
15
# GNU General Public License for more details.
 
16
#
 
17
# You should have received a copy of the GNU General Public License
 
18
# along with this program; if not, write to the Free Software
 
19
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
20
 
 
21
"""Git-specific subcommands for Bazaar."""
 
22
 
 
23
from bzrlib.commands import (
 
24
    Command,
 
25
    display_command,
 
26
    )
 
27
from bzrlib.option import (
 
28
    Option,
 
29
    )
 
30
 
 
31
 
 
32
class cmd_git_import(Command):
 
33
    """Import all branches from a git repository.
 
34
 
 
35
    """
 
36
 
 
37
    takes_args = ["src_location", "dest_location?"]
 
38
 
 
39
    def run(self, src_location, dest_location=None):
 
40
        from collections import defaultdict
 
41
        import os
 
42
        from bzrlib import (
 
43
            ui,
 
44
            urlutils,
 
45
            )
 
46
        from bzrlib.bzrdir import (
 
47
            BzrDir,
 
48
            )
 
49
        from bzrlib.errors import (
 
50
            BzrCommandError,
 
51
            NoRepositoryPresent,
 
52
            NotBranchError,
 
53
            )
 
54
        from bzrlib.repository import (
 
55
            InterRepository,
 
56
            Repository,
 
57
            )
 
58
        from bzrlib.plugins.git.branch import (
 
59
            GitBranch,
 
60
            extract_tags,
 
61
            )
 
62
        from bzrlib.plugins.git.refs import ref_to_branch_name
 
63
        from bzrlib.plugins.git.repository import GitRepository
 
64
 
 
65
        if dest_location is None:
 
66
            dest_location = os.path.basename(src_location.rstrip("/\\"))
 
67
 
 
68
        source_repo = Repository.open(src_location)
 
69
        if not isinstance(source_repo, GitRepository):
 
70
            raise BzrCommandError("%r is not a git repository" % src_location)
 
71
        try:
 
72
            target_bzrdir = BzrDir.open(dest_location)
 
73
        except NotBranchError:
 
74
            target_bzrdir = BzrDir.create(dest_location)
 
75
        try:
 
76
            target_repo = target_bzrdir.find_repository()
 
77
        except NoRepositoryPresent:
 
78
            target_repo = target_bzrdir.create_repository(shared=True)
 
79
 
 
80
        if not target_repo.supports_rich_root():
 
81
            raise BzrCommandError("Target repository doesn't support rich roots")
 
82
 
 
83
        interrepo = InterRepository.get(source_repo, target_repo)
 
84
        mapping = source_repo.get_mapping()
 
85
        refs = interrepo.fetch()
 
86
        unpeeled_tags = defaultdict(set)
 
87
        tags = {}
 
88
        for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
 
89
            tags[k] = mapping.revision_id_foreign_to_bzr(peeled)
 
90
            if unpeeled is not None:
 
91
                unpeeled_tags[peeled].add(unpeeled)
 
92
        # FIXME: Store unpeeled tag map
 
93
        pb = ui.ui_factory.nested_progress_bar()
 
94
        try:
 
95
            for i, (name, ref) in enumerate(refs.iteritems()):
 
96
                try:
 
97
                    ref_to_branch_name(name)
 
98
                except ValueError:
 
99
                    # Not a branch, ignore
 
100
                    continue
 
101
                pb.update("creating branches", i, len(refs))
 
102
                head_loc = os.path.join(dest_location, name)
 
103
                try:
 
104
                    head_bzrdir = BzrDir.open(head_loc)
 
105
                except NotBranchError:
 
106
                    parent_path = urlutils.dirname(head_loc)
 
107
                    if not os.path.isdir(parent_path):
 
108
                        os.makedirs(parent_path)
 
109
                    head_bzrdir = BzrDir.create(head_loc)
 
110
                try:
 
111
                    head_branch = head_bzrdir.open_branch()
 
112
                except NotBranchError:
 
113
                    head_branch = head_bzrdir.create_branch()
 
114
                revid = mapping.revision_id_foreign_to_bzr(ref)
 
115
                source_branch = GitBranch(source_repo.bzrdir, source_repo,
 
116
                    name, None, tags)
 
117
                source_branch.head = ref
 
118
                if head_branch.last_revision() != revid:
 
119
                    head_branch.generate_revision_history(revid)
 
120
                source_branch.tags.merge_to(head_branch.tags)
 
121
        finally:
 
122
            pb.finished()
 
123
 
 
124
 
 
125
class cmd_git_object(Command):
 
126
    """List or display Git objects by SHA.
 
127
 
 
128
    Cat a particular object's Git representation if a SHA is specified.
 
129
    List all available SHAs otherwise.
 
130
    """
 
131
 
 
132
    hidden = True
 
133
 
 
134
    aliases = ["git-objects", "git-cat"]
 
135
    takes_args = ["sha1?"]
 
136
    takes_options = [Option('directory',
 
137
        short_name='d',
 
138
        help='Location of repository.', type=unicode),
 
139
        Option('pretty', help='Pretty-print objects.')]
 
140
    encoding_type = 'exact'
 
141
 
 
142
    @display_command
 
143
    def run(self, sha1=None, directory=".", pretty=False):
 
144
        from bzrlib.errors import (
 
145
            BzrCommandError,
 
146
            )
 
147
        from bzrlib.bzrdir import (
 
148
            BzrDir,
 
149
            )
 
150
        bzrdir, _ = BzrDir.open_containing(directory)
 
151
        repo = bzrdir.find_repository()
 
152
        from bzrlib.plugins.git.object_store import (
 
153
            get_object_store,
 
154
            )
 
155
        object_store = get_object_store(repo)
 
156
        repo.lock_read()
 
157
        try:
 
158
            if sha1 is not None:
 
159
                try:
 
160
                    obj = object_store[str(sha1)]
 
161
                except KeyError:
 
162
                    raise BzrCommandError("Object not found: %s" % sha1)
 
163
                if pretty:
 
164
                    text = obj.as_pretty_string()
 
165
                else:
 
166
                    text = obj.as_raw_string()
 
167
                self.outf.write(text)
 
168
            else:
 
169
                for sha1 in object_store:
 
170
                    self.outf.write("%s\n" % sha1)
 
171
        finally:
 
172
            repo.unlock()
 
173
 
 
174
 
 
175
class cmd_git_refs(Command):
 
176
    """Output all of the virtual refs for a repository.
 
177
 
 
178
    """
 
179
 
 
180
    hidden = True
 
181
 
 
182
    takes_options = [Option('directory',
 
183
        short_name='d',
 
184
        help='Location of repository.', type=unicode)]
 
185
 
 
186
    @display_command
 
187
    def run(self, directory="."):
 
188
        from bzrlib.bzrdir import (
 
189
            BzrDir,
 
190
            )
 
191
        from bzrlib.plugins.git.refs import (
 
192
            BazaarRefsContainer,
 
193
            )
 
194
        from bzrlib.plugins.git.object_store import (
 
195
            get_object_store,
 
196
            )
 
197
        bzrdir, _ = BzrDir.open_containing(directory)
 
198
        repo = bzrdir.find_repository()
 
199
        repo.lock_read()
 
200
        try:
 
201
            object_store = get_object_store(repo)
 
202
            refs = BazaarRefsContainer(bzrdir, object_store)
 
203
            for k, v in refs.as_dict().iteritems():
 
204
                self.outf.write("%s -> %s\n" % (k, v))
 
205
        finally:
 
206
            repo.unlock()
 
207
 
 
208
 
 
209
class cmd_git_apply(Command):
 
210
    """Apply a series of git-am style patches.
 
211
 
 
212
    This command will in the future probably be integrated into 
 
213
    "bzr pull".
 
214
    """
 
215
 
 
216
    takes_options = [
 
217
        Option('signoff', short_name='s', help='Add a Signed-off-by line.'),
 
218
        'force']
 
219
    takes_args = ["patches*"]
 
220
 
 
221
    def _apply_patch(self, wt, f, signoff):
 
222
        """Apply a patch.
 
223
 
 
224
        :param wt: A Bazaar working tree object.
 
225
        :param f: Patch file to read.
 
226
        :param signoff: Add Signed-Off-By flag.
 
227
        """
 
228
        from bzrlib.errors import BzrCommandError
 
229
        from dulwich.patch import git_am_patch_split
 
230
        import subprocess
 
231
        (c, diff, version) = git_am_patch_split(f)
 
232
        # FIXME: Cope with git-specific bits in patch
 
233
        p = subprocess.Popen(["patch", "-p1"], stdin=subprocess.PIPE, cwd=wt.basedir)
 
234
        p.communicate(diff)
 
235
        exitcode = p.wait()
 
236
        if exitcode != 0:
 
237
            raise BzrCommandError("error running patch")
 
238
        message = c.message
 
239
        if signoff:
 
240
            signed_off_by = wt.branch.get_config().username()
 
241
            message += "Signed-off-by: %s\n" % signed_off_by.encode('utf-8')
 
242
        wt.commit(authors=[c.author], message=message)
 
243
 
 
244
    def run(self, patches_list=None, signoff=False, force=False):
 
245
        from bzrlib.errors import UncommittedChanges
 
246
        from bzrlib.workingtree import WorkingTree
 
247
        if patches_list is None:
 
248
            patches_list = []
 
249
 
 
250
        tree, _ = WorkingTree.open_containing(".")
 
251
        if tree.basis_tree().changes_from(tree).has_changed() and not force:
 
252
            raise UncommittedChanges(tree)
 
253
        tree.lock_write()
 
254
        try:
 
255
            for patch in patches_list:
 
256
                f = open(patch, 'r')
 
257
                try:
 
258
                    self._apply_patch(tree, f, signoff=signoff)
 
259
                finally:
 
260
                    f.close()
 
261
        finally:
 
262
            tree.unlock()