1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
2
# Copyright (C) 2006-2009 Canonical Ltd
4
# Authors: Robert Collins <robert.collins@canonical.com>
5
# Jelmer Vernooij <jelmer@jelmer.uk>
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
23
"""A GIT branch and repository format implementation for bzr."""
25
from __future__ import absolute_import
30
dulwich_minimum_version = (0, 19, 0)
32
from breezy.i18n import gettext
35
__version__ as breezy_version,
41
from ..controldir import (
45
network_format_registry as controldir_network_format_registry,
48
from ..transport import (
49
register_lazy_transport,
50
register_transport_proto,
51
transport_server_registry,
53
from ..commands import (
58
if getattr(sys, "frozen", None):
59
# allow import additional libs from ./_lib for bzr.exe only
60
sys.path.append(os.path.normpath(
61
os.path.join(os.path.dirname(__file__), '_lib')))
66
from dulwich import __version__ as dulwich_version
68
raise bzr_errors.DependencyNotPresent("dulwich",
69
"bzr-git: Please install dulwich, https://www.dulwich.io/")
71
if dulwich_version < dulwich_minimum_version:
72
raise bzr_errors.DependencyNotPresent("dulwich",
73
"bzr-git: Dulwich is too old; at least %d.%d.%d is required" %
74
dulwich_minimum_version)
77
_versions_checked = False
78
def lazy_check_versions():
79
global _versions_checked
83
_versions_checked = True
85
format_registry.register_lazy('git',
86
__name__ + ".dir", "LocalGitControlDirFormat",
87
help='GIT repository.', native=False, experimental=False,
90
format_registry.register_lazy('git-bare',
91
__name__ + ".dir", "BareLocalGitControlDirFormat",
92
help='Bare GIT repository (no working tree).', native=False,
96
from ..revisionspec import (RevisionSpec_dwim, revspec_registry)
97
revspec_registry.register_lazy("git:", __name__ + ".revspec",
99
RevisionSpec_dwim.append_possible_lazy_revspec(
100
__name__ + ".revspec", "RevisionSpec_git")
103
class LocalGitProber(Prober):
105
def probe_transport(self, transport):
107
external_url = transport.external_url()
108
except bzr_errors.InProcessTransport:
109
raise bzr_errors.NotBranchError(path=transport.base)
110
if (external_url.startswith("http:") or
111
external_url.startswith("https:")):
112
# Already handled by RemoteGitProber
113
raise bzr_errors.NotBranchError(path=transport.base)
114
from .. import urlutils
115
if urlutils.split(transport.base)[1] == ".git":
116
raise bzr_errors.NotBranchError(path=transport.base)
117
if not transport.has_any(['objects', '.git/objects', '.git']):
118
raise bzr_errors.NotBranchError(path=transport.base)
119
lazy_check_versions()
121
BareLocalGitControlDirFormat,
122
LocalGitControlDirFormat,
124
if transport.has_any(['.git/objects', '.git']):
125
return LocalGitControlDirFormat()
126
if transport.has('info') and transport.has('objects'):
127
return BareLocalGitControlDirFormat()
128
raise bzr_errors.NotBranchError(path=transport.base)
131
def known_formats(cls):
133
BareLocalGitControlDirFormat,
134
LocalGitControlDirFormat,
136
return [BareLocalGitControlDirFormat(), LocalGitControlDirFormat()]
139
def user_agent_for_github():
140
# GitHub requires we lie. https://github.com/dulwich/dulwich/issues/562
141
return "git/Breezy/%s" % breezy_version
144
class RemoteGitProber(Prober):
146
def probe_http_transport(self, transport):
147
from .. import urlutils
148
base_url, _ = urlutils.split_segment_parameters(transport.external_url())
149
url = urlutils.join(base_url, "info/refs") + "?service=git-upload-pack"
150
from ..transport.http import Request
151
headers = {"Content-Type": "application/x-git-upload-pack-request",
152
"Accept": "application/x-git-upload-pack-result",
154
req = Request('GET', url, accepted_errors=[200, 403, 404, 405],
156
(scheme, user, password, host, port, path) = urlutils.parse_url(req.get_full_url())
157
if host == "github.com":
158
# GitHub requires we lie. https://github.com/dulwich/dulwich/issues/562
159
req.add_header("User-Agent", user_agent_for_github())
160
elif host == "bazaar.launchpad.net":
161
# Don't attempt Git probes against bazaar.launchpad.net; pad.lv/1744830
162
raise bzr_errors.NotBranchError(transport.base)
163
resp = transport._perform(req)
164
if resp.code in (404, 405):
165
raise bzr_errors.NotBranchError(transport.base)
166
headers = resp.headers
167
ct = headers.getheader("Content-Type")
169
raise bzr_errors.NotBranchError(transport.base)
170
if ct.startswith("application/x-git"):
171
from .remote import RemoteGitControlDirFormat
172
return RemoteGitControlDirFormat()
175
BareLocalGitControlDirFormat,
177
ret = BareLocalGitControlDirFormat()
178
ret._refs_text = resp.read()
181
def probe_transport(self, transport):
183
external_url = transport.external_url()
184
except bzr_errors.InProcessTransport:
185
raise bzr_errors.NotBranchError(path=transport.base)
187
if (external_url.startswith("http:") or
188
external_url.startswith("https:")):
189
return self.probe_http_transport(transport)
191
if (not external_url.startswith("git://") and
192
not external_url.startswith("git+")):
193
raise bzr_errors.NotBranchError(transport.base)
195
# little ugly, but works
196
from .remote import (
198
RemoteGitControlDirFormat,
200
if isinstance(transport, GitSmartTransport):
201
return RemoteGitControlDirFormat()
202
raise bzr_errors.NotBranchError(path=transport.base)
205
def known_formats(cls):
206
from .remote import RemoteGitControlDirFormat
207
return [RemoteGitControlDirFormat()]
210
ControlDirFormat.register_prober(LocalGitProber)
211
ControlDirFormat._server_probers.append(RemoteGitProber)
213
register_transport_proto('git://',
214
help="Access using the Git smart server protocol.")
215
register_transport_proto('git+ssh://',
216
help="Access using the Git smart server protocol over SSH.")
218
register_lazy_transport("git://", __name__ + '.remote',
219
'TCPGitSmartTransport')
220
register_lazy_transport("git+ssh://", __name__ + '.remote',
221
'SSHGitSmartTransport')
224
plugin_cmds.register_lazy("cmd_git_import", [], __name__ + ".commands")
225
plugin_cmds.register_lazy("cmd_git_object", ["git-objects", "git-cat"],
226
__name__ + ".commands")
227
plugin_cmds.register_lazy("cmd_git_refs", [], __name__ + ".commands")
228
plugin_cmds.register_lazy("cmd_git_apply", [], __name__ + ".commands")
229
plugin_cmds.register_lazy("cmd_git_push_pristine_tar_deltas",
230
['git-push-pristine-tar', 'git-push-pristine'],
231
__name__ + ".commands")
233
def extract_git_foreign_revid(rev):
235
foreign_revid = rev.foreign_revid
236
except AttributeError:
237
from .mapping import mapping_registry
238
foreign_revid, mapping = \
239
mapping_registry.parse_revision_id(rev.revision_id)
242
from .mapping import foreign_vcs_git
243
if rev.mapping.vcs == foreign_vcs_git:
246
raise bzr_errors.InvalidRevisionId(rev.revision_id, None)
249
def update_stanza(rev, stanza):
250
mapping = getattr(rev, "mapping", None)
252
git_commit = extract_git_foreign_revid(rev)
253
except bzr_errors.InvalidRevisionId:
256
stanza.add("git-commit", git_commit)
258
from ..hooks import install_lazy_named_hook
259
install_lazy_named_hook("breezy.version_info_formats.format_rio",
260
"RioVersionInfoBuilder.hooks", "revision", update_stanza,
264
transport_server_registry.register_lazy('git',
265
__name__ + '.server',
267
'Git Smart server protocol over TCP. (default port: 9418)')
269
transport_server_registry.register_lazy('git-receive-pack',
270
__name__ + '.server',
271
'serve_git_receive_pack',
272
help='Git Smart server receive pack command. (inetd mode only)')
273
transport_server_registry.register_lazy('git-upload-pack',
274
__name__ + 'git.server',
275
'serve_git_upload_pack',
276
help='Git Smart server upload pack command. (inetd mode only)')
278
from ..repository import (
279
format_registry as repository_format_registry,
280
network_format_registry as repository_network_format_registry,
282
repository_network_format_registry.register_lazy(b'git',
283
__name__ + '.repository', 'GitRepositoryFormat')
285
register_extra_lazy_repository_format = getattr(repository_format_registry,
286
"register_extra_lazy")
287
register_extra_lazy_repository_format(__name__ + '.repository',
288
'GitRepositoryFormat')
290
from ..branch import (
291
network_format_registry as branch_network_format_registry,
293
branch_network_format_registry.register_lazy(b'git',
294
__name__ + '.branch', 'LocalGitBranchFormat')
297
from ..branch import (
298
format_registry as branch_format_registry,
300
branch_format_registry.register_extra_lazy(
301
__name__ + '.branch',
302
'LocalGitBranchFormat',
304
branch_format_registry.register_extra_lazy(
305
__name__ + '.remote',
306
'RemoteGitBranchFormat',
310
from ..workingtree import (
311
format_registry as workingtree_format_registry,
313
workingtree_format_registry.register_extra_lazy(
314
__name__ + '.workingtree',
315
'GitWorkingTreeFormat',
318
controldir_network_format_registry.register_lazy(b'git',
319
__name__ + ".dir", "GitControlDirFormat")
323
from ..registry import register_lazy
325
from ..diff import format_registry as diff_format_registry
326
diff_format_registry.register_lazy('git', __name__ + '.send',
327
'GitDiffTree', 'Git am-style diff format')
330
format_registry as send_format_registry,
332
send_format_registry.register_lazy('git', __name__ + '.send',
333
'send_git', 'Git am-style diff format')
335
from ..directory_service import directories
336
directories.register_lazy('github:', __name__ + '.directory',
339
directories.register_lazy('git@github.com:', __name__ + '.directory',
343
from ..help_topics import (
346
topic_registry.register_lazy('git', __name__ + '.help', 'help_git',
347
'Using Bazaar with Git')
349
from ..foreign import (
350
foreign_vcs_registry,
352
foreign_vcs_registry.register_lazy("git",
353
__name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
355
register_lazy("breezy.diff", "format_registry",
356
'git', __name__ + '.send', 'GitDiffTree',
357
'Git am-style diff format')
358
register_lazy("breezy.send", "format_registry",
359
'git', __name__ + '.send', 'send_git',
360
'Git am-style diff format')
361
register_lazy('breezy.directory_service', 'directories', 'github:',
362
__name__ + '.directory', 'GitHubDirectory',
364
register_lazy('breezy.directory_service', 'directories',
365
'git@github.com:', __name__ + '.directory',
366
'GitHubDirectory', 'GitHub directory.')
367
register_lazy('breezy.help_topics', 'topic_registry',
368
'git', __name__ + '.help', 'help_git',
369
'Using Bazaar with Git')
370
register_lazy('breezy.foreign', 'foreign_vcs_registry', "git",
371
__name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
373
def update_git_cache(repository, revid):
374
"""Update the git cache after a local commit."""
375
if getattr(repository, "_git", None) is not None:
376
return # No need to update cache for git repositories
378
if not repository.control_transport.has("git"):
379
return # No existing cache, don't bother updating
381
lazy_check_versions()
382
except bzr_errors.DependencyNotPresent as e:
383
# dulwich is probably missing. silently ignore
384
trace.mutter("not updating git map for %r: %s",
387
from .object_store import BazaarObjectStore
388
store = BazaarObjectStore(repository)
389
with store.lock_write():
391
parent_revisions = set(repository.get_parent_map([revid])[revid])
393
# Isn't this a bit odd - how can a revision that was just committed be missing?
395
missing_revisions = store._missing_revisions(parent_revisions)
396
if not missing_revisions:
397
store._cache.idmap.start_write_group()
399
# Only update if the cache was up to date previously
400
store._update_sha_map_revision(revid)
401
except BaseException:
402
store._cache.idmap.abort_write_group()
405
store._cache.idmap.commit_write_group()
408
def post_commit_update_cache(local_branch, master_branch, old_revno, old_revid,
409
new_revno, new_revid):
410
if local_branch is not None:
411
update_git_cache(local_branch.repository, new_revid)
412
update_git_cache(master_branch.repository, new_revid)
415
def loggerhead_git_hook(branch_app, environ):
416
branch = branch_app.branch
417
config_stack = branch.get_config_stack()
418
if config_stack.get('http_git'):
420
from .server import git_http_hook
421
return git_http_hook(branch, environ['REQUEST_METHOD'],
422
environ['PATH_INFO'])
424
install_lazy_named_hook("breezy.branch",
425
"Branch.hooks", "post_commit", post_commit_update_cache,
427
install_lazy_named_hook("breezy.plugins.loggerhead.apps.branch",
428
"BranchWSGIApp.hooks", "controller",
429
loggerhead_git_hook, "git support")
432
from ..config import (
438
option_registry.register(
440
default=None, from_unicode=bool_from_store, invalid='warning',
442
Allow fetching of Git packs over HTTP.
444
This enables support for fetching Git packs over HTTP in Loggerhead.
449
return tests.test_suite()