/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

Fix revision_history test when no DeprecationWarning is printed and bzr 2.5
is used.

Older prereleases of bzr 2.5 didn't deprecate Branch.revision_history.

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 _get_colocated_branch(self, target_bzrdir, name):
 
40
        from bzrlib.errors import NotBranchError
 
41
        try:
 
42
            return target_bzrdir.open_branch(name=name)
 
43
        except NotBranchError:
 
44
            return target_bzrdir.create_branch(name=name)
 
45
 
 
46
    def _get_nested_branch(self, dest_transport, dest_format, name):
 
47
        from bzrlib.bzrdir import BzrDir
 
48
        from bzrlib.errors import NotBranchError
 
49
        head_transport = dest_transport.clone(name)
 
50
        try:
 
51
            head_bzrdir = BzrDir.open_from_transport(head_transport)
 
52
        except NotBranchError:
 
53
            head_bzrdir = dest_format.initialize_on_transport_ex(
 
54
                head_transport, create_prefix=True)[1]
 
55
        try:
 
56
            return head_bzrdir.open_branch()
 
57
        except NotBranchError:
 
58
            return head_bzrdir.create_branch()
 
59
 
 
60
    def run(self, src_location, dest_location=None):
 
61
        from collections import defaultdict
 
62
        import os
 
63
        import urllib
 
64
        from bzrlib import (
 
65
            controldir,
 
66
            trace,
 
67
            ui,
 
68
            urlutils,
 
69
            )
 
70
        from bzrlib.bzrdir import (
 
71
            BzrDir,
 
72
            )
 
73
        from bzrlib.errors import (
 
74
            BzrCommandError,
 
75
            NoRepositoryPresent,
 
76
            NotBranchError,
 
77
            )
 
78
        from bzrlib.repository import (
 
79
            InterRepository,
 
80
            Repository,
 
81
            )
 
82
        from bzrlib.transport import get_transport
 
83
        from bzrlib.plugins.git.branch import (
 
84
            GitBranch,
 
85
            extract_tags,
 
86
            )
 
87
        from bzrlib.plugins.git.refs import ref_to_branch_name
 
88
        from bzrlib.plugins.git.repository import GitRepository
 
89
 
 
90
        dest_format = controldir.ControlDirFormat.get_default_format()
 
91
 
 
92
        if dest_location is None:
 
93
            dest_location = os.path.basename(src_location.rstrip("/\\"))
 
94
 
 
95
        dest_transport = get_transport(dest_location)
 
96
 
 
97
        source_repo = Repository.open(src_location)
 
98
        if not isinstance(source_repo, GitRepository):
 
99
            raise BzrCommandError("%r is not a git repository" % src_location)
 
100
        try:
 
101
            target_bzrdir = BzrDir.open_from_transport(dest_transport)
 
102
        except NotBranchError:
 
103
            target_bzrdir = dest_format.initialize_on_transport_ex(
 
104
                dest_transport, shared_repo=True)[1]
 
105
        try:
 
106
            target_repo = target_bzrdir.find_repository()
 
107
        except NoRepositoryPresent:
 
108
            target_repo = target_bzrdir.create_repository(shared=True)
 
109
 
 
110
        if not target_repo.supports_rich_root():
 
111
            raise BzrCommandError("Target repository doesn't support rich roots")
 
112
 
 
113
        interrepo = InterRepository.get(source_repo, target_repo)
 
114
        mapping = source_repo.get_mapping()
 
115
        refs = interrepo.fetch()
 
116
        unpeeled_tags = defaultdict(set)
 
117
        tags = {}
 
118
        for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
 
119
            tags[k] = mapping.revision_id_foreign_to_bzr(peeled)
 
120
            if unpeeled is not None:
 
121
                unpeeled_tags[peeled].add(unpeeled)
 
122
        # FIXME: Store unpeeled tag map
 
123
        pb = ui.ui_factory.nested_progress_bar()
 
124
        try:
 
125
            for i, (name, ref) in enumerate(refs.iteritems()):
 
126
                try:
 
127
                    branch_name = ref_to_branch_name(name)
 
128
                except ValueError:
 
129
                    # Not a branch, ignore
 
130
                    continue
 
131
                pb.update("creating branches", i, len(refs))
 
132
                if getattr(target_bzrdir._format, "colocated_branches", False):
 
133
                    if name == "HEAD":
 
134
                        branch_name = None
 
135
                    head_branch = self._get_colocated_branch(target_bzrdir, branch_name)
 
136
                else:
 
137
                    head_branch = self._get_nested_branch(dest_transport, dest_format, branch_name)
 
138
                revid = mapping.revision_id_foreign_to_bzr(ref)
 
139
                source_branch = GitBranch(source_repo.bzrdir, source_repo,
 
140
                    ref, tags)
 
141
                source_branch.head = ref
 
142
                if head_branch.last_revision() != revid:
 
143
                    head_branch.generate_revision_history(revid)
 
144
                source_branch.tags.merge_to(head_branch.tags)
 
145
                if not head_branch.get_parent():
 
146
                    url = urlutils.join_segment_parameters(
 
147
                        source_branch.base, {"ref": urllib.quote(name, '')})
 
148
                    head_branch.set_parent(url)
 
149
        finally:
 
150
            pb.finished()
 
