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

Support the git smart server http protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007-2010 Jelmer Vernooij <jelmer@samba.org>
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from bzrlib import (
 
18
    config,
 
19
    debug,
 
20
    trace,
 
21
    ui,
 
22
    urlutils,
 
23
    )
 
24
from bzrlib.errors import (
 
25
    BzrError,
 
26
    InvalidRevisionId,
 
27
    NoSuchFile,
 
28
    NoSuchRevision,
 
29
    NotBranchError,
 
30
    NotLocalUrl,
 
31
    UninitializableFormat,
 
32
    )
 
33
from bzrlib.transport import (
 
34
    Transport,
 
35
    )
 
36
 
 
37
from bzrlib.plugins.git import (
 
38
    lazy_check_versions,
 
39
    )
 
40
lazy_check_versions()
 
41
 
 
42
from bzrlib.plugins.git.branch import (
 
43
    GitBranch,
 
44
    GitTags,
 
45
    )
 
46
from bzrlib.plugins.git.dir import (
 
47
    GitControlDirFormat,
 
48
    GitDir,
 
49
    GitLockableFiles,
 
50
    GitLock,
 
51
    )
 
52
from bzrlib.plugins.git.errors import (
 
53
    GitSmartRemoteNotSupported,
 
54
    NoSuchRef,
 
55
    )
 
56
from bzrlib.plugins.git.mapping import (
 
57
    mapping_registry,
 
58
    )
 
59
from bzrlib.plugins.git.repository import (
 
60
    GitRepository,
 
61
    )
 
62
from bzrlib.plugins.git.refs import (
 
63
    extract_tags,
 
64
    branch_name_to_ref,
 
65
    )
 
66
 
 
67
import dulwich
 
68
import dulwich.client
 
69
from dulwich.errors import (
 
70
    GitProtocolError,
 
71
    )
 
72
from dulwich.pack import (
 
73
    Pack,
 
74
    PackData,
 
75
    )
 
76
import os
 
77
import tempfile
 
78
import urllib
 
79
import urlparse
 
80
urlparse.uses_netloc.extend(['git', 'git+ssh'])
 
81
 
 
82
from dulwich.pack import load_pack_index
 
83
 
 
84
 
 
85
# Don't run any tests on GitSmartTransport as it is not intended to be
 
86
# a full implementation of Transport
 
87
def get_test_permutations():
 
88
    return []
 
89
 
 
90
 
 
91
def split_git_url(url):
 
92
    """Split a Git URL.
 
93
 
 
94
    :param url: Git URL
 
95
    :return: Tuple with host, port, username, path.
 
96
    """
 
97
    (scheme, netloc, loc, _, _) = urlparse.urlsplit(url)
 
98
    path = urllib.unquote(loc)
 
99
    if path.startswith("/~"):
 
100
        path = path[1:]
 
101
    (username, hostport) = urllib.splituser(netloc)
 
102
    (host, port) = urllib.splitnport(hostport, None)
 
103
    return (host, port, username, path)
 
104
 
 
105
 
 
106
def parse_git_error(url, message):
 
107
    """Parse a remote git server error and return a bzr exception.
 
108
 
 
109
    :param url: URL of the remote repository
 
110
    :param message: Message sent by the remote git server
 
111
    """
 
112
    message = str(message).strip()
 
113
    if message.startswith("Could not find Repository "):
 
114
        return NotBranchError(url, message)
 
115
    # Don't know, just return it to the user as-is
 
116
    return BzrError(message)
 
117
 
 
118
 
 
119
class GitSmartTransport(Transport):
 
120
 
 
121
    def __init__(self, url, _client=None):
 
122
        Transport.__init__(self, url)
 
123
        (self._host, self._port, self._username, self._path) = \
 
124
            split_git_url(url)
 
125
        if 'transport' in debug.debug_flags:
 
126
            trace.mutter('host: %r, user: %r, port: %r, path: %r',
 
127
                         self._host, self._username, self._port, self._path)
 
128
        self._client = _client
 
129
 
 
130
    def external_url(self):
 
131
        return self.base
 
132
 
 
133
    def has(self, relpath):
 
134
        return False
 
