/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

Fix space.

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