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
22
"""A GIT branch and repository format implementation for bzr."""
24
from __future__ import absolute_import
32
bzr_compatible_versions,
33
bzr_plugin_version as version_info,
34
dulwich_minimum_version,
37
if version_info[3] == 'final':
38
version_string = '%d.%d.%d' % version_info[:3]
40
version_string = '%d.%d.%d%s%d' % version_info
41
__version__ = version_string
43
if breezy.version_info[:3] not in bzr_compatible_versions:
44
from ...errors import IncompatibleVersion
45
raise IncompatibleVersion(breezy,
46
bzr_compatible_versions, breezy.version_info[:3])
49
from ...i18n import load_plugin_translations
50
except ImportError: # No translations for bzr < 2.5
53
translation = load_plugin_translations("bzr-git")
54
gettext = translation.gettext
57
__version__ as breezy_version,
62
from ...controldir import (
66
network_format_registry as controldir_network_format_registry,
69
from ...transport import (
70
register_lazy_transport,
71
register_transport_proto,
72
transport_server_registry,
74
from ...commands import (
79
if getattr(sys, "frozen", None):
80
# allow import additional libs from ./_lib for bzr.exe only
81
sys.path.append(os.path.normpath(
82
os.path.join(os.path.dirname(__file__), '_lib')))
87
from dulwich import __version__ as dulwich_version
89
raise bzr_errors.DependencyNotPresent("dulwich",
90
"bzr-git: Please install dulwich, https://launchpad.net/dulwich")
92
if dulwich_version < dulwich_minimum_version:
93
raise bzr_errors.DependencyNotPresent("dulwich",
94
"bzr-git: Dulwich is too old; at least %d.%d.%d is required" %
95
dulwich_minimum_version)
98
_versions_checked = False
99
def lazy_check_versions():
100
global _versions_checked
101
if _versions_checked:
104
_versions_checked = True
106
format_registry.register_lazy('git',
107
__name__ + ".dir", "LocalGitControlDirFormat",
108
help='GIT repository.', native=False, experimental=False,
111
format_registry.register_lazy('git-bare',
112
__name__ + ".dir", "BareLocalGitControlDirFormat",
113
help='Bare GIT repository (no working tree).', native=False,
117
from ...revisionspec import (RevisionSpec_dwim, revspec_registry)
118
revspec_registry.register_lazy("git:", __name__ + ".revspec",
120
RevisionSpec_dwim.append_possible_lazy_revspec(
121
__name__ + ".revspec", "RevisionSpec_git")
124
class LocalGitProber(Prober):
126
def probe_transport(self, transport):
128
external_url = transport.external_url()
129
except bzr_errors.InProcessTransport:
130
raise bzr_errors.NotBranchError(path=transport.base)
131
if (external_url.startswith("http:") or
132
external_url.startswith("https:")):
133
# Already handled by RemoteGitProber
134
raise bzr_errors.NotBranchError(path=transport.base)
135
from ... import urlutils
136
if urlutils.split(transport.base)[1] == ".git":
137
raise bzr_errors.NotBranchError(path=transport.base)
138
if not transport.has_any(['objects', '.git/objects']):
139
raise bzr_errors.NotBranchError(path=transport.base)
140
lazy_check_versions()
142
BareLocalGitControlDirFormat,
143
LocalGitControlDirFormat,
145
if transport.has_any(['.git/objects']):
146
return LocalGitControlDirFormat()
147
if transport.has('info') and transport.has('objects'):
148
return BareLocalGitControlDirFormat()
149
raise bzr_errors.NotBranchError(path=transport.base)
152
def known_formats(cls):
154
BareLocalGitControlDirFormat,
155
LocalGitControlDirFormat,
157
return set([BareLocalGitControlDirFormat(), LocalGitControlDirFormat()])
160
class RemoteGitProber(Prober):
162
def probe_http_transport(self, transport):
163
from ... import urlutils
164
base_url, _ = urlutils.split_segment_parameters(transport.external_url())
165
url = urlutils.join(base_url, "info/refs") + "?service=git-upload-pack"
166
from ...transport.http._urllib import HttpTransport_urllib, Request
167
headers = {"Content-Type": "application/x-git-upload-pack-request"}
168
if "github.com" in url:
169
# GitHub requires we lie. https://github.com/dulwich/dulwich/issues/562
170
headers["User-agent"] = "git/Breezy/%s" % breezy_version
171
req = Request('GET', url, accepted_errors=[200, 403, 404, 405],
173
req.follow_redirections = True
174
resp = transport._perform(req)
175
if resp.code in (404, 405):
176
raise bzr_errors.NotBranchError(transport.base)
177
headers = resp.headers
178
ct = headers.getheader("Content-Type")
180
raise bzr_errors.NotBranchError(transport.base)
181
if ct.startswith("application/x-git"):
182
from .remote import RemoteGitControlDirFormat
183
return RemoteGitControlDirFormat()
186
BareLocalGitControlDirFormat,
188
ret = BareLocalGitControlDirFormat()
189
ret._refs_text = resp.read()
192
def probe_transport(self, transport):
194
external_url = transport.external_url()
195
except bzr_errors.InProcessTransport:
196
raise bzr_errors.NotBranchError(path=transport.base)
198
if (external_url.startswith("http:") or
199
external_url.startswith("https:")):
200
return self.probe_http_transport(transport)
202
if (not external_url.startswith("git://") and
203
not external_url.startswith("git+")):
204
raise bzr_errors.NotBranchError(transport.base)
206
# little ugly, but works
207
from .remote import (
209
RemoteGitControlDirFormat,
211
if isinstance(transport, GitSmartTransport):
212
return RemoteGitControlDirFormat()
213
raise bzr_errors.NotBranchError(path=transport.base)
216
def known_formats(cls):
217
from .remote import RemoteGitControlDirFormat
218
return set([RemoteGitControlDirFormat()])
221
ControlDirFormat.register_prober(LocalGitProber)
222
ControlDirFormat._server_probers.append(RemoteGitProber)
224
register_transport_proto('git://',
225
help="Access using the Git smart server protocol.")
226
register_transport_proto('git+ssh://',
227
help="Access using the Git smart server protocol over SSH.")
229
register_lazy_transport("git://", __name__ + '.remote',
230
'TCPGitSmartTransport')
231
register_lazy_transport("git+ssh://", __name__ + '.remote',
232
'SSHGitSmartTransport')
235
plugin_cmds.register_lazy("cmd_git_import", [], __name__ + ".commands")
236
plugin_cmds.register_lazy("cmd_git_object", ["git-objects", "git-cat"],
237
__name__ + ".commands")
238
plugin_cmds.register_lazy("cmd_git_refs", [], __name__ + ".commands")
239
plugin_cmds.register_lazy("cmd_git_apply", [], __name__ + ".commands")
240
plugin_cmds.register_lazy("cmd_git_push_pristine_tar_deltas",
241
['git-push-pristine-tar', 'git-push-pristine'],
242
__name__ + ".commands")
244
def extract_git_foreign_revid(rev):
246
foreign_revid = rev.foreign_revid
247
except AttributeError:
248
from .mapping import mapping_registry
249
foreign_revid, mapping = \
250
mapping_registry.parse_revision_id(rev.revision_id)
253
from .mapping import foreign_vcs_git
254
if rev.mapping.vcs == foreign_vcs_git:
257
raise bzr_errors.InvalidRevisionId(rev.revision_id, None)
260
def update_stanza(rev, stanza):
261
mapping = getattr(rev, "mapping", None)
263
git_commit = extract_git_foreign_revid(rev)
264
except bzr_errors.InvalidRevisionId:
267
stanza.add("git-commit", git_commit)
269
from ...hooks import install_lazy_named_hook
270
install_lazy_named_hook("breezy.version_info_formats.format_rio",
271
"RioVersionInfoBuilder.hooks", "revision", update_stanza,
275
transport_server_registry.register_lazy('git',
276
__name__ + '.server',
278
'Git Smart server protocol over TCP. (default port: 9418)')
280
transport_server_registry.register_lazy('git-receive-pack',
281
__name__ + '.server',
282
'serve_git_receive_pack',
283
help='Git Smart server receive pack command. (inetd mode only)')
284
transport_server_registry.register_lazy('git-upload-pack',
285
__name__ + 'git.server',
286
'serve_git_upload_pack',
287
help='Git Smart server upload pack command. (inetd mode only)')
289
from ...repository import (
290
format_registry as repository_format_registry,
291
network_format_registry as repository_network_format_registry,
293
repository_network_format_registry.register_lazy('git',
294
__name__ + '.repository', 'GitRepositoryFormat')
296
register_extra_lazy_repository_format = getattr(repository_format_registry,
297
"register_extra_lazy")
298
register_extra_lazy_repository_format(__name__ + '.repository',
299
'GitRepositoryFormat')
301
from ...branch import (
302
network_format_registry as branch_network_format_registry,
304
branch_network_format_registry.register_lazy('git',
305
__name__ + '.branch', 'LocalGitBranchFormat')
308
from ...branch import (
309
format_registry as branch_format_registry,
311
branch_format_registry.register_extra_lazy(
312
__name__ + '.branch',
313
'LocalGitBranchFormat',
315
branch_format_registry.register_extra_lazy(
316
__name__ + '.remote',
317
'RemoteGitBranchFormat',
321
from ...workingtree import (
322
format_registry as workingtree_format_registry,
324
workingtree_format_registry.register_extra_lazy(
325
__name__ + '.workingtree',
326
'GitWorkingTreeFormat',
329
controldir_network_format_registry.register_lazy('git',
330
__name__ + ".dir", "GitControlDirFormat")
334
from ...registry import register_lazy
336
from ...diff import format_registry as diff_format_registry
337
diff_format_registry.register_lazy('git', __name__ + '.send',
338
'GitDiffTree', 'Git am-style diff format')
340
from ...send import (
341
format_registry as send_format_registry,
343
send_format_registry.register_lazy('git', __name__ + '.send',
344
'send_git', 'Git am-style diff format')
346
from ...directory_service import directories
347
directories.register_lazy('github:', __name__ + '.directory',
350
directories.register_lazy('git@github.com:', __name__ + '.directory',
354
from ...help_topics import (
357
topic_registry.register_lazy('git', __name__ + '.help', 'help_git',
358
'Using Bazaar with Git')
360
from ...foreign import (
361
foreign_vcs_registry,
363
foreign_vcs_registry.register_lazy("git",
364
__name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
366
register_lazy("breezy.diff", "format_registry",
367
'git', __name__ + '.send', 'GitDiffTree',
368
'Git am-style diff format')
369
register_lazy("breezy.send", "format_registry",
370
'git', __name__ + '.send', 'send_git',
371
'Git am-style diff format')
372
register_lazy('breezy.directory_service', 'directories', 'github:',
373
__name__ + '.directory', 'GitHubDirectory',
375
register_lazy('breezy.directory_service', 'directories',
376
'git@github.com:', __name__ + '.directory',
377
'GitHubDirectory', 'GitHub directory.')
378
register_lazy('breezy.help_topics', 'topic_registry',
379
'git', __name__ + '.help', 'help_git',
380
'Using Bazaar with Git')
381
register_lazy('breezy.foreign', 'foreign_vcs_registry', "git",
382
__name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
384
def update_git_cache(repository, revid):
385
"""Update the git cache after a local commit."""
386
if getattr(repository, "_git", None) is not None:
387
return # No need to update cache for git repositories
389
if not repository.control_transport.has("git"):
390
return # No existing cache, don't bother updating
392
lazy_check_versions()
393
except bzr_errors.DependencyNotPresent, e:
394
# dulwich is probably missing. silently ignore
395
trace.mutter("not updating git map for %r: %s",
398
from .object_store import BazaarObjectStore
399
store = BazaarObjectStore(repository)
400
with store.lock_write():
402
parent_revisions = set(repository.get_parent_map([revid])[revid])
404
# Isn't this a bit odd - how can a revision that was just committed be missing?
406
missing_revisions = store._missing_revisions(parent_revisions)
407
if not missing_revisions:
408
# Only update if the cache was up to date previously
409
store._update_sha_map_revision(revid)
412
def post_commit_update_cache(local_branch, master_branch, old_revno, old_revid,
413
new_revno, new_revid):
414
if local_branch is not None:
415
update_git_cache(local_branch.repository, new_revid)
416
update_git_cache(master_branch.repository, new_revid)
419
def loggerhead_git_hook(branch_app, environ):
420
branch = branch_app.branch
421
config_stack = branch.get_config_stack()
422
if config_stack.get('http_git'):
424
from .server import git_http_hook
425
return git_http_hook(branch, environ['REQUEST_METHOD'],
426
environ['PATH_INFO'])
428
install_lazy_named_hook("breezy.branch",
429
"Branch.hooks", "post_commit", post_commit_update_cache,
431
install_lazy_named_hook("breezy.plugins.loggerhead.apps.branch",
432
"BranchWSGIApp.hooks", "controller",
433
loggerhead_git_hook, "git support")
436
from ...config import (
442
option_registry.register(
444
default=None, from_unicode=bool_from_store, invalid='warning',
446
Allow fetching of Git packs over HTTP.
448
This enables support for fetching Git packs over HTTP in Loggerhead.
453
return tests.test_suite()