/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: Canonical.com Patch Queue Manager
  • Date: 2006-04-13 23:16:57 UTC
  • mfrom: (1662.1.1 bzr.mbp.integration)
  • Revision ID: pqm@pqm.ubuntu.com-20060413231657-bce3d67d3e7a4f2b
(mbp/olaf) push/pull/merge --remember improvements

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
 
    errors as bzr_errors,
58
 
    trace,
59
 
    )
60
 
 
61
 
from ...controldir import (
62
 
    ControlDirFormat,
63
 
    Prober,
64
 
    format_registry,
65
 
    network_format_registry as controldir_network_format_registry,
66
 
    )
67
 
 
68
 
from ...transport import (
69
 
    register_lazy_transport,
70
 
    register_transport_proto,
71
 
    transport_server_registry,
72
 
    )
73
 
from ...commands import (
74
 
    plugin_cmds,
75
 
    )
76
 
 
77
 
 
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')))
82
 
 
83
 
 
84
 
def import_dulwich():
85
 
    try:
86
 
        from dulwich import __version__ as dulwich_version
87
 
    except ImportError:
88
 
        raise bzr_errors.DependencyNotPresent("dulwich",
89
 
            "bzr-git: Please install dulwich, https://launchpad.net/dulwich")
90
 
    else:
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)
95
 
 
96
 
 
97
 
_versions_checked = False
98
 
def lazy_check_versions():
99
 
    global _versions_checked
100
 
    if _versions_checked:
101
 
        return
102
 
    import_dulwich()
103
 
    _versions_checked = True
104
 
 
105
 
format_registry.register_lazy('git',
106
 
    __name__ + ".dir", "LocalGitControlDirFormat",
107
 
    help='GIT repository.', native=False, experimental=False,
108
 
    )
109
 
 
110
 
format_registry.register_lazy('git-bare',
111
 
    __name__ + ".dir", "BareLocalGitControlDirFormat",
112
 
    help='Bare GIT repository (no working tree).', native=False,
113
 
    experimental=False,
114
 
    )
115
 
 
116
 
from ...revisionspec import (RevisionSpec_dwim, revspec_registry)
117
 
revspec_registry.register_lazy("git:", __name__ + ".revspec",
118
 
    "RevisionSpec_git")
119
 
RevisionSpec_dwim.append_possible_lazy_revspec(
120
 
    __name__ + ".revspec", "RevisionSpec_git")
121
 
 
122
 
 
123
 
class LocalGitProber(Prober):
124
 
 
125
 
    def probe_transport(self, transport):
126
 
        try:
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()
140
 
        from .dir import (
141
 
            BareLocalGitControlDirFormat,
142
 
            LocalGitControlDirFormat,
143
 
            )
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)
149
 
 
150
 
    @classmethod
151
 
    def known_formats(cls):
152
 
        from .dir import (
153
 
            BareLocalGitControlDirFormat,
154
 
            LocalGitControlDirFormat,
155
 
            )
156
 
        return set([BareLocalGitControlDirFormat(), LocalGitControlDirFormat()])
157
 
 
158
 
 
159
 
class RemoteGitProber(Prober):
160
 
 
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()
175
 
        else:
176
 
            try:
177
 
                from ...transport.http._pycurl import PyCurlTransport
178
 
            except bzr_errors.DependencyNotPresent:
179
 
                raise bzr_errors.NotBranchError(transport.base)
180
 
            else:
181
 
                import pycurl
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)
189
 
                    header = StringIO()
190
 
                    data = StringIO()
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)
198
 
                    if code != 200:
199
 
                        raise bzr_errors.InvalidHttpResponse(transport._path,
200
 
                            str(code))
201
 
                    headers = transport._parse_headers(header)
202
 
                else:
203
 
                    raise bzr_errors.NotBranchError(transport.base)
204
 
                refs_text = data.getvalue()
205
 
        ct = headers.getheader("Content-Type")
206
 
        if ct is None:
207
 
            raise bzr_errors.NotBranchError(transport.base)