135
 
 
136
    def _get_client(self, thin_packs):
 
137
        raise NotImplementedError(self._get_client)
 
138
 
 
139
    def _get_path(self):
 
140
        return urlutils.split_segment_parameters_raw(self._path)[0]
 
141
 
 
142
    def get(self, path):
 
143
        raise NoSuchFile(path)
 
144
 
 
145
    def abspath(self, relpath):
 
146
        return urlutils.join(self.base, relpath)
 
147
 
 
148
    def clone(self, offset=None):
 
149
        """See Transport.clone()."""
 
150
        if offset is None:
 
151
            newurl = self.base
 
152
        else:
 
153
            newurl = urlutils.join(self.base, offset)
 
154
 
 
155
        return self.__class__(newurl, self._client)
 
156
 
 
157
 
 
158
class TCPGitSmartTransport(GitSmartTransport):
 
159
 
 
160
    _scheme = 'git'
 
161
 
 
162
    def _get_client(self, thin_packs):
 
163
        if self._client is not None:
 
164
            ret = self._client
 
165
            self._client = None
 
166
            return ret
 
167
        return dulwich.client.TCPGitClient(self._host, self._port,
 
168
            thin_packs=thin_packs, report_activity=self._report_activity)
 
169
 
 
170
 
 
171
class SSHGitSmartTransport(GitSmartTransport):
 
172
 
 
173
    _scheme = 'git+ssh'
 
174
 
 
175
    def _get_path(self):
 
176
        path = urlutils.split_segment_parameters_raw(self._path)[0]
 
177
        if path.startswith("/~/"):
 
178
            return path[3:]
 
179
        return path
 
180
 
 
181
    def _get_client(self, thin_packs):
 
182
        if self._client is not None:
 
183
            ret = self._client
 
184
            self._client = None
 
185
            return ret
 
186
        location_config = config.LocationConfig(self.base)
 
187
        client = dulwich.client.SSHGitClient(self._host, self._port, self._username,
 
188
            thin_packs=thin_packs, report_activity=self._report_activity)
 
189
        # Set up alternate pack program paths
 
190
        upload_pack = location_config.get_user_option('git_upload_pack')
 
191
        if upload_pack:
 
192
            client.alternative_paths["upload-pack"] = upload_pack
 
193
        receive_pack = location_config.get_user_option('git_receive_pack')
 
194
        if receive_pack:
 
195
            client.alternative_paths["receive-pack"] = receive_pack
 
196
        return client
 
197
 
 
198
 
 
199
class RemoteGitDir(GitDir):
 
200
 
 
201
    def __init__(self, transport, lockfiles, format, get_client, client_path):
 
202
        self._format = format
 
203
        self.root_transport = transport
 
204
        self.transport = transport
 
205
        self._lockfiles = lockfiles
 
206
        self._mode_check_done = None
 
207
        self._get_client = get_client
 
208
        self._client_path = client_path
 
209
 
 
210
    def fetch_pack(self, determine_wants, graph_walker, pack_data, progress=None):
 
211
        if progress is None:
 
212
            def progress(text):
 
213
                trace.info("git: %s" % text)
 
214
        client = self._get_client(thin_packs=False)
 
215
        try:
 
216
            return client.fetch_pack(self._client_path, determine_wants,
 
217
                graph_walker, pack_data, progress)
 
218
        except GitProtocolError, e:
 
219
            raise parse_git_error(self.transport.external_url(), e)
 
220
 
 
221
    def send_pack(self, get_changed_refs, generate_pack_contents):
 
222
        client = self._get_client(thin_packs=False)
 
223
        try:
 
224
            return client.send_pack(self._client_path, get_changed_refs,
 
225
                generate_pack_contents)
 
226
        except GitProtocolError, e:
 
227
            raise parse_git_error(self.transport.external_url(), e)
 
228
 
 
229
    @property
 
230
    def user_url(self):
 
231
        return self.control_url
 
232
 
 
233
    @property
 
234
    def user_transport(self):
 
235
        return self.root_transport
 
236
 
 
237
    def open_repository(self):
 
238
        return RemoteGitRepository(self, self._lockfiles)
 
