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, 11)
32
from .. import ( # noqa: F401
33
__version__ as breezy_version,
39
from ..controldir import (
43
network_format_registry as controldir_network_format_registry,
46
from ..transport import (
47
register_lazy_transport,
48
register_transport_proto,
49
transport_server_registry,
51
from ..commands import (
56
if getattr(sys, "frozen", None):
57
# allow import additional libs from ./_lib for bzr.exe only
58
sys.path.append(os.path.normpath(
59
os.path.join(os.path.dirname(__file__), '_lib')))
64
from dulwich import __version__ as dulwich_version
66
raise brz_errors.DependencyNotPresent(
68
"bzr-git: Please install dulwich, https://www.dulwich.io/")
70
if dulwich_version < dulwich_minimum_version:
71
raise brz_errors.DependencyNotPresent(
73
"bzr-git: Dulwich is too old; at least %d.%d.%d is required" %
74
dulwich_minimum_version)
77
_versions_checked = False
80
def lazy_check_versions():
81
global _versions_checked
85
_versions_checked = True
88
format_registry.register_lazy(
89
'git', __name__ + ".dir", "LocalGitControlDirFormat",
90
help='GIT repository.', native=False, experimental=False)
92
format_registry.register_lazy(
93
'git-bare', __name__ + ".dir", "BareLocalGitControlDirFormat",
94
help='Bare GIT repository (no working tree).', native=False,
97
from ..revisionspec import (RevisionSpec_dwim, revspec_registry)
98
revspec_registry.register_lazy("git:", __name__ + ".revspec",
100
RevisionSpec_dwim.append_possible_lazy_revspec(
101
__name__ + ".revspec", "RevisionSpec_git")
104
class LocalGitProber(Prober):
106
def probe_transport(self, transport):
108
external_url = transport.external_url()
109
except brz_errors.InProcessTransport:
110
raise brz_errors.NotBranchError(path=transport.base)
111
if (external_url.startswith("http:") or
112
external_url.startswith("https:")):
113
# Already handled by RemoteGitProber
114
raise brz_errors.NotBranchError(path=transport.base)
115
from .. import urlutils
116
if urlutils.split(transport.base)[1] == ".git":
117
raise brz_errors.NotBranchError(path=transport.base)
118
if not transport.has_any(['objects', '.git/objects', '.git']):
119
raise brz_errors.NotBranchError(path=transport.base)
120
lazy_check_versions()
122
BareLocalGitControlDirFormat,
123
LocalGitControlDirFormat,
125
if transport.has_any(['.git/objects', '.git']):
126
return LocalGitControlDirFormat()
127
if transport.has('info') and transport.has('objects'):
128
return BareLocalGitControlDirFormat()
129
raise brz_errors.NotBranchError(path=transport.base)
132
def known_formats(cls):
134
BareLocalGitControlDirFormat,
135
LocalGitControlDirFormat,
137
return [BareLocalGitControlDirFormat(), LocalGitControlDirFormat()]
140
def user_agent_for_github():
141
# GitHub requires we lie. https://github.com/dulwich/dulwich/issues/562
142
return "git/Breezy/%s" % breezy_version
145
class RemoteGitProber(Prober):
147
def probe_http_transport(self, transport):
148
# This function intentionally doesn't use any of the support code under
149
# breezy.git, since it's called for every repository that's
150
# accessed over HTTP, whether it's Git, Bzr or something else.
151
# Importing Dulwich and the other support code adds unnecessray slowdowns.
152
from .. import urlutils
153
base_url, _ = urlutils.split_segment_parameters(
154
transport.external_url())
155
url = urlutils.URL.from_string(base_url)
156
url.user = url.quoted_user = None
157
url.password = url.quoted_password = None
158
url = urlutils.join(str(url), "info/refs") + "?service=git-upload-pack"
159
headers = {"Content-Type": "application/x-git-upload-pack-request",
160
"Accept": "application/x-git-upload-pack-result",
162
(scheme, user, password, host, port,
163
path) = urlutils.parse_url(url)
164
if host == "github.com":
165
# GitHub requires we lie.
166
# https://github.com/dulwich/dulwich/issues/562
167
req.add_header("User-Agent", user_agent_for_github())
168
elif host == "bazaar.launchpad.net":
169
# Don't attempt Git probes against bazaar.launchpad.net; pad.lv/1744830
170
raise brz_errors.NotBranchError(transport.base)
171
resp = transport.request('GET', url, headers=headers)
172
if resp.status in (404, 405):
173
raise brz_errors.NotBranchError(transport.base)
175
raise errors.InvalidHttpResponse(
176
url, 'Unable to handle http code %d' % resp.status)
178
headers = resp.headers
179
ct = headers.get("Content-Type")
181
raise brz_errors.NotBranchError(transport.base)
182
if ct.startswith("application/x-git"):
183
from .remote import RemoteGitControlDirFormat
184
return RemoteGitControlDirFormat()
187
BareLocalGitControlDirFormat,
189
ret = BareLocalGitControlDirFormat()
190
ret._refs_text = resp.read()
193
def probe_transport(self, transport):
195
external_url = transport.external_url()
196
except brz_errors.InProcessTransport:
197
raise brz_errors.NotBranchError(path=transport.base)
199
if (external_url.startswith("http:") or
200
external_url.startswith("https:")):
201
return self.probe_http_transport(transport)
203
if (not external_url.startswith("git://") and
204
not external_url.startswith("git+")):
205
raise brz_errors.NotBranchError(transport.base)
207
# little ugly, but works
208
from .remote import (
210
RemoteGitControlDirFormat,
212
if isinstance(transport, GitSmartTransport):
213
return RemoteGitControlDirFormat()
214
raise brz_errors.NotBranchError(path=transport.base)
217
def known_formats(cls):
218
from .remote import RemoteGitControlDirFormat
219
return [RemoteGitControlDirFormat()]
222
ControlDirFormat.register_prober(LocalGitProber)
223
ControlDirFormat._server_probers.append(RemoteGitProber)
225
register_transport_proto(
226
'git://', help="Access using the Git smart server protocol.")
227
register_transport_proto(
229
help="Access using the Git smart server protocol over SSH.")
231
register_lazy_transport("git://", __name__ + '.remote',
232
'TCPGitSmartTransport')
233
register_lazy_transport("git+ssh://", __name__ + '.remote',
234
'SSHGitSmartTransport')
237
plugin_cmds.register_lazy("cmd_git_import", [], __name__ + ".commands")
238
plugin_cmds.register_lazy("cmd_git_object", ["git-objects", "git-cat"],
239
__name__ + ".commands")
240
plugin_cmds.register_lazy("cmd_git_refs", [], __name__ + ".commands")
241
plugin_cmds.register_lazy("cmd_git_apply", [], __name__ + ".commands")
242
plugin_cmds.register_lazy("cmd_git_push_pristine_tar_deltas",
243
['git-push-pristine-tar', 'git-push-pristine'],
244
__name__ + ".commands")
247
def extract_git_foreign_revid(rev):
249
foreign_revid = rev.foreign_revid
250
except AttributeError:
251
from .mapping import mapping_registry
252
foreign_revid, mapping = \
253
mapping_registry.parse_revision_id(rev.revision_id)
256
from .mapping import foreign_vcs_git
257
if rev.mapping.vcs == foreign_vcs_git:
260
raise brz_errors.InvalidRevisionId(rev.revision_id, None)
263
def update_stanza(rev, stanza):
265
git_commit = extract_git_foreign_revid(rev)
266
except brz_errors.InvalidRevisionId:
269
stanza.add("git-commit", git_commit)
272
from ..hooks import install_lazy_named_hook
273
install_lazy_named_hook(
274
"breezy.version_info_formats.format_rio",
275
"RioVersionInfoBuilder.hooks", "revision", update_stanza,
278
transport_server_registry.register_lazy(
279
'git', __name__ + '.server', 'serve_git',
280
'Git Smart server protocol over TCP. (default port: 9418)')
282
transport_server_registry.register_lazy(
283
'git-receive-pack', __name__ + '.server',
284
'serve_git_receive_pack',
285
help='Git Smart server receive pack command. (inetd mode only)')
286
transport_server_registry.register_lazy(
287
'git-upload-pack', __name__ + 'git.server',
288
'serve_git_upload_pack',
289
help='Git Smart server upload pack command. (inetd mode only)')
291
from ..repository import (
292
format_registry as repository_format_registry,
293
network_format_registry as repository_network_format_registry,
295
repository_network_format_registry.register_lazy(
296
b'git', __name__ + '.repository', 'GitRepositoryFormat')
298
register_extra_lazy_repository_format = getattr(repository_format_registry,
299
"register_extra_lazy")
300
register_extra_lazy_repository_format(__name__ + '.repository',
301
'GitRepositoryFormat')
303
from ..branch import (
304
network_format_registry as branch_network_format_registry,
306
branch_network_format_registry.register_lazy(
307
b'git', __name__ + '.branch', 'LocalGitBranchFormat')
310
from ..branch import (
311
format_registry as branch_format_registry,
313
branch_format_registry.register_extra_lazy(
314
__name__ + '.branch',
315
'LocalGitBranchFormat',
317
branch_format_registry.register_extra_lazy(
318
__name__ + '.remote',
319
'RemoteGitBranchFormat',
323
from ..workingtree import (
324
format_registry as workingtree_format_registry,
326
workingtree_format_registry.register_extra_lazy(
327
__name__ + '.workingtree',
328
'GitWorkingTreeFormat',
331
controldir_network_format_registry.register_lazy(
332
b'git', __name__ + ".dir", "GitControlDirFormat")
335
from ..diff import format_registry as diff_format_registry
336
diff_format_registry.register_lazy(
337
'git', __name__ + '.send',
338
'GitDiffTree', 'Git am-style diff format')
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(
358
'git', __name__ + '.help', 'help_git', 'Using Bazaar with Git')
360
from ..foreign import (
361
foreign_vcs_registry,
363
foreign_vcs_registry.register_lazy(
364
"git", __name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
367
def update_git_cache(repository, revid):
368
"""Update the git cache after a local commit."""
369
if getattr(repository, "_git", None) is not None:
370
return # No need to update cache for git repositories
372
if not repository.control_transport.has("git"):
373
return # No existing cache, don't bother updating
375
lazy_check_versions()
376
except brz_errors.DependencyNotPresent as e:
377
# dulwich is probably missing. silently ignore
378
trace.mutter("not updating git map for %r: %s",
381
from .object_store import BazaarObjectStore
382
store = BazaarObjectStore(repository)
383
with store.lock_write():
385
parent_revisions = set(repository.get_parent_map([revid])[revid])
387
# Isn't this a bit odd - how can a revision that was just committed
390
missing_revisions = store._missing_revisions(parent_revisions)
391
if not missing_revisions:
392
store._cache.idmap.start_write_group()
394
# Only update if the cache was up to date previously
395
store._update_sha_map_revision(revid)
396
except BaseException:
397
store._cache.idmap.abort_write_group()
400
store._cache.idmap.commit_write_group()
403
def post_commit_update_cache(local_branch, master_branch, old_revno, old_revid,
404
new_revno, new_revid):
405
if local_branch is not None:
406
update_git_cache(local_branch.repository, new_revid)
407
update_git_cache(master_branch.repository, new_revid)
410
def loggerhead_git_hook(branch_app, environ):
411
branch = branch_app.branch
412
config_stack = branch.get_config_stack()
413
if config_stack.get('http_git'):
415
from .server import git_http_hook
416
return git_http_hook(branch, environ['REQUEST_METHOD'],
417
environ['PATH_INFO'])
420
install_lazy_named_hook("breezy.branch",
421
"Branch.hooks", "post_commit",
422
post_commit_update_cache, "git cache")
423
install_lazy_named_hook("breezy.plugins.loggerhead.apps.branch",
424
"BranchWSGIApp.hooks", "controller",
425
loggerhead_git_hook, "git support")
428
from ..config import (
434
option_registry.register(
436
default=None, from_unicode=bool_from_store, invalid='warning',
438
Allow fetching of Git packs over HTTP.
440
This enables support for fetching Git packs over HTTP in Loggerhead.
446
return tests.test_suite()