208
 
        if ct.startswith("application/x-git"):
209
 
            from .remote import RemoteGitControlDirFormat
210
 
            return RemoteGitControlDirFormat()
211
 
        else:
212
 
            from .dir import (
213
 
                BareLocalGitControlDirFormat,
214
 
                )
215
 
            ret = BareLocalGitControlDirFormat()
216
 
            ret._refs_text = refs_text
217
 
            return ret
218
 
 
219
 
    def probe_transport(self, transport):
220
 
        try:
221
 
            external_url = transport.external_url()
222
 
        except bzr_errors.InProcessTransport:
223
 
            raise bzr_errors.NotBranchError(path=transport.base)
224
 
 
225
 
        if (external_url.startswith("http:") or
226
 
            external_url.startswith("https:")):
227
 
            return self.probe_http_transport(transport)
228
 
 
229
 
        if (not external_url.startswith("git://") and
230
 
            not external_url.startswith("git+")):
231
 
            raise bzr_errors.NotBranchError(transport.base)
232
 
 
233
 
        # little ugly, but works
234
 
        from .remote import (
235
 
            GitSmartTransport,
236
 
            RemoteGitControlDirFormat,
237
 
            )
238
 
        if isinstance(transport, GitSmartTransport):
239
 
            return RemoteGitControlDirFormat()
240
 
        raise bzr_errors.NotBranchError(path=transport.base)
241
 
 
242
 
    @classmethod
243
 
    def known_formats(cls):
244
 
        from .remote import RemoteGitControlDirFormat
245
 
        return set([RemoteGitControlDirFormat()])
246
 
 
247
 
 
248
 
ControlDirFormat.register_prober(LocalGitProber)
249
 
ControlDirFormat._server_probers.append(RemoteGitProber)
250
 
 
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.")
255
 
 
256
 
register_lazy_transport("git://", __name__ + '.remote',
257
 
                        'TCPGitSmartTransport')
258
 
register_lazy_transport("git+ssh://", __name__ + '.remote',
259
 
                        'SSHGitSmartTransport')
260
 
 
261
 
 
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")
270
 
 
271
 
def extract_git_foreign_revid(rev):
272
 
    try:
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)
278
 
        return foreign_revid
279
 
    else:
280
 
        from .mapping import foreign_vcs_git
281
 
        if rev.mapping.vcs == foreign_vcs_git:
282
 
            return foreign_revid
283
 
        else:
284
 
            raise bzr_errors.InvalidRevisionId(rev.revision_id, None)
285
 
 
286
 
 
287
 
def update_stanza(rev, stanza):
288
 
    mapping = getattr(rev, "mapping", None)
289
 
    try:
290
 
        git_commit = extract_git_foreign_revid(rev)
291
 
    except bzr_errors.InvalidRevisionId:
292
 
        pass
293
 
    else:
294
 
        stanza.add("git-commit", git_commit)
295
 
 
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,
299
 
    "git commits")
300
 
 
301
 
 
302
 
transport_server_registry.register_lazy('git',
303
 
    __name__ + '.server',
304
 
    'serve_git',
305
 
    'Git Smart server protocol over TCP. (default port: 9418)')
306
 
 
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)')
315
 
 
316
 
from ...repository import (
317
 
    format_registry as repository_format_registry,
318
 
    network_format_registry as repository_network_format_registry,
319
 
    )
320
 
repository_network_format_registry.register_lazy('git',
321
 
    __name__ + '.repository', 'GitRepositoryFormat')
322
 
 
323
 
register_extra_lazy_repository_format = getattr(repository_format_registry,
324
 
    "register_extra_lazy")
325
 
register_extra_lazy_repository_format(__name__ + '.repository',
326
 
    'GitRepositoryFormat')
327
 
 
328
 
from ...branch import (
329
 
    network_format_registry as branch_network_format_registry,
330
 
    )
331
 
branch_network_format_registry.register_lazy('git',
332
 
    __name__ + '.branch', 'GitBranchFormat')