239
 
 
240
    def open_branch(self, name=None, unsupported=False,
 
241
            ignore_fallbacks=False):
 
242
        repo = self.open_repository()
 
243
        refname = self._get_selected_ref(name)
 
244
        return RemoteGitBranch(self, repo, refname, self._lockfiles)
 
245
 
 
246
    def open_workingtree(self, recommend_upgrade=False):
 
247
        raise NotLocalUrl(self.transport.base)
 
248
 
 
249
 
 
250
class EmptyObjectStoreIterator(dict):
 
251
 
 
252
    def iterobjects(self):
 
253
        return []
 
254
 
 
255
 
 
256
class TemporaryPackIterator(Pack):
 
257
 
 
258
    def __init__(self, path, resolve_ext_ref):
 
259
        super(TemporaryPackIterator, self).__init__(path)
 
260
        self.resolve_ext_ref = resolve_ext_ref
 
261
 
 
262
    @property
 
263
    def data(self):
 
264
        if self._data is None:
 
265
            self._data = PackData(self._data_path)
 
266
        return self._data
 
267
 
 
268
    @property
 
269
    def index(self):
 
270
        if self._idx is None:
 
271
            if not os.path.exists(self._idx_path):
 
272
                pb = ui.ui_factory.nested_progress_bar()
 
273
                try:
 
274
                    def report_progress(cur, total):
 
275
                        pb.update("generating index", cur, total)
 
276
                    self.data.create_index(self._idx_path, 
 
277
                        progress=report_progress)
 
278
                finally:
 
279
                    pb.finished()
 
280
            self._idx = load_pack_index(self._idx_path)
 
281
        return self._idx
 
282
 
 
283
    def __del__(self):
 
284
        if self._idx is not None:
 
285
            self._idx.close()
 
286
            os.remove(self._idx_path)
 
287
        if self._data is not None:
 
288
            self._data.close()
 
289
            os.remove(self._data_path)
 
290
 
 
291
 
 
292
class RemoteGitControlDirFormat(GitControlDirFormat):
 
293
    """The .git directory control format."""
 
294
 
 
295
    supports_workingtrees = False
 
296
 
 
297
    @classmethod
 
298
    def _known_formats(self):
 
299
        return set([RemoteGitControlDirFormat()])
 
300
 
 
301
    def open(self, transport, _found=None):
 
302
        """Open this directory.
 
303
 
 
304
        """
 
305
        # we dont grok readonly - git isn't integrated with transport.
 
306
        url = transport.base
 
307
        if url.startswith('readonly+'):
 
308
            url = url[len('readonly+'):]
 
309
        if isinstance(transport, GitSmartTransport):
 
310
            get_client = transport._get_client
 
311
            client_path = transport._get_path()
 
312
        elif urlparse.urlsplit(transport.external_url())[0] in ("http", "https"):
 
313
            def get_client(thin_packs=False):
 
314
                return dulwich.client.HttpGitClient(transport._host, transport._port,
 
315
                    transport._user, transport._password, thin_packs=thin_packs)
 
316
            client_path = transport._path
 
317
        else:
 
318
            raise NotBranchError(transport.base)
 
319
        lockfiles = GitLockableFiles(transport, GitLock())
 
320
        return RemoteGitDir(transport, lockfiles, self, get_client, client_path)
 
321
 
 
322
    def get_format_description(self):
 
323
        return "Remote Git Repository"
 
324
 
 
325
    def initialize_on_transport(self, transport):
 
326
        raise UninitializableFormat(self)
 
327
 
 
328
 
 
329
class RemoteGitRepository(GitRepository):
 
330
 
 
331
    def __init__(self, gitdir, lockfiles):
 
332
        GitRepository.__init__(self, gitdir, lockfiles)
 
333
        self._refs = None
 
334
 
 
335
    @property
 
336
    def user_url(self):
 
337
        return self.control_url
 
338
 
 
339
    def get_parent_map(self, revids):
 
340
        raise GitSmartRemoteNotSupported()
 
341
 
 
342
    def get_refs(self):
 
343
        if self._refs is not None:
 
344
            return self._refs
 
345
        self._refs = self.bzrdir.fetch_pack(lambda x: [], None,
 
346
            lambda x: None, lambda x: trace.mutter("git: %s" % x))
 
