/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

Share sha map cache connections inside threads.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
 
1
# Copyright (C) 2006-2009 Canonical Ltd
 
2
 
2
3
# Authors: Robert Collins <robert.collins@canonical.com>
 
4
#          Jelmer Vernooij <jelmer@samba.org>
 
5
#          John Carr <john.carr@unrouted.co.uk>
3
6
#
4
7
# This program is free software; you can redistribute it and/or modify
5
8
# it under the terms of the GNU General Public License as published by
18
21
 
19
22
"""A GIT branch and repository format implementation for bzr."""
20
23
 
21
 
try:
22
 
    import dulwich as git
23
 
except ImportError:
24
 
    import os, sys
25
 
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), "dulwich"))
26
 
    import dulwich as git
27
 
from bzrlib import bzrdir
28
 
from bzrlib.foreign import ForeignVcs, VcsMappingRegistry, foreign_vcs_registry
29
 
from bzrlib.plugins.git.dir import LocalGitBzrDirFormat, RemoteGitBzrDirFormat
30
 
from bzrlib.transport import register_lazy_transport
31
 
from bzrlib.commands import Command, register_command
32
 
from bzrlib.option import Option
33
 
 
34
 
bzrdir.format_registry.register(
35
 
    'git', LocalGitBzrDirFormat,
36
 
    help='GIT repository.', 
37
 
    native=False, experimental=True,
38
 
    )
 
24
import os
 
25
import sys
 
26
 
 
27
import bzrlib
 
28
import bzrlib.api
 
29
from bzrlib import (
 
30
    bzrdir,
 
31
    errors as bzr_errors,
 
32
    )
 
33
from bzrlib.foreign import (
 
34
    foreign_vcs_registry,
 
35
    )
 
36
from bzrlib.lockable_files import (
 
37
    TransportLock,
 
38
    )
 
39
from bzrlib.transport import (
 
40
    register_lazy_transport,
 
41
    register_transport_proto,
 
42
    )
 
43
from bzrlib.commands import (
 
44
    plugin_cmds,
 
45
    )
 
46
from bzrlib.trace import (
 
47
    warning,
 
48
    )
 
49
from bzrlib.version_info_formats.format_rio import (
 
50
    RioVersionInfoBuilder,
 
51
    )
 
52
 
 
53
 
 
54
# versions ending in 'exp' mean experimental mappings
 
55
# versions ending in 'dev' mean development version
 
56
# versions ending in 'final' mean release (well tested, etc)
 
57
version_info = (0, 2, 0, 'dev', 0)
 
58
 
 
59
if version_info[3] == 'final':
 
60
    version_string = '%d.%d.%d' % version_info[:3]
 
61
else:
 
62
    version_string = '%d.%d.%d%s%d' % version_info
 
63
__version__ = version_string
 
64
 
 
65
MINIMUM_DULWICH_VERSION = (0, 1, 1)
 
66
COMPATIBLE_BZR_VERSIONS = [(1, 15, 0)]
 
67
 
 
68
if getattr(sys, "frozen", None):
 
69
    # allow import additional libs from ./_lib for bzr.exe only
 
70
    sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '_lib')))
 
71
 
 
72
_versions_checked = False
 
73
def lazy_check_versions():
 
74
    global _versions_checked
 
75
    if _versions_checked:
 
76
        return
 
77
    _versions_checked = True
 
78
    try:
 
79
        from dulwich import __version__ as dulwich_version
 
80
    except ImportError:
 
81
        raise ImportError("bzr-git: Please install dulwich, https://launchpad.net/dulwich")
 
82
    else:
 
83
        if dulwich_version < MINIMUM_DULWICH_VERSION:
 
84
            raise ImportError("bzr-git: Dulwich is too old; at least %d.%d.%d is required" % MINIMUM_DULWICH_VERSION)
 
85
 
 
86
bzrlib.api.require_any_api(bzrlib, COMPATIBLE_BZR_VERSIONS)
 
87
 
 
88
bzrdir.format_registry.register_lazy('git', 
 
89
    "bzrlib.plugins.git.dir", "LocalGitBzrDirFormat",
 
90
    help='GIT repository.', native=False, experimental=True,
 
91
    )
 
92
 
 
93
from bzrlib.revisionspec import revspec_registry
 
94
revspec_registry.register_lazy("git:", "bzrlib.plugins.git.revspec", 
 
95
    "RevisionSpec_git")
 
96
 
 
97
 
 
98
class GitBzrDirFormat(bzrdir.BzrDirFormat):
 
99
    _lock_class = TransportLock
 
100
 
 
101
    def is_supported(self):
 
102
        return True
 
103
 
 
104
 
 
105
class LocalGitBzrDirFormat(GitBzrDirFormat):
 
106
    """The .git directory control format."""
 
