client.py 46 KB

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