347
        return self._refs
 
348
 
 
349
    def fetch_pack(self, determine_wants, graph_walker, pack_data,
 
350
                   progress=None):
 
351
        return self.bzrdir.fetch_pack(determine_wants, graph_walker,
 
352
                                          pack_data, progress)
 
353
 
 
354
    def send_pack(self, get_changed_refs, generate_pack_contents):
 
355
        return self.bzrdir.send_pack(get_changed_refs, generate_pack_contents)
 
356
 
 
357
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
 
358
                      progress=None):
 
359
        fd, path = tempfile.mkstemp(suffix=".pack")
 
360
        try:
 
361
            self.fetch_pack(determine_wants, graph_walker,
 
362
                lambda x: os.write(fd, x), progress)
 
363
        finally:
 
364
            os.close(fd)
 
365
        if os.path.getsize(path) == 0:
 
366
            return EmptyObjectStoreIterator()
 
367
        return TemporaryPackIterator(path[:-len(".pack")], resolve_ext_ref)
 
368
 
 
369
    def lookup_bzr_revision_id(self, bzr_revid):
 
370
        # This won't work for any round-tripped bzr revisions, but it's a start..
 
371
        try:
 
372
            return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
 
373
        except InvalidRevisionId:
 
374
            raise NoSuchRevision(self, bzr_revid)
 
375
 
 
376
    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
 
377
        """Lookup a revision id.
 
378
 
 
379
        """
 
380
        if mapping is None:
 
381
            mapping = self.get_mapping()
 
382
        # Not really an easy way to parse foreign revids here..
 
383
        return mapping.revision_id_foreign_to_bzr(foreign_revid)
 
384
 
 
385
 
 
386
class RemoteGitTagDict(GitTags):
 
387
 
 
388
    def get_refs(self):
 
389
        return self.repository.get_refs()
 
390
 
 
391
    def _iter_tag_refs(self, refs):
 
392
        for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
 
393
            yield (k, peeled, unpeeled,
 
394
                  self.branch.mapping.revision_id_foreign_to_bzr(peeled))
 
395
 
 
396
    def set_tag(self, name, revid):
 
397
        # FIXME: Not supported yet, should do a push of a new ref
 
398
        raise NotImplementedError(self.set_tag)
 
399
 
 
400
 
 
401
class RemoteGitBranch(GitBranch):
 
402
 
 
403
    def __init__(self, bzrdir, repository, name, lockfiles):
 
404
        self._sha = None
 
405
        super(RemoteGitBranch, self).__init__(bzrdir, repository, name,
 
406
                lockfiles)
 
407
 
 
408
    def last_revision_info(self):
 
409
        raise GitSmartRemoteNotSupported()
 
410
 
 
411
    @property
 
412
    def user_url(self):
 
413
        return self.control_url
 
414
 
 
415
    @property
 
416
    def control_url(self):
 
417
        return self.base
 
418
 
 
419
    def revision_history(self):
 
420
        raise GitSmartRemoteNotSupported()
 
421
 
 
422
    def last_revision(self):
 
423
        return self.lookup_foreign_revision_id(self.head)
 
424
 
 
425
    def _get_config(self):
 
426
        class EmptyConfig(object):
 
427
 
 
428
            def _get_configobj(self):
 
429
                return config.ConfigObj()
 
430
 
 
431
        return EmptyConfig()
 
432
 
 
433
    @property
 
434
    def head(self):
 
435
        if self._sha is not None:
 
436
            return self._sha
 
437
        heads = self.repository.get_refs()
 
438
        name = branch_name_to_ref(self.name, "HEAD")
 
439
        if name in heads:
 
440
            self._sha = heads[name]
 
441
        else:
 
442
            raise NoSuchRef(self.name)
 
443
        return self._sha
 
444
 
 
445
    def _synchronize_history(self, destination, revision_id):
 
446
        """See Branch._synchronize_history()."""
 
447
        destination.generate_revision_history(self.last_revision())
 
448
 
 
449
    def get_push_location(self):
 
450
        return None
 
451
 
 
452
    def set_push_location(self, url):
 
453
        pass