/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 __init__.py

  • Committer: Jelmer Vernooij
  • Date: 2018-03-17 17:54:17 UTC
  • mto: (0.200.1859 work)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180317175417-4ag21da38udunec9
Add tests for memorytree.

Show diffs side-by-side

added added

removed removed

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