client.py 28 KB

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