1 # client.py -- Implementation of the server side git protocols
2 # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
3 # Copyright (C) 2008 John Carr
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # or (at your option) a later version of the License.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 """Client side support for the Git protocol."""
22 __docformat__ = 'restructuredText'
28 from dulwich.errors import (
32 from dulwich.protocol import (
38 from dulwich.pack import (
43 def _fileno_can_read(fileno):
44 """Check if a file descriptor is readable."""
45 return len(select.select([fileno], [], [], 0)[0]) > 0
47 COMMON_CAPABILITIES = ["ofs-delta"]
48 FETCH_CAPABILITIES = ["multi_ack", "side-band-64k"] + COMMON_CAPABILITIES
49 SEND_CAPABILITIES = ['report-status'] + COMMON_CAPABILITIES
51 # TODO(durin42): this doesn't correctly degrade if the server doesn't
52 # support some capabilities. This should work properly with servers
53 # that don't support side-band-64k and multi_ack.
54 class GitClient(object):
55 """Git smart server client.
59 def __init__(self, thin_packs=True, report_activity=None):
60 """Create a new GitClient instance.
62 :param thin_packs: Whether or not thin packs should be retrieved
63 :param report_activity: Optional callback for reporting transport
66 self._report_activity = report_activity
67 self._fetch_capabilities = list(FETCH_CAPABILITIES)
68 self._send_capabilities = list(SEND_CAPABILITIES)
70 self._fetch_capabilities.append("thin-pack")
72 def _connect(self, cmd, path):
73 """Create a connection to the server.
75 This method is abstract - concrete implementations should
76 implement their own variant which connects to the server and
77 returns an initialized Protocol object with the service ready
78 for use and a can_read function which may be used to see if
81 :param cmd: The git service name to which we should connect.
82 :param path: The path we should pass to the service.
84 raise NotImplementedError()
86 def read_refs(self, proto):
87 server_capabilities = None
89 # Receive refs from server
90 for pkt in proto.read_pkt_seq():
91 (sha, ref) = pkt.rstrip("\n").split(" ", 1)
92 if server_capabilities is None:
93 (ref, server_capabilities) = extract_capabilities(ref)
95 return refs, server_capabilities
97 def _parse_status_report(self, proto):
98 unpack = proto.read_pkt_line().strip()
99 if unpack != 'unpack ok':
101 # flush remaining error data
102 while st is not None:
103 st = proto.read_pkt_line()
104 raise SendPackError(unpack)
107 ref_status = proto.read_pkt_line()
109 ref_status = ref_status.strip()
110 statuses.append(ref_status)
111 if not ref_status.startswith('ok '):
113 ref_status = proto.read_pkt_line()
118 for status in statuses:
119 if ' ' not in status:
120 # malformed response, move on to the next one
122 status, ref = status.split(' ', 1)
126 ref, status = ref.split(' ', 1)
129 ref_status[ref] = status
130 raise UpdateRefsError('%s failed to update' %
131 ', '.join([ref for ref in ref_status
133 ref_status=ref_status)
136 # TODO(durin42): add side-band-64k capability support here and advertise it
137 def send_pack(self, path, determine_wants, generate_pack_contents):
138 """Upload a pack to a remote repository.
140 :param path: Repository path
141 :param generate_pack_contents: Function that can return the shas of the
144 :raises SendPackError: if server rejects the pack data
145 :raises UpdateRefsError: if the server supports report-status
146 and rejects ref updates
148 proto, unused_can_read = self._connect('receive-pack', path)
149 old_refs, server_capabilities = self.read_refs(proto)
150 if 'report-status' not in server_capabilities:
151 self._send_capabilities.remove('report-status')
152 new_refs = determine_wants(old_refs)
154 proto.write_pkt_line(None)
157 have = [x for x in old_refs.values() if not x == ZERO_SHA]
158 sent_capabilities = False
159 for refname in set(new_refs.keys() + old_refs.keys()):
160 old_sha1 = old_refs.get(refname, ZERO_SHA)
161 new_sha1 = new_refs.get(refname, ZERO_SHA)
162 if old_sha1 != new_sha1:
163 if sent_capabilities:
164 proto.write_pkt_line("%s %s %s" % (old_sha1, new_sha1,
167 proto.write_pkt_line(
168 "%s %s %s\0%s" % (old_sha1, new_sha1, refname,
169 ' '.join(self._send_capabilities)))
170 sent_capabilities = True
171 if new_sha1 not in have and new_sha1 != ZERO_SHA:
172 want.append(new_sha1)
173 proto.write_pkt_line(None)
176 objects = generate_pack_contents(have, want)
177 entries, sha = write_pack_data(proto.write_file(), objects,
180 if 'report-status' in self._send_capabilities:
181 self._parse_status_report(proto)
182 # wait for EOF before returning
185 raise SendPackError('Unexpected response %r' % data)
188 def fetch(self, path, target, determine_wants=None, progress=None):
189 """Fetch into a target repository.
191 :param path: Path to fetch from
192 :param target: Target repository to fetch into
193 :param determine_wants: Optional function to determine what refs
195 :param progress: Optional progress function
198 if determine_wants is None:
199 determine_wants = target.object_store.determine_wants_all
200 f, commit = target.object_store.add_pack()
202 return self.fetch_pack(path, determine_wants,
203 target.get_graph_walker(), f.write, progress)
207 def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
209 """Retrieve a pack from a git smart server.
211 :param determine_wants: Callback that returns list of commits to fetch
212 :param graph_walker: Object with next() and ack().
213 :param pack_data: Callback called for each bit of data in the pack
214 :param progress: Callback for progress reports (strings)
216 proto, can_read = self._connect('upload-pack', path)
217 (refs, server_capabilities) = self.read_refs(proto)
218 wants = determine_wants(refs)
220 proto.write_pkt_line(None)
222 assert isinstance(wants, list) and type(wants[0]) == str
223 proto.write_pkt_line("want %s %s\n" % (
224 wants[0], ' '.join(self._fetch_capabilities)))
225 for want in wants[1:]:
226 proto.write_pkt_line("want %s\n" % want)
227 proto.write_pkt_line(None)
228 have = graph_walker.next()
230 proto.write_pkt_line("have %s\n" % have)
232 pkt = proto.read_pkt_line()
233 parts = pkt.rstrip("\n").split(" ")
234 if parts[0] == "ACK":
235 graph_walker.ack(parts[1])
236 assert parts[2] == "continue"
237 have = graph_walker.next()
238 proto.write_pkt_line("done\n")
239 pkt = proto.read_pkt_line()
241 parts = pkt.rstrip("\n").split(" ")
242 if parts[0] == "ACK":
243 graph_walker.ack(pkt.split(" ")[1])
244 if len(parts) < 3 or parts[2] != "continue":
246 pkt = proto.read_pkt_line()
247 # TODO(durin42): this is broken if the server didn't support the
248 # side-band-64k capability.
249 for pkt in proto.read_pkt_seq():
250 channel = ord(pkt[0])
255 if progress is not None:
258 raise AssertionError("Invalid sideband channel %d" % channel)
263 """Check if a file descriptor is readable.
265 :args f: either the number of the file descriptor or a file-like
266 object which returns the fileno when f.fileno() is called.
268 return len(select.select([f], [], [], 0)[0]) > 0
271 class TCPGitClient(GitClient):
272 """A Git Client that works over TCP directly (i.e. git://)."""
274 def __init__(self, host, port=None, *args, **kwargs):
279 GitClient.__init__(self, *args, **kwargs)
281 def _connect(self, cmd, path):
282 s = socket.socket(type=socket.SOCK_STREAM)
283 s.connect((self._host, self._port))
284 # -1 means system default buffering
285 rfile = s.makefile('rb', -1)
287 wfile = s.makefile('wb', 0)
288 proto = Protocol(rfile.read, wfile.write,
289 report_activity=self._report_activity)
290 proto.send_cmd('git-%s' % cmd, path, 'host=%s' % self._host)
291 return proto, lambda: can_read(s)
294 class SubprocessWrapper(object):
295 """A socket-like object that talks to a subprocess via pipes."""
297 def __init__(self, proc):
299 self.read = proc.stdout.read
300 self.write = proc.stdin.write
303 return can_read(self.proc.stdout.fileno())
306 self.proc.stdin.close()
307 self.proc.stdout.close()
311 class SubprocessGitClient(GitClient):
312 """Git client that talks to a server using a subprocess."""
314 def __init__(self, *args, **kwargs):
315 self._connection = None
316 GitClient.__init__(self, *args, **kwargs)
318 def _connect(self, service, path):
319 argv = ['git', service, path]
320 p = SubprocessWrapper(
321 subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
322 stdout=subprocess.PIPE))
323 return Protocol(p.read, p.write,
324 report_activity=self._report_activity), p.can_read
326 class SSHVendor(object):
328 def connect_ssh(self, host, command, username=None, port=None):
329 #FIXME: This has no way to deal with passwords..
332 args.extend(['-p', str(port)])
333 if username is not None:
334 host = "%s@%s" % (username, host)
336 proc = subprocess.Popen(args + command,
337 stdin=subprocess.PIPE,
338 stdout=subprocess.PIPE)
339 return SubprocessWrapper(proc)
341 # Can be overridden by users
342 get_ssh_vendor = SSHVendor
345 class SSHGitClient(GitClient):
347 def __init__(self, host, port=None, username=None, *args, **kwargs):
350 self.username = username
351 GitClient.__init__(self, *args, **kwargs)
353 def _connect(self, cmd, path):
354 con = get_ssh_vendor().connect_ssh(
355 self.host, ["%s '%s'" % ('git-' + cmd, path)],
356 port=self.port, username=self.username)
357 return Protocol(con.read, con.write), con.can_read
360 def get_transport_and_path(uri):
361 """Obtain a git client from a URI or path.
363 :param uri: URI or path
364 :return: Tuple with client instance and relative path.
366 from dulwich.client import TCPGitClient, SSHGitClient, SubprocessGitClient
367 for handler, transport in (("git://", TCPGitClient), ("git+ssh://", SSHGitClient)):
368 if uri.startswith(handler):
369 host, path = uri[len(handler):].split("/", 1)
370 return transport(host), "/"+path
371 # FIXME: Parse rsync-like git URLs (user@host:/path), bug 568493
372 # if its not git or git+ssh, try a local url..
373 return SubprocessGitClient(), uri