/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/git/__init__.py

  • Committer: Jelmer Vernooij
  • Date: 2019-11-03 12:38:45 UTC
  • mto: This revision was merged to the branch mainline in revision 7413.
  • Revision ID: jelmer@jelmer.uk-20191103123845-5726o8n89u0i5bjw
Fix tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
 
2
# Copyright (C) 2006-2009 Canonical Ltd
 
3
 
 
4
# Authors: Robert Collins <robert.collins@canonical.com>
 
5
#          Jelmer Vernooij <jelmer@jelmer.uk>
 
6
#          John Carr <john.carr@unrouted.co.uk>
 
7
#
 
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.
 
12
#
 
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.
 
17
#
 
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
 
21
 
 
22
 
 
23
"""A GIT branch and repository format implementation for bzr."""
 
24
 
 
25
from __future__ import absolute_import
 
26
 
 
27
import os
 
28
import sys
 
29
 
 
30
dulwich_minimum_version = (0, 19, 11)
 
31
 
 
32
from .. import (  # noqa: F401
 
33
    __version__ as breezy_version,
 
34
    errors as brz_errors,
 
35
    trace,
 
36
    urlutils,
 
37
    version_info,
 
38
    )
 
39
 
 
40
from ..controldir import (
 
41
    ControlDirFormat,
 
42
    Prober,
 
43
    format_registry,
 
44
    network_format_registry as controldir_network_format_registry,
 
45
    )
 
46
 
 
47
from ..transport import (
 
48
    register_lazy_transport,
 
49
    register_transport_proto,
 
50
    transport_server_registry,
 
51
    )
 
52
from ..commands import (
 
53
    plugin_cmds,
 
54
    )
 
55
 
 
56
 
 
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')))
 
61
 
 
62
 
 
63
def import_dulwich():
 
64
    try:
 
65
        from dulwich import __version__ as dulwich_version
 
66
    except ImportError:
 
67
        raise brz_errors.DependencyNotPresent(
 
68
            "dulwich",
 
69
            "bzr-git: Please install dulwich, https://www.dulwich.io/")
 
70
    else:
 
71
        if dulwich_version < dulwich_minimum_version:
 
72
            raise brz_errors.DependencyNotPresent(
 
73
                "dulwich",
 
74
                "bzr-git: Dulwich is too old; at least %d.%d.%d is required" %
 
75
                dulwich_minimum_version)
 
76
 
 
77
 
 
78
_versions_checked = False
 
79
 
 
80
 
 
81
def lazy_check_versions():
 
82
    global _versions_checked
 
83
    if _versions_checked:
 
84
        return
 
85
    import_dulwich()
 
86
    _versions_checked = True
 
87
 
 
88
 
 
89
format_registry.register_lazy(
 
90
    'git', __name__ + ".dir", "LocalGitControlDirFormat",
 
91
    help='GIT repository.', native=False, experimental=False)
 
92
 
 
93
format_registry.register_lazy(
 
94
    'git-bare', __name__ + ".dir", "BareLocalGitControlDirFormat",
 
95
    help='Bare GIT repository (no working tree).', native=False,
 
96
    experimental=False)
 
97
 
 
98
from ..revisionspec import (RevisionSpec_dwim, revspec_registry)
 
99
revspec_registry.register_lazy("git:", __name__ + ".revspec",
 
100
                               "RevisionSpec_git")
 
101
RevisionSpec_dwim.append_possible_lazy_revspec(
 
102
    __name__ + ".revspec", "RevisionSpec_git")
 
103
 
 
104
 
 
105
class LocalGitProber(Prober):
 
106
 
 
107
    def probe_transport(self, transport):
 
108
        try:
 
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()
 
121
        from .dir import (
 
122
            BareLocalGitControlDirFormat,
 
123
            LocalGitControlDirFormat,
 
124
            )
 
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)
 
130
 
 
131
    @classmethod
 
132
    def known_formats(cls):
 