107
 
 
108
    @classmethod
 
109
    def _known_formats(self):
 
110
        return set([LocalGitBzrDirFormat()])
 
111
 
 
112
    def open(self, transport, _found=None):
 
113
        """Open this directory.
 
114
 
 
115
        """
 
116
        import dulwich as git
 
117
        # we dont grok readonly - git isn't integrated with transport.
 
118
        url = transport.base
 
119
        if url.startswith('readonly+'):
 
120
            url = url[len('readonly+'):]
 
121
 
 
122
        try:
 
123
            gitrepo = git.repo.Repo(transport.local_abspath("."))
 
124
        except bzr_errors.NotLocalUrl:
 
125
            raise bzr_errors.NotBranchError(path=transport.base)
 
126
        from bzrlib.plugins.git.dir import LocalGitDir, GitLockableFiles, GitLock
 
127
        lockfiles = GitLockableFiles(transport, GitLock())
 
128
        return LocalGitDir(transport, lockfiles, gitrepo, self)
 
129
 
 
130
    @classmethod
 
131
    def probe_transport(klass, transport):
 
132
        """Our format is present if the transport ends in '.not/'."""
 
133
        from bzrlib.transport.local import LocalTransport
 
134
 
 
135
        if not isinstance(transport, LocalTransport):
 
136
            raise bzr_errors.NotBranchError(path=transport.base)
 
137
 
 
138
        # This should quickly filter out most things that are not 
 
139
        # git repositories, saving us the trouble from loading dulwich.
 
140
        if not transport.has(".git") and not transport.has("objects"):
 
141
            raise bzr_errors.NotBranchError(path=transport.base)
 
142
 
 
143
        import dulwich as git
 
144
        format = klass()
 
145
        try:
 
146
            format.open(transport)
 
147
            return format
 
148
        except git.errors.NotGitRepository, e:
 
149
            raise bzr_errors.NotBranchError(path=transport.base)
 
150
        raise bzr_errors.NotBranchError(path=transport.base)
 
151
 
 
152
    def get_format_description(self):
 
153
        return "Local Git Repository"
 
154
 
 
155
    def get_format_string(self):
 
156
        return "Local Git Repository"
 
157
 
 
158
    def initialize_on_transport(self, transport):
 
159
        from bzrlib.transport.local import LocalTransport
 
160
 
 
161
        if not isinstance(transport, LocalTransport):
 
162
            raise NotImplementedError(self.initialize, 
 
163
                "Can't create Git Repositories/branches on "
 
164
                "non-local transports")
 
165
 
 
166
        from dulwich.repo import Repo
 
167
        Repo.create(transport.local_abspath(".")) 
 
168
        return self.open(transport)
 
169
 
 
170
    def is_supported(self):
 
171
        return True
 
172
 
 
173
 
 
174
class RemoteGitBzrDirFormat(GitBzrDirFormat):
 
175
    """The .git directory control format."""
 
176
 
 
177
    @classmethod
 
178
    def _known_formats(self):
 
179
        return set([RemoteGitBzrDirFormat()])
 
180
 
 
181
    def open(self, transport, _found=None):
 
182
        """Open this directory.
 
183
 
 
184
        """
 
185
        # we dont grok readonly - git isn't integrated with transport.
 
186
        url = transport.base
 
187
        if url.startswith('readonly+'):
 
188
            url = url[len('readonly+'):]
 
189
        if (not url.startswith("git://") and 
 
190
            not url.startswith("git+")):
 
191
            raise bzr_errors.NotBranchError(transport.base)
 
192
        from bzrlib.plugins.git.remote import RemoteGitDir, GitSmartTransport
 
193
        if not isinstance(transport, GitSmartTransport):
 
194
            raise bzr_errors.NotBranchError(transport.base)
 
195
        from bzrlib.plugins.git.dir import GitLockableFiles, GitLock
 
196
        lockfiles = GitLockableFiles(transport, GitLock())
 
197
        return RemoteGitDir(transport, lockfiles, self)
 
198
 
 
199
    @classmethod
 
200
    def probe_transport(klass, transport):
 
201
        """Our format is present if the transport ends in '.not/'."""
 
202
        url = transport.base
 
203
        if url.startswith('readonly+'):
 
204
            url = url[len('readonly+'):]
 
205
        if (not url.startswith("git://") and 
 
206
            not url.startswith("git+")):
 
207
            raise bzr_errors.NotBranchError(transport.base)
 
208
        # little ugly, but works
 
209
        format = klass()
 
210
        from bzrlib.plugins.git.remote import GitSmartTransport
 
211
        if not isinstance(transport, GitSmartTransport):
 
212
            raise bzr_errors.NotBranchError(transport.base)
 
213
        # The only way to know a path exists and contains a valid repository 
 
