1
# Copyright (C) 2006-2009 Canonical Ltd
3
# Authors: Robert Collins <robert.collins@canonical.com>
4
# Jelmer Vernooij <jelmer@samba.org>
5
# John Carr <john.carr@unrouted.co.uk>
7
# This program is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU General Public License as published by
9
# the Free Software Foundation; either version 2 of the License, or
10
# (at your option) any later version.
12
# This program is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU General Public License for more details.
17
# You should have received a copy of the GNU General Public License
18
# along with this program; if not, write to the Free Software
19
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
"""A GIT branch and repository format implementation for bzr."""
24
from __future__ import absolute_import
32
bzr_compatible_versions,
33
bzr_plugin_version as version_info,
34
dulwich_minimum_version,
37
if version_info[3] == 'final':
38
version_string = '%d.%d.%d' % version_info[:3]
40
version_string = '%d.%d.%d%s%d' % version_info
41
__version__ = version_string
43
if breezy.version_info[:3] not in bzr_compatible_versions:
44
from ...errors import IncompatibleVersion
45
raise IncompatibleVersion(breezy,
46
bzr_compatible_versions, breezy.version_info[:3])
49
from ...i18n import load_plugin_translations
50
except ImportError: # No translations for bzr < 2.5
53
translation = load_plugin_translations("bzr-git")
54
gettext = translation.gettext
61
from ...controldir import (
65
network_format_registry as controldir_network_format_registry,
68
from ...transport import (
69
register_lazy_transport,
70
register_transport_proto,
71
transport_server_registry,
73
from ...commands import (
78
if getattr(sys, "frozen", None):
79
# allow import additional libs from ./_lib for bzr.exe only
80
sys.path.append(os.path.normpath(
81
os.path.join(os.path.dirname(__file__), '_lib')))
86
from dulwich import __version__ as dulwich_version
88
raise bzr_errors.DependencyNotPresent("dulwich",
89
"bzr-git: Please install dulwich, https://launchpad.net/dulwich")
91
if dulwich_version < dulwich_minimum_version:
92
raise bzr_errors.DependencyNotPresent("dulwich",
93
"bzr-git: Dulwich is too old; at least %d.%d.%d is required" %
94
dulwich_minimum_version)
97
_versions_checked = False
98
def lazy_check_versions():
99
global _versions_checked
100
if _versions_checked:
103
_versions_checked = True
105
format_registry.register_lazy('git',
106
__name__ + ".dir", "LocalGitControlDirFormat",
107
help='GIT repository.', native=False, experimental=False,
110
format_registry.register_lazy('git-bare',
111
__name__ + ".dir", "BareLocalGitControlDirFormat",
112
help='Bare GIT repository (no working tree).', native=False,
116
from ...revisionspec import (RevisionSpec_dwim, revspec_registry)
117
revspec_registry.register_lazy("git:", __name__ + ".revspec",
119
RevisionSpec_dwim.append_possible_lazy_revspec(
120
__name__ + ".revspec", "RevisionSpec_git")
123
class LocalGitProber(Prober):
125
def probe_transport(self, transport):
127
external_url = transport.external_url()
128
except bzr_errors.InProcessTransport:
129
raise bzr_errors.NotBranchError(path=transport.base)
130
if (external_url.startswith("http:") or
131
external_url.startswith("https:")):
132
# Already handled by RemoteGitProber
133
raise bzr_errors.NotBranchError(path=transport.base)
134
from ... import urlutils
135
if urlutils.split(transport.base)[1] == ".git":
136
raise bzr_errors.NotBranchError(path=transport.base)
137
if not transport.has_any(['objects', '.git/objects']):
138
raise bzr_errors.NotBranchError(path=transport.base)
139
lazy_check_versions()
141
BareLocalGitControlDirFormat,
142
LocalGitControlDirFormat,
144
if transport.has_any(['.git/objects']):
145
return LocalGitControlDirFormat()
146
if transport.has('info') and transport.has('objects'):
147
return BareLocalGitControlDirFormat()
148
raise bzr_errors.NotBranchError(path=transport.base)
151
def known_formats(cls):
153
BareLocalGitControlDirFormat,
154
LocalGitControlDirFormat,
156
return set([BareLocalGitControlDirFormat(), LocalGitControlDirFormat()])
159
class RemoteGitProber(Prober):
161
def probe_http_transport(self, transport):
162
from ... import urlutils
163
base_url, _ = urlutils.split_segment_parameters(transport.external_url())
164
url = urlutils.join(base_url, "info/refs") + "?service=git-upload-pack"
165
from ...transport.http._urllib import HttpTransport_urllib, Request
166
if isinstance(transport, HttpTransport_urllib):
167
req = Request('GET', url, accepted_errors=[200, 403, 404, 405],
168
headers={"Content-Type": "application/x-git-upload-pack-request"})
169
req.follow_redirections = True
170
resp = transport._perform(req)
171
if resp.code in (404, 405):
172
raise bzr_errors.NotBranchError(transport.base)
173
headers = resp.headers
174
refs_text = resp.read()
177
from ...transport.http._pycurl import PyCurlTransport
178
except bzr_errors.DependencyNotPresent:
179
raise bzr_errors.NotBranchError(transport.base)
182
from cStringIO import StringIO
183
if isinstance(transport, PyCurlTransport):
184
conn = transport._get_curl()
185
conn.setopt(pycurl.URL, url)
186
conn.setopt(pycurl.FOLLOWLOCATION, 1)
187
transport._set_curl_options(conn)
188
conn.setopt(pycurl.HTTPGET, 1)
191
conn.setopt(pycurl.HEADERFUNCTION, header.write)
192
conn.setopt(pycurl.WRITEFUNCTION, data.write)
193
transport._curl_perform(conn, header,
194
["Content-Type: application/x-git-upload-pack-request"])
195
code = conn.getinfo(pycurl.HTTP_CODE)
196
if code in (404, 405):
197
raise bzr_errors.NotBranchError(transport.base)
199
raise bzr_errors.InvalidHttpResponse(transport._path,
201
headers = transport._parse_headers(header)
203
raise bzr_errors.NotBranchError(transport.base)
204
refs_text = data.getvalue()
205
ct = headers.getheader("Content-Type")
207
raise bzr_errors.NotBranchError(transport.base)
208
if ct.startswith("application/x-git"):
209
from .remote import RemoteGitControlDirFormat
210
return RemoteGitControlDirFormat()
213
BareLocalGitControlDirFormat,
215
ret = BareLocalGitControlDirFormat()
216
ret._refs_text = refs_text
219
def probe_transport(self, transport):
221
external_url = transport.external_url()
222
except bzr_errors.InProcessTransport:
223
raise bzr_errors.NotBranchError(path=transport.base)
225
if (external_url.startswith("http:") or
226
external_url.startswith("https:")):
227
return self.probe_http_transport(transport)
229
if (not external_url.startswith("git://") and
230
not external_url.startswith("git+")):
231
raise bzr_errors.NotBranchError(transport.base)
233
# little ugly, but works
234
from .remote import (
236
RemoteGitControlDirFormat,
238
if isinstance(transport, GitSmartTransport):
239
return RemoteGitControlDirFormat()
240
raise bzr_errors.NotBranchError(path=transport.base)
243
def known_formats(cls):
244
from .remote import RemoteGitControlDirFormat
245
return set([RemoteGitControlDirFormat()])
248
ControlDirFormat.register_prober(LocalGitProber)
249
ControlDirFormat._server_probers.append(RemoteGitProber)
251
register_transport_proto('git://',
252
help="Access using the Git smart server protocol.")
253
register_transport_proto('git+ssh://',
254
help="Access using the Git smart server protocol over SSH.")
256
register_lazy_transport("git://", __name__ + '.remote',
257
'TCPGitSmartTransport')
258
register_lazy_transport("git+ssh://", __name__ + '.remote',
259
'SSHGitSmartTransport')
262
plugin_cmds.register_lazy("cmd_git_import", [], __name__ + ".commands")
263
plugin_cmds.register_lazy("cmd_git_object", ["git-objects", "git-cat"],
264
__name__ + ".commands")
265
plugin_cmds.register_lazy("cmd_git_refs", [], __name__ + ".commands")
266
plugin_cmds.register_lazy("cmd_git_apply", [], __name__ + ".commands")
267
plugin_cmds.register_lazy("cmd_git_push_pristine_tar_deltas",
268
['git-push-pristine-tar', 'git-push-pristine'],
269
__name__ + ".commands")
271
def extract_git_foreign_revid(rev):
273
foreign_revid = rev.foreign_revid
274
except AttributeError:
275
from .mapping import mapping_registry
276
foreign_revid, mapping = \
277
mapping_registry.parse_revision_id(rev.revision_id)
280
from .mapping import foreign_vcs_git
281
if rev.mapping.vcs == foreign_vcs_git:
284
raise bzr_errors.InvalidRevisionId(rev.revision_id, None)
287
def update_stanza(rev, stanza):
288
mapping = getattr(rev, "mapping", None)
290
git_commit = extract_git_foreign_revid(rev)
291
except bzr_errors.InvalidRevisionId:
294
stanza.add("git-commit", git_commit)
296
from ...hooks import install_lazy_named_hook
297
install_lazy_named_hook("breezy.version_info_formats.format_rio",
298
"RioVersionInfoBuilder.hooks", "revision", update_stanza,
302
transport_server_registry.register_lazy('git',
303
__name__ + '.server',
305
'Git Smart server protocol over TCP. (default port: 9418)')
307
transport_server_registry.register_lazy('git-receive-pack',
308
__name__ + '.server',
309
'serve_git_receive_pack',
310
help='Git Smart server receive pack command. (inetd mode only)')
311
transport_server_registry.register_lazy('git-upload-pack',
312
__name__ + 'git.server',
313
'serve_git_upload_pack',
314
help='Git Smart server upload pack command. (inetd mode only)')
316
from ...repository import (
317
format_registry as repository_format_registry,
318
network_format_registry as repository_network_format_registry,
320
repository_network_format_registry.register_lazy('git',
321
__name__ + '.repository', 'GitRepositoryFormat')
323
register_extra_lazy_repository_format = getattr(repository_format_registry,
324
"register_extra_lazy")
325
register_extra_lazy_repository_format(__name__ + '.repository',
326
'GitRepositoryFormat')
328
from ...branch import (
329
network_format_registry as branch_network_format_registry,
331
branch_network_format_registry.register_lazy('git',
332
__name__ + '.branch', 'GitBranchFormat')
334
from ...branch import (
335
format_registry as branch_format_registry,
337
branch_format_registry.register_extra_lazy(
338
__name__ + '.branch',
342
from ...workingtree import (
343
format_registry as workingtree_format_registry,
345
workingtree_format_registry.register_extra_lazy(
346
__name__ + '.workingtree',
347
'GitWorkingTreeFormat',
350
controldir_network_format_registry.register_lazy('git',
351
__name__ + ".dir", "GitControlDirFormat")
355
from ...registry import register_lazy
357
from ...diff import format_registry as diff_format_registry
358
diff_format_registry.register_lazy('git', __name__ + '.send',
359
'GitDiffTree', 'Git am-style diff format')
361
from ...send import (
362
format_registry as send_format_registry,
364
send_format_registry.register_lazy('git', __name__ + '.send',
365
'send_git', 'Git am-style diff format')
367
from ...directory_service import directories
368
directories.register_lazy('github:', __name__ + '.directory',
371
directories.register_lazy('git@github.com:', __name__ + '.directory',
375
from ...help_topics import (
378
topic_registry.register_lazy('git', __name__ + '.help', 'help_git',
379
'Using Bazaar with Git')
381
from ...foreign import (
382
foreign_vcs_registry,
384
foreign_vcs_registry.register_lazy("git",
385
__name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
387
register_lazy("breezy.diff", "format_registry",
388
'git', __name__ + '.send', 'GitDiffTree',
389
'Git am-style diff format')
390
register_lazy("breezy.send", "format_registry",
391
'git', __name__ + '.send', 'send_git',
392
'Git am-style diff format')
393
register_lazy('breezy.directory_service', 'directories', 'github:',
394
__name__ + '.directory', 'GitHubDirectory',
396
register_lazy('breezy.directory_service', 'directories',
397
'git@github.com:', __name__ + '.directory',
398
'GitHubDirectory', 'GitHub directory.')
399
register_lazy('breezy.help_topics', 'topic_registry',
400
'git', __name__ + '.help', 'help_git',
401
'Using Bazaar with Git')
402
register_lazy('breezy.foreign', 'foreign_vcs_registry', "git",
403
__name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
405
def update_git_cache(repository, revid):
406
"""Update the git cache after a local commit."""
407
if getattr(repository, "_git", None) is not None:
408
return # No need to update cache for git repositories
410
if not repository.control_transport.has("git"):
411
return # No existing cache, don't bother updating
413
lazy_check_versions()
414
except bzr_errors.DependencyNotPresent, e:
415
# dulwich is probably missing. silently ignore
416
trace.mutter("not updating git map for %r: %s",
419
from .object_store import BazaarObjectStore
420
store = BazaarObjectStore(repository)
424
parent_revisions = set(repository.get_parent_map([revid])[revid])
426
# Isn't this a bit odd - how can a revision that was just committed be missing?
428
missing_revisions = store._missing_revisions(parent_revisions)
429
if not missing_revisions:
430
# Only update if the cache was up to date previously
431
store._update_sha_map_revision(revid)
436
def post_commit_update_cache(local_branch, master_branch, old_revno, old_revid,
437
new_revno, new_revid):
438
if local_branch is not None:
439
update_git_cache(local_branch.repository, new_revid)
440
update_git_cache(master_branch.repository, new_revid)
443
def loggerhead_git_hook(branch_app, environ):
444
branch = branch_app.branch
445
config_stack = branch.get_config_stack()
446
if config_stack.get('http_git'):
448
from .server import git_http_hook
449
return git_http_hook(branch, environ['REQUEST_METHOD'],
450
environ['PATH_INFO'])
452
install_lazy_named_hook("breezy.branch",
453
"Branch.hooks", "post_commit", post_commit_update_cache,
455
install_lazy_named_hook("breezy.plugins.loggerhead.apps.branch",
456
"BranchWSGIApp.hooks", "controller",
457
loggerhead_git_hook, "git support")
460
from ...config import (
466
option_registry.register(
468
default=None, from_unicode=bool_from_store, invalid='warning',
470
Allow fetching of Git packs over HTTP.
472
This enables support for fetching Git packs over HTTP in Loggerhead.
477
return tests.test_suite()