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
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 bzr_errors.NotBranchError(transport.base)
161
req.follow_redirections = True
162
resp = transport._perform(req)
163
if resp.code in (404, 405):
164
raise bzr_errors.NotBranchError(transport.base)
165
headers = resp.headers
166
ct = headers.getheader("Content-Type")
168
raise bzr_errors.NotBranchError(transport.base)
169
if ct.startswith("application/x-git"):
170
from .remote import RemoteGitControlDirFormat
171
return RemoteGitControlDirFormat()
174
BareLocalGitControlDirFormat,
176
ret = BareLocalGitControlDirFormat()
177
ret._refs_text = resp.read()
180
def probe_transport(self, transport):
182
external_url = transport.external_url()
183
except bzr_errors.InProcessTransport:
184
raise bzr_errors.NotBranchError(path=transport.base)
186
if (external_url.startswith("http:") or
187
external_url.startswith("https:")):
188
return self.probe_http_transport(transport)
190
if (not external_url.startswith("git://") and
191
not external_url.startswith("git+")):
192
raise bzr_errors.NotBranchError(transport.base)
194
# little ugly, but works
195
from .remote import (
197
RemoteGitControlDirFormat,
199
if isinstance(transport, GitSmartTransport):
200
return RemoteGitControlDirFormat()
201
raise bzr_errors.NotBranchError(path=transport.base)
204
def known_formats(cls):
205
from .remote import RemoteGitControlDirFormat
206
return [RemoteGitControlDirFormat()]
209
ControlDirFormat.register_prober(LocalGitProber)
210
ControlDirFormat._server_probers.append(RemoteGitProber)
212
register_transport_proto('git://',
213
help="Access using the Git smart server protocol.")
214
register_transport_proto('git+ssh://',
215
help="Access using the Git smart server protocol over SSH.")
217
register_lazy_transport("git://", __name__ + '.remote',
218
'TCPGitSmartTransport')
219
register_lazy_transport("git+ssh://", __name__ + '.remote',
220
'SSHGitSmartTransport')
223
plugin_cmds.register_lazy("cmd_git_import", [], __name__ + ".commands")
224
plugin_cmds.register_lazy("cmd_git_object", ["git-objects", "git-cat"],
225
__name__ + ".commands")
226
plugin_cmds.register_lazy("cmd_git_refs", [], __name__ + ".commands")
227
plugin_cmds.register_lazy("cmd_git_apply", [], __name__ + ".commands")
228
plugin_cmds.register_lazy("cmd_git_push_pristine_tar_deltas",
229
['git-push-pristine-tar', 'git-push-pristine'],
230
__name__ + ".commands")
232
def extract_git_foreign_revid(rev):
234
foreign_revid = rev.foreign_revid
235
except AttributeError:
236
from .mapping import mapping_registry
237
foreign_revid, mapping = \
238
mapping_registry.parse_revision_id(rev.revision_id)
241
from .mapping import foreign_vcs_git
242
if rev.mapping.vcs == foreign_vcs_git:
245
raise bzr_errors.InvalidRevisionId(rev.revision_id, None)
248
def update_stanza(rev, stanza):
249
mapping = getattr(rev, "mapping", None)
251
git_commit = extract_git_foreign_revid(rev)
252
except bzr_errors.InvalidRevisionId:
255
stanza.add("git-commit", git_commit)
257
from ..hooks import install_lazy_named_hook
258
install_lazy_named_hook("breezy.version_info_formats.format_rio",
259
"RioVersionInfoBuilder.hooks", "revision", update_stanza,
263
transport_server_registry.register_lazy('git',
264
__name__ + '.server',
266
'Git Smart server protocol over TCP. (default port: 9418)')
268
transport_server_registry.register_lazy('git-receive-pack',
269
__name__ + '.server',
270
'serve_git_receive_pack',
271
help='Git Smart server receive pack command. (inetd mode only)')
272
transport_server_registry.register_lazy('git-upload-pack',
273
__name__ + 'git.server',
274
'serve_git_upload_pack',
275
help='Git Smart server upload pack command. (inetd mode only)')
277
from ..repository import (
278
format_registry as repository_format_registry,
279
network_format_registry as repository_network_format_registry,
281
repository_network_format_registry.register_lazy(b'git',
282
__name__ + '.repository', 'GitRepositoryFormat')
284
register_extra_lazy_repository_format = getattr(repository_format_registry,
285
"register_extra_lazy")
286
register_extra_lazy_repository_format(__name__ + '.repository',
287
'GitRepositoryFormat')
289
from ..branch import (
290
network_format_registry as branch_network_format_registry,
292
branch_network_format_registry.register_lazy(b'git',
293
__name__ + '.branch', 'LocalGitBranchFormat')
296
from ..branch import (
297
format_registry as branch_format_registry,
299
branch_format_registry.register_extra_lazy(
300
__name__ + '.branch',
301
'LocalGitBranchFormat',
303
branch_format_registry.register_extra_lazy(
304
__name__ + '.remote',
305
'RemoteGitBranchFormat',
309
from ..workingtree import (
310
format_registry as workingtree_format_registry,
312
workingtree_format_registry.register_extra_lazy(
313
__name__ + '.workingtree',
314
'GitWorkingTreeFormat',
317
controldir_network_format_registry.register_lazy(b'git',
318
__name__ + ".dir", "GitControlDirFormat")
322
from ..registry import register_lazy
324
from ..diff import format_registry as diff_format_registry
325
diff_format_registry.register_lazy('git', __name__ + '.send',
326
'GitDiffTree', 'Git am-style diff format')
329
format_registry as send_format_registry,
331
send_format_registry.register_lazy('git', __name__ + '.send',
332
'send_git', 'Git am-style diff format')
334
from ..directory_service import directories
335
directories.register_lazy('github:', __name__ + '.directory',
338
directories.register_lazy('git@github.com:', __name__ + '.directory',
342
from ..help_topics import (
345
topic_registry.register_lazy('git', __name__ + '.help', 'help_git',
346
'Using Bazaar with Git')
348
from ..foreign import (
349
foreign_vcs_registry,
351
foreign_vcs_registry.register_lazy("git",
352
__name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
354
register_lazy("breezy.diff", "format_registry",
355
'git', __name__ + '.send', 'GitDiffTree',
356
'Git am-style diff format')
357
register_lazy("breezy.send", "format_registry",
358
'git', __name__ + '.send', 'send_git',
359
'Git am-style diff format')
360
register_lazy('breezy.directory_service', 'directories', 'github:',
361
__name__ + '.directory', 'GitHubDirectory',
363
register_lazy('breezy.directory_service', 'directories',
364
'git@github.com:', __name__ + '.directory',
365
'GitHubDirectory', 'GitHub directory.')
366
register_lazy('breezy.help_topics', 'topic_registry',
367
'git', __name__ + '.help', 'help_git',
368
'Using Bazaar with Git')
369
register_lazy('breezy.foreign', 'foreign_vcs_registry', "git",
370
__name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
372
def update_git_cache(repository, revid):
373
"""Update the git cache after a local commit."""
374
if getattr(repository, "_git", None) is not None:
375
return # No need to update cache for git repositories
377
if not repository.control_transport.has("git"):
378
return # No existing cache, don't bother updating
380
lazy_check_versions()
381
except bzr_errors.DependencyNotPresent as e:
382
# dulwich is probably missing. silently ignore
383
trace.mutter("not updating git map for %r: %s",
386
from .object_store import BazaarObjectStore
387
store = BazaarObjectStore(repository)
388
with store.lock_write():
390
parent_revisions = set(repository.get_parent_map([revid])[revid])
392
# Isn't this a bit odd - how can a revision that was just committed be missing?
394
missing_revisions = store._missing_revisions(parent_revisions)
395
if not missing_revisions:
396
store._cache.idmap.start_write_group()
398
# Only update if the cache was up to date previously
399
store._update_sha_map_revision(revid)
400
except BaseException:
401
store._cache.idmap.abort_write_group()
404
store._cache.idmap.commit_write_group()
407
def post_commit_update_cache(local_branch, master_branch, old_revno, old_revid,
408
new_revno, new_revid):
409
if local_branch is not None:
410
update_git_cache(local_branch.repository, new_revid)
411
update_git_cache(master_branch.repository, new_revid)
414
def loggerhead_git_hook(branch_app, environ):
415
branch = branch_app.branch
416
config_stack = branch.get_config_stack()
417
if config_stack.get('http_git'):
419
from .server import git_http_hook
420
return git_http_hook(branch, environ['REQUEST_METHOD'],
421
environ['PATH_INFO'])
423
install_lazy_named_hook("breezy.branch",
424
"Branch.hooks", "post_commit", post_commit_update_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.
448
return tests.test_suite()