/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

Raise SettingFileIdUnsupported

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