/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
# Copyright (C) 2008 John Carr
# Copyright (C) 2008-2011 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

from dulwich.server import TCPGitServer

import sys

from .. import (
    errors,
    trace,
    )

from ..controldir import (
    ControlDir,
    )

from .mapping import (
    default_mapping,
    decode_git_path,
    )
from .object_store import (
    BazaarObjectStore,
    get_object_store,
    )
from .refs import (
    get_refs_container,
    )

from dulwich.protocol import Protocol
from dulwich.server import (
    Backend,
    BackendRepo,
    ReceivePackHandler,
    UploadPackHandler,
    )


class BzrBackend(Backend):
    """A git serve backend that can use a Bazaar repository."""

    def __init__(self, transport):
        self.transport = transport
        self.mapping = default_mapping

    def open_repository(self, path):
        # FIXME: More secure path sanitization
        transport = self.transport.clone(decode_git_path(path).lstrip("/"))
        trace.mutter('client opens %r: %r', path, transport)
        return BzrBackendRepo(transport, self.mapping)


class BzrBackendRepo(BackendRepo):

    def __init__(self, transport, mapping):
        self.mapping = mapping
        self.repo_dir = ControlDir.open_from_transport(transport)
        self.repo = self.repo_dir.find_repository()
        self.object_store = get_object_store(self.repo)
        self.refs = get_refs_container(self.repo_dir, self.object_store)

    def get_refs(self):
        with self.object_store.lock_read():
            return self.refs.as_dict()

    def get_peeled(self, name):
        cached = self.refs.get_peeled(name)
        if cached is not None:
            return cached
        return self.object_store.peel_sha(self.refs[name]).id

    def fetch_objects(self, determine_wants, graph_walker, progress,
                      get_tagged=None):
        """Yield git objects to send to client """
        with self.object_store.lock_read():
            wants = determine_wants(self.get_refs())
            have = self.object_store.find_common_revisions(graph_walker)
            if wants is None:
                return
            shallows = getattr(graph_walker, 'shallow', frozenset())
            if isinstance(self.object_store, BazaarObjectStore):
                return self.object_store.generate_pack_contents(
                    have, wants, shallow=shallows,
                    progress=progress, get_tagged=get_tagged, lossy=True)
            else:
                if shallows:
                    return self.object_store.generate_pack_contents(
                        have, wants, shallow=shallows, progress=progress)
                else:
                    return self.object_store.generate_pack_contents(
                        have, wants, progress=progress)


class BzrTCPGitServer(TCPGitServer):

    def handle_error(self, request, client_address):
        trace.log_exception_quietly()
        trace.warning('Exception happened during processing of request '
                      'from %s', client_address)


def serve_git(transport, host=None, port=None, inet=False, timeout=None):
    backend = BzrBackend(transport)

    if host is None:
        host = 'localhost'
    if port:
        server = BzrTCPGitServer(backend, host, port)
    else:
        server = BzrTCPGitServer(backend, host)
    server.serve_forever()


def git_http_hook(branch, method, path):
    from dulwich.web import HTTPGitApplication, HTTPGitRequest, DEFAULT_HANDLERS
    handler = None
    for (smethod, spath) in HTTPGitApplication.services:
        if smethod != method:
            continue
        mat = spath.search(path)
        if mat:
            handler = HTTPGitApplication.services[smethod, spath]
            break
    if handler is None:
        return None
    backend = BzrBackend(branch.user_transport)

    def git_call(environ, start_response):
        req = HTTPGitRequest(environ, start_response, dumb=False,
                             handlers=DEFAULT_HANDLERS)
        return handler(req, backend, mat)
    return git_call


def serve_command(handler_cls, backend, inf=sys.stdin, outf=sys.stdout):
    """Serve a single command.

    This is mostly useful for the implementation of commands used by e.g. git+ssh.

    :param handler_cls: `Handler` class to use for the request
    :param argv: execv-style command-line arguments. Defaults to sys.argv.
    :param backend: `Backend` to use
    :param inf: File-like object to read from, defaults to standard input.
    :param outf: File-like object to write to, defaults to standard output.
    :return: Exit code for use with sys.exit. 0 on success, 1 on failure.
    """
    def send_fn(data):
        outf.write(data)
        outf.flush()
    proto = Protocol(inf.read, send_fn)
    handler = handler_cls(backend, ["/"], proto)
    # FIXME: Catch exceptions and write a single-line summary to outf.
    handler.handle()
    return 0


def serve_git_receive_pack(transport, host=None, port=None, inet=False):
    if not inet:
        raise errors.CommandError(
            "git-receive-pack only works in inetd mode")
    backend = BzrBackend(transport)
    sys.exit(serve_command(ReceivePackHandler, backend=backend))


def serve_git_upload_pack(transport, host=None, port=None, inet=False):
    if not inet:
        raise errors.CommandError(
            "git-receive-pack only works in inetd mode")
    backend = BzrBackend(transport)
    sys.exit(serve_command(UploadPackHandler, backend=backend))