133
        from .dir import (
 
134
            BareLocalGitControlDirFormat,
 
135
            LocalGitControlDirFormat,
 
136
            )
 
137
        return [BareLocalGitControlDirFormat(), LocalGitControlDirFormat()]
 
138
 
 
139
 
 
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
 
143
 
 
144
 
 
145
def is_github_url(url):
 
146
    (scheme, user, password, host, port,
 
147
     path) = urlutils.parse_url(url)
 
148
    return host == "github.com"
 
149
 
 
150
 
 
151
class RemoteGitProber(Prober):
 
152
 
 
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
 
163
        host = url.host
 
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",
 
167
                   }
 
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)
 
181
 
 
182
        ct = resp.getheader("Content-Type")
 
183
        if ct and ct.startswith("application/x-git"):
 
184
            from .remote import RemoteGitControlDirFormat
 
185
            return RemoteGitControlDirFormat()
 
186
        else:
 
187
            from .dir import (
 
188
                BareLocalGitControlDirFormat,
 
189
                )
 
190
            ret = BareLocalGitControlDirFormat()
 
191
            ret._refs_text = resp.read()
 
192
            return ret
 
193
 
 
194
    def probe_transport(self, transport):
 
195
        try:
 
196
            external_url = transport.external_url()
 
197
        except brz_errors.InProcessTransport:
 
198
            raise brz_errors.NotBranchError(path=transport.base)
 
199
 
 
200
        if (external_url.startswith("http:") or
 
201
                external_url.startswith("https:")):
 
202
            return self.probe_http_transport(transport)
 
203
 
 
204
        if (not external_url.startswith("git://") and
 
205
                not external_url.startswith("git+")):
 
206
            raise brz_errors.NotBranchError(transport.base)
 
207
 
 
208
        # little ugly, but works
 
209
        from .remote import (
 
210
            GitSmartTransport,
 
211
            RemoteGitControlDirFormat,
 
212
            )
 
213
        if isinstance(transport, GitSmartTransport):
 
214
            return RemoteGitControlDirFormat()
 
215
        raise brz_errors.NotBranchError(path=transport.base)
 
216
 
 
217
    @classmethod
 
218
    def known_formats(cls):
 
219
        from .remote import RemoteGitControlDirFormat
 
220
        return [RemoteGitControlDirFormat()]
 
221
 
 
222
 
 
223
ControlDirFormat.register_prober(LocalGitProber)
 
224
ControlDirFormat._server_probers.append(RemoteGitProber)
 
225
 
 
226
register_transport_proto(
 
227
    'git://', help="Access using the Git smart server protocol.")
 
228
register_transport_proto(
 
229
    'git+ssh://',
 
230
    help="Access using the Git smart server protocol over SSH.")
 
231
 
 
232
register_lazy_transport("git://", __name__ + '.remote',
 
233
                        'TCPGitSmartTransport')
 
234
register_lazy_transport("git+ssh://", __name__ + '.remote',
 
235
                        'SSHGitSmartTransport')
 
236
 
 
237
 
 
238
plugin_cmds.register_lazy("cmd_git_import", [], __name__ + ".commands")
 
239
plugin_cmds.register_lazy("cmd_git_object", ["git-objects", "git-cat"],
 
240
                          __name__ + ".commands")
 
241
plugin_cmds.register_lazy("cmd_git_refs", [], __name__ + ".commands")
 
242
plugin_cmds.register_lazy("cmd_git_apply", [], __name__ + ".commands")
 
243
plugin_cmds.register_lazy("cmd_git_push_pristine_tar_deltas",
 
244
                          ['git-push-pristine-tar', 'git-push-pristine'],
 
245
                          __name__ + ".commands")
 
246
 
 
247
 
 
248
def extract_git_foreign_revid(rev):
 
249
    try:
 
250
        foreign_revid = rev.foreign_revid
 
251
    except AttributeError:
 
252
        from .mapping import mapping_registry
 
253
        foreign_revid, mapping = \
 
254
            mapping_registry.parse_revision_id(rev.revision_id)
 
