1
# Copyright (C) 2006-2009 Canonical Ltd
2
# Copyright (C) 2012-2018 Jelmer Vernooij <jelmer@jelmer.uk>
4
# Authors: Robert Collins <robert.collins@canonical.com>
5
# Jelmer Vernooij <jelmer@samba.org>
6
# John Carr <john.carr@unrouted.co.uk>
8
# This program is free software; you can redistribute it and/or modify
9
# it under the terms of the GNU General Public License as published by
10
# the Free Software Foundation; either version 2 of the License, or
11
# (at your option) any later version.
13
# This program is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
# GNU General Public License for more details.
18
# You should have received a copy of the GNU General Public License
19
# along with this program; if not, write to the Free Software
20
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22
"""Git-specific subcommands for Bazaar."""
24
from __future__ import absolute_import
26
import breezy.bzr # noqa: F401
27
from breezy import controldir
28
from ..commands import (
32
from ..option import (
36
from ..sixish import (
42
class cmd_git_import(Command):
43
"""Import all branches from a git repository.
47
takes_args = ["src_location", "dest_location?"]
50
Option('colocated', help='Create colocated branches.'),
51
RegistryOption('dest-format',
52
help='Specify a format for this branch. '
53
'See "help formats" for a full list.',
54
lazy_registry=('breezy.controldir', 'format_registry'),
55
converter=lambda name: controldir.format_registry.make_controldir(
58
title="Branch format",
62
def _get_colocated_branch(self, target_controldir, name):
63
from ..errors import NotBranchError
65
return target_controldir.open_branch(name=name)
66
except NotBranchError:
67
return target_controldir.create_branch(name=name)
69
def _get_nested_branch(self, dest_transport, dest_format, name):
70
from ..controldir import ControlDir
71
from ..errors import NotBranchError
72
head_transport = dest_transport.clone(name)
74
head_controldir = ControlDir.open_from_transport(head_transport)
75
except NotBranchError:
76
head_controldir = dest_format.initialize_on_transport_ex(
77
head_transport, create_prefix=True)[1]
79
return head_controldir.open_branch()
80
except NotBranchError:
81
return head_controldir.create_branch()
83
def run(self, src_location, dest_location=None, colocated=False, dest_format=None):
91
from ..controldir import (
94
from ..errors import (
100
from ..i18n import gettext
101
from ..repository import (
105
from ..transport import get_transport
106
from .branch import (
112
from .repository import GitRepository
114
if dest_format is None:
115
dest_format = controldir.format_registry.make_controldir('default')
117
if dest_location is None:
118
dest_location = os.path.basename(src_location.rstrip("/\\"))
120
dest_transport = get_transport(dest_location)
122
source_repo = Repository.open(src_location)
123
if not isinstance(source_repo, GitRepository):
124
raise BzrCommandError(
125
gettext("%r is not a git repository") % src_location)
127
target_controldir = ControlDir.open_from_transport(dest_transport)
128
except NotBranchError:
129
target_controldir = dest_format.initialize_on_transport_ex(
130
dest_transport, shared_repo=True)[1]
132
target_repo = target_controldir.find_repository()
133
except NoRepositoryPresent:
134
target_repo = target_controldir.create_repository(shared=True)
136
if not target_repo.supports_rich_root():
137
raise BzrCommandError(
138
gettext("Target repository doesn't support rich roots"))
140
interrepo = InterRepository.get(source_repo, target_repo)
141
mapping = source_repo.get_mapping()
142
result = interrepo.fetch()
143
with ui.ui_factory.nested_progress_bar() as pb:
144
for i, (name, sha) in enumerate(viewitems(result.refs)):
146
branch_name = ref_to_branch_name(name)
148
# Not a branch, ignore
150
pb.update(gettext("creating branches"), i, len(result.refs))
151
if (getattr(target_controldir._format, "colocated_branches",
152
False) and colocated):
155
head_branch = self._get_colocated_branch(
156
target_controldir, branch_name)
158
head_branch = self._get_nested_branch(
159
dest_transport, dest_format, branch_name)
160
revid = mapping.revision_id_foreign_to_bzr(sha)
161
source_branch = LocalGitBranch(
162
source_repo.controldir, source_repo, sha)
163
if head_branch.last_revision() != revid:
164
head_branch.generate_revision_history(revid)
165
source_branch.tags.merge_to(head_branch.tags)
166
if not head_branch.get_parent():
167
url = urlutils.join_segment_parameters(
169
{"branch": urlutils.escape(branch_name)})
170
head_branch.set_parent(url)
172
"Use 'bzr checkout' to create a working tree in "
173
"the newly created branches."))
176
class cmd_git_object(Command):
177
"""List or display Git objects by SHA.
179
Cat a particular object's Git representation if a SHA is specified.
180
List all available SHAs otherwise.
185
aliases = ["git-objects", "git-cat"]
186
takes_args = ["sha1?"]
187
takes_options = [Option('directory',
189
help='Location of repository.', type=text_type),
190
Option('pretty', help='Pretty-print objects.')]
191
encoding_type = 'exact'
194
def run(self, sha1=None, directory=".", pretty=False):
195
from ..errors import (
198
from ..controldir import (
201
from .object_store import (
204
from ..i18n import gettext
205
controldir, _ = ControlDir.open_containing(directory)
206
repo = controldir.find_repository()
207
object_store = get_object_store(repo)
208
with object_store.lock_read():
211
obj = object_store[sha1.encode('ascii')]
213
raise BzrCommandError(
214
gettext("Object not found: %s") % sha1)
216
text = obj.as_pretty_string()
218
text = obj.as_raw_string()
219
self.outf.write(text)
221
for sha1 in object_store:
222
self.outf.write("%s\n" % sha1.decode('ascii'))
225
class cmd_git_refs(Command):
226
"""Output all of the virtual refs for a repository.
232
takes_args = ["location?"]
235
def run(self, location="."):
236
from ..controldir import (
242
from .object_store import (
245
controldir, _ = ControlDir.open_containing(location)
246
repo = controldir.find_repository()
247
object_store = get_object_store(repo)
248
with object_store.lock_read():
249
refs = get_refs_container(controldir, object_store)
250
for k, v in sorted(viewitems(refs.as_dict())):
251
self.outf.write("%s -> %s\n" %
252
(k.decode('utf-8'), v.decode('utf-8')))
255
class cmd_git_apply(Command):
256
"""Apply a series of git-am style patches.
258
This command will in the future probably be integrated into "bzr pull".
262
Option('signoff', short_name='s', help='Add a Signed-off-by line.'),
264
help='Apply patches even if tree has uncommitted changes.')
266
takes_args = ["patches*"]
268
def _apply_patch(self, wt, f, signoff):
271
:param wt: A Bazaar working tree object.
272
:param f: Patch file to read.
273
:param signoff: Add Signed-Off-By flag.
275
from dulwich.patch import git_am_patch_split
276
from breezy.patch import patch_tree
277
(c, diff, version) = git_am_patch_split(f)
278
# FIXME: Cope with git-specific bits in patch
279
# FIXME: Add new files to working tree
280
patch_tree(wt, [diff], strip=1, out=self.outf)
281
message = c.message.decode('utf-8')
283
signed_off_by = wt.branch.get_config().username()
284
message += "Signed-off-by: %s\n" % (signed_off_by, )
285
wt.commit(authors=[c.author.decode('utf-8')], message=message)
287
def run(self, patches_list=None, signoff=False, force=False):
288
from ..errors import UncommittedChanges
289
from ..workingtree import WorkingTree
290
if patches_list is None:
293
tree, _ = WorkingTree.open_containing(".")
294
if tree.basis_tree().changes_from(tree).has_changed() and not force:
295
raise UncommittedChanges(tree)
296
with tree.lock_write():
297
for patch in patches_list:
298
with open(patch, 'r') as f:
299
self._apply_patch(tree, f, signoff=signoff)
302
class cmd_git_push_pristine_tar_deltas(Command):
303
"""Push pristine tar deltas to a git repository."""
305
takes_options = [Option('directory',
307
help='Location of repository.', type=text_type)]
308
takes_args = ['target', 'package']
310
def run(self, target, package, directory='.'):
311
from ..branch import Branch
312
from ..errors import (
316
from ..trace import warning
317
from ..repository import Repository
318
from .object_store import get_object_store
319
from .pristine_tar import (
320
revision_pristine_tar_data,
321
store_git_pristine_tar_data,
323
source = Branch.open_containing(directory)[0]
324
target_bzr = Repository.open(target)
325
target = getattr(target_bzr, '_git', None)
327
raise BzrCommandError("Target not a git repository")
328
git_store = get_object_store(source.repository)
329
with git_store.lock_read():
330
tag_dict = source.tags.get_tag_dict()
331
for name, revid in tag_dict.iteritems():
333
rev = source.repository.get_revision(revid)
334
except NoSuchRevision:
337
delta, kind = revision_pristine_tar_data(rev)
340
gitid = git_store._lookup_revision_sha1(revid)
341
if (not (name.startswith('upstream/') or
342
name.startswith('upstream-'))):
344
"Unexpected pristine tar revision tagged %s. "
347
upstream_version = name[len("upstream/"):]
348
filename = '%s_%s.orig.tar.%s' % (
349
package, upstream_version, kind)
350
if gitid not in target:
352
"base git id %s for %s missing in target repository",
354
store_git_pristine_tar_data(target, filename.encode('utf-8'),