/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.200.206 by Jelmer Vernooij
Move commands to a separate python module and register them lazily.
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
0.200.292 by Jelmer Vernooij
Fix formatting.
23
from bzrlib.commands import (
24
    Command,
0.200.423 by Jelmer Vernooij
Support pretty-printing git objects.
25
    display_command,
0.200.292 by Jelmer Vernooij
Fix formatting.
26
    )
27
from bzrlib.option import (
28
    Option,
29
    )
0.200.206 by Jelmer Vernooij
Move commands to a separate python module and register them lazily.
30
0.228.1 by Jelmer Vernooij
Add basic tests for local fetch.
31
0.200.206 by Jelmer Vernooij
Move commands to a separate python module and register them lazily.
32
class cmd_git_import(Command):
33
    """Import all branches from a git repository.
34
35
    """
36
0.200.234 by Jelmer Vernooij
Derive to_location from from_location, simialr to bzr branch.
37
    takes_args = ["src_location", "dest_location?"]
0.200.206 by Jelmer Vernooij
Move commands to a separate python module and register them lazily.
38
0.200.234 by Jelmer Vernooij
Derive to_location from from_location, simialr to bzr branch.
39
    def run(self, src_location, dest_location=None):
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
40
        from collections import defaultdict
0.200.247 by Jelmer Vernooij
Fix git-import.
41
        import os
42
        from bzrlib import (
43
            ui,
44
            urlutils,
45
            )
46
        from bzrlib.bzrdir import (
47
            BzrDir,
48
            )
0.200.243 by Jelmer Vernooij
Error out on non-git repositories.
49
        from bzrlib.errors import (
50
            BzrCommandError,
51
            NoRepositoryPresent,
52
            NotBranchError,
53
            )
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
54
        from bzrlib.repository import (
55
            InterRepository,
56
            Repository,
57
            )
0.239.1 by Jelmer Vernooij
Avoid re-connecting to fetch tags we already know.
58
        from bzrlib.plugins.git.branch import (
59
            GitBranch,
60
            extract_tags,
61
            )
0.200.1055 by Jelmer Vernooij
Cope with unknown refs.
62
        from bzrlib.plugins.git.refs import ref_to_branch_name
0.200.243 by Jelmer Vernooij
Error out on non-git repositories.
63
        from bzrlib.plugins.git.repository import GitRepository
0.200.234 by Jelmer Vernooij
Derive to_location from from_location, simialr to bzr branch.
64
65
        if dest_location is None:
66
            dest_location = os.path.basename(src_location.rstrip("/\\"))
67
0.200.206 by Jelmer Vernooij
Move commands to a separate python module and register them lazily.
68
        source_repo = Repository.open(src_location)
0.200.243 by Jelmer Vernooij
Error out on non-git repositories.
69
        if not isinstance(source_repo, GitRepository):
70
            raise BzrCommandError("%r is not a git repository" % src_location)
0.200.206 by Jelmer Vernooij
Move commands to a separate python module and register them lazily.
71
        try:
72
            target_bzrdir = BzrDir.open(dest_location)
73
        except NotBranchError:
0.200.927 by Jelmer Vernooij
Remove explicit use of rich root formats.
74
            target_bzrdir = BzrDir.create(dest_location)
0.200.206 by Jelmer Vernooij
Move commands to a separate python module and register them lazily.
75
        try:
0.200.612 by Jelmer Vernooij
Cope with Dulwich returning KeyError when a commit is not found.
76
            target_repo = target_bzrdir.find_repository()
0.200.206 by Jelmer Vernooij
Move commands to a separate python module and register them lazily.
77
        except NoRepositoryPresent:
78
            target_repo = target_bzrdir.create_repository(shared=True)
79
0.200.569 by Jelmer Vernooij
Check for rich root target repository.
80
        if not target_repo.supports_rich_root():
81
            raise BzrCommandError("Target repository doesn't support rich roots")
82
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
83
        interrepo = InterRepository.get(source_repo, target_repo)
