client.py 44 KB

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