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

  • Committer: Jelmer Vernooij
  • Date: 2018-05-19 13:16:11 UTC
  • mto: (6968.4.3 git-archive)
  • mto: This revision was merged to the branch mainline in revision 6972.
  • Revision ID: jelmer@jelmer.uk-20180519131611-l9h9ud41j7qg1m03
Move tar/zip to breezy.archive.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2006-2009 Canonical Ltd
 
2
# Copyright (C) 2012-2018 Jelmer Vernooij <jelmer@jelmer.uk>
2
3
 
3
4
# Authors: Robert Collins <robert.collins@canonical.com>
4
5
#          Jelmer Vernooij <jelmer@samba.org>
16
17
#
17
18
# You should have received a copy of the GNU General Public License
18
19
# 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
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
21
 
21
22
"""Git-specific subcommands for Bazaar."""
22
23
 
23
 
from bzrlib.commands import (
 
24
from __future__ import absolute_import
 
25
 
 
26
import breezy.bzr.bzrdir
 
27
from ...commands import (
24
28
    Command,
25
29
    display_command,
26
30
    )
27
 
from bzrlib.option import (
 
31
from ...option import (
28
32
    Option,
29
33
    )
 
34
from ...sixish import (
 
35
    text_type,
 
36
    )
30
37
 
31
38
 
32
39
class cmd_git_import(Command):
36
43
 
37
44
    takes_args = ["src_location", "dest_location?"]
38
45
 
39
 
    def run(self, src_location, dest_location=None):
 
46
    takes_options = [
 
47
                     Option('colocated', help='Create colocated branches.'),
 
48
                     ]
 
49
 
 
50
    def _get_colocated_branch(self, target_controldir, name):
 
51
        from ...errors import NotBranchError
 
52
        try:
 
53
            return target_controldir.open_branch(name=name)
 
54
        except NotBranchError:
 
55
            return target_controldir.create_branch(name=name)
 
56
 
 
57
    def _get_nested_branch(self, dest_transport, dest_format, name):
 
58
        from ...controldir import ControlDir
 
59
        from ...errors import NotBranchError
 
60
        head_transport = dest_transport.clone(name)
 
61
        try:
 
62
            head_controldir = ControlDir.open_from_transport(head_transport)
 
63
        except NotBranchError:
 
64
            head_controldir = dest_format.initialize_on_transport_ex(
 
65
                head_transport, create_prefix=True)[1]
 
66
        try:
 
67
            return head_controldir.open_branch()
 
68
        except NotBranchError:
 
69
            return head_controldir.create_branch()
 
70
 
 
71
    def run(self, src_location, dest_location=None, colocated=False):
40
72
        import os
41
 
        from bzrlib import (
 
73
        import urllib
 
74
        from ... import (
 
75
            controldir,
 
76
            trace,
42
77
            ui,
43
78
            urlutils,
44
79
            )
45
 
        from bzrlib.bzrdir import (
46
 
            BzrDir,
 
80
        from ...controldir import (
 
81
            ControlDir,
47
82
            )
48
 
        from bzrlib.errors import (
 
83
        from ...errors import (
49
84
            BzrCommandError,
50
85
            NoRepositoryPresent,
51
86
            NotBranchError,
52
87
            )
53
 
        from bzrlib.repository import (
 
88
        from . import gettext
 
89
        from ...repository import (
54
90
            InterRepository,
55
91
            Repository,
56
92
            )
57
 
        from bzrlib.plugins.git.branch import (
58
 
            GitBranch,
59
 
            extract_tags,
60
 
            )
61
 
        from bzrlib.plugins.git.repository import GitRepository
 
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')
62
105
 
63
106
        if dest_location is None:
64
107
            dest_location = os.path.basename(src_location.rstrip("/\\"))
65
108
 
 
109
        dest_transport = get_transport(dest_location)
 
110
 
66
111
        source_repo = Repository.open(src_location)
67
112
        if not isinstance(source_repo, GitRepository):
68
 
            raise BzrCommandError("%r is not a git repository" % src_location)
 
113
            raise BzrCommandError(gettext("%r is not a git repository") % src_location)
69
114
        try:
70
 
            target_bzrdir = BzrDir.open(dest_location)
 
115
            target_controldir = ControlDir.open_from_transport(dest_transport)
71
116
        except NotBranchError:
72
 
            target_bzrdir = BzrDir.create(dest_location)
 
117
            target_controldir = dest_format.initialize_on_transport_ex(
 
118
                dest_transport, shared_repo=True)[1]
73
119
        try:
74
 
            target_repo = target_bzrdir.find_repository()
 
120
            target_repo = target_controldir.find_repository()
75
121
        except NoRepositoryPresent:
76
 
            target_repo = target_bzrdir.create_repository(shared=True)
 
122
            target_repo = target_controldir.create_repository(shared=True)
77
123
 
78
124
        if not target_repo.supports_rich_root():
79
 
            raise BzrCommandError("Target repository doesn't support rich roots")
 
125
            raise BzrCommandError(gettext("Target repository doesn't support rich roots"))
80
126
 
81
127
        interrepo = InterRepository.get(source_repo, target_repo)
82
128
        mapping = source_repo.get_mapping()
83
129
        refs = interrepo.fetch()
84
 
        tags = {}
85
 
        for k, v in extract_tags(refs).iteritems():
86
 
            tags[k] = mapping.revision_id_foreign_to_bzr(v)
87
130
        pb = ui.ui_factory.nested_progress_bar()
88
131
        try:
89
 
            for i, (name, ref) in enumerate(refs.iteritems()):
90
 
                if name.startswith("refs/tags/"):
 
132
            for i, (name, sha) in enumerate(refs.iteritems()):
 
133
                try:
 
134
                    branch_name = ref_to_branch_name(name)
 
135
                except ValueError:
 
136
                    # Not a branch, ignore
91
137
                    continue
92
 
                pb.update("creating branches", i, len(refs))
93
 
                head_loc = os.path.join(dest_location, name)
94
 
                try:
95
 
                    head_bzrdir = BzrDir.open(head_loc)
96
 
                except NotBranchError:
97
 
                    parent_path = urlutils.dirname(head_loc)
98
 
                    if not os.path.isdir(parent_path):
99
 
                        os.makedirs(parent_path)
100
 
                    head_bzrdir = BzrDir.create(head_loc)
101
 
                try:
102
 
                    head_branch = head_bzrdir.open_branch()
103
 
                except NotBranchError:
104
 
                    head_branch = head_bzrdir.create_branch()
105
 
                revid = mapping.revision_id_foreign_to_bzr(ref)
106
 
                source_branch = GitBranch(source_repo.bzrdir, source_repo,
107
 
                    name, None, tags)
108
 
                source_branch.head = ref
 
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)
109
148
                if head_branch.last_revision() != revid:
110
149
                    head_branch.generate_revision_history(revid)
111
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": urllib.quote(branch_name.encode('utf-8'), '')})
 
154
                    head_branch.set_parent(url)
112
155
        finally:
113
156
            pb.finished()
 
157
        trace.note(gettext(
 
158
            "Use 'bzr checkout' to create a working tree in "
 
159
            "the newly created branches."))
114
160
 
115
161
 
116
162
class cmd_git_object(Command):
126
172
    takes_args = ["sha1?"]
127
173
    takes_options = [Option('directory',
128
174
        short_name='d',
129
 
        help='Location of repository.', type=unicode),
 
175
        help='Location of repository.', type=text_type),
130
176
        Option('pretty', help='Pretty-print objects.')]
131
177
    encoding_type = 'exact'
132
178
 
133
179
    @display_command
134
180
    def run(self, sha1=None, directory=".", pretty=False):
135
 
        from bzrlib.errors import (
 
181
        from ...errors import (
136
182
            BzrCommandError,
137
183
            )
138
 
        from bzrlib.bzrdir import (
139
 
            BzrDir,
 
184
        from ...controldir import (
 
185
            ControlDir,
140
186
            )
141
 
        bzrdir, _ = BzrDir.open_containing(directory)
142
 
        repo = bzrdir.find_repository()
143
 
        from bzrlib.plugins.git.object_store import (
 
187
        from .object_store import (
144
188
            get_object_store,
145
189
            )
 
190
        from . import gettext
 
191
        controldir, _ = ControlDir.open_containing(directory)
 
192
        repo = controldir.find_repository()
146
193
        object_store = get_object_store(repo)
147
 
        repo.lock_read()
148
 
        try:
 
194
        with object_store.lock_read():
149
195
            if sha1 is not None:
150
196
                try:
151
197
                    obj = object_store[str(sha1)]
152
198
                except KeyError:
153
 
                    raise BzrCommandError("Object not found: %s" % sha1)
 
199
                    raise BzrCommandError(gettext("Object not found: %s") % sha1)
154
200
                if pretty:
155
201
                    text = obj.as_pretty_string()
156
202
                else:
159
205
            else:
160
206
                for sha1 in object_store:
161
207
                    self.outf.write("%s\n" % sha1)
162
 
        finally:
163
 
            repo.unlock()
164
208
 
165
209
 
166
210
class cmd_git_refs(Command):
170
214
 
171
215
    hidden = True
172
216
 
173
 
    takes_options = [Option('directory',
174
 
        short_name='d',
175
 
        help='Location of repository.', type=unicode)]
 
217
    takes_args = ["location?"]
176
218
 
177
219
    @display_command
178
 
    def run(self, directory="."):
179
 
        from bzrlib.bzrdir import (
180
 
            BzrDir,
181
 
            )
182
 
        from bzrlib.plugins.git.refs import (
183
 
            BazaarRefsContainer,
184
 
            )
185
 
        from bzrlib.plugins.git.object_store import (
 
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 (
186
228
            get_object_store,
187
229
            )
188
 
        bzrdir, _ = BzrDir.open_containing(directory)
189
 
        repo = bzrdir.find_repository()
190
 
        repo.lock_read()
191
 
        try:
192
 
            object_store = get_object_store(repo)
193
 
            refs = BazaarRefsContainer(bzrdir, object_store)
 
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)
194
235
            for k, v in refs.as_dict().iteritems():
195
236
                self.outf.write("%s -> %s\n" % (k, v))
196
 
        finally:
197
 
            repo.unlock()
198
237
 
199
238
 
200
239
class cmd_git_apply(Command):
204
243
    "bzr pull".
205
244
    """
206
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
        ]
207
251
    takes_args = ["patches*"]
208
252
 
209
 
    def _apply_patch(self, wt, f):
 
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
210
262
        from dulwich.patch import git_am_patch_split
 
263
        import subprocess
211
264
        (c, diff, version) = git_am_patch_split(f)
212
 
        # FIXME: Process diff
213
 
        wt.commit(committer=c.committer,
214
 
                  message=c.message)
 
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)
215
278
 
216
 
    def run(self, patches_list=None):
217
 
        from bzrlib.workingtree import WorkingTree
 
279
    def run(self, patches_list=None, signoff=False, force=False):
 
280
        from ...errors import UncommittedChanges
 
281
        from ...workingtree import WorkingTree
218
282
        if patches_list is None:
219
283
            patches_list = []
220
 
        
 
284
 
221
285
        tree, _ = WorkingTree.open_containing(".")
222
 
        tree.lock_write()
223
 
        try:
 
286
        if tree.basis_tree().changes_from(tree).has_changed() and not force:
 
287
            raise UncommittedChanges(tree)
 
288
        with tree.lock_write():
224
289
            for patch in patches_list:
225
 
                f = open(patch, 'r')
226
 
                try:
227
 
                    self._apply_patch(tree, f)
228
 
                finally:
229
 
                    f.close()
230
 
        finally:
231
 
            tree.unlock()
 
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)