0.200.247 by Jelmer Vernooij
Fix git-import.
84
        mapping = source_repo.get_mapping()
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
85
        refs = interrepo.fetch()
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
86
        unpeeled_tags = defaultdict(set)
0.200.648 by Jelmer Vernooij
Fix tag handling when encountering packed refs.
87
        tags = {}
0.200.1060 by Jelmer Vernooij
Return unpeeled tags in extract_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:
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
91
                unpeeled_tags[peeled].add(unpeeled)
92
        # FIXME: Store unpeeled tag map
0.200.247 by Jelmer Vernooij
Fix git-import.
93
        pb = ui.ui_factory.nested_progress_bar()
94
        try:
95
            for i, (name, ref) in enumerate(refs.iteritems()):
0.200.1055 by Jelmer Vernooij
Cope with unknown refs.
96
                try:
97
                    ref_to_branch_name(name)
98
                except ValueError:
99
                    # Not a branch, ignore
0.200.271 by Jelmer Vernooij
Stop importing tags as branches as part of git-import.
100
                    continue
0.200.247 by Jelmer Vernooij
Fix git-import.
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)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
109
                    head_bzrdir = BzrDir.create(head_loc)
0.200.247 by Jelmer Vernooij
Fix git-import.
110
                try:
111
                    head_branch = head_bzrdir.open_branch()
112
                except NotBranchError:
113
                    head_branch = head_bzrdir.create_branch()
0.200.271 by Jelmer Vernooij
Stop importing tags as branches as part of git-import.
114
                revid = mapping.revision_id_foreign_to_bzr(ref)
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
115
                source_branch = GitBranch(source_repo.bzrdir, source_repo,
0.239.1 by Jelmer Vernooij
Avoid re-connecting to fetch tags we already know.
116
                    name, None, tags)
0.200.488 by Jelmer Vernooij
Fix git-import.
117
                source_branch.head = ref
0.239.1 by Jelmer Vernooij
Avoid re-connecting to fetch tags we already know.
118
                if head_branch.last_revision() != revid:
119
                    head_branch.generate_revision_history(revid)
0.200.273 by Jelmer Vernooij
Fix import of tags in git-import.
120
                source_branch.tags.merge_to(head_branch.tags)
0.200.247 by Jelmer Vernooij
Fix git-import.
121
        finally:
122
            pb.finished()
0.200.206 by Jelmer Vernooij
Move commands to a separate python module and register them lazily.
123
0.200.419 by Jelmer Vernooij
Add hidden git-cat command that can cat git objects from Bazaar repositories.
124
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
125
class cmd_git_object(Command):
126
    """List or display Git objects by SHA.
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
127
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
128
    Cat a particular object's Git representation if a SHA is specified.
129
    List all available SHAs otherwise.
130
    """
0.200.419 by Jelmer Vernooij
Add hidden git-cat command that can cat git objects from Bazaar repositories.
131
132
    hidden = True
133
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
134
    aliases = ["git-objects", "git-cat"]
135
    takes_args = ["sha1?"]
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
136
    takes_options = [Option('directory',
0.200.440 by Jelmer Vernooij
Remove silly mapping of timezones; dulwich uses offsets now as well.
137
        short_name='d',
0.200.424 by Jelmer Vernooij
Fix formatting.
138
        help='Location of repository.', type=unicode),
139
        Option('pretty', help='Pretty-print objects.')]
0.200.423 by Jelmer Vernooij
Support pretty-printing git objects.
140
    encoding_type = 'exact'
0.200.419 by Jelmer Vernooij
Add hidden git-cat command that can cat git objects from Bazaar repositories.
141
0.200.423 by Jelmer Vernooij
Support pretty-printing git objects.
142
    @display_command
143
    def run(self, sha1=None, directory=".", pretty=False):
0.200.419 by Jelmer Vernooij
Add hidden git-cat command that can cat git objects from Bazaar repositories.
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()
0.200.452 by Jelmer Vernooij
Rename converter -> object_store, provide utility function for getting ObjectStore's.
152
        from bzrlib.plugins.git.object_store import (
153
            get_object_store,
154
            )
