1
# Copyright (C) 2007-2010 Jelmer Vernooij <jelmer@samba.org>
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.
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.
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
24
from bzrlib.errors import (
32
UninitializableFormat,
34
from bzrlib.transport import (
38
from bzrlib.plugins.git import (
43
from bzrlib.plugins.git.branch import (
47
from bzrlib.plugins.git.dir import (
51
from bzrlib.plugins.git.errors import (
52
GitSmartRemoteNotSupported,
55
from bzrlib.plugins.git.mapping import (
58
from bzrlib.plugins.git.repository import (
61
from bzrlib.plugins.git.refs import (
68
from dulwich.errors import (
71
from dulwich.pack import (
79
urlparse.uses_netloc.extend(['git', 'git+ssh'])
81
from dulwich.pack import load_pack_index
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():
90
def split_git_url(url):
94
:return: Tuple with host, port, username, path.
96
(scheme, netloc, loc, _, _) = urlparse.urlsplit(url)
97
path = urllib.unquote(loc)
98
if path.startswith("/~"):
100
(username, hostport) = urllib.splituser(netloc)
101
(host, port) = urllib.splitnport(hostport, None)
102
return (host, port, username, path)
105
def parse_git_error(url, message):
106
"""Parse a remote git server error and return a bzr exception.
108
:param url: URL of the remote repository
109
:param message: Message sent by the remote git server
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)
118
class GitSmartTransport(Transport):
120
def __init__(self, url, _client=None):
121
Transport.__init__(self, url)
122
(self._host, self._port, self._username, self._path) = \
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
129
def external_url(self):
132
def has(self, relpath):
135
def _get_client(self, thin_packs):
136
raise NotImplementedError(self._get_client)
139
return self._path.rsplit(",", 1)[0]
142
raise NoSuchFile(path)
144
def abspath(self, relpath):
145
return urlutils.join(self.base, relpath)
147
def clone(self, offset=None):
148
"""See Transport.clone()."""
152
newurl = urlutils.join(self.base, offset)
154
return self.__class__(newurl, self._client)
157
class TCPGitSmartTransport(GitSmartTransport):
161
def _get_client(self, thin_packs):
162
if self._client is not None:
166
return dulwich.client.TCPGitClient(self._host, self._port,
167
thin_packs=thin_packs, report_activity=self._report_activity)
170
class SSHGitSmartTransport(GitSmartTransport):
175
path = self._path.rsplit(",", 1)[0]
176
if path.startswith("/~/"):
180
def _get_client(self, thin_packs):
181
if self._client is not None:
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')
191
client.alternative_paths["upload-pack"] = upload_pack
192
receive_pack = location_config.get_user_option('git_receive_pack')
194
client.alternative_paths["receive-pack"] = receive_pack
198
class RemoteGitDir(GitDir):
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
209
def fetch_pack(self, determine_wants, graph_walker, pack_data, progress=None):
212
trace.info("git: %s" % text)
213
client = self._get_client(thin_packs=False)
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)
220
def send_pack(self, get_changed_refs, generate_pack_contents):
221
client = self._get_client(thin_packs=False)
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)
228
def destroy_branch(self, name=None):
229
refname = self._get_selected_ref(name)
232
def get_changed_refs(old_refs):
234
if not refname in ret:
235
raise NotBranchError(self.user_url)
236
ret[refname] = "00" * 20
238
self.send_pack(get_changed_refs, lambda have, want: [])
242
return self.control_url
245
def user_transport(self):
246
return self.root_transport
249
def control_url(self):
250
return self.control_transport.base
253
def control_transport(self):
254
return self.root_transport
256
def open_repository(self):
257
return RemoteGitRepository(self, self._lockfiles)
259
def open_branch(self, name=None, unsupported=False,
260
ignore_fallbacks=False):
261
repo = self.open_repository()
262
refname = self._get_selected_ref(name)
263
return RemoteGitBranch(self, repo, refname, self._lockfiles)
265
def open_workingtree(self, recommend_upgrade=False):
266
raise NotLocalUrl(self.transport.base)
269
class EmptyObjectStoreIterator(dict):
271
def iterobjects(self):
275
class TemporaryPackIterator(Pack):
277
def __init__(self, path, resolve_ext_ref):
278
super(TemporaryPackIterator, self).__init__(path)
279
self.resolve_ext_ref = resolve_ext_ref
283
if self._data is None:
284
self._data = PackData(self._data_path)
289
if self._idx is None:
290
if not os.path.exists(self._idx_path):
291
pb = ui.ui_factory.nested_progress_bar()
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)
299
self._idx = load_pack_index(self._idx_path)
303
if self._idx is not None:
305
os.remove(self._idx_path)
306
if self._data is not None:
308
os.remove(self._data_path)
311
class BzrGitHttpClient(dulwich.client.HttpGitClient):
313
def __init__(self, transport, *args, **kwargs):
314
self.transport = transport
315
super(BzrGitHttpClient, self).__init__(transport.external_url(), *args, **kwargs)
317
self._http_perform = getattr(self.transport, "_perform", urllib2.urlopen)
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)
326
class RemoteGitControlDirFormat(GitControlDirFormat):
327
"""The .git directory control format."""
329
supports_workingtrees = False
332
def _known_formats(self):
333
return set([RemoteGitControlDirFormat()])
335
def is_initializable(self):
338
def is_supported(self):
341
def open(self, transport, _found=None):
342
"""Open this directory.
345
# we dont grok readonly - git isn't integrated with transport.
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
357
raise NotBranchError(transport.base)
358
return RemoteGitDir(transport, self, get_client, client_path)
360
def get_format_description(self):
361
return "Remote Git Repository"
363
def initialize_on_transport(self, transport):
364
raise UninitializableFormat(self)
366
def supports_transport(self, transport):
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:"))
377
class RemoteGitRepository(GitRepository):
379
def __init__(self, gitdir, lockfiles):
380
GitRepository.__init__(self, gitdir, lockfiles)
385
return self.bzrdir.base
389
return self.control_url
391
def get_parent_map(self, revids):
392
raise GitSmartRemoteNotSupported(self.get_parent_map, self)
395
if self._refs is not None:
397
self._refs = self.bzrdir.fetch_pack(lambda x: [], None,
398
lambda x: None, lambda x: trace.mutter("git: %s" % x))
401
def fetch_pack(self, determine_wants, graph_walker, pack_data,
403
return self.bzrdir.fetch_pack(determine_wants, graph_walker,
406
def send_pack(self, get_changed_refs, generate_pack_contents):
407
return self.bzrdir.send_pack(get_changed_refs, generate_pack_contents)
409
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
411
fd, path = tempfile.mkstemp(suffix=".pack")
413
self.fetch_pack(determine_wants, graph_walker,
414
lambda x: os.write(fd, x), progress)
417
if os.path.getsize(path) == 0:
418
return EmptyObjectStoreIterator()
419
return TemporaryPackIterator(path[:-len(".pack")], resolve_ext_ref)
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..
424
return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
425
except InvalidRevisionId:
426
raise NoSuchRevision(self, bzr_revid)
428
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
429
"""Lookup a revision id.
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)
438
class RemoteGitTagDict(GitTags):
441
return self.repository.get_refs()
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))
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)
453
class RemoteGitBranch(GitBranch):
455
def __init__(self, bzrdir, repository, name, lockfiles):
457
super(RemoteGitBranch, self).__init__(bzrdir, repository, name,
460
def last_revision_info(self):
461
raise GitSmartRemoteNotSupported(self.last_revision_info, self)
465
return self.control_url
468
def control_url(self):
471
def revision_history(self):
472
raise GitSmartRemoteNotSupported(self.last_revision_info, self)
474
def last_revision(self):
475
return self.lookup_foreign_revision_id(self.head)
479
if self._sha is not None:
481
refs = self.repository.get_refs()
482
name = branch_name_to_ref(self.name, "HEAD")
484
self._sha = refs[name]
486
raise NoSuchRef(name, self.repository.user_url, refs)
489
def _synchronize_history(self, destination, revision_id):
490
"""See Branch._synchronize_history()."""
491
destination.generate_revision_history(self.last_revision())
493
def get_push_location(self):
496
def set_push_location(self, url):