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, 7)
33
__version__ as breezy_version,
36
version_info, # noqa: F401
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("dulwich",
67
"bzr-git: Please install dulwich, https://www.dulwich.io/")
69
if dulwich_version < dulwich_minimum_version:
70
raise brz_errors.DependencyNotPresent("dulwich",
71
"bzr-git: Dulwich is too old; at least %d.%d.%d is required" %
72
dulwich_minimum_version)
75
_versions_checked = False
76
def lazy_check_versions():
77
global _versions_checked
81
_versions_checked = True
83
format_registry.register_lazy('git',
84
__name__ + ".dir", "LocalGitControlDirFormat",
85
help='GIT repository.', native=False, experimental=False,
88
format_registry.register_lazy('git-bare',
89
__name__ + ".dir", "BareLocalGitControlDirFormat",
90
help='Bare GIT repository (no working tree).', native=False,
94
from ..revisionspec import (RevisionSpec_dwim, revspec_registry)
95
revspec_registry.register_lazy("git:", __name__ + ".revspec",
97
RevisionSpec_dwim.append_possible_lazy_revspec(
98
__name__ + ".revspec", "RevisionSpec_git")
101
class LocalGitProber(Prober):
103
def probe_transport(self, transport):
105
external_url = transport.external_url()
106
except brz_errors.InProcessTransport:
107
raise brz_errors.NotBranchError(path=transport.base)
108
if (external_url.startswith("http:") or
109
external_url.startswith("https:")):
110
# Already handled by RemoteGitProber
111
raise brz_errors.NotBranchError(path=transport.base)
112
from .. import urlutils
113
if urlutils.split(transport.base)[1] == ".git":
114
raise brz_errors.NotBranchError(path=transport.base)
115
if not transport.has_any(['objects', '.git/objects', '.git']):
116
raise brz_errors.NotBranchError(path=transport.base)
117
lazy_check_versions()
119
BareLocalGitControlDirFormat,
120
LocalGitControlDirFormat,
122
if transport.has_any(['.git/objects', '.git']):
123
return LocalGitControlDirFormat()
124
if transport.has('info') and transport.has('objects'):
125
return BareLocalGitControlDirFormat()
126
raise brz_errors.NotBranchError(path=transport.base)
129
def known_formats(cls):
131
BareLocalGitControlDirFormat,
132
LocalGitControlDirFormat,
134
return [BareLocalGitControlDirFormat(), LocalGitControlDirFormat()]
137
def user_agent_for_github():
138
# GitHub requires we lie. https://github.com/dulwich/dulwich/issues/562
139
return "git/Breezy/%s" % breezy_version
142
class RemoteGitProber(Prober):
144
def probe_http_transport(self, transport):
145
from .. import urlutils
146
base_url, _ = urlutils.split_segment_parameters(transport.external_url())
147
url = urlutils.join(base_url, "info/refs") + "?service=git-upload-pack"
148
from ..transport.http import Request
149
headers = {"Content-Type": "application/x-git-upload-pack-request",
150
"Accept": "application/x-git-upload-pack-result",
152
req = Request('GET', url, accepted_errors=[200, 403, 404, 405],
154
(scheme, user, password, host, port, path) = urlutils.parse_url(req.get_full_url())
155
if host == "github.com":
156
# GitHub requires we lie. https://github.com/dulwich/dulwich/issues/562
157
req.add_header("User-Agent", user_agent_for_github())
158
elif host == "bazaar.launchpad.net":
159
# Don't attempt Git probes against bazaar.launchpad.net; pad.lv/1744830
160
raise brz_errors.NotBranchError(transport.base)
161
resp = transport._perform(req)
162
if resp.code in (404, 405):
163
raise brz_errors.NotBranchError(transport.base)
164
headers = resp.headers
165
ct = headers.get("Content-Type")
167
raise brz_errors.NotBranchError(transport.base)
168
if ct.startswith("application/x-git"):
169
from .remote import RemoteGitControlDirFormat
170
return RemoteGitControlDirFormat()
173
BareLocalGitControlDirFormat,
175
ret = BareLocalGitControlDirFormat()
176
ret._refs_text = resp.read()
179
def probe_transport(self, transport):
181
external_url = transport.external_url()
182
except brz_errors.InProcessTransport:
183
raise brz_errors.NotBranchError(path=transport.base)
185
if (external_url.startswith("http:") or
186
external_url.startswith("https:")):
187
return self.probe_http_transport(transport)
189
if (not external_url.startswith("git://") and
190
not external_url.startswith("git+")):
191
raise brz_errors.NotBranchError(transport.base)
193
# little ugly, but works
194
from .remote import (
196
RemoteGitControlDirFormat,
198
if isinstance(transport, GitSmartTransport):
199
return RemoteGitControlDirFormat()
200
raise brz_errors.NotBranchError(path=transport.base)
203
def known_formats(cls):
204
from .remote import RemoteGitControlDirFormat
205
return [RemoteGitControlDirFormat()]
208
ControlDirFormat.register_prober(LocalGitProber)
209
ControlDirFormat._server_probers.append(RemoteGitProber)
211
register_transport_proto('git://',
212
help="Access using the Git smart server protocol.")
213
register_transport_proto('git+ssh://',
214
help="Access using the Git smart server protocol over SSH.")
216
register_lazy_transport("git://", __name__ + '.remote',
217
'TCPGitSmartTransport')
218
register_lazy_transport("git+ssh://", __name__ + '.remote',
219
'SSHGitSmartTransport')
222
plugin_cmds.register_lazy("cmd_git_import", [], __name__ + ".commands")
223
plugin_cmds.register_lazy("cmd_git_object", ["git-objects", "git-cat"],
224
__name__ + ".commands")
225
plugin_cmds.register_lazy("cmd_git_refs", [], __name__ + ".commands")
226
plugin_cmds.register_lazy("cmd_git_apply", [], __name__ + ".commands")
227
plugin_cmds.register_lazy("cmd_git_push_pristine_tar_deltas",
228
['git-push-pristine-tar', 'git-push-pristine'],
229
__name__ + ".commands")
231
def extract_git_foreign_revid(rev):
233
foreign_revid = rev.foreign_revid
234
except AttributeError:
235
from .mapping import mapping_registry
236
foreign_revid, mapping = \
237
mapping_registry.parse_revision_id(rev.revision_id)
240
from .mapping import foreign_vcs_git
241
if rev.mapping.vcs == foreign_vcs_git:
244
raise brz_errors.InvalidRevisionId(rev.revision_id, None)
247
def update_stanza(rev, stanza):
248
mapping = getattr(rev, "mapping", None)
250
git_commit = extract_git_foreign_revid(rev)
251
except brz_errors.InvalidRevisionId:
254
stanza.add("git-commit", git_commit)
256
from ..hooks import install_lazy_named_hook
257
install_lazy_named_hook("breezy.version_info_formats.format_rio",
258
"RioVersionInfoBuilder.hooks", "revision", update_stanza,
262
transport_server_registry.register_lazy('git',
263
__name__ + '.server',
265
'Git Smart server protocol over TCP. (default port: 9418)')
267
transport_server_registry.register_lazy('git-receive-pack',
268
__name__ + '.server',
269
'serve_git_receive_pack',
270
help='Git Smart server receive pack command. (inetd mode only)')
271
transport_server_registry.register_lazy('git-upload-pack',
272
__name__ + 'git.server',
273
'serve_git_upload_pack',
274
help='Git Smart server upload pack command. (inetd mode only)')
276
from ..repository import (
277
format_registry as repository_format_registry,
278
network_format_registry as repository_network_format_registry,
280
repository_network_format_registry.register_lazy(b'git',
281
__name__ + '.repository', 'GitRepositoryFormat')
283
register_extra_lazy_repository_format = getattr(repository_format_registry,
284
"register_extra_lazy")
285
register_extra_lazy_repository_format(__name__ + '.repository',
286
'GitRepositoryFormat')
288
from ..branch import (
289
network_format_registry as branch_network_format_registry,
291
branch_network_format_registry.register_lazy(b'git',
292
__name__ + '.branch', 'LocalGitBranchFormat')
295
from ..branch import (
296
format_registry as branch_format_registry,
298
branch_format_registry.register_extra_lazy(
299
__name__ + '.branch',
300
'LocalGitBranchFormat',
302
branch_format_registry.register_extra_lazy(
303
__name__ + '.remote',
304
'RemoteGitBranchFormat',
308
from ..workingtree import (
309
format_registry as workingtree_format_registry,
311
workingtree_format_registry.register_extra_lazy(
312
__name__ + '.workingtree',
313
'GitWorkingTreeFormat',
316
controldir_network_format_registry.register_lazy(b'git',
317
__name__ + ".dir", "GitControlDirFormat")
320
from ..diff import format_registry as diff_format_registry
321
diff_format_registry.register_lazy('git', __name__ + '.send',
322
'GitDiffTree', 'Git am-style diff format')
325
format_registry as send_format_registry,
327
send_format_registry.register_lazy('git', __name__ + '.send',
328
'send_git', 'Git am-style diff format')
330
from ..directory_service import directories
331
directories.register_lazy('github:', __name__ + '.directory',
334
directories.register_lazy('git@github.com:', __name__ + '.directory',
338
from ..help_topics import (
341
topic_registry.register_lazy('git', __name__ + '.help', 'help_git',
342
'Using Bazaar with Git')
344
from ..foreign import (
345
foreign_vcs_registry,
347
foreign_vcs_registry.register_lazy("git",
348
__name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
351
def update_git_cache(repository, revid):
352
"""Update the git cache after a local commit."""
353
if getattr(repository, "_git", None) is not None:
354
return # No need to update cache for git repositories
356
if not repository.control_transport.has("git"):
357
return # No existing cache, don't bother updating
359
lazy_check_versions()
360
except brz_errors.DependencyNotPresent as e:
361
# dulwich is probably missing. silently ignore
362
trace.mutter("not updating git map for %r: %s",
365
from .object_store import BazaarObjectStore
366
store = BazaarObjectStore(repository)
367
with store.lock_write():
369
parent_revisions = set(repository.get_parent_map([revid])[revid])
371
# Isn't this a bit odd - how can a revision that was just committed be missing?
373
missing_revisions = store._missing_revisions(parent_revisions)
374
if not missing_revisions:
375
store._cache.idmap.start_write_group()
377
# Only update if the cache was up to date previously
378
store._update_sha_map_revision(revid)
379
except BaseException:
380
store._cache.idmap.abort_write_group()
383
store._cache.idmap.commit_write_group()
386
def post_commit_update_cache(local_branch, master_branch, old_revno, old_revid,
387
new_revno, new_revid):
388
if local_branch is not None:
389
update_git_cache(local_branch.repository, new_revid)
390
update_git_cache(master_branch.repository, new_revid)
393
def loggerhead_git_hook(branch_app, environ):
394
branch = branch_app.branch
395
config_stack = branch.get_config_stack()
396
if config_stack.get('http_git'):
398
from .server import git_http_hook
399
return git_http_hook(branch, environ['REQUEST_METHOD'],
400
environ['PATH_INFO'])
402
install_lazy_named_hook("breezy.branch",
403
"Branch.hooks", "post_commit", post_commit_update_cache,
405
install_lazy_named_hook("breezy.plugins.loggerhead.apps.branch",
406
"BranchWSGIApp.hooks", "controller",
407
loggerhead_git_hook, "git support")
410
from ..config import (
416
option_registry.register(
418
default=None, from_unicode=bool_from_store, invalid='warning',
420
Allow fetching of Git packs over HTTP.
422
This enables support for fetching Git packs over HTTP in Loggerhead.
427
return tests.test_suite()