client.py 53 KB

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