255
        return foreign_revid
 
256
    else:
 
257
        from .mapping import foreign_vcs_git
 
258
        if rev.mapping.vcs == foreign_vcs_git:
 
259
            return foreign_revid
 
260
        else:
 
261
            raise brz_errors.InvalidRevisionId(rev.revision_id, None)
 
262
 
 
263
 
 
264
def update_stanza(rev, stanza):
 
265
    try:
 
266
        git_commit = extract_git_foreign_revid(rev)
 
267
    except brz_errors.InvalidRevisionId:
 
268
        pass
 
269
    else:
 
270
        stanza.add("git-commit", git_commit)
 
271
 
 
272
 
 
273
from ..hooks import install_lazy_named_hook
 
274
install_lazy_named_hook(
 
275
    "breezy.version_info_formats.format_rio",
 
276
    "RioVersionInfoBuilder.hooks", "revision", update_stanza,
 
277
    "git commits")
 
278
 
 
279
transport_server_registry.register_lazy(
 
280
    'git', __name__ + '.server', 'serve_git',
 
281
    'Git Smart server protocol over TCP. (default port: 9418)')
 
282
 
 
283
transport_server_registry.register_lazy(
 
284
    'git-receive-pack', __name__ + '.server',
 
285
    'serve_git_receive_pack',
 
286
    help='Git Smart server receive pack command. (inetd mode only)')
 
287
transport_server_registry.register_lazy(
 
288
    'git-upload-pack', __name__ + 'git.server',
 
289
    'serve_git_upload_pack',
 
290
    help='Git Smart server upload pack command. (inetd mode only)')
 
291
 
 
292
from ..repository import (
 
293
    format_registry as repository_format_registry,
 
294
    network_format_registry as repository_network_format_registry,
 
295
    )
 
296
repository_network_format_registry.register_lazy(
 
297
    b'git', __name__ + '.repository', 'GitRepositoryFormat')
 
298
 
 
299
register_extra_lazy_repository_format = getattr(repository_format_registry,
 
300
                                                "register_extra_lazy")
 
301
register_extra_lazy_repository_format(__name__ + '.repository',
 
302
                                      'GitRepositoryFormat')
 
303
 
 
304
from ..branch import (
 
305
    network_format_registry as branch_network_format_registry,
 
306
    )
 
307
branch_network_format_registry.register_lazy(
 
308
    b'git', __name__ + '.branch', 'LocalGitBranchFormat')
 
309
 
 
310
 
 
311
from ..branch import (
 
312
    format_registry as branch_format_registry,
 
313
    )
 
314
branch_format_registry.register_extra_lazy(
 
315
    __name__ + '.branch',
 
316
    'LocalGitBranchFormat',
 
317
    )
 
318
branch_format_registry.register_extra_lazy(
 
319
    __name__ + '.remote',
 
320
    'RemoteGitBranchFormat',
 
321
    )
 
322
 
 
323
 
 
324
from ..workingtree import (
 
325
    format_registry as workingtree_format_registry,
 
326
    )
 
327
workingtree_format_registry.register_extra_lazy(
 
328
    __name__ + '.workingtree',
 
329
    'GitWorkingTreeFormat',
 
330
    )
 
331
 
 
332
controldir_network_format_registry.register_lazy(
 
333
    b'git', __name__ + ".dir", "GitControlDirFormat")
 
334
 
 
335
 
 
336
from ..diff import format_registry as diff_format_registry
 
337
diff_format_registry.register_lazy(
 
338
    'git', __name__ + '.send',
 
339
    'GitDiffTree', 'Git am-style diff format')
 
340
 
 
341
from ..send import (
 
342
    format_registry as send_format_registry,
 
343
    )
 
344
send_format_registry.register_lazy('git', __name__ + '.send',
 
345
                                   'send_git', 'Git am-style diff format')
 
346
 
 
347
from ..directory_service import directories
 
