client.py 27 KB

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