/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

Fix revision_history test when no DeprecationWarning is printed and bzr 2.5
is used.

Older prereleases of bzr 2.5 didn't deprecate Branch.revision_history.

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