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,
40
from ..controldir import (
44
network_format_registry as controldir_network_format_registry,
47
from ..transport import (
48
register_lazy_transport,
49
register_transport_proto,
50
transport_server_registry,
52
from ..commands import (
57
if getattr(sys, "frozen", None):
58
# allow import additional libs from ./_lib for bzr.exe only
59
sys.path.append(os.path.normpath(
60
os.path.join(os.path.dirname(__file__), '_lib')))
65
from dulwich import __version__ as dulwich_version
67
raise brz_errors.DependencyNotPresent(
69
"bzr-git: Please install dulwich, https://www.dulwich.io/")
71
if dulwich_version < dulwich_minimum_version:
72
raise brz_errors.DependencyNotPresent(
74
"bzr-git: Dulwich is too old; at least %d.%d.%d is required" %
75
dulwich_minimum_version)
78
_versions_checked = False
81
def lazy_check_versions():
82
global _versions_checked
86
_versions_checked = True
89
format_registry.register_lazy(
90
'git', __name__ + ".dir", "LocalGitControlDirFormat",
91
help='GIT repository.', native=False, experimental=False)
93
format_registry.register_lazy(
94
'git-bare', __name__ + ".dir", "BareLocalGitControlDirFormat",
95
help='Bare GIT repository (no working tree).', native=False,
98
from ..revisionspec import (RevisionSpec_dwim, revspec_registry)
99
revspec_registry.register_lazy("git:", __name__ + ".revspec",
101
RevisionSpec_dwim.append_possible_lazy_revspec(
102
__name__ + ".revspec", "RevisionSpec_git")
105
class LocalGitProber(Prober):
107
def probe_transport(self, transport):
109
external_url = transport.external_url()
110
except brz_errors.InProcessTransport:
111
raise brz_errors.NotBranchError(path=transport.base)
112
if (external_url.startswith("http:") or
113
external_url.startswith("https:")):
114
# Already handled by RemoteGitProber
115
raise brz_errors.NotBranchError(path=transport.base)
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
def is_github_url(url):
146
(scheme, user, password, host, port,
147
path) = urlutils.parse_url(url)
148
return host == "github.com"
151
class RemoteGitProber(Prober):
153
def probe_http_transport(self, transport):
154
# This function intentionally doesn't use any of the support code under
155
# breezy.git, since it's called for every repository that's
156
# accessed over HTTP, whether it's Git, Bzr or something else.
157
# Importing Dulwich and the other support code adds unnecessray slowdowns.
158
base_url, _ = urlutils.split_segment_parameters(
159
transport.external_url())
160
url = urlutils.URL.from_string(base_url)
161
url.user = url.quoted_user = None
162
url.password = url.quoted_password = None
164
url = urlutils.join(str(url), "info/refs") + "?service=git-upload-pack"
165
headers = {"Content-Type": "application/x-git-upload-pack-request",
166
"Accept": "application/x-git-upload-pack-result",
168
if is_github_url(url):
169
# GitHub requires we lie.
170
# https://github.com/dulwich/dulwich/issues/562
171
headers["User-Agent"] = user_agent_for_github()
172
elif host == "bazaar.launchpad.net":
173
# Don't attempt Git probes against bazaar.launchpad.net; pad.lv/1744830
174
raise brz_errors.NotBranchError(transport.base)
175
resp = transport.request('GET', url, headers=headers)
176
if resp.status in (404, 405):
177
raise brz_errors.NotBranchError(transport.base)
178
elif resp.status != 200:
179
raise brz_errors.InvalidHttpResponse(
180
url, 'Unable to handle http code %d' % resp.status)
182
ct = resp.getheader("Content-Type")
184
raise brz_errors.NotBranchError(transport.base)
185
if ct.startswith("application/x-git"):
186
from .remote import RemoteGitControlDirFormat
187
return RemoteGitControlDirFormat()
190
BareLocalGitControlDirFormat,
192
ret = BareLocalGitControlDirFormat()
193
ret._refs_text = resp.read()
196
def probe_transport(self, transport):
198
external_url = transport.external_url()
199
except brz_errors.InProcessTransport:
200
raise brz_errors.NotBranchError(path=transport.base)
202
if (external_url.startswith("http:") or
203
external_url.startswith("https:")):
204
return self.probe_http_transport(transport)
206
if (not external_url.startswith("git://") and
207
not external_url.startswith("git+")):
208
raise brz_errors.NotBranchError(transport.base)
210
# little ugly, but works
211
from .remote import (
213
RemoteGitControlDirFormat,
215
if isinstance(transport, GitSmartTransport):
216
return RemoteGitControlDirFormat()
217
raise brz_errors.NotBranchError(path=transport.base)
220
def known_formats(cls):
221
from .remote import RemoteGitControlDirFormat
222
return [RemoteGitControlDirFormat()]
225
ControlDirFormat.register_prober(LocalGitProber)
226
ControlDirFormat._server_probers.append(RemoteGitProber)
228
register_transport_proto(
229
'git://', help="Access using the Git smart server protocol.")
230
register_transport_proto(
232
help="Access using the Git smart server protocol over SSH.")
234
register_lazy_transport("git://", __name__ + '.remote',
235
'TCPGitSmartTransport')
236
register_lazy_transport("git+ssh://", __name__ + '.remote',
237
'SSHGitSmartTransport')
240
plugin_cmds.register_lazy("cmd_git_import", [], __name__ + ".commands")
241
plugin_cmds.register_lazy("cmd_git_object", ["git-objects", "git-cat"],
242
__name__ + ".commands")
243
plugin_cmds.register_lazy("cmd_git_refs", [], __name__ + ".commands")
244
plugin_cmds.register_lazy("cmd_git_apply", [], __name__ + ".commands")
245
plugin_cmds.register_lazy("cmd_git_push_pristine_tar_deltas",
246
['git-push-pristine-tar', 'git-push-pristine'],
247
__name__ + ".commands")
250
def extract_git_foreign_revid(rev):
252
foreign_revid = rev.foreign_revid
253
except AttributeError:
254
from .mapping import mapping_registry
255
foreign_revid, mapping = \
256
mapping_registry.parse_revision_id(rev.revision_id)
259
from .mapping import foreign_vcs_git
260
if rev.mapping.vcs == foreign_vcs_git:
263
raise brz_errors.InvalidRevisionId(rev.revision_id, None)
266
def update_stanza(rev, stanza):
268
git_commit = extract_git_foreign_revid(rev)
269
except brz_errors.InvalidRevisionId:
272
stanza.add("git-commit", git_commit)
275
from ..hooks import install_lazy_named_hook
276
install_lazy_named_hook(
277
"breezy.version_info_formats.format_rio",
278
"RioVersionInfoBuilder.hooks", "revision", update_stanza,
281
transport_server_registry.register_lazy(
282
'git', __name__ + '.server', 'serve_git',
283
'Git Smart server protocol over TCP. (default port: 9418)')
285
transport_server_registry.register_lazy(
286
'git-receive-pack', __name__ + '.server',
287
'serve_git_receive_pack',
288
help='Git Smart server receive pack command. (inetd mode only)')
289
transport_server_registry.register_lazy(
290
'git-upload-pack', __name__ + 'git.server',
291
'serve_git_upload_pack',
292
help='Git Smart server upload pack command. (inetd mode only)')
294
from ..repository import (
295
format_registry as repository_format_registry,
296
network_format_registry as repository_network_format_registry,
298
repository_network_format_registry.register_lazy(
299
b'git', __name__ + '.repository', 'GitRepositoryFormat')
301
register_extra_lazy_repository_format = getattr(repository_format_registry,
302
"register_extra_lazy")
303
register_extra_lazy_repository_format(__name__ + '.repository',
304
'GitRepositoryFormat')
306
from ..branch import (
307
network_format_registry as branch_network_format_registry,
309
branch_network_format_registry.register_lazy(
310
b'git', __name__ + '.branch', 'LocalGitBranchFormat')
313
from ..branch import (
314
format_registry as branch_format_registry,
316
branch_format_registry.register_extra_lazy(
317
__name__ + '.branch',
318
'LocalGitBranchFormat',
320
branch_format_registry.register_extra_lazy(
321
__name__ + '.remote',
322
'RemoteGitBranchFormat',
326
from ..workingtree import (
327
format_registry as workingtree_format_registry,
329
workingtree_format_registry.register_extra_lazy(
330
__name__ + '.workingtree',
331
'GitWorkingTreeFormat',
334
controldir_network_format_registry.register_lazy(
335
b'git', __name__ + ".dir", "GitControlDirFormat")
338
from ..diff import format_registry as diff_format_registry
339
diff_format_registry.register_lazy(
340
'git', __name__ + '.send',
341
'GitDiffTree', 'Git am-style diff format')
344
format_registry as send_format_registry,
346
send_format_registry.register_lazy('git', __name__ + '.send',
347
'send_git', 'Git am-style diff format')
349
from ..directory_service import directories
350
directories.register_lazy('github:', __name__ + '.directory',
353
directories.register_lazy('git@github.com:', __name__ + '.directory',
357
from ..help_topics import (
360
topic_registry.register_lazy(
361
'git', __name__ + '.help', 'help_git', 'Using Bazaar with Git')
363
from ..foreign import (
364
foreign_vcs_registry,
366
foreign_vcs_registry.register_lazy(
367
"git", __name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
370
def update_git_cache(repository, revid):
371
"""Update the git cache after a local commit."""
372
if getattr(repository, "_git", None) is not None:
373
return # No need to update cache for git repositories
375
if not repository.control_transport.has("git"):
376
return # No existing cache, don't bother updating
378
lazy_check_versions()
379
except brz_errors.DependencyNotPresent as e:
380
# dulwich is probably missing. silently ignore
381
trace.mutter("not updating git map for %r: %s",
384
from .object_store import BazaarObjectStore
385
store = BazaarObjectStore(repository)
386
with store.lock_write():
388
parent_revisions = set(repository.get_parent_map([revid])[revid])
390
# Isn't this a bit odd - how can a revision that was just committed
393
missing_revisions = store._missing_revisions(parent_revisions)
394
if not missing_revisions:
395
store._cache.idmap.start_write_group()
397
# Only update if the cache was up to date previously
398
store._update_sha_map_revision(revid)
399
except BaseException:
400
store._cache.idmap.abort_write_group()
403
store._cache.idmap.commit_write_group()
406
def post_commit_update_cache(local_branch, master_branch, old_revno, old_revid,
407
new_revno, new_revid):
408
if local_branch is not None:
409
update_git_cache(local_branch.repository, new_revid)
410
update_git_cache(master_branch.repository, new_revid)
413
def loggerhead_git_hook(branch_app, environ):
414
branch = branch_app.branch
415
config_stack = branch.get_config_stack()
416
if config_stack.get('http_git'):
418
from .server import git_http_hook
419
return git_http_hook(branch, environ['REQUEST_METHOD'],
420
environ['PATH_INFO'])
423
install_lazy_named_hook("breezy.branch",
424
"Branch.hooks", "post_commit",
425
post_commit_update_cache, "git cache")
426
install_lazy_named_hook("breezy.plugins.loggerhead.apps.branch",
427
"BranchWSGIApp.hooks", "controller",
428
loggerhead_git_hook, "git support")
431
from ..config import (
437
option_registry.register(
439
default=None, from_unicode=bool_from_store, invalid='warning',
441
Allow fetching of Git packs over HTTP.
443
This enables support for fetching Git packs over HTTP in Loggerhead.
449
return tests.test_suite()