client.py 55 KB

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