client.py 30 KB

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