333
 
 
334
 
from ...branch import (
335
 
    format_registry as branch_format_registry,
336
 
    )
337
 
branch_format_registry.register_extra_lazy(
338
 
    __name__ + '.branch',
339
 
    'GitBranchFormat',
340
 
    )
341
 
 
342
 
from ...workingtree import (
343
 
    format_registry as workingtree_format_registry,
344
 
    )
345
 
workingtree_format_registry.register_extra_lazy(
346
 
    __name__ + '.workingtree',
347
 
    'GitWorkingTreeFormat',
348
 
    )
349
 
 
350
 
controldir_network_format_registry.register_lazy('git',
351
 
    __name__ + ".dir", "GitControlDirFormat")
352
 
 
353
 
 
354
 
try:
355
 
    from ...registry import register_lazy
356
 
except ImportError:
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')
360
 
 
361
 
    from ...send import (
362
 
        format_registry as send_format_registry,
363
 
        )
364
 
    send_format_registry.register_lazy('git', __name__ + '.send',
365
 
                                       'send_git', 'Git am-style diff format')
366
 
 
367
 
    from ...directory_service import directories
368
 
    directories.register_lazy('github:', __name__ + '.directory',
369
 
                              'GitHubDirectory',
370
 
                              'GitHub directory.')
371
 
    directories.register_lazy('git@github.com:', __name__ + '.directory',
372
 
                              'GitHubDirectory',
373
 
                              'GitHub directory.')
374
 
 
375
 
    from ...help_topics import (
376
 
        topic_registry,
377
 
        )
378
 
    topic_registry.register_lazy('git', __name__ + '.help', 'help_git',
379
 
        'Using Bazaar with Git')
380
 
 
381
 
    from ...foreign import (
382
 
        foreign_vcs_registry,
383
 
        )
384
 
    foreign_vcs_registry.register_lazy("git",
385
 
        __name__ + ".mapping", "foreign_vcs_git", "Stupid content tracker")
386
 
else:
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',
395
 
            'GitHub directory.')
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")
404
 
 
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
409
 
 
410
 
    if not repository.control_transport.has("git"):
411
 
        return # No existing cache, don't bother updating
412
 
    try:
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",
417
 
            repository, e)
418
 
 
419
 
    from .object_store import BazaarObjectStore
420
 
    store = BazaarObjectStore(repository)
421
 
    store.lock_write()
422
 
    try:
423
 
        try:
424
 
            parent_revisions = set(repository.get_parent_map([revid])[revid])
425
 
        except KeyError:
426
 
            # Isn't this a bit odd - how can a revision that was just committed be missing?
427
 
            return
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)
432
 
    finally:
433
 
        store.unlock()
434
 
 
435
 
 
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)
441
 
 
442
 
 
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'):
447
 
        return None
448
 
    from .server import git_http_hook
449
 
    return git_http_hook(branch, environ['REQUEST_METHOD'],
450
 
        environ['PATH_INFO'])
451
 
 
452
 
install_lazy_named_hook("breezy.branch",
453
 
    "Branch.hooks", "post_commit", post_commit_update_cache,
454
 
    "git cache")
455
 
install_lazy_named_hook("breezy.plugins.loggerhead.apps.branch",
456
 
    "BranchWSGIApp.hooks", "controller",
457
 
    loggerhead_git_hook, "git support")
458
 
 
459
 
 
460
 
from ...config import (
461
 
    option_registry,
462
 
    Option,
463
 
    bool_from_store,
464
 
    )
465
 
 
466
 
option_registry.register(
467
 
    Option('git.http',
468
 
           default=None, from_unicode=bool_from_store, invalid='warning',
469
 
           help='''\
470
 
Allow fetching of Git packs over HTTP.
471
 
 
472
 
This enables support for fetching Git packs over HTTP in Loggerhead.
473
 
'''))
474
 
 
475
 
def test_suite():
476
 
    from . import tests
477
 
    return tests.test_suite()