155
        object_store = get_object_store(repo)
0.200.419 by Jelmer Vernooij
Add hidden git-cat command that can cat git objects from Bazaar repositories.
156
        repo.lock_read()
157
        try:
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
158
            if sha1 is not None:
159
                try:
0.200.532 by Jelmer Vernooij
The object store requires plain strings.
160
                    obj = object_store[str(sha1)]
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
161
                except KeyError:
162
                    raise BzrCommandError("Object not found: %s" % sha1)
0.200.423 by Jelmer Vernooij
Support pretty-printing git objects.
163
                if pretty:
164
                    text = obj.as_pretty_string()
165
                else:
166
                    text = obj.as_raw_string()
167
                self.outf.write(text)
0.200.419 by Jelmer Vernooij
Add hidden git-cat command that can cat git objects from Bazaar repositories.
168
            else:
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
169
                for sha1 in object_store:
170
                    self.outf.write("%s\n" % sha1)
0.200.419 by Jelmer Vernooij
Add hidden git-cat command that can cat git objects from Bazaar repositories.
171
        finally:
172
            repo.unlock()
0.200.873 by Jelmer Vernooij
Add convenience command for accessing virtual git refs.
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()
0.200.895 by Jelmer Vernooij
Add initial work on git-apply.
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
0.200.1050 by Jelmer Vernooij
Add --force option to 'bzr git-apply'.
216
    takes_options = [
217
        Option('signoff', short_name='s', help='Add a Signed-off-by line.'),
218
        'force']
0.200.895 by Jelmer Vernooij
Add initial work on git-apply.
219
    takes_args = ["patches*"]
220
0.200.1049 by Jelmer Vernooij
Add --signoff option to 'bzr git-apply'.
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
        """
0.200.1043 by Jelmer Vernooij
Finish git-apply command.
228
        from bzrlib.errors import BzrCommandError
0.200.895 by Jelmer Vernooij
Add initial work on git-apply.
229
        from dulwich.patch import git_am_patch_split
0.200.1043 by Jelmer Vernooij
Finish git-apply command.
230
        import subprocess
0.200.895 by Jelmer Vernooij
Add initial work on git-apply.
231
        (c, diff, version) = git_am_patch_split(f)
0.200.1043 by Jelmer Vernooij
Finish git-apply command.
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")
0.200.1049 by Jelmer Vernooij
Add --signoff option to 'bzr git-apply'.
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)
0.200.895 by Jelmer Vernooij
Add initial work on git-apply.
243
0.200.1050 by Jelmer Vernooij
Add --force option to 'bzr git-apply'.
244
    def run(self, patches_list=None, signoff=False, force=False):
0.200.1040 by Jelmer Vernooij
Error out about applying to a tree with changes.
245
        from bzrlib.errors import UncommittedChanges
0.200.895 by Jelmer Vernooij
Add initial work on git-apply.
246
        from bzrlib.workingtree import WorkingTree
247
        if patches_list is None:
248
            patches_list = []
0.200.1040 by Jelmer Vernooij
Error out about applying to a tree with changes.
249
0.200.895 by Jelmer Vernooij
Add initial work on git-apply.
250
        tree, _ = WorkingTree.open_containing(".")
0.200.1050 by Jelmer Vernooij
Add --force option to 'bzr git-apply'.
251
        if tree.basis_tree().changes_from(tree).has_changed() and not force:
0.200.1040 by Jelmer Vernooij
Error out about applying to a tree with changes.
252
            raise UncommittedChanges(tree)
0.200.895 by Jelmer Vernooij
Add initial work on git-apply.
253
        tree.lock_write()
254
        try:
255
            for patch in patches_list:
256
                f = open(patch, 'r')
257
                try:
0.200.1049 by Jelmer Vernooij
Add --signoff option to 'bzr git-apply'.
258
                    self._apply_patch(tree, f, signoff=signoff)
0.200.895 by Jelmer Vernooij
Add initial work on git-apply.
259
                finally:
260
                    f.close()
261
        finally:
262
            tree.unlock()