client.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  1. # client.py -- Implementation of the server side git protocols
  2. # Copyright (C) 2008-2013 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 io import BytesIO
  35. import dulwich
  36. import select
  37. import socket
  38. import subprocess
  39. import sys
  40. try:
  41. import urllib2
  42. import urlparse
  43. except ImportError:
  44. import urllib.request as urllib2
  45. import urllib.parse as urlparse
  46. from dulwich.errors import (
  47. GitProtocolError,
  48. NotGitRepository,
  49. SendPackError,
  50. UpdateRefsError,
  51. )
  52. from dulwich.protocol import (
  53. _RBUFSIZE,
  54. PktLineParser,
  55. Protocol,
  56. ProtocolFile,
  57. TCP_GIT_PORT,
  58. ZERO_SHA,
  59. extract_capabilities,
  60. )
  61. from dulwich.pack import (
  62. write_pack_objects,
  63. )
  64. from dulwich.refs import (
  65. read_info_refs,
  66. )
  67. def _fileno_can_read(fileno):
  68. """Check if a file descriptor is readable."""
  69. return len(select.select([fileno], [], [], 0)[0]) > 0
  70. COMMON_CAPABILITIES = ['ofs-delta', 'side-band-64k']
  71. FETCH_CAPABILITIES = (['thin-pack', 'multi_ack', 'multi_ack_detailed'] +
  72. COMMON_CAPABILITIES)
  73. SEND_CAPABILITIES = ['report-status'] + COMMON_CAPABILITIES
  74. class ReportStatusParser(object):
  75. """Handle status as reported by servers with 'report-status' capability.
  76. """
  77. def __init__(self):
  78. self._done = False
  79. self._pack_status = None
  80. self._ref_status_ok = True
  81. self._ref_statuses = []
  82. def check(self):
  83. """Check if there were any errors and, if so, raise exceptions.
  84. :raise SendPackError: Raised when the server could not unpack
  85. :raise UpdateRefsError: Raised when refs could not be updated
  86. """
  87. if self._pack_status not in ('unpack ok', None):
  88. raise SendPackError(self._pack_status)
  89. if not self._ref_status_ok:
  90. ref_status = {}
  91. ok = set()
  92. for status in self._ref_statuses:
  93. if ' ' not in status:
  94. # malformed response, move on to the next one
  95. continue
  96. status, ref = status.split(' ', 1)
  97. if status == 'ng':
  98. if ' ' in ref:
  99. ref, status = ref.split(' ', 1)
  100. else:
  101. ok.add(ref)
  102. ref_status[ref] = status
  103. raise UpdateRefsError('%s failed to update' %
  104. ', '.join([ref for ref in ref_status
  105. if ref not in ok]),
  106. ref_status=ref_status)
  107. def handle_packet(self, pkt):
  108. """Handle a packet.
  109. :raise GitProtocolError: Raised when packets are received after a
  110. flush packet.
  111. """
  112. if self._done:
  113. raise GitProtocolError("received more data after status report")
  114. if pkt is None:
  115. self._done = True
  116. return
  117. if self._pack_status is None:
  118. self._pack_status = pkt.strip()
  119. else:
  120. ref_status = pkt.strip()
  121. self._ref_statuses.append(ref_status)
  122. if not ref_status.startswith('ok '):
  123. self._ref_status_ok = False
  124. def read_pkt_refs(proto):
  125. server_capabilities = None
  126. refs = {}
  127. # Receive refs from server
  128. for pkt in proto.read_pkt_seq():
  129. (sha, ref) = pkt.rstrip('\n').split(None, 1)
  130. if sha == 'ERR':
  131. raise GitProtocolError(ref)
  132. if server_capabilities is None:
  133. (ref, server_capabilities) = extract_capabilities(ref)
  134. refs[ref] = sha
  135. if len(refs) == 0:
  136. return None, set([])
  137. return refs, set(server_capabilities)
  138. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  139. # support some capabilities. This should work properly with servers
  140. # that don't support multi_ack.
  141. class GitClient(object):
  142. """Git smart server client.
  143. """
  144. def __init__(self, thin_packs=True, report_activity=None):
  145. """Create a new GitClient instance.
  146. :param thin_packs: Whether or not thin packs should be retrieved
  147. :param report_activity: Optional callback for reporting transport
  148. activity.
  149. """
  150. self._report_activity = report_activity
  151. self._report_status_parser = None
  152. self._fetch_capabilities = set(FETCH_CAPABILITIES)
  153. self._send_capabilities = set(SEND_CAPABILITIES)
  154. if not thin_packs:
  155. self._fetch_capabilities.remove('thin-pack')
  156. def send_pack(self, path, determine_wants, generate_pack_contents,
  157. progress=None, write_pack=write_pack_objects):
  158. """Upload a pack to a remote repository.
  159. :param path: Repository path
  160. :param generate_pack_contents: Function that can return a sequence of
  161. the shas of the objects to upload.
  162. :param progress: Optional progress function
  163. :param write_pack: Function called with (file, iterable of objects) to
  164. write the objects returned by generate_pack_contents to the server.
  165. :raises SendPackError: if server rejects the pack data
  166. :raises UpdateRefsError: if the server supports report-status
  167. and rejects ref updates
  168. """
  169. raise NotImplementedError(self.send_pack)
  170. def fetch(self, path, target, determine_wants=None, progress=None):
  171. """Fetch into a target repository.
  172. :param path: Path to fetch from
  173. :param target: Target repository to fetch into
  174. :param determine_wants: Optional function to determine what refs
  175. to fetch
  176. :param progress: Optional progress function
  177. :return: remote refs as dictionary
  178. """
  179. if determine_wants is None:
  180. determine_wants = target.object_store.determine_wants_all
  181. f, commit, abort = target.object_store.add_pack()
  182. try:
  183. result = self.fetch_pack(
  184. path, determine_wants, target.get_graph_walker(), f.write,
  185. progress)
  186. except:
  187. abort()
  188. raise
  189. else:
  190. commit()
  191. return result
  192. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  193. progress=None):
  194. """Retrieve a pack from a git smart server.
  195. :param determine_wants: Callback that returns list of commits to fetch
  196. :param graph_walker: Object with next() and ack().
  197. :param pack_data: Callback called for each bit of data in the pack
  198. :param progress: Callback for progress reports (strings)
  199. """
  200. raise NotImplementedError(self.fetch_pack)
  201. def _parse_status_report(self, proto):
  202. unpack = proto.read_pkt_line().strip()
  203. if unpack != 'unpack ok':
  204. st = True
  205. # flush remaining error data
  206. while st is not None:
  207. st = proto.read_pkt_line()
  208. raise SendPackError(unpack)
  209. statuses = []
  210. errs = False
  211. ref_status = proto.read_pkt_line()
  212. while ref_status:
  213. ref_status = ref_status.strip()
  214. statuses.append(ref_status)
  215. if not ref_status.startswith('ok '):
  216. errs = True
  217. ref_status = proto.read_pkt_line()
  218. if errs:
  219. ref_status = {}
  220. ok = set()
  221. for status in statuses:
  222. if ' ' not in status:
  223. # malformed response, move on to the next one
  224. continue
  225. status, ref = status.split(' ', 1)
  226. if status == 'ng':
  227. if ' ' in ref:
  228. ref, status = ref.split(' ', 1)
  229. else:
  230. ok.add(ref)
  231. ref_status[ref] = status
  232. raise UpdateRefsError('%s failed to update' %
  233. ', '.join([ref for ref in ref_status
  234. if ref not in ok]),
  235. ref_status=ref_status)
  236. def _read_side_band64k_data(self, proto, channel_callbacks):
  237. """Read per-channel data.
  238. This requires the side-band-64k capability.
  239. :param proto: Protocol object to read from
  240. :param channel_callbacks: Dictionary mapping channels to packet
  241. handlers to use. None for a callback discards channel data.
  242. """
  243. for pkt in proto.read_pkt_seq():
  244. channel = ord(pkt[0])
  245. pkt = pkt[1:]
  246. try:
  247. cb = channel_callbacks[channel]
  248. except KeyError:
  249. raise AssertionError('Invalid sideband channel %d' % channel)
  250. else:
  251. if cb is not None:
  252. cb(pkt)
  253. def _handle_receive_pack_head(self, proto, capabilities, old_refs,
  254. new_refs):
  255. """Handle the head of a 'git-receive-pack' request.
  256. :param proto: Protocol object to read from
  257. :param capabilities: List of negotiated capabilities
  258. :param old_refs: Old refs, as received from the server
  259. :param new_refs: New refs
  260. :return: (have, want) tuple
  261. """
  262. want = []
  263. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  264. sent_capabilities = False
  265. for refname in set(new_refs.keys() + old_refs.keys()):
  266. old_sha1 = old_refs.get(refname, ZERO_SHA)
  267. new_sha1 = new_refs.get(refname, ZERO_SHA)
  268. if old_sha1 != new_sha1:
  269. if sent_capabilities:
  270. proto.write_pkt_line('%s %s %s' % (
  271. old_sha1, new_sha1, refname))
  272. else:
  273. proto.write_pkt_line(
  274. '%s %s %s\0%s' % (old_sha1, new_sha1, refname,
  275. ' '.join(capabilities)))
  276. sent_capabilities = True
  277. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  278. want.append(new_sha1)
  279. proto.write_pkt_line(None)
  280. return (have, want)
  281. def _handle_receive_pack_tail(self, proto, capabilities, progress=None):
  282. """Handle the tail of a 'git-receive-pack' request.
  283. :param proto: Protocol object to read from
  284. :param capabilities: List of negotiated capabilities
  285. :param progress: Optional progress reporting function
  286. """
  287. if "side-band-64k" in capabilities:
  288. if progress is None:
  289. progress = lambda x: None
  290. channel_callbacks = {2: progress}
  291. if 'report-status' in capabilities:
  292. channel_callbacks[1] = PktLineParser(
  293. self._report_status_parser.handle_packet).parse
  294. self._read_side_band64k_data(proto, channel_callbacks)
  295. else:
  296. if 'report-status' in capabilities:
  297. for pkt in proto.read_pkt_seq():
  298. self._report_status_parser.handle_packet(pkt)
  299. if self._report_status_parser is not None:
  300. self._report_status_parser.check()
  301. def _handle_upload_pack_head(self, proto, capabilities, graph_walker,
  302. wants, can_read):
  303. """Handle the head of a 'git-upload-pack' request.
  304. :param proto: Protocol object to read from
  305. :param capabilities: List of negotiated capabilities
  306. :param graph_walker: GraphWalker instance to call .ack() on
  307. :param wants: List of commits to fetch
  308. :param can_read: function that returns a boolean that indicates
  309. whether there is extra graph data to read on proto
  310. """
  311. assert isinstance(wants, list) and isinstance(wants[0], str)
  312. proto.write_pkt_line('want %s %s\n' % (
  313. wants[0], ' '.join(capabilities)))
  314. for want in wants[1:]:
  315. proto.write_pkt_line('want %s\n' % want)
  316. proto.write_pkt_line(None)
  317. have = next(graph_walker)
  318. while have:
  319. proto.write_pkt_line('have %s\n' % have)
  320. if can_read():
  321. pkt = proto.read_pkt_line()
  322. parts = pkt.rstrip('\n').split(' ')
  323. if parts[0] == 'ACK':
  324. graph_walker.ack(parts[1])
  325. if parts[2] in ('continue', 'common'):
  326. pass
  327. elif parts[2] == 'ready':
  328. break
  329. else:
  330. raise AssertionError(
  331. "%s not in ('continue', 'ready', 'common)" %
  332. parts[2])
  333. have = next(graph_walker)
  334. proto.write_pkt_line('done\n')
  335. def _handle_upload_pack_tail(self, proto, capabilities, graph_walker,
  336. pack_data, progress=None, rbufsize=_RBUFSIZE):
  337. """Handle the tail of a 'git-upload-pack' request.
  338. :param proto: Protocol object to read from
  339. :param capabilities: List of negotiated capabilities
  340. :param graph_walker: GraphWalker instance to call .ack() on
  341. :param pack_data: Function to call with pack data
  342. :param progress: Optional progress reporting function
  343. :param rbufsize: Read buffer size
  344. """
  345. pkt = proto.read_pkt_line()
  346. while pkt:
  347. parts = pkt.rstrip('\n').split(' ')
  348. if parts[0] == 'ACK':
  349. graph_walker.ack(parts[1])
  350. if len(parts) < 3 or parts[2] not in (
  351. 'ready', 'continue', 'common'):
  352. break
  353. pkt = proto.read_pkt_line()
  354. if "side-band-64k" in capabilities:
  355. if progress is None:
  356. # Just ignore progress data
  357. progress = lambda x: None
  358. self._read_side_band64k_data(proto, {1: pack_data, 2: progress})
  359. else:
  360. while True:
  361. data = proto.read(rbufsize)
  362. if data == "":
  363. break
  364. pack_data(data)
  365. class TraditionalGitClient(GitClient):
  366. """Traditional Git client."""
  367. def _connect(self, cmd, path):
  368. """Create a connection to the server.
  369. This method is abstract - concrete implementations should
  370. implement their own variant which connects to the server and
  371. returns an initialized Protocol object with the service ready
  372. for use and a can_read function which may be used to see if
  373. reads would block.
  374. :param cmd: The git service name to which we should connect.
  375. :param path: The path we should pass to the service.
  376. """
  377. raise NotImplementedError()
  378. def send_pack(self, path, determine_wants, generate_pack_contents,
  379. progress=None, write_pack=write_pack_objects):
  380. """Upload a pack to a remote repository.
  381. :param path: Repository path
  382. :param generate_pack_contents: Function that can return a sequence of
  383. the shas of the objects to upload.
  384. :param progress: Optional callback called with progress updates
  385. :param write_pack: Function called with (file, iterable of objects) to
  386. write the objects returned by generate_pack_contents to the server.
  387. :raises SendPackError: if server rejects the pack data
  388. :raises UpdateRefsError: if the server supports report-status
  389. and rejects ref updates
  390. """
  391. proto, unused_can_read = self._connect('receive-pack', path)
  392. with proto:
  393. old_refs, server_capabilities = read_pkt_refs(proto)
  394. negotiated_capabilities = self._send_capabilities & server_capabilities
  395. if 'report-status' in negotiated_capabilities:
  396. self._report_status_parser = ReportStatusParser()
  397. report_status_parser = self._report_status_parser
  398. try:
  399. new_refs = orig_new_refs = determine_wants(dict(old_refs))
  400. except:
  401. proto.write_pkt_line(None)
  402. raise
  403. if not 'delete-refs' in server_capabilities:
  404. # Server does not support deletions. Fail later.
  405. new_refs = dict(orig_new_refs)
  406. for ref, sha in orig_new_refs.iteritems():
  407. if sha == ZERO_SHA:
  408. if 'report-status' in negotiated_capabilities:
  409. report_status_parser._ref_statuses.append(
  410. 'ng %s remote does not support deleting refs'
  411. % sha)
  412. report_status_parser._ref_status_ok = False
  413. del new_refs[ref]
  414. if new_refs is None:
  415. proto.write_pkt_line(None)
  416. return old_refs
  417. if len(new_refs) == 0 and len(orig_new_refs):
  418. # NOOP - Original new refs filtered out by policy
  419. proto.write_pkt_line(None)
  420. if report_status_parser is not None:
  421. report_status_parser.check()
  422. return old_refs
  423. (have, want) = self._handle_receive_pack_head(
  424. proto, negotiated_capabilities, old_refs, new_refs)
  425. if not want and old_refs == new_refs:
  426. return new_refs
  427. objects = generate_pack_contents(have, want)
  428. dowrite = len(objects) > 0
  429. dowrite = dowrite or any(old_refs.get(ref) != sha
  430. for (ref, sha) in new_refs.iteritems()
  431. if sha != ZERO_SHA)
  432. if dowrite:
  433. write_pack(proto.write_file(), objects)
  434. self._handle_receive_pack_tail(
  435. proto, negotiated_capabilities, progress)
  436. return new_refs
  437. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  438. progress=None):
  439. """Retrieve a pack from a git smart server.
  440. :param determine_wants: Callback that returns list of commits to fetch
  441. :param graph_walker: Object with next() and ack().
  442. :param pack_data: Callback called for each bit of data in the pack
  443. :param progress: Callback for progress reports (strings)
  444. """
  445. proto, can_read = self._connect('upload-pack', path)
  446. with proto:
  447. refs, server_capabilities = read_pkt_refs(proto)
  448. negotiated_capabilities = (
  449. self._fetch_capabilities & server_capabilities)
  450. if refs is None:
  451. proto.write_pkt_line(None)
  452. return refs
  453. try:
  454. wants = determine_wants(refs)
  455. except:
  456. proto.write_pkt_line(None)
  457. raise
  458. if wants is not None:
  459. wants = [cid for cid in wants if cid != ZERO_SHA]
  460. if not wants:
  461. proto.write_pkt_line(None)
  462. return refs
  463. self._handle_upload_pack_head(
  464. proto, negotiated_capabilities, graph_walker, wants, can_read)
  465. self._handle_upload_pack_tail(
  466. proto, negotiated_capabilities, graph_walker, pack_data, progress)
  467. return refs
  468. def archive(self, path, committish, write_data, progress=None,
  469. write_error=None):
  470. proto, can_read = self._connect(b'upload-archive', path)
  471. with proto:
  472. proto.write_pkt_line("argument %s" % committish)
  473. proto.write_pkt_line(None)
  474. pkt = proto.read_pkt_line()
  475. if pkt == "NACK\n":
  476. return
  477. elif pkt == "ACK\n":
  478. pass
  479. elif pkt.startswith("ERR "):
  480. raise GitProtocolError(pkt[4:].rstrip("\n"))
  481. else:
  482. raise AssertionError("invalid response %r" % pkt)
  483. ret = proto.read_pkt_line()
  484. if ret is not None:
  485. raise AssertionError("expected pkt tail")
  486. self._read_side_band64k_data(proto, {
  487. 1: write_data, 2: progress, 3: write_error})
  488. class TCPGitClient(TraditionalGitClient):
  489. """A Git Client that works over TCP directly (i.e. git://)."""
  490. def __init__(self, host, port=None, *args, **kwargs):
  491. if port is None:
  492. port = TCP_GIT_PORT
  493. self._host = host
  494. self._port = port
  495. TraditionalGitClient.__init__(self, *args, **kwargs)
  496. def _connect(self, cmd, path):
  497. sockaddrs = socket.getaddrinfo(
  498. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  499. s = None
  500. err = socket.error("no address found for %s" % self._host)
  501. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  502. s = socket.socket(family, socktype, proto)
  503. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  504. try:
  505. s.connect(sockaddr)
  506. break
  507. except socket.error as err:
  508. if s is not None:
  509. s.close()
  510. s = None
  511. if s is None:
  512. raise err
  513. # -1 means system default buffering
  514. rfile = s.makefile('rb', -1)
  515. # 0 means unbuffered
  516. wfile = s.makefile('wb', 0)
  517. def close():
  518. rfile.close()
  519. wfile.close()
  520. s.close()
  521. proto = Protocol(rfile.read, wfile.write, close,
  522. report_activity=self._report_activity)
  523. if path.startswith("/~"):
  524. path = path[1:]
  525. proto.send_cmd('git-%s' % cmd, path, 'host=%s' % self._host)
  526. return proto, lambda: _fileno_can_read(s)
  527. class SubprocessWrapper(object):
  528. """A socket-like object that talks to a subprocess via pipes."""
  529. def __init__(self, proc):
  530. self.proc = proc
  531. self.read = proc.stdout.read
  532. self.write = proc.stdin.write
  533. def can_read(self):
  534. if subprocess.mswindows:
  535. from msvcrt import get_osfhandle
  536. from win32pipe import PeekNamedPipe
  537. handle = get_osfhandle(self.proc.stdout.fileno())
  538. return PeekNamedPipe(handle, 0)[2] != 0
  539. else:
  540. return _fileno_can_read(self.proc.stdout.fileno())
  541. def close(self):
  542. self.proc.stdin.close()
  543. self.proc.stdout.close()
  544. if self.proc.stderr:
  545. self.proc.stderr.close()
  546. self.proc.wait()
  547. class SubprocessGitClient(TraditionalGitClient):
  548. """Git client that talks to a server using a subprocess."""
  549. def __init__(self, *args, **kwargs):
  550. self._connection = None
  551. self._stderr = None
  552. self._stderr = kwargs.get('stderr')
  553. if 'stderr' in kwargs:
  554. del kwargs['stderr']
  555. TraditionalGitClient.__init__(self, *args, **kwargs)
  556. def _connect(self, service, path):
  557. import subprocess
  558. argv = ['git', service, path]
  559. p = SubprocessWrapper(
  560. subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  561. stdout=subprocess.PIPE,
  562. stderr=self._stderr))
  563. return Protocol(p.read, p.write, p.close,
  564. report_activity=self._report_activity), p.can_read
  565. class LocalGitClient(GitClient):
  566. """Git Client that just uses a local Repo."""
  567. def __init__(self, thin_packs=True, report_activity=None):
  568. """Create a new LocalGitClient instance.
  569. :param path: Path to the local repository
  570. :param thin_packs: Whether or not thin packs should be retrieved
  571. :param report_activity: Optional callback for reporting transport
  572. activity.
  573. """
  574. self._report_activity = report_activity
  575. # Ignore the thin_packs argument
  576. def send_pack(self, path, determine_wants, generate_pack_contents,
  577. progress=None, write_pack=write_pack_objects):
  578. """Upload a pack to a remote repository.
  579. :param path: Repository path
  580. :param generate_pack_contents: Function that can return a sequence of
  581. the shas of the objects to upload.
  582. :param progress: Optional progress function
  583. :param write_pack: Function called with (file, iterable of objects) to
  584. write the objects returned by generate_pack_contents to the server.
  585. :raises SendPackError: if server rejects the pack data
  586. :raises UpdateRefsError: if the server supports report-status
  587. and rejects ref updates
  588. """
  589. raise NotImplementedError(self.send_pack)
  590. def fetch(self, path, target, determine_wants=None, progress=None):
  591. """Fetch into a target repository.
  592. :param path: Path to fetch from
  593. :param target: Target repository to fetch into
  594. :param determine_wants: Optional function to determine what refs
  595. to fetch
  596. :param progress: Optional progress function
  597. :return: remote refs as dictionary
  598. """
  599. from dulwich.repo import Repo
  600. r = Repo(path)
  601. return r.fetch(target, determine_wants=determine_wants,
  602. progress=progress)
  603. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  604. progress=None):
  605. """Retrieve a pack from a git smart server.
  606. :param determine_wants: Callback that returns list of commits to fetch
  607. :param graph_walker: Object with next() and ack().
  608. :param pack_data: Callback called for each bit of data in the pack
  609. :param progress: Callback for progress reports (strings)
  610. """
  611. from dulwich.repo import Repo
  612. r = Repo(path)
  613. objects_iter = r.fetch_objects(determine_wants, graph_walker, progress)
  614. # Did the process short-circuit (e.g. in a stateless RPC call)? Note
  615. # that the client still expects a 0-object pack in most cases.
  616. if objects_iter is None:
  617. return
  618. write_pack_objects(ProtocolFile(None, pack_data), objects_iter)
  619. # What Git client to use for local access
  620. default_local_git_client_cls = SubprocessGitClient
  621. class SSHVendor(object):
  622. """A client side SSH implementation."""
  623. def connect_ssh(self, host, command, username=None, port=None):
  624. import warnings
  625. warnings.warn(
  626. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  627. DeprecationWarning)
  628. return self.run_command(host, command, username=username, port=port)
  629. def run_command(self, host, command, username=None, port=None):
  630. """Connect to an SSH server.
  631. Run a command remotely and return a file-like object for interaction
  632. with the remote command.
  633. :param host: Host name
  634. :param command: Command to run
  635. :param username: Optional ame of user to log in as
  636. :param port: Optional SSH port to use
  637. """
  638. raise NotImplementedError(self.run_command)
  639. class SubprocessSSHVendor(SSHVendor):
  640. """SSH vendor that shells out to the local 'ssh' command."""
  641. def run_command(self, host, command, username=None, port=None):
  642. import subprocess
  643. #FIXME: This has no way to deal with passwords..
  644. args = ['ssh', '-x']
  645. if port is not None:
  646. args.extend(['-p', str(port)])
  647. if username is not None:
  648. host = '%s@%s' % (username, host)
  649. args.append(host)
  650. proc = subprocess.Popen(args + command,
  651. stdin=subprocess.PIPE,
  652. stdout=subprocess.PIPE)
  653. return SubprocessWrapper(proc)
  654. try:
  655. import paramiko
  656. except ImportError:
  657. pass
  658. else:
  659. import threading
  660. class ParamikoWrapper(object):
  661. STDERR_READ_N = 2048 # 2k
  662. def __init__(self, client, channel, progress_stderr=None):
  663. self.client = client
  664. self.channel = channel
  665. self.progress_stderr = progress_stderr
  666. self.should_monitor = bool(progress_stderr) or True
  667. self.monitor_thread = None
  668. self.stderr = ''
  669. # Channel must block
  670. self.channel.setblocking(True)
  671. # Start
  672. if self.should_monitor:
  673. self.monitor_thread = threading.Thread(
  674. target=self.monitor_stderr)
  675. self.monitor_thread.start()
  676. def monitor_stderr(self):
  677. while self.should_monitor:
  678. # Block and read
  679. data = self.read_stderr(self.STDERR_READ_N)
  680. # Socket closed
  681. if not data:
  682. self.should_monitor = False
  683. break
  684. # Emit data
  685. if self.progress_stderr:
  686. self.progress_stderr(data)
  687. # Append to buffer
  688. self.stderr += data
  689. def stop_monitoring(self):
  690. # Stop StdErr thread
  691. if self.should_monitor:
  692. self.should_monitor = False
  693. self.monitor_thread.join()
  694. # Get left over data
  695. data = self.channel.in_stderr_buffer.empty()
  696. self.stderr += data
  697. def can_read(self):
  698. return self.channel.recv_ready()
  699. def write(self, data):
  700. return self.channel.sendall(data)
  701. def read_stderr(self, n):
  702. return self.channel.recv_stderr(n)
  703. def read(self, n=None):
  704. data = self.channel.recv(n)
  705. data_len = len(data)
  706. # Closed socket
  707. if not data:
  708. return
  709. # Read more if needed
  710. if n and data_len < n:
  711. diff_len = n - data_len
  712. return data + self.read(diff_len)
  713. return data
  714. def close(self):
  715. self.channel.close()
  716. self.stop_monitoring()
  717. class ParamikoSSHVendor(object):
  718. def __init__(self):
  719. self.ssh_kwargs = {}
  720. def run_command(self, host, command, username=None, port=None,
  721. progress_stderr=None):
  722. # Paramiko needs an explicit port. None is not valid
  723. if port is None:
  724. port = 22
  725. client = paramiko.SSHClient()
  726. policy = paramiko.client.MissingHostKeyPolicy()
  727. client.set_missing_host_key_policy(policy)
  728. client.connect(host, username=username, port=port,
  729. **self.ssh_kwargs)
  730. # Open SSH session
  731. channel = client.get_transport().open_session()
  732. # Run commands
  733. channel.exec_command(*command)
  734. return ParamikoWrapper(
  735. client, channel, progress_stderr=progress_stderr)
  736. # Can be overridden by users
  737. get_ssh_vendor = SubprocessSSHVendor
  738. class SSHGitClient(TraditionalGitClient):
  739. def __init__(self, host, port=None, username=None, *args, **kwargs):
  740. self.host = host
  741. self.port = port
  742. self.username = username
  743. TraditionalGitClient.__init__(self, *args, **kwargs)
  744. self.alternative_paths = {}
  745. def _get_cmd_path(self, cmd):
  746. return self.alternative_paths.get(cmd, 'git-%s' % cmd)
  747. def _connect(self, cmd, path):
  748. if path.startswith("/~"):
  749. path = path[1:]
  750. con = get_ssh_vendor().run_command(
  751. self.host, ["%s '%s'" % (self._get_cmd_path(cmd), path)],
  752. port=self.port, username=self.username)
  753. return (Protocol(con.read, con.write, con.close,
  754. report_activity=self._report_activity),
  755. con.can_read)
  756. def default_user_agent_string():
  757. return "dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  758. def default_urllib2_opener(config):
  759. if config is not None:
  760. proxy_server = config.get("http", "proxy")
  761. else:
  762. proxy_server = None
  763. handlers = []
  764. if proxy_server is not None:
  765. handlers.append(urllib2.ProxyHandler({"http": proxy_server}))
  766. opener = urllib2.build_opener(*handlers)
  767. if config is not None:
  768. user_agent = config.get("http", "useragent")
  769. else:
  770. user_agent = None
  771. if user_agent is None:
  772. user_agent = default_user_agent_string()
  773. opener.addheaders = [('User-agent', user_agent)]
  774. return opener
  775. class HttpGitClient(GitClient):
  776. def __init__(self, base_url, dumb=None, opener=None, config=None, *args,
  777. **kwargs):
  778. self.base_url = base_url.rstrip("/") + "/"
  779. self.dumb = dumb
  780. if opener is None:
  781. self.opener = default_urllib2_opener(config)
  782. else:
  783. self.opener = opener
  784. GitClient.__init__(self, *args, **kwargs)
  785. def _get_url(self, path):
  786. return urlparse.urljoin(self.base_url, path).rstrip("/") + "/"
  787. def _http_request(self, url, headers={}, data=None):
  788. req = urllib2.Request(url, headers=headers, data=data)
  789. try:
  790. resp = self.opener.open(req)
  791. except urllib2.HTTPError as e:
  792. if e.code == 404:
  793. raise NotGitRepository()
  794. if e.code != 200:
  795. raise GitProtocolError("unexpected http response %d" % e.code)
  796. return resp
  797. def _discover_references(self, service, url):
  798. assert url[-1] == "/"
  799. url = urlparse.urljoin(url, "info/refs")
  800. headers = {}
  801. if self.dumb is not False:
  802. url += "?service=%s" % service
  803. headers["Content-Type"] = "application/x-%s-request" % service
  804. resp = self._http_request(url, headers)
  805. try:
  806. self.dumb = (not resp.info().gettype().startswith("application/x-git-"))
  807. if not self.dumb:
  808. proto = Protocol(resp.read, None)
  809. # The first line should mention the service
  810. pkts = list(proto.read_pkt_seq())
  811. if pkts != [('# service=%s\n' % service)]:
  812. raise GitProtocolError(
  813. "unexpected first line %r from smart server" % pkts)
  814. return read_pkt_refs(proto)
  815. else:
  816. return read_info_refs(resp), set()
  817. finally:
  818. resp.close()
  819. def _smart_request(self, service, url, data):
  820. assert url[-1] == "/"
  821. url = urlparse.urljoin(url, service)
  822. headers = {"Content-Type": "application/x-%s-request" % service}
  823. resp = self._http_request(url, headers, data)
  824. if resp.info().gettype() != ("application/x-%s-result" % service):
  825. raise GitProtocolError("Invalid content-type from server: %s"
  826. % resp.info().gettype())
  827. return resp
  828. def send_pack(self, path, determine_wants, generate_pack_contents,
  829. progress=None, write_pack=write_pack_objects):
  830. """Upload a pack to a remote repository.
  831. :param path: Repository path
  832. :param generate_pack_contents: Function that can return a sequence of
  833. the shas of the objects to upload.
  834. :param progress: Optional progress function
  835. :param write_pack: Function called with (file, iterable of objects) to
  836. write the objects returned by generate_pack_contents to the server.
  837. :raises SendPackError: if server rejects the pack data
  838. :raises UpdateRefsError: if the server supports report-status
  839. and rejects ref updates
  840. """
  841. url = self._get_url(path)
  842. old_refs, server_capabilities = self._discover_references(
  843. "git-receive-pack", url)
  844. negotiated_capabilities = self._send_capabilities & server_capabilities
  845. if 'report-status' in negotiated_capabilities:
  846. self._report_status_parser = ReportStatusParser()
  847. new_refs = determine_wants(dict(old_refs))
  848. if new_refs is None:
  849. return old_refs
  850. if self.dumb:
  851. raise NotImplementedError(self.fetch_pack)
  852. req_data = BytesIO()
  853. req_proto = Protocol(None, req_data.write)
  854. (have, want) = self._handle_receive_pack_head(
  855. req_proto, negotiated_capabilities, old_refs, new_refs)
  856. if not want and old_refs == new_refs:
  857. return new_refs
  858. objects = generate_pack_contents(have, want)
  859. if len(objects) > 0:
  860. write_pack(req_proto.write_file(), objects)
  861. resp = self._smart_request("git-receive-pack", url,
  862. data=req_data.getvalue())
  863. try:
  864. resp_proto = Protocol(resp.read, None)
  865. self._handle_receive_pack_tail(resp_proto, negotiated_capabilities,
  866. progress)
  867. return new_refs
  868. finally:
  869. resp.close()
  870. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  871. progress=None):
  872. """Retrieve a pack from a git smart server.
  873. :param determine_wants: Callback that returns list of commits to fetch
  874. :param graph_walker: Object with next() and ack().
  875. :param pack_data: Callback called for each bit of data in the pack
  876. :param progress: Callback for progress reports (strings)
  877. :return: Dictionary with the refs of the remote repository
  878. """
  879. url = self._get_url(path)
  880. refs, server_capabilities = self._discover_references(
  881. "git-upload-pack", url)
  882. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  883. wants = determine_wants(refs)
  884. if wants is not None:
  885. wants = [cid for cid in wants if cid != ZERO_SHA]
  886. if not wants:
  887. return refs
  888. if self.dumb:
  889. raise NotImplementedError(self.send_pack)
  890. req_data = BytesIO()
  891. req_proto = Protocol(None, req_data.write)
  892. self._handle_upload_pack_head(
  893. req_proto, negotiated_capabilities, graph_walker, wants,
  894. lambda: False)
  895. resp = self._smart_request(
  896. "git-upload-pack", url, data=req_data.getvalue())
  897. try:
  898. resp_proto = Protocol(resp.read, None)
  899. self._handle_upload_pack_tail(resp_proto, negotiated_capabilities,
  900. graph_walker, pack_data, progress)
  901. return refs
  902. finally:
  903. resp.close()
  904. def get_transport_and_path_from_url(url, config=None, **kwargs):
  905. """Obtain a git client from a URL.
  906. :param url: URL to open
  907. :param config: Optional config object
  908. :param thin_packs: Whether or not thin packs should be retrieved
  909. :param report_activity: Optional callback for reporting transport
  910. activity.
  911. :return: Tuple with client instance and relative path.
  912. """
  913. parsed = urlparse.urlparse(url)
  914. if parsed.scheme == 'git':
  915. return (TCPGitClient(parsed.hostname, port=parsed.port, **kwargs),
  916. parsed.path)
  917. elif parsed.scheme == 'git+ssh':
  918. path = parsed.path
  919. if path.startswith('/'):
  920. path = parsed.path[1:]
  921. return SSHGitClient(parsed.hostname, port=parsed.port,
  922. username=parsed.username, **kwargs), path
  923. elif parsed.scheme in ('http', 'https'):
  924. return HttpGitClient(urlparse.urlunparse(parsed), config=config,
  925. **kwargs), parsed.path
  926. elif parsed.scheme == 'file':
  927. return default_local_git_client_cls(**kwargs), parsed.path
  928. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  929. def get_transport_and_path(location, **kwargs):
  930. """Obtain a git client from a URL.
  931. :param location: URL or path
  932. :param config: Optional config object
  933. :param thin_packs: Whether or not thin packs should be retrieved
  934. :param report_activity: Optional callback for reporting transport
  935. activity.
  936. :return: Tuple with client instance and relative path.
  937. """
  938. # First, try to parse it as a URL
  939. try:
  940. return get_transport_and_path_from_url(location, **kwargs)
  941. except ValueError:
  942. pass
  943. if (sys.platform == 'win32' and
  944. location[0].isalpha() and location[1:2] == ':\\'):
  945. # Windows local path
  946. return default_local_git_client_cls(**kwargs), location
  947. if ':' in location and not '@' in location:
  948. # SSH with no user@, zero or one leading slash.
  949. (hostname, path) = location.split(':')
  950. return SSHGitClient(hostname, **kwargs), path
  951. elif '@' in location and ':' in location:
  952. # SSH with user@host:foo.
  953. user_host, path = location.split(':')
  954. user, host = user_host.rsplit('@')
  955. return SSHGitClient(host, username=user, **kwargs), path
  956. # Otherwise, assume it's a local path.
  957. return default_local_git_client_cls(**kwargs), location