client.py 30 KB

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