214
        # is to do a request against it:
 
215
        try:
 
216
            transport.fetch_pack(lambda x: [], None, lambda x: None, 
 
217
                                 lambda x: mutter("git: %s" % x))
 
218
        except errors.git_errors.GitProtocolError:
 
219
            raise bzr_errors.NotBranchError(path=transport.base)
 
220
        else:
 
221
            return format
 
222
        raise bzr_errors.NotBranchError(path=transport.base)
 
223
 
 
224
    def get_format_description(self):
 
225
        return "Remote Git Repository"
 
226
 
 
227
    def get_format_string(self):
 
228
        return "Remote Git Repository"
 
229
 
 
230
    def initialize_on_transport(self, transport):
 
231
        raise bzr_errors.UninitializableFormat(self)
 
232
 
39
233
 
40
234
bzrdir.BzrDirFormat.register_control_format(LocalGitBzrDirFormat)
41
235
bzrdir.BzrDirFormat.register_control_format(RemoteGitBzrDirFormat)
42
236
 
 
237
register_transport_proto('git://', 
 
238
        help="Access using the Git smart server protocol.")
 
239
register_transport_proto('git+ssh://', 
 
240
        help="Access using the Git smart server protocol over SSH.")
 
241
 
43
242
register_lazy_transport("git://", 'bzrlib.plugins.git.remote',
44
 
                        'GitSmartTransport')
45
 
 
46
 
 
47
 
class ForeignGit(ForeignVcs):
48
 
    """Foreign Git."""
49
 
 
50
 
 
51
 
git_mapping_registry = VcsMappingRegistry()
52
 
git_mapping_registry.register_lazy('git-experimental', "bzrlib.plugins.git.mapping",
53
 
                                   "BzrGitMappingExperimental")
54
 
foreign_vcs_registry.register("git", ForeignGit(git_mapping_registry), 
55
 
                                      "Stupid content tracker")
56
 
 
57
 
 
58
 
class cmd_git_serve(Command):
59
 
    """Provide access to a Bazaar branch using the git protocol.
60
 
 
61
 
    This command is experimental and doesn't do much yet.
62
 
    """
63
 
    takes_options = [
64
 
        Option('inet',
65
 
               help='serve on stdin/out for use from inetd or sshd'),
66
 
        Option('directory',
67
 
               help='serve contents of directory',
68
 
               type=unicode)
69
 
    ]
70
 
 
71
 
    def run(self, inet=None, port=None, directory=None):
72
 
        from dulwich.server import TCPGitServer
73
 
        from bzrlib.plugins.git.server import BzrBackend
74
 
        from bzrlib.trace import warning
75
 
        import os
76
 
 
77
 
        warning("server support in bzr-git is experimental.")
78
 
 
79
 
        if directory is None:
80
 
            directory = os.getcwd()
81
 
 
82
 
        backend = BzrBackend(directory)
83
 
 
84
 
        if inet:
85
 
            #def send_fn(data):
86
 
            #    sys.stdout.write(data)
87
 
            #    sys.stdout.flush()
88
 
            #server = GitServer(sys.stdin.read, send_fn)
89
 
            raise NotImplementedError
90
 
        else:
91
 
            server = TCPGitServer(backend, 'localhost')
92
 
            server.serve_forever()
93
 
 
94
 
register_command(cmd_git_serve)
95
 
 
 
243
                        'TCPGitSmartTransport')
 
244
register_lazy_transport("git+ssh://", 'bzrlib.plugins.git.remote',
 
245
                        'SSHGitSmartTransport')
 
246
 
 
247
foreign_vcs_registry.register_lazy("git", 
 
248
    "bzrlib.plugins.git.mapping", "foreign_git", "Stupid content tracker")
 
249
 
 
250
plugin_cmds.register_lazy("cmd_git_serve", [], "bzrlib.plugins.git.commands")
 
251
plugin_cmds.register_lazy("cmd_git_import", [], "bzrlib.plugins.git.commands")
 
252
 
 
253
def update_stanza(rev, stanza):
 
254
    mapping = getattr(rev, "mapping", None)
 
255
    if mapping is not None and mapping.revid_prefix.startswith("git-"):
 
256
        stanza.add("git-commit", rev.foreign_revid)
 
257
 
 
258
 
 
259
RioVersionInfoBuilder.hooks.install_named_hook('revision',
 
260
    update_stanza, None)
 
261
 
 
262
def get_rich_root_format(stacked=False):
 
263
    if stacked:
 
264
        return bzrdir.format_registry.make_bzrdir("1.9-rich-root")
 
265
    else:
 
266
        return bzrdir.format_registry.make_bzrdir("default-rich-root")
96
267
 
97
268
def test_suite():
98
269
    from bzrlib.plugins.git import tests