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 (
31
UninitializableFormat,
33
from bzrlib.transport import (
37
from bzrlib.plugins.git import (
42
from bzrlib.plugins.git.branch import (
46
from bzrlib.plugins.git.dir import (
52
from bzrlib.plugins.git.errors import (
53
GitSmartRemoteNotSupported,
56
from bzrlib.plugins.git.mapping import (
59
from bzrlib.plugins.git.repository import (
62
from bzrlib.plugins.git.refs import (
68
from dulwich.errors import (
71
from dulwich.pack import (
75
from dulwich.protocol import Protocol
80
urlparse.uses_netloc.extend(['git', 'git+ssh'])
82
from dulwich.pack import load_pack_index
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():
91
def split_git_url(url):
95
:return: Tuple with host, port, username, path.
97
(scheme, netloc, loc, _, _) = urlparse.urlsplit(url)
98
path = urllib.unquote(loc)
99
if path.startswith("/~"):
101
(username, hostport) = urllib.splituser(netloc)
102
(host, port) = urllib.splitnport(hostport, None)
103
return (host, port, username, path)
106
class GitSmartTransport(Transport):
108
def __init__(self, url, _client=None):
109
Transport.__init__(self, url)
110
(self._host, self._port, self._username, self._path) = \
112
if 'transport' in debug.debug_flags:
113
trace.mutter('host: %r, user: %r, port: %r, path: %r',
114
self._host, self._username, self._port, self._path)
115
self._client = _client
117
def external_url(self):
120
def has(self, relpath):
123
def _get_client(self, thin_packs):
124
raise NotImplementedError(self._get_client)
129
def fetch_pack(self, determine_wants, graph_walker, pack_data, progress=None):
132
trace.info("git: %s" % text)
133
client = self._get_client(thin_packs=False)
135
return client.fetch_pack(self._get_path(), determine_wants,
136
graph_walker, pack_data, progress)
137
except GitProtocolError, e:
140
def send_pack(self, get_changed_refs, generate_pack_contents):
141
client = self._get_client(thin_packs=False)
143
return client.send_pack(self._get_path(), get_changed_refs,
144
generate_pack_contents)
145
except GitProtocolError, e:
149
raise NoSuchFile(path)
151
def abspath(self, relpath):
152
return urlutils.join(self.base, relpath)
154
def clone(self, offset=None):
155
"""See Transport.clone()."""
159
newurl = urlutils.join(self.base, offset)
161
return self.__class__(newurl, self._client)
164
class TCPGitSmartTransport(GitSmartTransport):
168
def _get_client(self, thin_packs):
169
if self._client is not None:
173
return dulwich.client.TCPGitClient(self._host, self._port,
174
thin_packs=thin_packs, report_activity=self._report_activity)
177
class BzrGitSSHGitClient(dulwich.client.SSHGitClient):
179
def __init__(self, *args, **kwargs):
180
super(BzrGitSSHGitClient, self).__init__(*args, **kwargs)
181
self._read_buffer = ""
184
if self._read_buffer != "":
186
self._read_buffer = self._read(1)
187
return (self._read_buffer != "")
189
def _read(self, count):
190
ret = self._read_buffer[:count]
191
self._read_buffer = self._read_buffer[len(ret):]
192
while len(ret) < count:
193
if self._io_kind == "socket":
194
ret += self._io_object.recv(count - len(ret))
196
ret += self._io_object[0].read(count - len(ret))
199
def _write(self, data):
200
if self._io_kind == "socket":
201
self._io_object.send(data)
203
self._io_object[1].write(data)
205
def _connect(self, cmd, path):
206
from bzrlib.transport import ssh as _mod_ssh
207
vendor = _mod_ssh._get_ssh_vendor()
208
self._ssh_connection = vendor.connect_ssh(self.username, None,
209
self.host, self.port, command=[self._get_cmd_path(cmd), path])
210
self._io_kind, self._io_object = self._ssh_connection.get_sock_or_pipes()
211
if self._io_kind not in ("socket", "pipes"):
212
raise AssertionError(
213
"Unexpected io_kind %r from %r"
214
% (self._io_kind, self._ssh_connection))
215
return (Protocol(self._read, self._write,
216
report_activity=self._report_activity), self._can_read)
219
class SSHGitSmartTransport(GitSmartTransport):
224
if self._path.startswith("/~/"):
225
return self._path[3:]
228
def _get_client(self, thin_packs):
229
if self._client is not None:
233
location_config = config.LocationConfig(self.base)
234
client = BzrGitSSHGitClient(self._host, self._port, self._username,
235
thin_packs=thin_packs, report_activity=self._report_activity)
236
# Set up alternate pack program paths
237
upload_pack = location_config.get_user_option('git_upload_pack')
239
client.alternative_paths["upload-pack"] = upload_pack
240
receive_pack = location_config.get_user_option('git_receive_pack')
242
client.alternative_paths["receive-pack"] = receive_pack
246
class RemoteGitDir(GitDir):
248
def __init__(self, transport, lockfiles, format):
249
self._format = format
250
self.root_transport = transport
251
self.transport = transport
252
self._lockfiles = lockfiles
253
self._mode_check_done = None
257
return self.control_url
259
def _branch_name_to_ref(self, name, default=None):
260
return branch_name_to_ref(name, default=default)
262
def open_repository(self):
263
return RemoteGitRepository(self, self._lockfiles)
265
def open_branch(self, name=None, unsupported=False, ignore_fallbacks=False):
266
repo = self.open_repository()
267
refname = self._branch_name_to_ref(name)
268
return RemoteGitBranch(self, repo, refname, self._lockfiles)
270
def open_workingtree(self, recommend_upgrade=False):
271
raise NotLocalUrl(self.transport.base)
274
class EmptyObjectStoreIterator(dict):
276
def iterobjects(self):
280
class TemporaryPackIterator(Pack):
282
def __init__(self, path, resolve_ext_ref):
283
super(TemporaryPackIterator, self).__init__(path)
284
self.resolve_ext_ref = resolve_ext_ref
288
if self._data is None:
289
self._data = ThinPackData(self.resolve_ext_ref, self._data_path)
294
if self._idx is None:
295
if not os.path.exists(self._idx_path):
296
pb = ui.ui_factory.nested_progress_bar()
298
def report_progress(cur, total):
299
pb.update("generating index", cur, total)
300
self.data.create_index(self._idx_path,
301
progress=report_progress)
304
self._idx = load_pack_index(self._idx_path)
308
if self._idx is not None:
310
os.remove(self._idx_path)
311
if self._data is not None:
313
os.remove(self._data_path)
316
class RemoteGitControlDirFormat(GitControlDirFormat):
317
"""The .git directory control format."""
319
supports_workingtrees = False
322
def _known_formats(self):
323
return set([RemoteGitControlDirFormat()])
325
def open(self, transport, _found=None):
326
"""Open this directory.
329
# we dont grok readonly - git isn't integrated with transport.
331
if url.startswith('readonly+'):
332
url = url[len('readonly+'):]
333
if (not url.startswith("git://") and not url.startswith("git+")):
334
raise NotBranchError(transport.base)
335
if not isinstance(transport, GitSmartTransport):
336
raise NotBranchError(transport.base)
337
lockfiles = GitLockableFiles(transport, GitLock())
338
return RemoteGitDir(transport, lockfiles, self)
340
def get_format_description(self):
341
return "Remote Git Repository"
343
def initialize_on_transport(self, transport):
344
raise UninitializableFormat(self)
347
class RemoteGitRepository(GitRepository):
349
def __init__(self, gitdir, lockfiles):
350
GitRepository.__init__(self, gitdir, lockfiles)
355
return self.control_url
358
def inventories(self):
359
raise GitSmartRemoteNotSupported()
363
raise GitSmartRemoteNotSupported()
367
raise GitSmartRemoteNotSupported()
370
if self._refs is not None:
372
self._refs = self.bzrdir.root_transport.fetch_pack(lambda x: [], None,
373
lambda x: None, lambda x: trace.mutter("git: %s" % x))
376
def fetch_pack(self, determine_wants, graph_walker, pack_data,
378
return self._transport.fetch_pack(determine_wants, graph_walker,
381
def send_pack(self, get_changed_refs, generate_pack_contents):
382
return self._transport.send_pack(get_changed_refs, generate_pack_contents)
384
def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
386
fd, path = tempfile.mkstemp(suffix=".pack")
387
self.fetch_pack(determine_wants, graph_walker,
388
lambda x: os.write(fd, x), progress)
390
if os.path.getsize(path) == 0:
391
return EmptyObjectStoreIterator()
392
return TemporaryPackIterator(path[:-len(".pack")], resolve_ext_ref)
394
def lookup_bzr_revision_id(self, bzr_revid):
395
# This won't work for any round-tripped bzr revisions, but it's a start..
397
return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
398
except InvalidRevisionId:
399
raise NoSuchRevision(self, bzr_revid)
401
def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
402
"""Lookup a revision id.
406
mapping = self.get_mapping()
407
# Not really an easy way to parse foreign revids here..
408
return mapping.revision_id_foreign_to_bzr(foreign_revid)
411
class RemoteGitTagDict(GitTags):
414
return self.repository.get_refs()
416
def _iter_tag_refs(self, refs):
417
for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
418
yield (k, peeled, unpeeled,
419
self.branch.mapping.revision_id_foreign_to_bzr(peeled))
421
def set_tag(self, name, revid):
422
# FIXME: Not supported yet, should do a push of a new ref
423
raise NotImplementedError(self.set_tag)
426
class RemoteGitBranch(GitBranch):
428
def __init__(self, bzrdir, repository, name, lockfiles):
430
super(RemoteGitBranch, self).__init__(bzrdir, repository, name,
435
return self.control_url
438
def control_url(self):
441
def revision_history(self):
442
raise GitSmartRemoteNotSupported()
444
def last_revision(self):
445
return self.lookup_foreign_revision_id(self.head)
447
def _get_config(self):
448
class EmptyConfig(object):
450
def _get_configobj(self):
451
return config.ConfigObj()
457
if self._sha is not None:
459
heads = self.repository.get_refs()
460
name = self.bzrdir._branch_name_to_ref(self.name, "HEAD")
462
self._sha = heads[name]
464
raise NoSuchRef(self.name)
467
def _synchronize_history(self, destination, revision_id):
468
"""See Branch._synchronize_history()."""
469
destination.generate_revision_history(self.last_revision())
471
def get_push_location(self):
474
def set_push_location(self, url):