151
        trace.note("Use 'bzr checkout' to create a working tree in "
 
152
                   "the newly created branches.")
 
153
 
 
154
 
 
155
class cmd_git_object(Command):
 
156
    """List or display Git objects by SHA.
 
157
 
 
158
    Cat a particular object's Git representation if a SHA is specified.
 
159
    List all available SHAs otherwise.
 
160
    """
 
161
 
 
162
    hidden = True
 
163
 
 
164
    aliases = ["git-objects", "git-cat"]
 
165
    takes_args = ["sha1?"]
 
166
    takes_options = [Option('directory',
 
167
        short_name='d',
 
168
        help='Location of repository.', type=unicode),
 
169
        Option('pretty', help='Pretty-print objects.')]
 
170
    encoding_type = 'exact'
 
171
 
 
172
    @display_command
 
173
    def run(self, sha1=None, directory=".", pretty=False):
 
174
        from bzrlib.errors import (
 
175
            BzrCommandError,
 
176
            )
 
177
        from bzrlib.bzrdir import (
 
178
            BzrDir,
 
179
            )
 
180
        bzrdir, _ = BzrDir.open_containing(directory)
 
181
        repo = bzrdir.find_repository()
 
182
        from bzrlib.plugins.git.object_store import (
 
183
            get_object_store,
 
184
            )
 
185
        object_store = get_object_store(repo)
 
186
        object_store.lock_read()
 
187
        try:
 
188
            if sha1 is not None:
 
189
                try:
 
190
                    obj = object_store[str(sha1)]
 
191
                except KeyError:
 
192
                    raise BzrCommandError("Object not found: %s" % sha1)
 
193
                if pretty:
 
194
                    text = obj.as_pretty_string()
 
195
                else:
 
196
                    text = obj.as_raw_string()
 
197
                self.outf.write(text)
 
198
            else:
 
199
                for sha1 in object_store:
 
200
                    self.outf.write("%s\n" % sha1)
 
201
        finally:
 
202
            object_store.unlock()
 
203
 
 
204
 
 
205
class cmd_git_refs(Command):
 
206
    """Output all of the virtual refs for a repository.
 
207
 
 
208
    """
 
209
 
 
210
    hidden = True
 
211
 
 
212
    takes_options = [Option('directory',
 
213
        short_name='d',
 
214
        help='Location of repository.', type=unicode)]
 
215
 
 
216
    @display_command
 
217
    def run(self, directory="."):
 
218
        from bzrlib.bzrdir import (
 
219
            BzrDir,
 
220
            )
 
221
        from bzrlib.plugins.git.refs import (
 
222
            get_refs,
 
223
            )
 
224
        from bzrlib.plugins.git.object_store import (
 
225
            get_object_store,
 
226
            )
 
227
        bzrdir, _ = BzrDir.open_containing(directory)
 
228
        repo = bzrdir.find_repository()
 
229
        object_store = get_object_store(repo)
 
230
        object_store.lock_read()
 
231
        try:
 
232
            refs = get_refs(bzrdir)
 
233
            for k, v in refs.iteritems():
 
234
                self.outf.write("%s -> %s\n" % (k, v))
 
235
        finally:
 
236
            object_store.unlock()
 
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
        'force']
 
249
    takes_args = ["patches*"]
 
250
 
 
251
    def _apply_patch(self, wt, f, signoff):
 
252
        """Apply a patch.
 
253
 
 
254
        :param wt: A Bazaar working tree object.
 
255
        :param f: Patch file to read.
 
256
        :param signoff: Add Signed-Off-By flag.
 
257
        """
 
258
        from bzrlib.errors import BzrCommandError
 
259
        from dulwich.patch import git_am_patch_split
 
260
        import subprocess
 
261
        (c, diff, version) = git_am_patch_split(f)
 
262
        # FIXME: Cope with git-specific bits in patch
 
263
        # FIXME: Add new files to working tree
 
264
        p = subprocess.Popen(["patch", "-p1"], stdin=subprocess.PIPE,
 
265
            cwd=wt.basedir)
 
266
        p.communicate(diff)
 
267
        exitcode = p.wait()
 
268
        if exitcode != 0:
 
269
            raise BzrCommandError("error running patch")
 
270
        message = c.message
 
271
        if signoff:
 
272
            signed_off_by = wt.branch.get_config().username()
 
273
            message += "Signed-off-by: %s\n" % signed_off_by.encode('utf-8')
 
274
        wt.commit(authors=[c.author], message=message)
 
275
 
 
276
    def run(self, patches_list=None, signoff=False, force=False):
 
277
        from bzrlib.errors import UncommittedChanges
 
278
        from bzrlib.workingtree import WorkingTree
 
279
        if patches_list is None:
 
280
            patches_list = []
 
281
 
 
282
        tree, _ = WorkingTree.open_containing(".")
 
283
        if tree.basis_tree().changes_from(tree).has_changed() and not force:
 
284
            raise UncommittedChanges(tree)
 
285
        tree.lock_write()
 
286
        try:
 
287
            for patch in patches_list:
 
288
                f = open(patch, 'r')
 
289
                try:
 
290
                    self._apply_patch(tree, f, signoff=signoff)
 
291
                finally:
 
292
                    f.close()
 
293
        finally:
 
294
            tree.unlock()