348
directories.register_lazy('github:', __name__ + '.directory',
 
349
                          'GitHubDirectory',
 
350
                          'GitHub directory.')
 
351
directories.register_lazy('git@github.com:', __name__ + '.directory',
 
352
                          'GitHubDirectory',
 
353
                          'GitHub directory.')
 
354
 
 
355
from ..help_topics import (
 
356
    topic_registry,
 
357
    )
 
358
topic_registry.register_lazy(
 
359
    'git', __name__ + '.help', 'help_git', 'Using Bazaar with Git')
 
360
 
 
361
from ..foreign import (
 
362
    foreign_vcs_registry,
 
363
    )
 
364
foreign_vcs_registry.register_lazy(
 
365
    "git", __name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
 
366
 
 
367
 
 
368
def update_git_cache(repository, revid):
 
369
    """Update the git cache after a local commit."""
 
370
    if getattr(repository, "_git", None) is not None:
 
371
        return  # No need to update cache for git repositories
 
372
 
 
373
    if not repository.control_transport.has("git"):
 
374
        return  # No existing cache, don't bother updating
 
375
    try:
 
376
        lazy_check_versions()
 
377
    except brz_errors.DependencyNotPresent as e:
 
378
        # dulwich is probably missing. silently ignore
 
379
        trace.mutter("not updating git map for %r: %s",
 
380
                     repository, e)
 
381
 
 
382
    from .object_store import BazaarObjectStore
 
383
    store = BazaarObjectStore(repository)
 
384
    with store.lock_write():
 
385
        try:
 
386
            parent_revisions = set(repository.get_parent_map([revid])[revid])
 
387
        except KeyError:
 
388
            # Isn't this a bit odd - how can a revision that was just committed
 
389
            # be missing?
 
390
            return
 
391
        missing_revisions = store._missing_revisions(parent_revisions)
 
392
        if not missing_revisions:
 
393
            store._cache.idmap.start_write_group()
 
394
            try:
 
395
                # Only update if the cache was up to date previously
 
396
                store._update_sha_map_revision(revid)
 
397
            except BaseException:
 
398
                store._cache.idmap.abort_write_group()
 
399
                raise
 
400
            else:
 
401
                store._cache.idmap.commit_write_group()
 
402
 
 
403
 
 
404
def post_commit_update_cache(local_branch, master_branch, old_revno, old_revid,
 
405
                             new_revno, new_revid):
 
406
    if local_branch is not None:
 
407
        update_git_cache(local_branch.repository, new_revid)
 
408
    update_git_cache(master_branch.repository, new_revid)
 
409
 
 
410
 
 
411
def loggerhead_git_hook(branch_app, environ):
 
412
    branch = branch_app.branch
 
413
    config_stack = branch.get_config_stack()
 
414
    if config_stack.get('http_git'):
 
415
        return None
 
416
    from .server import git_http_hook
 
417
    return git_http_hook(branch, environ['REQUEST_METHOD'],
 
418
                         environ['PATH_INFO'])
 
419
 
 
420
 
 
421
install_lazy_named_hook("breezy.branch",
 
422
                        "Branch.hooks", "post_commit",
 
423
                        post_commit_update_cache, "git cache")
 
424
install_lazy_named_hook("breezy.plugins.loggerhead.apps.branch",
 
425
                        "BranchWSGIApp.hooks", "controller",
 
426
                        loggerhead_git_hook, "git support")
 
427
 
 
428
 
 
429
from ..config import (
 
430
    option_registry,
 
431
    Option,
 
432
    bool_from_store,
 
433
    )
 
434
 
 
435
option_registry.register(
 
436
    Option('git.http',
 
437
           default=None, from_unicode=bool_from_store, invalid='warning',
 
438
           help='''\
 
439
Allow fetching of Git packs over HTTP.
 
440
 
 
441
This enables support for fetching Git packs over HTTP in Loggerhead.
 
442
'''))
 
443
 
 
444
 
 
445
def test_suite():
 
446
    from . import tests
 
447
    return tests.test_suite()