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
import breezy.bzr # noqa: F401
25
from breezy import controldir
26
from ..commands import (
30
from ..option import (
36
class cmd_git_import(Command):
37
"""Import all branches from a git repository.
41
takes_args = ["src_location", "dest_location?"]
44
Option('colocated', help='Create colocated branches.'),
45
RegistryOption('dest-format',
46
help='Specify a format for this branch. '
47
'See "help formats" for a full list.',
48
lazy_registry=('breezy.controldir', 'format_registry'),
49
converter=lambda name: controldir.format_registry.make_controldir(
52
title="Branch format",
56
def _get_colocated_branch(self, target_controldir, name):
57
from ..errors import NotBranchError
59
return target_controldir.open_branch(name=name)
60
except NotBranchError:
61
return target_controldir.create_branch(name=name)
63
def _get_nested_branch(self, dest_transport, dest_format, name):
64
from ..controldir import ControlDir
65
from ..errors import NotBranchError
66
head_transport = dest_transport.clone(name)
68
head_controldir = ControlDir.open_from_transport(head_transport)
69
except NotBranchError:
70
head_controldir = dest_format.initialize_on_transport_ex(
71
head_transport, create_prefix=True)[1]
73
return head_controldir.open_branch()
74
except NotBranchError:
75
return head_controldir.create_branch()
77
def run(self, src_location, dest_location=None, colocated=False, dest_format=None):
85
from ..controldir import (
88
from ..errors import (
94
from ..i18n import gettext
95
from ..repository import (
99
from ..transport import get_transport
100
from .branch import (
106
from .repository import GitRepository
108
if dest_format is None:
109
dest_format = controldir.format_registry.make_controldir('default')
111
if dest_location is None:
112
dest_location = os.path.basename(src_location.rstrip("/\\"))
114
dest_transport = get_transport(dest_location)
116
source_repo = Repository.open(src_location)
117
if not isinstance(source_repo, GitRepository):
119
gettext("%r is not a git repository") % src_location)
121
target_controldir = ControlDir.open_from_transport(dest_transport)
122
except NotBranchError:
123
target_controldir = dest_format.initialize_on_transport_ex(
124
dest_transport, shared_repo=True)[1]
126
target_repo = target_controldir.find_repository()
127
except NoRepositoryPresent:
128
target_repo = target_controldir.create_repository(shared=True)
130
if not target_repo.supports_rich_root():
132
gettext("Target repository doesn't support rich roots"))
134
interrepo = InterRepository.get(source_repo, target_repo)
135
mapping = source_repo.get_mapping()
136
result = interrepo.fetch()
137
with ui.ui_factory.nested_progress_bar() as pb:
138
for i, (name, sha) in enumerate(result.refs.items()):
140
branch_name = ref_to_branch_name(name)
142
# Not a branch, ignore
144
pb.update(gettext("creating branches"), i, len(result.refs))
145
if (getattr(target_controldir._format, "colocated_branches",
146
False) and colocated):
149
head_branch = self._get_colocated_branch(
150
target_controldir, branch_name)
152
head_branch = self._get_nested_branch(
153
dest_transport, dest_format, branch_name)
154
revid = mapping.revision_id_foreign_to_bzr(sha)
155
source_branch = LocalGitBranch(
156
source_repo.controldir, source_repo, sha)
157
if head_branch.last_revision() != revid:
158
head_branch.generate_revision_history(revid)
159
source_branch.tags.merge_to(head_branch.tags)
160
if not head_branch.get_parent():
161
url = urlutils.join_segment_parameters(
163
{"branch": urlutils.escape(branch_name)})
164
head_branch.set_parent(url)
166
"Use 'bzr checkout' to create a working tree in "
167
"the newly created branches."))
170
class cmd_git_object(Command):
171
"""List or display Git objects by SHA.
173
Cat a particular object's Git representation if a SHA is specified.
174
List all available SHAs otherwise.
179
aliases = ["git-objects", "git-cat"]
180
takes_args = ["sha1?"]
181
takes_options = [Option('directory',
183
help='Location of repository.', type=str),
184
Option('pretty', help='Pretty-print objects.')]
185
encoding_type = 'exact'
188
def run(self, sha1=None, directory=".", pretty=False):
189
from ..errors import (
192
from ..controldir import (
195
from .object_store import (
198
from ..i18n import gettext
199
controldir, _ = ControlDir.open_containing(directory)
200
repo = controldir.find_repository()
201
object_store = get_object_store(repo)
202
with object_store.lock_read():
205
obj = object_store[sha1.encode('ascii')]
208
gettext("Object not found: %s") % sha1)
210
text = obj.as_pretty_string()
212
text = obj.as_raw_string()
213
self.outf.write(text)
215
for sha1 in object_store:
216
self.outf.write("%s\n" % sha1.decode('ascii'))
219
class cmd_git_refs(Command):
220
"""Output all of the virtual refs for a repository.
226
takes_args = ["location?"]
229
def run(self, location="."):
230
from ..controldir import (
236
from .object_store import (
239
controldir, _ = ControlDir.open_containing(location)
240
repo = controldir.find_repository()
241
object_store = get_object_store(repo)
242
with object_store.lock_read():
243
refs = get_refs_container(controldir, object_store)
244
for k, v in sorted(refs.as_dict().items()):
245
self.outf.write("%s -> %s\n" %
246
(k.decode('utf-8'), v.decode('utf-8')))
249
class cmd_git_apply(Command):
250
"""Apply a series of git-am style patches.
252
This command will in the future probably be integrated into "bzr pull".
256
Option('signoff', short_name='s', help='Add a Signed-off-by line.'),
258
help='Apply patches even if tree has uncommitted changes.')
260
takes_args = ["patches*"]
262
def _apply_patch(self, wt, f, signoff):
265
:param wt: A Bazaar working tree object.
266
:param f: Patch file to read.
267
:param signoff: Add Signed-Off-By flag.
269
from dulwich.patch import git_am_patch_split
270
from breezy.patch import patch_tree
271
(c, diff, version) = git_am_patch_split(f)
272
# FIXME: Cope with git-specific bits in patch
273
# FIXME: Add new files to working tree
274
patch_tree(wt, [diff], strip=1, out=self.outf)
275
message = c.message.decode('utf-8')
277
signed_off_by = wt.branch.get_config().username()
278
message += "Signed-off-by: %s\n" % (signed_off_by, )
279
wt.commit(authors=[c.author.decode('utf-8')], message=message)
281
def run(self, patches_list=None, signoff=False, force=False):
282
from ..errors import UncommittedChanges
283
from ..workingtree import WorkingTree
284
if patches_list is None:
287
tree, _ = WorkingTree.open_containing(".")
288
if tree.basis_tree().changes_from(tree).has_changed() and not force:
289
raise UncommittedChanges(tree)
290
with tree.lock_write():
291
for patch in patches_list:
292
with open(patch, 'r') as f:
293
self._apply_patch(tree, f, signoff=signoff)
296
class cmd_git_push_pristine_tar_deltas(Command):
297
"""Push pristine tar deltas to a git repository."""
299
takes_options = [Option('directory',
301
help='Location of repository.', type=str)]
302
takes_args = ['target', 'package']
304
def run(self, target, package, directory='.'):
305
from ..branch import Branch
306
from ..errors import (
310
from ..trace import warning
311
from ..repository import Repository
312
from .mapping import encode_git_path
313
from .object_store import get_object_store
314
from .pristine_tar import (
315
revision_pristine_tar_data,
316
store_git_pristine_tar_data,
318
source = Branch.open_containing(directory)[0]
319
target_bzr = Repository.open(target)
320
target = getattr(target_bzr, '_git', None)
322
raise CommandError("Target not a git repository")
323
git_store = get_object_store(source.repository)
324
with git_store.lock_read():
325
tag_dict = source.tags.get_tag_dict()
326
for name, revid in tag_dict.iteritems():
328
rev = source.repository.get_revision(revid)
329
except NoSuchRevision:
332
delta, kind = revision_pristine_tar_data(rev)
335
gitid = git_store._lookup_revision_sha1(revid)
336
if (not (name.startswith('upstream/') or
337
name.startswith('upstream-'))):
339
"Unexpected pristine tar revision tagged %s. "
342
upstream_version = name[len("upstream/"):]
343
filename = '%s_%s.orig.tar.%s' % (
344
package, upstream_version, kind)
345
if gitid not in target:
347
"base git id %s for %s missing in target repository",
349
store_git_pristine_tar_data(target, encode_git_path(filename),