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 ..commands import (
31
from ..option import (
34
from ..sixish import (
40
class cmd_git_import(Command):
41
"""Import all branches from a git repository.
45
takes_args = ["src_location", "dest_location?"]
48
Option('colocated', help='Create colocated branches.'),
51
def _get_colocated_branch(self, target_controldir, name):
52
from ..errors import NotBranchError
54
return target_controldir.open_branch(name=name)
55
except NotBranchError:
56
return target_controldir.create_branch(name=name)
58
def _get_nested_branch(self, dest_transport, dest_format, name):
59
from ..controldir import ControlDir
60
from ..errors import NotBranchError
61
head_transport = dest_transport.clone(name)
63
head_controldir = ControlDir.open_from_transport(head_transport)
64
except NotBranchError:
65
head_controldir = dest_format.initialize_on_transport_ex(
66
head_transport, create_prefix=True)[1]
68
return head_controldir.open_branch()
69
except NotBranchError:
70
return head_controldir.create_branch()
72
def run(self, src_location, dest_location=None, colocated=False):
80
from ..controldir import (
83
from ..errors import (
89
from ..repository import (
93
from ..transport import get_transport
100
from .repository import GitRepository
102
dest_format = controldir.ControlDirFormat.get_default_format()
103
if dest_format is None:
104
raise errors.BzrError('no default format')
106
if dest_location is None:
107
dest_location = os.path.basename(src_location.rstrip("/\\"))
109
dest_transport = get_transport(dest_location)
111
source_repo = Repository.open(src_location)
112
if not isinstance(source_repo, GitRepository):
113
raise BzrCommandError(
114
gettext("%r is not a git repository") % src_location)
116
target_controldir = ControlDir.open_from_transport(dest_transport)
117
except NotBranchError:
118
target_controldir = dest_format.initialize_on_transport_ex(
119
dest_transport, shared_repo=True)[1]
121
target_repo = target_controldir.find_repository()
122
except NoRepositoryPresent:
123
target_repo = target_controldir.create_repository(shared=True)
125
if not target_repo.supports_rich_root():
126
raise BzrCommandError(
127
gettext("Target repository doesn't support rich roots"))
129
interrepo = InterRepository.get(source_repo, target_repo)
130
mapping = source_repo.get_mapping()
131
refs = interrepo.fetch()
132
pb = ui.ui_factory.nested_progress_bar()
134
for i, (name, sha) in enumerate(viewitems(refs)):
136
branch_name = ref_to_branch_name(name)
138
# Not a branch, ignore
140
pb.update(gettext("creating branches"), i, len(refs))
141
if getattr(target_controldir._format, "colocated_branches", False) and colocated:
144
head_branch = self._get_colocated_branch(
145
target_controldir, branch_name)
147
head_branch = self._get_nested_branch(
148
dest_transport, dest_format, branch_name)
149
revid = mapping.revision_id_foreign_to_bzr(sha)
150
source_branch = LocalGitBranch(source_repo.controldir, source_repo,
152
if head_branch.last_revision() != revid:
153
head_branch.generate_revision_history(revid)
154
source_branch.tags.merge_to(head_branch.tags)
155
if not head_branch.get_parent():
156
url = urlutils.join_segment_parameters(
157
source_branch.base, {"branch": urlutils.escape(branch_name)})
158
head_branch.set_parent(url)
162
"Use 'bzr checkout' to create a working tree in "
163
"the newly created branches."))
166
class cmd_git_object(Command):
167
"""List or display Git objects by SHA.
169
Cat a particular object's Git representation if a SHA is specified.
170
List all available SHAs otherwise.
175
aliases = ["git-objects", "git-cat"]
176
takes_args = ["sha1?"]
177
takes_options = [Option('directory',
179
help='Location of repository.', type=text_type),
180
Option('pretty', help='Pretty-print objects.')]
181
encoding_type = 'exact'
184
def run(self, sha1=None, directory=".", pretty=False):
185
from ..errors import (
188
from ..controldir import (
191
from .object_store import (
194
from . import gettext
195
controldir, _ = ControlDir.open_containing(directory)
196
repo = controldir.find_repository()
197
object_store = get_object_store(repo)
198
with object_store.lock_read():
201
obj = object_store[str(sha1)]
203
raise BzrCommandError(
204
gettext("Object not found: %s") % sha1)
206
text = obj.as_pretty_string()
208
text = obj.as_raw_string()
209
self.outf.write(text)
211
for sha1 in object_store:
212
self.outf.write("%s\n" % sha1)
215
class cmd_git_refs(Command):
216
"""Output all of the virtual refs for a repository.
222
takes_args = ["location?"]
225
def run(self, location="."):
226
from ..controldir import (
232
from .object_store import (
235
controldir, _ = ControlDir.open_containing(location)
236
repo = controldir.find_repository()
237
object_store = get_object_store(repo)
238
with object_store.lock_read():
239
refs = get_refs_container(controldir, object_store)
240
for k, v in sorted(viewitems(refs.as_dict())):
241
self.outf.write("%s -> %s\n" %
242
(k.decode('utf-8'), v.decode('utf-8')))
245
class cmd_git_apply(Command):
246
"""Apply a series of git-am style patches.
248
This command will in the future probably be integrated into
253
Option('signoff', short_name='s', help='Add a Signed-off-by line.'),
255
help='Apply patches even if tree has uncommitted changes.')
257
takes_args = ["patches*"]
259
def _apply_patch(self, wt, f, signoff):
262
:param wt: A Bazaar working tree object.
263
:param f: Patch file to read.
264
:param signoff: Add Signed-Off-By flag.
266
from . import gettext
267
from ..errors import BzrCommandError
268
from dulwich.patch import git_am_patch_split
270
(c, diff, version) = git_am_patch_split(f)
271
# FIXME: Cope with git-specific bits in patch
272
# FIXME: Add new files to working tree
273
p = subprocess.Popen(["patch", "-p1"], stdin=subprocess.PIPE,
278
raise BzrCommandError(gettext("error running patch"))
281
signed_off_by = wt.branch.get_config().username()
282
message += "Signed-off-by: %s\n" % signed_off_by.encode('utf-8')
283
wt.commit(authors=[c.author], message=message)
285
def run(self, patches_list=None, signoff=False, force=False):
286
from ..errors import UncommittedChanges
287
from ..workingtree import WorkingTree
288
if patches_list is None:
291
tree, _ = WorkingTree.open_containing(".")
292
if tree.basis_tree().changes_from(tree).has_changed() and not force:
293
raise UncommittedChanges(tree)
294
with tree.lock_write():
295
for patch in patches_list:
296
with open(patch, 'r') as f:
297
self._apply_patch(tree, f, signoff=signoff)
300
class cmd_git_push_pristine_tar_deltas(Command):
301
"""Push pristine tar deltas to a git repository."""
303
takes_options = [Option('directory',
305
help='Location of repository.', type=text_type)]
306
takes_args = ['target', 'package']
308
def run(self, target, package, directory='.'):
309
from ..branch import Branch
310
from ..errors import (
314
from ..trace import warning
315
from ..repository import Repository
316
from .object_store import get_object_store
317
from .pristine_tar import (
318
revision_pristine_tar_data,
319
store_git_pristine_tar_data,
321
source = Branch.open_containing(directory)[0]
322
target_bzr = Repository.open(target)
323
target = getattr(target_bzr, '_git', None)
325
raise BzrCommandError("Target not a git repository")
326
git_store = get_object_store(source.repository)
327
with git_store.lock_read():
328
tag_dict = source.tags.get_tag_dict()
329
for name, revid in tag_dict.iteritems():
331
rev = source.repository.get_revision(revid)
332
except NoSuchRevision:
335
delta, kind = revision_pristine_tar_data(rev)
338
gitid = git_store._lookup_revision_sha1(revid)
339
if not (name.startswith('upstream/') or name.startswith('upstream-')):
340
warning("Unexpected pristine tar revision tagged %s. Ignoring.",
343
upstream_version = name[len("upstream/"):]
344
filename = '%s_%s.orig.tar.%s' % (
345
package, upstream_version, kind)
346
if not gitid in target:
347
warning("base git id %s for %s missing in target repository",
349
store_git_pristine_tar_data(target, filename.encode('utf-8'),