client.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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
  4. #
  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.
  9. #
  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.
  14. #
  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,
  18. # MA 02110-1301, USA.
  19. """Client side support for the Git protocol."""
  20. __docformat__ = 'restructuredText'
  21. from cStringIO import StringIO
  22. import select
  23. import socket
  24. import subprocess
  25. import urllib2
  26. import urlparse
  27. from dulwich.errors import (
  28. GitProtocolError,
  29. SendPackError,
  30. UpdateRefsError,
  31. )
  32. from dulwich.protocol import (
  33. PktLineParser,
  34. Protocol,
  35. TCP_GIT_PORT,
  36. ZERO_SHA,
  37. extract_capabilities,
  38. )
  39. from dulwich.pack import (
  40. write_pack_objects,
  41. )
  42. # Python 2.6.6 included these in urlparse.uses_netloc upstream. Do
  43. # monkeypatching to enable similar behaviour in earlier Pythons:
  44. for scheme in ('git', 'git+ssh'):
  45. if scheme not in urlparse.uses_netloc:
  46. urlparse.uses_netloc.append(scheme)
  47. def _fileno_can_read(fileno):
  48. """Check if a file descriptor is readable."""
  49. return len(select.select([fileno], [], [], 0)[0]) > 0
  50. COMMON_CAPABILITIES = ['ofs-delta', 'side-band-64k']
  51. FETCH_CAPABILITIES = ['multi_ack', 'multi_ack_detailed'] + COMMON_CAPABILITIES
  52. SEND_CAPABILITIES = ['report-status'] + COMMON_CAPABILITIES
  53. class ReportStatusParser(object):
  54. """Handle status as reported by servers with the 'report-status' capability.
  55. """
  56. def __init__(self):
  57. self._done = False
  58. self._pack_status = None
  59. self._ref_status_ok = True
  60. self._ref_statuses = []
  61. def check(self):
  62. """Check if there were any errors and, if so, raise exceptions.
  63. :raise SendPackError: Raised when the server could not unpack
  64. :raise UpdateRefsError: Raised when refs could not be updated
  65. """
  66. if self._pack_status not in ('unpack ok', None):
  67. raise SendPackError(self._pack_status)
  68. if not self._ref_status_ok:
  69. ref_status = {}
  70. ok = set()
  71. for status in self._ref_statuses:
  72. if ' ' not in status:
  73. # malformed response, move on to the next one
  74. continue
  75. status, ref = status.split(' ', 1)
  76. if status == 'ng':
  77. if ' ' in ref:
  78. ref, status = ref.split(' ', 1)
  79. else:
  80. ok.add(ref)
  81. ref_status[ref] = status
  82. raise UpdateRefsError('%s failed to update' %
  83. ', '.join([ref for ref in ref_status
  84. if ref not in ok]),
  85. ref_status=ref_status)
  86. def handle_packet(self, pkt):
  87. """Handle a packet.
  88. :raise GitProtocolError: Raised when packets are received after a
  89. flush packet.
  90. """
  91. if self._done:
  92. raise GitProtocolError("received more data after status report")
  93. if pkt is None:
  94. self._done = True
  95. return
  96. if self._pack_status is None:
  97. self._pack_status = pkt.strip()
  98. else:
  99. ref_status = pkt.strip()
  100. self._ref_statuses.append(ref_status)
  101. if not ref_status.startswith('ok '):
  102. self._ref_status_ok = False
  103. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  104. # support some capabilities. This should work properly with servers
  105. # that don't support multi_ack.
  106. class GitClient(object):
  107. """Git smart server client.
  108. """
  109. def __init__(self, thin_packs=True, report_activity=None):
  110. """Create a new GitClient instance.
  111. :param thin_packs: Whether or not thin packs should be retrieved
  112. :param report_activity: Optional callback for reporting transport
  113. activity.
  114. """
  115. self._report_activity = report_activity
  116. self._fetch_capabilities = list(FETCH_CAPABILITIES)
  117. self._send_capabilities = list(SEND_CAPABILITIES)
  118. if thin_packs:
  119. self._fetch_capabilities.append('thin-pack')
  120. def _read_refs(self, proto):
  121. server_capabilities = None
  122. refs = {}
  123. # Receive refs from server
  124. for pkt in proto.read_pkt_seq():
  125. (sha, ref) = pkt.rstrip('\n').split(' ', 1)
  126. if sha == 'ERR':
  127. raise GitProtocolError(ref)
  128. if server_capabilities is None:
  129. (ref, server_capabilities) = extract_capabilities(ref)
  130. refs[ref] = sha
  131. return refs, server_capabilities
  132. def send_pack(self, path, determine_wants, generate_pack_contents,
  133. progress=None):
  134. """Upload a pack to a remote repository.
  135. :param path: Repository path
  136. :param generate_pack_contents: Function that can return a sequence of the
  137. shas of the objects to upload.
  138. :param progress: Optional progress function
  139. :raises SendPackError: if server rejects the pack data
  140. :raises UpdateRefsError: if the server supports report-status
  141. and rejects ref updates
  142. """
  143. raise NotImplementedError(self.send_pack)
  144. def fetch(self, path, target, determine_wants=None, progress=None):
  145. """Fetch into a target repository.
  146. :param path: Path to fetch from
  147. :param target: Target repository to fetch into
  148. :param determine_wants: Optional function to determine what refs
  149. to fetch
  150. :param progress: Optional progress function
  151. :return: remote refs
  152. """
  153. if determine_wants is None:
  154. determine_wants = target.object_store.determine_wants_all
  155. f, commit = target.object_store.add_pack()
  156. try:
  157. return self.fetch_pack(path, determine_wants,
  158. target.get_graph_walker(), f.write, progress)
  159. finally:
  160. commit()
  161. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  162. progress):
  163. """Retrieve a pack from a git smart server.
  164. :param determine_wants: Callback that returns list of commits to fetch
  165. :param graph_walker: Object with next() and ack().
  166. :param pack_data: Callback called for each bit of data in the pack
  167. :param progress: Callback for progress reports (strings)
  168. """
  169. raise NotImplementedError(self.fetch_pack)
  170. def _parse_status_report(self, proto):
  171. unpack = proto.read_pkt_line().strip()
  172. if unpack != 'unpack ok':
  173. st = True
  174. # flush remaining error data
  175. while st is not None:
  176. st = proto.read_pkt_line()
  177. raise SendPackError(unpack)
  178. statuses = []
  179. errs = False
  180. ref_status = proto.read_pkt_line()
  181. while ref_status:
  182. ref_status = ref_status.strip()
  183. statuses.append(ref_status)
  184. if not ref_status.startswith('ok '):
  185. errs = True
  186. ref_status = proto.read_pkt_line()
  187. if errs:
  188. ref_status = {}
  189. ok = set()
  190. for status in statuses:
  191. if ' ' not in status:
  192. # malformed response, move on to the next one
  193. continue
  194. status, ref = status.split(' ', 1)
  195. if status == 'ng':
  196. if ' ' in ref:
  197. ref, status = ref.split(' ', 1)
  198. else:
  199. ok.add(ref)
  200. ref_status[ref] = status
  201. raise UpdateRefsError('%s failed to update' %
  202. ', '.join([ref for ref in ref_status
  203. if ref not in ok]),
  204. ref_status=ref_status)
  205. def _read_side_band64k_data(self, proto, channel_callbacks):
  206. """Read per-channel data.
  207. This requires the side-band-64k capability.
  208. :param proto: Protocol object to read from
  209. :param channel_callbacks: Dictionary mapping channels to packet
  210. handlers to use. None for a callback discards channel data.
  211. """
  212. for pkt in proto.read_pkt_seq():
  213. channel = ord(pkt[0])
  214. pkt = pkt[1:]
  215. try:
  216. cb = channel_callbacks[channel]
  217. except KeyError:
  218. raise AssertionError('Invalid sideband channel %d' % channel)
  219. else:
  220. if cb is not None:
  221. cb(pkt)
  222. def _handle_receive_pack_head(self, proto, capabilities, old_refs, new_refs):
  223. """Handle the head of a 'git-receive-pack' request.
  224. :param proto: Protocol object to read from
  225. :param capabilities: List of negotiated capabilities
  226. :param old_refs: Old refs, as received from the server
  227. :param new_refs: New refs
  228. :return: (have, want) tuple
  229. """
  230. want = []
  231. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  232. sent_capabilities = False
  233. for refname in set(new_refs.keys() + old_refs.keys()):
  234. old_sha1 = old_refs.get(refname, ZERO_SHA)
  235. new_sha1 = new_refs.get(refname, ZERO_SHA)
  236. if old_sha1 != new_sha1:
  237. if sent_capabilities:
  238. proto.write_pkt_line('%s %s %s' % (old_sha1, new_sha1,
  239. refname))
  240. else:
  241. proto.write_pkt_line(
  242. '%s %s %s\0%s' % (old_sha1, new_sha1, refname,
  243. ' '.join(capabilities)))
  244. sent_capabilities = True
  245. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  246. want.append(new_sha1)
  247. proto.write_pkt_line(None)
  248. return (have, want)
  249. def _handle_receive_pack_tail(self, proto, capabilities, progress):
  250. """Handle the tail of a 'git-receive-pack' request.
  251. :param proto: Protocol object to read from
  252. :param capabilities: List of negotiated capabilities
  253. :param progress: Optional progress reporting function
  254. """
  255. if 'report-status' in capabilities:
  256. report_status_parser = ReportStatusParser()
  257. else:
  258. report_status_parser = None
  259. if "side-band-64k" in capabilities:
  260. channel_callbacks = { 2: progress }
  261. if 'report-status' in capabilities:
  262. channel_callbacks[1] = PktLineParser(
  263. report_status_parser.handle_packet).parse
  264. self._read_side_band64k_data(proto, channel_callbacks)
  265. else:
  266. if 'report-status':
  267. for pkt in proto.read_pkt_seq():
  268. report_status_parser.handle_packet(pkt)
  269. if report_status_parser is not None:
  270. report_status_parser.check()
  271. # wait for EOF before returning
  272. data = proto.read()
  273. if data:
  274. raise SendPackError('Unexpected response %r' % data)
  275. def _handle_upload_pack_head(self, proto, capabilities, graph_walker,
  276. wants, can_read):
  277. """Handle the head of a 'git-upload-pack' request.
  278. :param proto: Protocol object to read from
  279. :param capabilities: List of negotiated capabilities
  280. :param graph_walker: GraphWalker instance to call .ack() on
  281. :param wants: List of commits to fetch
  282. :param can_read: function that returns a boolean that indicates
  283. whether there is extra graph data to read on proto
  284. """
  285. assert isinstance(wants, list) and type(wants[0]) == str
  286. proto.write_pkt_line('want %s %s\n' % (
  287. wants[0], ' '.join(capabilities)))
  288. for want in wants[1:]:
  289. proto.write_pkt_line('want %s\n' % want)
  290. proto.write_pkt_line(None)
  291. have = graph_walker.next()
  292. while have:
  293. proto.write_pkt_line('have %s\n' % have)
  294. if can_read():
  295. pkt = proto.read_pkt_line()
  296. parts = pkt.rstrip('\n').split(' ')
  297. if parts[0] == 'ACK':
  298. graph_walker.ack(parts[1])
  299. if parts[2] in ('continue', 'common'):
  300. pass
  301. elif parts[2] == 'ready':
  302. break
  303. else:
  304. raise AssertionError(
  305. "%s not in ('continue', 'ready', 'common)" %
  306. parts[2])
  307. have = graph_walker.next()
  308. proto.write_pkt_line('done\n')
  309. def _handle_upload_pack_tail(self, proto, capabilities, graph_walker,
  310. pack_data, progress):
  311. """Handle the tail of a 'git-upload-pack' request.
  312. :param proto: Protocol object to read from
  313. :param capabilities: List of negotiated capabilities
  314. :param graph_walker: GraphWalker instance to call .ack() on
  315. :param pack_data: Function to call with pack data
  316. :param progress: Optional progress reporting function
  317. """
  318. pkt = proto.read_pkt_line()
  319. while pkt:
  320. parts = pkt.rstrip('\n').split(' ')
  321. if parts[0] == 'ACK':
  322. graph_walker.ack(pkt.split(' ')[1])
  323. if len(parts) < 3 or parts[2] not in ('continue', 'common'):
  324. break
  325. pkt = proto.read_pkt_line()
  326. if "side-band-64k" in capabilities:
  327. self._read_side_band64k_data(proto, {1: pack_data, 2: progress})
  328. # wait for EOF before returning
  329. data = proto.read()
  330. if data:
  331. raise Exception('Unexpected response %r' % data)
  332. else:
  333. # FIXME: Buffering?
  334. pack_data(self.read())
  335. class TraditionalGitClient(GitClient):
  336. """Traditional Git client."""
  337. def _connect(self, cmd, path):
  338. """Create a connection to the server.
  339. This method is abstract - concrete implementations should
  340. implement their own variant which connects to the server and
  341. returns an initialized Protocol object with the service ready
  342. for use and a can_read function which may be used to see if
  343. reads would block.
  344. :param cmd: The git service name to which we should connect.
  345. :param path: The path we should pass to the service.
  346. """
  347. raise NotImplementedError()
  348. def send_pack(self, path, determine_wants, generate_pack_contents,
  349. progress=None):
  350. """Upload a pack to a remote repository.
  351. :param path: Repository path
  352. :param generate_pack_contents: Function that can return a sequence of the
  353. shas of the objects to upload.
  354. :param progress: Optional callback called with progress updates
  355. :raises SendPackError: if server rejects the pack data
  356. :raises UpdateRefsError: if the server supports report-status
  357. and rejects ref updates
  358. """
  359. proto, unused_can_read = self._connect('receive-pack', path)
  360. old_refs, server_capabilities = self._read_refs(proto)
  361. negotiated_capabilities = list(self._send_capabilities)
  362. if 'report-status' not in server_capabilities:
  363. negotiated_capabilities.remove('report-status')
  364. new_refs = determine_wants(old_refs)
  365. if not new_refs:
  366. proto.write_pkt_line(None)
  367. return {}
  368. (have, want) = self._handle_receive_pack_head(proto,
  369. negotiated_capabilities, old_refs, new_refs)
  370. if not want:
  371. return new_refs
  372. objects = generate_pack_contents(have, want)
  373. entries, sha = write_pack_objects(proto.write_file(), objects)
  374. self._handle_receive_pack_tail(proto, negotiated_capabilities,
  375. progress)
  376. return new_refs
  377. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  378. progress=None):
  379. """Retrieve a pack from a git smart server.
  380. :param determine_wants: Callback that returns list of commits to fetch
  381. :param graph_walker: Object with next() and ack().
  382. :param pack_data: Callback called for each bit of data in the pack
  383. :param progress: Callback for progress reports (strings)
  384. """
  385. proto, can_read = self._connect('upload-pack', path)
  386. (refs, server_capabilities) = self._read_refs(proto)
  387. negotiated_capabilities = list(self._fetch_capabilities)
  388. wants = determine_wants(refs)
  389. if not wants:
  390. proto.write_pkt_line(None)
  391. return refs
  392. self._handle_upload_pack_head(proto, negotiated_capabilities,
  393. graph_walker, wants, can_read)
  394. self._handle_upload_pack_tail(proto, negotiated_capabilities,
  395. graph_walker, pack_data, progress)
  396. return refs
  397. class TCPGitClient(TraditionalGitClient):
  398. """A Git Client that works over TCP directly (i.e. git://)."""
  399. def __init__(self, host, port=None, *args, **kwargs):
  400. if port is None:
  401. port = TCP_GIT_PORT
  402. self._host = host
  403. self._port = port
  404. GitClient.__init__(self, *args, **kwargs)
  405. def _connect(self, cmd, path):
  406. sockaddrs = socket.getaddrinfo(self._host, self._port,
  407. socket.AF_UNSPEC, socket.SOCK_STREAM)
  408. s = None
  409. err = socket.error("no address found for %s" % self._host)
  410. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  411. s = socket.socket(family, socktype, proto)
  412. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  413. try:
  414. s.connect(sockaddr)
  415. break
  416. except socket.error, err:
  417. if s is not None:
  418. s.close()
  419. s = None
  420. if s is None:
  421. raise err
  422. # -1 means system default buffering
  423. rfile = s.makefile('rb', -1)
  424. # 0 means unbuffered
  425. wfile = s.makefile('wb', 0)
  426. proto = Protocol(rfile.read, wfile.write,
  427. report_activity=self._report_activity)
  428. if path.startswith("/~"):
  429. path = path[1:]
  430. proto.send_cmd('git-%s' % cmd, path, 'host=%s' % self._host)
  431. return proto, lambda: _fileno_can_read(s)
  432. class SubprocessWrapper(object):
  433. """A socket-like object that talks to a subprocess via pipes."""
  434. def __init__(self, proc):
  435. self.proc = proc
  436. self.read = proc.stdout.read
  437. self.write = proc.stdin.write
  438. def can_read(self):
  439. if subprocess.mswindows:
  440. from msvcrt import get_osfhandle
  441. from win32pipe import PeekNamedPipe
  442. handle = get_osfhandle(self.proc.stdout.fileno())
  443. return PeekNamedPipe(handle, 0)[2] != 0
  444. else:
  445. return _fileno_can_read(self.proc.stdout.fileno())
  446. def close(self):
  447. self.proc.stdin.close()
  448. self.proc.stdout.close()
  449. self.proc.wait()
  450. class SubprocessGitClient(TraditionalGitClient):
  451. """Git client that talks to a server using a subprocess."""
  452. def __init__(self, *args, **kwargs):
  453. self._connection = None
  454. GitClient.__init__(self, *args, **kwargs)
  455. def _connect(self, service, path):
  456. import subprocess
  457. argv = ['git', service, path]
  458. p = SubprocessWrapper(
  459. subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  460. stdout=subprocess.PIPE))
  461. return Protocol(p.read, p.write,
  462. report_activity=self._report_activity), p.can_read
  463. class SSHVendor(object):
  464. def connect_ssh(self, host, command, username=None, port=None):
  465. import subprocess
  466. #FIXME: This has no way to deal with passwords..
  467. args = ['ssh', '-x']
  468. if port is not None:
  469. args.extend(['-p', str(port)])
  470. if username is not None:
  471. host = '%s@%s' % (username, host)
  472. args.append(host)
  473. proc = subprocess.Popen(args + command,
  474. stdin=subprocess.PIPE,
  475. stdout=subprocess.PIPE)
  476. return SubprocessWrapper(proc)
  477. # Can be overridden by users
  478. get_ssh_vendor = SSHVendor
  479. class SSHGitClient(TraditionalGitClient):
  480. def __init__(self, host, port=None, username=None, *args, **kwargs):
  481. self.host = host
  482. self.port = port
  483. self.username = username
  484. GitClient.__init__(self, *args, **kwargs)
  485. self.alternative_paths = {}
  486. def _get_cmd_path(self, cmd):
  487. return self.alternative_paths.get(cmd, 'git-%s' % cmd)
  488. def _connect(self, cmd, path):
  489. con = get_ssh_vendor().connect_ssh(
  490. self.host, ["%s '%s'" % (self._get_cmd_path(cmd), path)],
  491. port=self.port, username=self.username)
  492. return (Protocol(con.read, con.write, report_activity=self._report_activity),
  493. con.can_read)
  494. class HttpGitClient(GitClient):
  495. def __init__(self, host, port=None, username=None, password=None, dumb=None, *args, **kwargs):
  496. self.host = host
  497. self.port = port
  498. self.dumb = dumb
  499. self.username = username
  500. self.password = password
  501. netloc = self.host
  502. if self.port:
  503. netloc += ":%d" % self.port
  504. self.url = "http://%s/" % netloc
  505. GitClient.__init__(self, *args, **kwargs)
  506. @classmethod
  507. def from_url(cls, url):
  508. parsed = urlparse.urlparse(url)
  509. assert parsed.scheme == 'http'
  510. return cls(parsed.hostname, port=parsed.port, username=parsed.port,
  511. password=parsed.password), parsed.path
  512. def _discover_references(self, service, url):
  513. url = urlparse.urljoin(url+"/", "info/refs")
  514. if not self.dumb:
  515. url += "?service=%s" % service
  516. req = urllib2.Request(url)
  517. resp = urllib2.urlopen(req)
  518. self.dumb = (not resp.info().gettype().startswith("application/x-git-"))
  519. proto = Protocol(resp.read, None)
  520. if not self.dumb:
  521. # The first line should mention the service
  522. pkts = list(proto.read_pkt_seq())
  523. if pkts != [('# service=%s\n' % service)]:
  524. raise ValueError("unexpected first line %r from smart server" % pkts)
  525. return self._read_refs(proto)
  526. def _smart_request(self, service, url, data):
  527. url = urlparse.urljoin(url+"/", service)
  528. req = urllib2.Request(url,
  529. headers={"Content-Type": "application/x-%s-request" % service},
  530. data=data)
  531. resp = urllib2.urlopen(req)
  532. if resp.getcode() != 200:
  533. raise ValueError("Invalid HTTP response from server: %d" % resp.getcode())
  534. if resp.info().gettype() != ("application/x-%s-result" % service):
  535. raise ValueError("Invalid content-type from server: %s" % resp.info().gettype())
  536. return resp
  537. def send_pack(self, path, determine_wants, generate_pack_contents,
  538. progress=None):
  539. """Upload a pack to a remote repository.
  540. :param path: Repository path
  541. :param generate_pack_contents: Function that can return a sequence of the
  542. shas of the objects to upload.
  543. :param progress: Optional progress function
  544. :raises SendPackError: if server rejects the pack data
  545. :raises UpdateRefsError: if the server supports report-status
  546. and rejects ref updates
  547. """
  548. url = urlparse.urljoin(self.url, path)
  549. old_refs, server_capabilities = self._discover_references("git-receive-pack", url)
  550. negotiated_capabilities = list(self._send_capabilities)
  551. new_refs = determine_wants(old_refs)
  552. if not new_refs:
  553. return {}
  554. if self.dumb:
  555. raise NotImplementedError(self.fetch_pack)
  556. req_data = StringIO()
  557. req_proto = Protocol(None, req_data.write)
  558. (have, want) = self._handle_receive_pack_head(
  559. req_proto, negotiated_capabilities, old_refs, new_refs)
  560. if not want:
  561. return new_refs
  562. objects = generate_pack_contents(have, want)
  563. entries, sha = write_pack_objects(req_proto.write_file(), objects)
  564. resp = self._smart_request("git-receive-pack", url,
  565. data=req_data.getvalue())
  566. if resp.getcode() != 200:
  567. raise ValueError("invalid http response during git-receive-pack: %d"
  568. % resp.getcode())
  569. resp_proto = Protocol(resp.read, None)
  570. self._handle_receive_pack_tail(resp_proto, negotiated_capabilities,
  571. progress)
  572. return new_refs
  573. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  574. progress):
  575. """Retrieve a pack from a git smart server.
  576. :param determine_wants: Callback that returns list of commits to fetch
  577. :param graph_walker: Object with next() and ack().
  578. :param pack_data: Callback called for each bit of data in the pack
  579. :param progress: Callback for progress reports (strings)
  580. """
  581. url = urlparse.urljoin(self.url, path)
  582. refs, server_capabilities = self._discover_references(
  583. "git-upload-pack", url)
  584. negotiated_capabilities = list(server_capabilities)
  585. wants = determine_wants(refs)
  586. if not wants:
  587. return refs
  588. if self.dumb:
  589. raise NotImplementedError(self.send_pack)
  590. req_data = StringIO()
  591. req_proto = Protocol(None, req_data.write)
  592. self._handle_upload_pack_head(req_proto,
  593. negotiated_capabilities, graph_walker, wants,
  594. lambda: False)
  595. resp = self._smart_request("git-upload-pack", url,
  596. data=req_data.getvalue())
  597. resp_proto = Protocol(resp.read, None)
  598. self._handle_upload_pack_tail(resp_proto, negotiated_capabilities,
  599. graph_walker, pack_data, progress)
  600. return refs
  601. def get_transport_and_path(uri):
  602. """Obtain a git client from a URI or path.
  603. :param uri: URI or path
  604. :return: Tuple with client instance and relative path.
  605. """
  606. parsed = urlparse.urlparse(uri)
  607. if parsed.scheme == 'git':
  608. return TCPGitClient(parsed.hostname, port=parsed.port), parsed.path
  609. elif parsed.scheme == 'git+ssh':
  610. return SSHGitClient(parsed.hostname, port=parsed.port,
  611. username=parsed.username), parsed.path
  612. elif parsed.scheme == 'http':
  613. return HttpGitClient(parsed.hostname, port=parsed.port,
  614. username=parsed.username), parsed.path
  615. if parsed.scheme and not parsed.netloc:
  616. # SSH with no user@, zero or one leading slash.
  617. return SSHGitClient(parsed.scheme), parsed.path
  618. elif parsed.scheme:
  619. raise ValueError('Unknown git protocol scheme: %s' % parsed.scheme)
  620. elif '@' in parsed.path and ':' in parsed.path:
  621. # SSH with user@host:foo.
  622. user_host, path = parsed.path.split(':')
  623. user, host = user_host.rsplit('@')
  624. return SSHGitClient(host, username=user), path
  625. # Otherwise, assume it's a local path.
  626. return SubprocessGitClient(), uri