1
# Copyright (C) 2006-2009 Canonical Ltd
3
# Authors: Robert Collins <robert.collins@canonical.com>
4
# Jelmer Vernooij <jelmer@samba.org>
5
# John Carr <john.carr@unrouted.co.uk>
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.
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.
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
21
"""Git-specific subcommands for Bazaar."""
23
from __future__ import absolute_import
25
import breezy.bzr.bzrdir
26
from ...commands import (
30
from ...option import (
35
class cmd_git_import(Command):
36
"""Import all branches from a git repository.
40
takes_args = ["src_location", "dest_location?"]
43
Option('colocated', help='Create colocated branches.'),
46
def _get_colocated_branch(self, target_controldir, name):
47
from ...errors import NotBranchError
49
return target_controldir.open_branch(name=name)
50
except NotBranchError:
51
return target_controldir.create_branch(name=name)
53
def _get_nested_branch(self, dest_transport, dest_format, name):
54
from ...controldir import ControlDir
55
from ...errors import NotBranchError
56
head_transport = dest_transport.clone(name)
58
head_controldir = ControlDir.open_from_transport(head_transport)
59
except NotBranchError:
60
head_controldir = dest_format.initialize_on_transport_ex(
61
head_transport, create_prefix=True)[1]
63
return head_controldir.open_branch()
64
except NotBranchError:
65
return head_controldir.create_branch()
67
def run(self, src_location, dest_location=None, colocated=False):
76
from ...controldir import (
79
from ...errors import (
85
from ...repository import (
89
from ...transport import get_transport
96
from .repository import GitRepository
98
dest_format = controldir.ControlDirFormat.get_default_format()
99
assert dest_format is not None
101
if dest_location is None:
102
dest_location = os.path.basename(src_location.rstrip("/\\"))
104
dest_transport = get_transport(dest_location)
106
source_repo = Repository.open(src_location)
107
if not isinstance(source_repo, GitRepository):
108
raise BzrCommandError(gettext("%r is not a git repository") % src_location)
110
target_controldir = ControlDir.open_from_transport(dest_transport)
111
except NotBranchError:
112
target_controldir = dest_format.initialize_on_transport_ex(
113
dest_transport, shared_repo=True)[1]
115
target_repo = target_controldir.find_repository()
116
except NoRepositoryPresent:
117
target_repo = target_controldir.create_repository(shared=True)
119
if not target_repo.supports_rich_root():
120
raise BzrCommandError(gettext("Target repository doesn't support rich roots"))
122
interrepo = InterRepository.get(source_repo, target_repo)
123
mapping = source_repo.get_mapping()
124
refs = interrepo.fetch()
125
refs_dict = refs.as_dict()
126
pb = ui.ui_factory.nested_progress_bar()
128
for i, (name, sha) in enumerate(refs_dict.iteritems()):
130
branch_name = ref_to_branch_name(name)
132
# Not a branch, ignore
134
pb.update(gettext("creating branches"), i, len(refs_dict))
135
if getattr(target_controldir._format, "colocated_branches", False) and colocated:
138
head_branch = self._get_colocated_branch(target_controldir, branch_name)
140
head_branch = self._get_nested_branch(dest_transport, dest_format, branch_name)
141
revid = mapping.revision_id_foreign_to_bzr(sha)
142
source_branch = LocalGitBranch(source_repo.controldir, source_repo,
144
if head_branch.last_revision() != revid:
145
head_branch.generate_revision_history(revid)
146
source_branch.tags.merge_to(head_branch.tags)
147
if not head_branch.get_parent():
148
url = urlutils.join_segment_parameters(
149
source_branch.base, {"ref": urllib.quote(name, '')})
150
head_branch.set_parent(url)
154
"Use 'bzr checkout' to create a working tree in "
155
"the newly created branches."))
158
class cmd_git_object(Command):
159
"""List or display Git objects by SHA.
161
Cat a particular object's Git representation if a SHA is specified.
162
List all available SHAs otherwise.
167
aliases = ["git-objects", "git-cat"]
168
takes_args = ["sha1?"]
169
takes_options = [Option('directory',
171
help='Location of repository.', type=unicode),
172
Option('pretty', help='Pretty-print objects.')]
173
encoding_type = 'exact'
176
def run(self, sha1=None, directory=".", pretty=False):
177
from ...errors import (
180
from ...controldir import (
183
from .object_store import (
186
from . import gettext
187
controldir, _ = ControlDir.open_containing(directory)
188
repo = controldir.find_repository()
189
object_store = get_object_store(repo)
190
with object_store.lock_read():
193
obj = object_store[str(sha1)]
195
raise BzrCommandError(gettext("Object not found: %s") % sha1)
197
text = obj.as_pretty_string()
199
text = obj.as_raw_string()
200
self.outf.write(text)
202
for sha1 in object_store:
203
self.outf.write("%s\n" % sha1)
206
class cmd_git_refs(Command):
207
"""Output all of the virtual refs for a repository.
213
takes_args = ["location?"]
216
def run(self, location="."):
217
from ...controldir import (
223
from .object_store import (
226
controldir, _ = ControlDir.open_containing(location)
227
repo = controldir.find_repository()
228
object_store = get_object_store(repo)
229
with object_store.lock_read():
230
refs = get_refs_container(controldir, object_store)
231
for k, v in refs.as_dict().iteritems():
232
self.outf.write("%s -> %s\n" % (k, v))
235
class cmd_git_apply(Command):
236
"""Apply a series of git-am style patches.
238
This command will in the future probably be integrated into
243
Option('signoff', short_name='s', help='Add a Signed-off-by line.'),
245
help='Apply patches even if tree has uncommitted changes.')
247
takes_args = ["patches*"]
249
def _apply_patch(self, wt, f, signoff):
252
:param wt: A Bazaar working tree object.
253
:param f: Patch file to read.
254
:param signoff: Add Signed-Off-By flag.
256
from . import gettext
257
from ...errors import BzrCommandError
258
from dulwich.patch import git_am_patch_split
260
(c, diff, version) = git_am_patch_split(f)
261
# FIXME: Cope with git-specific bits in patch
262
# FIXME: Add new files to working tree
263
p = subprocess.Popen(["patch", "-p1"], stdin=subprocess.PIPE,
268
raise BzrCommandError(gettext("error running patch"))
271
signed_off_by = wt.branch.get_config().username()
272
message += "Signed-off-by: %s\n" % signed_off_by.encode('utf-8')
273
wt.commit(authors=[c.author], message=message)
275
def run(self, patches_list=None, signoff=False, force=False):
276
from ...errors import UncommittedChanges
277
from ...workingtree import WorkingTree
278
if patches_list is None:
281
tree, _ = WorkingTree.open_containing(".")
282
if tree.basis_tree().changes_from(tree).has_changed() and not force:
283
raise UncommittedChanges(tree)
284
with tree.lock_write():
285
for patch in patches_list:
286
with open(patch, 'r') as f:
287
self._apply_patch(tree, f, signoff=signoff)
290
class cmd_git_push_pristine_tar_deltas(Command):
291
"""Push pristine tar deltas to a git repository."""
293
takes_options = [Option('directory',
295
help='Location of repository.', type=unicode)]
296
takes_args = ['target', 'package']
298
def run(self, target, package, directory='.'):
299
from ...branch import Branch
300
from ...errors import (
304
from ...trace import warning
305
from ...repository import Repository
306
from .object_store import get_object_store
307
from .pristine_tar import (
308
revision_pristine_tar_data,
309
store_git_pristine_tar_data,
311
source = Branch.open_containing(directory)[0]
312
target_bzr = Repository.open(target)
313
target = getattr(target_bzr, '_git', None)
315
raise BzrCommandError("Target not a git repository")
316
git_store = get_object_store(source.repository)
317
with git_store.lock_read():
318
tag_dict = source.tags.get_tag_dict()
319
for name, revid in tag_dict.iteritems():
321
rev = source.repository.get_revision(revid)
322
except NoSuchRevision:
325
delta, kind = revision_pristine_tar_data(rev)
328
gitid = git_store._lookup_revision_sha1(revid)
329
if not (name.startswith('upstream/') or name.startswith('upstream-')):
330
warning("Unexpected pristine tar revision tagged %s. Ignoring.",
333
upstream_version = name[len("upstream/"):]
334
filename = '%s_%s.orig.tar.%s' % (package, upstream_version, kind)
335
if not gitid in target:
336
warning("base git id %s for %s missing in target repository",
338
store_git_pristine_tar_data(target, filename.encode('utf-8'),