client.py 29 KB

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