client.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238
  1. # client.py -- Implementation of the client side git protocols
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  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. * shallow
  31. Known capabilities that are not supported:
  32. * no-progress
  33. * include-tag
  34. """
  35. from contextlib import closing
  36. from io import BytesIO, BufferedReader
  37. import logging
  38. import os
  39. import select
  40. import socket
  41. import subprocess
  42. import sys
  43. from typing import Optional, Dict, Callable, Set
  44. from urllib.parse import (
  45. quote as urlquote,
  46. unquote as urlunquote,
  47. urlparse,
  48. urljoin,
  49. urlunsplit,
  50. urlunparse,
  51. )
  52. import dulwich
  53. from dulwich.config import get_xdg_config_home_path
  54. from dulwich.errors import (
  55. GitProtocolError,
  56. NotGitRepository,
  57. SendPackError,
  58. )
  59. from dulwich.protocol import (
  60. HangupException,
  61. _RBUFSIZE,
  62. agent_string,
  63. capability_agent,
  64. extract_capability_names,
  65. CAPABILITY_AGENT,
  66. CAPABILITY_DELETE_REFS,
  67. CAPABILITY_INCLUDE_TAG,
  68. CAPABILITY_MULTI_ACK,
  69. CAPABILITY_MULTI_ACK_DETAILED,
  70. CAPABILITY_OFS_DELTA,
  71. CAPABILITY_QUIET,
  72. CAPABILITY_REPORT_STATUS,
  73. CAPABILITY_SHALLOW,
  74. CAPABILITY_SYMREF,
  75. CAPABILITY_SIDE_BAND_64K,
  76. CAPABILITY_THIN_PACK,
  77. CAPABILITIES_REF,
  78. KNOWN_RECEIVE_CAPABILITIES,
  79. KNOWN_UPLOAD_CAPABILITIES,
  80. COMMAND_DEEPEN,
  81. COMMAND_SHALLOW,
  82. COMMAND_UNSHALLOW,
  83. COMMAND_DONE,
  84. COMMAND_HAVE,
  85. COMMAND_WANT,
  86. SIDE_BAND_CHANNEL_DATA,
  87. SIDE_BAND_CHANNEL_PROGRESS,
  88. SIDE_BAND_CHANNEL_FATAL,
  89. PktLineParser,
  90. Protocol,
  91. ProtocolFile,
  92. TCP_GIT_PORT,
  93. ZERO_SHA,
  94. extract_capabilities,
  95. parse_capability,
  96. )
  97. from dulwich.pack import (
  98. write_pack_data,
  99. write_pack_objects,
  100. )
  101. from dulwich.refs import (
  102. read_info_refs,
  103. ANNOTATED_TAG_SUFFIX,
  104. )
  105. logger = logging.getLogger(__name__)
  106. class InvalidWants(Exception):
  107. """Invalid wants."""
  108. def __init__(self, wants):
  109. Exception.__init__(
  110. self, "requested wants not in server provided refs: %r" % wants
  111. )
  112. class HTTPUnauthorized(Exception):
  113. """Raised when authentication fails."""
  114. def __init__(self, www_authenticate, url):
  115. Exception.__init__(self, "No valid credentials provided")
  116. self.www_authenticate = www_authenticate
  117. self.url = url
  118. class HTTPProxyUnauthorized(Exception):
  119. """Raised when proxy authentication fails."""
  120. def __init__(self, proxy_authenticate, url):
  121. Exception.__init__(self, "No valid proxy credentials provided")
  122. self.proxy_authenticate = proxy_authenticate
  123. self.url = url
  124. def _fileno_can_read(fileno):
  125. """Check if a file descriptor is readable."""
  126. return len(select.select([fileno], [], [], 0)[0]) > 0
  127. def _win32_peek_avail(handle):
  128. """Wrapper around PeekNamedPipe to check how many bytes are available."""
  129. from ctypes import byref, wintypes, windll
  130. c_avail = wintypes.DWORD()
  131. c_message = wintypes.DWORD()
  132. success = windll.kernel32.PeekNamedPipe(
  133. handle, None, 0, None, byref(c_avail), byref(c_message)
  134. )
  135. if not success:
  136. raise OSError(wintypes.GetLastError())
  137. return c_avail.value
  138. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  139. UPLOAD_CAPABILITIES = [
  140. CAPABILITY_THIN_PACK,
  141. CAPABILITY_MULTI_ACK,
  142. CAPABILITY_MULTI_ACK_DETAILED,
  143. CAPABILITY_SHALLOW,
  144. ] + COMMON_CAPABILITIES
  145. RECEIVE_CAPABILITIES = [
  146. CAPABILITY_REPORT_STATUS,
  147. CAPABILITY_DELETE_REFS,
  148. ] + COMMON_CAPABILITIES
  149. class ReportStatusParser(object):
  150. """Handle status as reported by servers with 'report-status' capability."""
  151. def __init__(self):
  152. self._done = False
  153. self._pack_status = None
  154. self._ref_statuses = []
  155. def check(self):
  156. """Check if there were any errors and, if so, raise exceptions.
  157. Raises:
  158. SendPackError: Raised when the server could not unpack
  159. Returns:
  160. iterator over refs
  161. """
  162. if self._pack_status not in (b"unpack ok", None):
  163. raise SendPackError(self._pack_status)
  164. for status in self._ref_statuses:
  165. try:
  166. status, rest = status.split(b" ", 1)
  167. except ValueError:
  168. # malformed response, move on to the next one
  169. continue
  170. if status == b"ng":
  171. ref, error = rest.split(b" ", 1)
  172. yield ref, error.decode("utf-8")
  173. elif status == b"ok":
  174. yield rest, None
  175. else:
  176. raise GitProtocolError("invalid ref status %r" % status)
  177. def handle_packet(self, pkt):
  178. """Handle a packet.
  179. Raises:
  180. GitProtocolError: Raised when packets are received after a flush
  181. packet.
  182. """
  183. if self._done:
  184. raise GitProtocolError("received more data after status report")
  185. if pkt is None:
  186. self._done = True
  187. return
  188. if self._pack_status is None:
  189. self._pack_status = pkt.strip()
  190. else:
  191. ref_status = pkt.strip()
  192. self._ref_statuses.append(ref_status)
  193. def read_pkt_refs(proto):
  194. server_capabilities = None
  195. refs = {}
  196. # Receive refs from server
  197. for pkt in proto.read_pkt_seq():
  198. (sha, ref) = pkt.rstrip(b"\n").split(None, 1)
  199. if sha == b"ERR":
  200. raise GitProtocolError(ref.decode("utf-8", "replace"))
  201. if server_capabilities is None:
  202. (ref, server_capabilities) = extract_capabilities(ref)
  203. refs[ref] = sha
  204. if len(refs) == 0:
  205. return {}, set([])
  206. if refs == {CAPABILITIES_REF: ZERO_SHA}:
  207. refs = {}
  208. return refs, set(server_capabilities)
  209. class FetchPackResult(object):
  210. """Result of a fetch-pack operation.
  211. Attributes:
  212. refs: Dictionary with all remote refs
  213. symrefs: Dictionary with remote symrefs
  214. agent: User agent string
  215. """
  216. _FORWARDED_ATTRS = [
  217. "clear",
  218. "copy",
  219. "fromkeys",
  220. "get",
  221. "items",
  222. "keys",
  223. "pop",
  224. "popitem",
  225. "setdefault",
  226. "update",
  227. "values",
  228. "viewitems",
  229. "viewkeys",
  230. "viewvalues",
  231. ]
  232. def __init__(self, refs, symrefs, agent, new_shallow=None, new_unshallow=None):
  233. self.refs = refs
  234. self.symrefs = symrefs
  235. self.agent = agent
  236. self.new_shallow = new_shallow
  237. self.new_unshallow = new_unshallow
  238. def _warn_deprecated(self):
  239. import warnings
  240. warnings.warn(
  241. "Use FetchPackResult.refs instead.",
  242. DeprecationWarning,
  243. stacklevel=3,
  244. )
  245. def __eq__(self, other):
  246. if isinstance(other, dict):
  247. self._warn_deprecated()
  248. return self.refs == other
  249. return (
  250. self.refs == other.refs
  251. and self.symrefs == other.symrefs
  252. and self.agent == other.agent
  253. )
  254. def __contains__(self, name):
  255. self._warn_deprecated()
  256. return name in self.refs
  257. def __getitem__(self, name):
  258. self._warn_deprecated()
  259. return self.refs[name]
  260. def __len__(self):
  261. self._warn_deprecated()
  262. return len(self.refs)
  263. def __iter__(self):
  264. self._warn_deprecated()
  265. return iter(self.refs)
  266. def __getattribute__(self, name):
  267. if name in type(self)._FORWARDED_ATTRS:
  268. self._warn_deprecated()
  269. return getattr(self.refs, name)
  270. return super(FetchPackResult, self).__getattribute__(name)
  271. def __repr__(self):
  272. return "%s(%r, %r, %r)" % (
  273. self.__class__.__name__,
  274. self.refs,
  275. self.symrefs,
  276. self.agent,
  277. )
  278. class SendPackResult(object):
  279. """Result of a upload-pack operation.
  280. Attributes:
  281. refs: Dictionary with all remote refs
  282. agent: User agent string
  283. ref_status: Optional dictionary mapping ref name to error message (if it
  284. failed to update), or None if it was updated successfully
  285. """
  286. _FORWARDED_ATTRS = [
  287. "clear",
  288. "copy",
  289. "fromkeys",
  290. "get",
  291. "items",
  292. "keys",
  293. "pop",
  294. "popitem",
  295. "setdefault",
  296. "update",
  297. "values",
  298. "viewitems",
  299. "viewkeys",
  300. "viewvalues",
  301. ]
  302. def __init__(self, refs, agent=None, ref_status=None):
  303. self.refs = refs
  304. self.agent = agent
  305. self.ref_status = ref_status
  306. def _warn_deprecated(self):
  307. import warnings
  308. warnings.warn(
  309. "Use SendPackResult.refs instead.",
  310. DeprecationWarning,
  311. stacklevel=3,
  312. )
  313. def __eq__(self, other):
  314. if isinstance(other, dict):
  315. self._warn_deprecated()
  316. return self.refs == other
  317. return self.refs == other.refs and self.agent == other.agent
  318. def __contains__(self, name):
  319. self._warn_deprecated()
  320. return name in self.refs
  321. def __getitem__(self, name):
  322. self._warn_deprecated()
  323. return self.refs[name]
  324. def __len__(self):
  325. self._warn_deprecated()
  326. return len(self.refs)
  327. def __iter__(self):
  328. self._warn_deprecated()
  329. return iter(self.refs)
  330. def __getattribute__(self, name):
  331. if name in type(self)._FORWARDED_ATTRS:
  332. self._warn_deprecated()
  333. return getattr(self.refs, name)
  334. return super(SendPackResult, self).__getattribute__(name)
  335. def __repr__(self):
  336. return "%s(%r, %r)" % (self.__class__.__name__, self.refs, self.agent)
  337. def _read_shallow_updates(proto):
  338. new_shallow = set()
  339. new_unshallow = set()
  340. for pkt in proto.read_pkt_seq():
  341. cmd, sha = pkt.split(b" ", 1)
  342. if cmd == COMMAND_SHALLOW:
  343. new_shallow.add(sha.strip())
  344. elif cmd == COMMAND_UNSHALLOW:
  345. new_unshallow.add(sha.strip())
  346. else:
  347. raise GitProtocolError("unknown command %s" % pkt)
  348. return (new_shallow, new_unshallow)
  349. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  350. # support some capabilities. This should work properly with servers
  351. # that don't support multi_ack.
  352. class GitClient(object):
  353. """Git smart server client."""
  354. def __init__(
  355. self,
  356. thin_packs=True,
  357. report_activity=None,
  358. quiet=False,
  359. include_tags=False,
  360. ):
  361. """Create a new GitClient instance.
  362. Args:
  363. thin_packs: Whether or not thin packs should be retrieved
  364. report_activity: Optional callback for reporting transport
  365. activity.
  366. include_tags: send annotated tags when sending the objects they point
  367. to
  368. """
  369. self._report_activity = report_activity
  370. self._report_status_parser = None
  371. self._fetch_capabilities = set(UPLOAD_CAPABILITIES)
  372. self._fetch_capabilities.add(capability_agent())
  373. self._send_capabilities = set(RECEIVE_CAPABILITIES)
  374. self._send_capabilities.add(capability_agent())
  375. if quiet:
  376. self._send_capabilities.add(CAPABILITY_QUIET)
  377. if not thin_packs:
  378. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  379. if include_tags:
  380. self._fetch_capabilities.add(CAPABILITY_INCLUDE_TAG)
  381. def get_url(self, path):
  382. """Retrieves full url to given path.
  383. Args:
  384. path: Repository path (as string)
  385. Returns:
  386. Url to path (as string)
  387. """
  388. raise NotImplementedError(self.get_url)
  389. @classmethod
  390. def from_parsedurl(cls, parsedurl, **kwargs):
  391. """Create an instance of this client from a urlparse.parsed object.
  392. Args:
  393. parsedurl: Result of urlparse()
  394. Returns:
  395. A `GitClient` object
  396. """
  397. raise NotImplementedError(cls.from_parsedurl)
  398. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  399. """Upload a pack to a remote repository.
  400. Args:
  401. path: Repository path (as bytestring)
  402. update_refs: Function to determine changes to remote refs. Receive
  403. dict with existing remote refs, returns dict with
  404. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  405. generate_pack_data: Function that can return a tuple
  406. with number of objects and list of pack data to include
  407. progress: Optional progress function
  408. Returns:
  409. SendPackResult object
  410. Raises:
  411. SendPackError: if server rejects the pack data
  412. """
  413. raise NotImplementedError(self.send_pack)
  414. def fetch(self, path, target, determine_wants=None, progress=None, depth=None):
  415. """Fetch into a target repository.
  416. Args:
  417. path: Path to fetch from (as bytestring)
  418. target: Target repository to fetch into
  419. determine_wants: Optional function to determine what refs to fetch.
  420. Receives dictionary of name->sha, should return
  421. list of shas to fetch. Defaults to all shas.
  422. progress: Optional progress function
  423. depth: Depth to fetch at
  424. Returns:
  425. Dictionary with all remote refs (not just those fetched)
  426. """
  427. if determine_wants is None:
  428. determine_wants = target.object_store.determine_wants_all
  429. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  430. # TODO(jelmer): Avoid reading entire file into memory and
  431. # only processing it after the whole file has been fetched.
  432. f = BytesIO()
  433. def commit():
  434. if f.tell():
  435. f.seek(0)
  436. target.object_store.add_thin_pack(f.read, None)
  437. def abort():
  438. pass
  439. else:
  440. f, commit, abort = target.object_store.add_pack()
  441. try:
  442. result = self.fetch_pack(
  443. path,
  444. determine_wants,
  445. target.get_graph_walker(),
  446. f.write,
  447. progress=progress,
  448. depth=depth,
  449. )
  450. except BaseException:
  451. abort()
  452. raise
  453. else:
  454. commit()
  455. target.update_shallow(result.new_shallow, result.new_unshallow)
  456. return result
  457. def fetch_pack(
  458. self,
  459. path,
  460. determine_wants,
  461. graph_walker,
  462. pack_data,
  463. progress=None,
  464. depth=None,
  465. ):
  466. """Retrieve a pack from a git smart server.
  467. Args:
  468. path: Remote path to fetch from
  469. determine_wants: Function determine what refs
  470. to fetch. Receives dictionary of name->sha, should return
  471. list of shas to fetch.
  472. graph_walker: Object with next() and ack().
  473. pack_data: Callback called for each bit of data in the pack
  474. progress: Callback for progress reports (strings)
  475. depth: Shallow fetch depth
  476. Returns:
  477. FetchPackResult object
  478. """
  479. raise NotImplementedError(self.fetch_pack)
  480. def get_refs(self, path):
  481. """Retrieve the current refs from a git smart server.
  482. Args:
  483. path: Path to the repo to fetch from. (as bytestring)
  484. Returns:
  485. """
  486. raise NotImplementedError(self.get_refs)
  487. def _read_side_band64k_data(self, proto, channel_callbacks):
  488. """Read per-channel data.
  489. This requires the side-band-64k capability.
  490. Args:
  491. proto: Protocol object to read from
  492. channel_callbacks: Dictionary mapping channels to packet
  493. handlers to use. None for a callback discards channel data.
  494. """
  495. for pkt in proto.read_pkt_seq():
  496. channel = ord(pkt[:1])
  497. pkt = pkt[1:]
  498. try:
  499. cb = channel_callbacks[channel]
  500. except KeyError:
  501. raise AssertionError("Invalid sideband channel %d" % channel)
  502. else:
  503. if cb is not None:
  504. cb(pkt)
  505. @staticmethod
  506. def _should_send_pack(new_refs):
  507. # The packfile MUST NOT be sent if the only command used is delete.
  508. return any(sha != ZERO_SHA for sha in new_refs.values())
  509. def _handle_receive_pack_head(self, proto, capabilities, old_refs, new_refs):
  510. """Handle the head of a 'git-receive-pack' request.
  511. Args:
  512. proto: Protocol object to read from
  513. capabilities: List of negotiated capabilities
  514. old_refs: Old refs, as received from the server
  515. new_refs: Refs to change
  516. Returns:
  517. (have, want) tuple
  518. """
  519. want = []
  520. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  521. sent_capabilities = False
  522. for refname in new_refs:
  523. if not isinstance(refname, bytes):
  524. raise TypeError("refname is not a bytestring: %r" % refname)
  525. old_sha1 = old_refs.get(refname, ZERO_SHA)
  526. if not isinstance(old_sha1, bytes):
  527. raise TypeError(
  528. "old sha1 for %s is not a bytestring: %r" % (refname, old_sha1)
  529. )
  530. new_sha1 = new_refs.get(refname, ZERO_SHA)
  531. if not isinstance(new_sha1, bytes):
  532. raise TypeError(
  533. "old sha1 for %s is not a bytestring %r" % (refname, new_sha1)
  534. )
  535. if old_sha1 != new_sha1:
  536. logger.debug(
  537. 'Sending updated ref %r: %r -> %r',
  538. refname, old_sha1, new_sha1)
  539. if sent_capabilities:
  540. proto.write_pkt_line(old_sha1 + b" " + new_sha1 + b" " + refname)
  541. else:
  542. proto.write_pkt_line(
  543. old_sha1
  544. + b" "
  545. + new_sha1
  546. + b" "
  547. + refname
  548. + b"\0"
  549. + b" ".join(sorted(capabilities))
  550. )
  551. sent_capabilities = True
  552. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  553. want.append(new_sha1)
  554. proto.write_pkt_line(None)
  555. return (have, want)
  556. def _negotiate_receive_pack_capabilities(self, server_capabilities):
  557. negotiated_capabilities = self._send_capabilities & server_capabilities
  558. agent = None
  559. for capability in server_capabilities:
  560. k, v = parse_capability(capability)
  561. if k == CAPABILITY_AGENT:
  562. agent = v
  563. unknown_capabilities = ( # noqa: F841
  564. extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES
  565. )
  566. # TODO(jelmer): warn about unknown capabilities
  567. return negotiated_capabilities, agent
  568. def _handle_receive_pack_tail(
  569. self,
  570. proto: Protocol,
  571. capabilities: Set[bytes],
  572. progress: Callable[[bytes], None] = None,
  573. ) -> Optional[Dict[bytes, Optional[str]]]:
  574. """Handle the tail of a 'git-receive-pack' request.
  575. Args:
  576. proto: Protocol object to read from
  577. capabilities: List of negotiated capabilities
  578. progress: Optional progress reporting function
  579. Returns:
  580. dict mapping ref name to:
  581. error message if the ref failed to update
  582. None if it was updated successfully
  583. """
  584. if CAPABILITY_SIDE_BAND_64K in capabilities:
  585. if progress is None:
  586. def progress(x):
  587. pass
  588. channel_callbacks = {2: progress}
  589. if CAPABILITY_REPORT_STATUS in capabilities:
  590. channel_callbacks[1] = PktLineParser(
  591. self._report_status_parser.handle_packet
  592. ).parse
  593. self._read_side_band64k_data(proto, channel_callbacks)
  594. else:
  595. if CAPABILITY_REPORT_STATUS in capabilities:
  596. for pkt in proto.read_pkt_seq():
  597. self._report_status_parser.handle_packet(pkt)
  598. if self._report_status_parser is not None:
  599. return dict(self._report_status_parser.check())
  600. return None
  601. def _negotiate_upload_pack_capabilities(self, server_capabilities):
  602. unknown_capabilities = ( # noqa: F841
  603. extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES
  604. )
  605. # TODO(jelmer): warn about unknown capabilities
  606. symrefs = {}
  607. agent = None
  608. for capability in server_capabilities:
  609. k, v = parse_capability(capability)
  610. if k == CAPABILITY_SYMREF:
  611. (src, dst) = v.split(b":", 1)
  612. symrefs[src] = dst
  613. if k == CAPABILITY_AGENT:
  614. agent = v
  615. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  616. return (negotiated_capabilities, symrefs, agent)
  617. def _handle_upload_pack_head(
  618. self, proto, capabilities, graph_walker, wants, can_read, depth
  619. ):
  620. """Handle the head of a 'git-upload-pack' request.
  621. Args:
  622. proto: Protocol object to read from
  623. capabilities: List of negotiated capabilities
  624. graph_walker: GraphWalker instance to call .ack() on
  625. wants: List of commits to fetch
  626. can_read: function that returns a boolean that indicates
  627. whether there is extra graph data to read on proto
  628. depth: Depth for request
  629. Returns:
  630. """
  631. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  632. proto.write_pkt_line(
  633. COMMAND_WANT
  634. + b" "
  635. + wants[0]
  636. + b" "
  637. + b" ".join(sorted(capabilities))
  638. + b"\n"
  639. )
  640. for want in wants[1:]:
  641. proto.write_pkt_line(COMMAND_WANT + b" " + want + b"\n")
  642. if depth not in (0, None) or getattr(graph_walker, "shallow", None):
  643. if CAPABILITY_SHALLOW not in capabilities:
  644. raise GitProtocolError(
  645. "server does not support shallow capability required for " "depth"
  646. )
  647. for sha in graph_walker.shallow:
  648. proto.write_pkt_line(COMMAND_SHALLOW + b" " + sha + b"\n")
  649. if depth is not None:
  650. proto.write_pkt_line(
  651. COMMAND_DEEPEN + b" " + str(depth).encode("ascii") + b"\n"
  652. )
  653. proto.write_pkt_line(None)
  654. if can_read is not None:
  655. (new_shallow, new_unshallow) = _read_shallow_updates(proto)
  656. else:
  657. new_shallow = new_unshallow = None
  658. else:
  659. new_shallow = new_unshallow = set()
  660. proto.write_pkt_line(None)
  661. have = next(graph_walker)
  662. while have:
  663. proto.write_pkt_line(COMMAND_HAVE + b" " + have + b"\n")
  664. if can_read is not None and can_read():
  665. pkt = proto.read_pkt_line()
  666. parts = pkt.rstrip(b"\n").split(b" ")
  667. if parts[0] == b"ACK":
  668. graph_walker.ack(parts[1])
  669. if parts[2] in (b"continue", b"common"):
  670. pass
  671. elif parts[2] == b"ready":
  672. break
  673. else:
  674. raise AssertionError(
  675. "%s not in ('continue', 'ready', 'common)" % parts[2]
  676. )
  677. have = next(graph_walker)
  678. proto.write_pkt_line(COMMAND_DONE + b"\n")
  679. return (new_shallow, new_unshallow)
  680. def _handle_upload_pack_tail(
  681. self,
  682. proto,
  683. capabilities,
  684. graph_walker,
  685. pack_data,
  686. progress=None,
  687. rbufsize=_RBUFSIZE,
  688. ):
  689. """Handle the tail of a 'git-upload-pack' request.
  690. Args:
  691. proto: Protocol object to read from
  692. capabilities: List of negotiated capabilities
  693. graph_walker: GraphWalker instance to call .ack() on
  694. pack_data: Function to call with pack data
  695. progress: Optional progress reporting function
  696. rbufsize: Read buffer size
  697. Returns:
  698. """
  699. pkt = proto.read_pkt_line()
  700. while pkt:
  701. parts = pkt.rstrip(b"\n").split(b" ")
  702. if parts[0] == b"ACK":
  703. graph_walker.ack(parts[1])
  704. if len(parts) < 3 or parts[2] not in (
  705. b"ready",
  706. b"continue",
  707. b"common",
  708. ):
  709. break
  710. pkt = proto.read_pkt_line()
  711. if CAPABILITY_SIDE_BAND_64K in capabilities:
  712. if progress is None:
  713. # Just ignore progress data
  714. def progress(x):
  715. pass
  716. self._read_side_band64k_data(
  717. proto,
  718. {
  719. SIDE_BAND_CHANNEL_DATA: pack_data,
  720. SIDE_BAND_CHANNEL_PROGRESS: progress,
  721. },
  722. )
  723. else:
  724. while True:
  725. data = proto.read(rbufsize)
  726. if data == b"":
  727. break
  728. pack_data(data)
  729. def check_wants(wants, refs):
  730. """Check that a set of wants is valid.
  731. Args:
  732. wants: Set of object SHAs to fetch
  733. refs: Refs dictionary to check against
  734. Returns:
  735. """
  736. missing = set(wants) - {
  737. v for (k, v) in refs.items() if not k.endswith(ANNOTATED_TAG_SUFFIX)
  738. }
  739. if missing:
  740. raise InvalidWants(missing)
  741. def _remote_error_from_stderr(stderr):
  742. if stderr is None:
  743. return HangupException()
  744. lines = [line.rstrip(b"\n") for line in stderr.readlines()]
  745. for line in lines:
  746. if line.startswith(b"ERROR: "):
  747. return GitProtocolError(line[len(b"ERROR: ") :].decode("utf-8", "replace"))
  748. return HangupException(lines)
  749. class TraditionalGitClient(GitClient):
  750. """Traditional Git client."""
  751. DEFAULT_ENCODING = "utf-8"
  752. def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs):
  753. self._remote_path_encoding = path_encoding
  754. super(TraditionalGitClient, self).__init__(**kwargs)
  755. async def _connect(self, cmd, path):
  756. """Create a connection to the server.
  757. This method is abstract - concrete implementations should
  758. implement their own variant which connects to the server and
  759. returns an initialized Protocol object with the service ready
  760. for use and a can_read function which may be used to see if
  761. reads would block.
  762. Args:
  763. cmd: The git service name to which we should connect.
  764. path: The path we should pass to the service. (as bytestirng)
  765. """
  766. raise NotImplementedError()
  767. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  768. """Upload a pack to a remote repository.
  769. Args:
  770. path: Repository path (as bytestring)
  771. update_refs: Function to determine changes to remote refs.
  772. Receive dict with existing remote refs, returns dict with
  773. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  774. generate_pack_data: Function that can return a tuple with
  775. number of objects and pack data to upload.
  776. progress: Optional callback called with progress updates
  777. Returns:
  778. SendPackResult
  779. Raises:
  780. SendPackError: if server rejects the pack data
  781. """
  782. proto, unused_can_read, stderr = self._connect(b"receive-pack", path)
  783. with proto:
  784. try:
  785. old_refs, server_capabilities = read_pkt_refs(proto)
  786. except HangupException:
  787. raise _remote_error_from_stderr(stderr)
  788. (
  789. negotiated_capabilities,
  790. agent,
  791. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  792. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  793. self._report_status_parser = ReportStatusParser()
  794. report_status_parser = self._report_status_parser
  795. try:
  796. new_refs = orig_new_refs = update_refs(dict(old_refs))
  797. except BaseException:
  798. proto.write_pkt_line(None)
  799. raise
  800. if set(new_refs.items()).issubset(set(old_refs.items())):
  801. proto.write_pkt_line(None)
  802. return SendPackResult(new_refs, agent=agent, ref_status={})
  803. if CAPABILITY_DELETE_REFS not in server_capabilities:
  804. # Server does not support deletions. Fail later.
  805. new_refs = dict(orig_new_refs)
  806. for ref, sha in orig_new_refs.items():
  807. if sha == ZERO_SHA:
  808. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  809. report_status_parser._ref_statuses.append(
  810. b"ng " + ref + b" remote does not support deleting refs"
  811. )
  812. report_status_parser._ref_status_ok = False
  813. del new_refs[ref]
  814. if new_refs is None:
  815. proto.write_pkt_line(None)
  816. return SendPackResult(old_refs, agent=agent, ref_status={})
  817. if len(new_refs) == 0 and orig_new_refs:
  818. # NOOP - Original new refs filtered out by policy
  819. proto.write_pkt_line(None)
  820. if report_status_parser is not None:
  821. ref_status = dict(report_status_parser.check())
  822. else:
  823. ref_status = None
  824. return SendPackResult(old_refs, agent=agent, ref_status=ref_status)
  825. (have, want) = self._handle_receive_pack_head(
  826. proto, negotiated_capabilities, old_refs, new_refs
  827. )
  828. pack_data_count, pack_data = generate_pack_data(
  829. have,
  830. want,
  831. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  832. )
  833. if self._should_send_pack(new_refs):
  834. write_pack_data(proto.write_file(), pack_data_count, pack_data)
  835. ref_status = self._handle_receive_pack_tail(
  836. proto, negotiated_capabilities, progress
  837. )
  838. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  839. def fetch_pack(
  840. self,
  841. path,
  842. determine_wants,
  843. graph_walker,
  844. pack_data,
  845. progress=None,
  846. depth=None,
  847. ):
  848. """Retrieve a pack from a git smart server.
  849. Args:
  850. path: Remote path to fetch from
  851. determine_wants: Function determine what refs
  852. to fetch. Receives dictionary of name->sha, should return
  853. list of shas to fetch.
  854. graph_walker: Object with next() and ack().
  855. pack_data: Callback called for each bit of data in the pack
  856. progress: Callback for progress reports (strings)
  857. depth: Shallow fetch depth
  858. Returns:
  859. FetchPackResult object
  860. """
  861. proto, can_read, stderr = self._connect(b"upload-pack", path)
  862. with proto:
  863. try:
  864. refs, server_capabilities = read_pkt_refs(proto)
  865. except HangupException:
  866. raise _remote_error_from_stderr(stderr)
  867. (
  868. negotiated_capabilities,
  869. symrefs,
  870. agent,
  871. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  872. if refs is None:
  873. proto.write_pkt_line(None)
  874. return FetchPackResult(refs, symrefs, agent)
  875. try:
  876. if depth is not None:
  877. wants = determine_wants(refs, depth=depth)
  878. else:
  879. wants = determine_wants(refs)
  880. except BaseException:
  881. proto.write_pkt_line(None)
  882. raise
  883. if wants is not None:
  884. wants = [cid for cid in wants if cid != ZERO_SHA]
  885. if not wants:
  886. proto.write_pkt_line(None)
  887. return FetchPackResult(refs, symrefs, agent)
  888. (new_shallow, new_unshallow) = self._handle_upload_pack_head(
  889. proto,
  890. negotiated_capabilities,
  891. graph_walker,
  892. wants,
  893. can_read,
  894. depth=depth,
  895. )
  896. self._handle_upload_pack_tail(
  897. proto,
  898. negotiated_capabilities,
  899. graph_walker,
  900. pack_data,
  901. progress,
  902. )
  903. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  904. def get_refs(self, path):
  905. """Retrieve the current refs from a git smart server."""
  906. # stock `git ls-remote` uses upload-pack
  907. proto, _, stderr = self._connect(b"upload-pack", path)
  908. with proto:
  909. try:
  910. refs, _ = read_pkt_refs(proto)
  911. except HangupException:
  912. raise _remote_error_from_stderr(stderr)
  913. proto.write_pkt_line(None)
  914. return refs
  915. def archive(
  916. self,
  917. path,
  918. committish,
  919. write_data,
  920. progress=None,
  921. write_error=None,
  922. format=None,
  923. subdirs=None,
  924. prefix=None,
  925. ):
  926. proto, can_read, stderr = self._connect(b"upload-archive", path)
  927. with proto:
  928. if format is not None:
  929. proto.write_pkt_line(b"argument --format=" + format)
  930. proto.write_pkt_line(b"argument " + committish)
  931. if subdirs is not None:
  932. for subdir in subdirs:
  933. proto.write_pkt_line(b"argument " + subdir)
  934. if prefix is not None:
  935. proto.write_pkt_line(b"argument --prefix=" + prefix)
  936. proto.write_pkt_line(None)
  937. try:
  938. pkt = proto.read_pkt_line()
  939. except HangupException:
  940. raise _remote_error_from_stderr(stderr)
  941. if pkt == b"NACK\n" or pkt == b"NACK":
  942. return
  943. elif pkt == b"ACK\n" or pkt == b"ACK":
  944. pass
  945. elif pkt.startswith(b"ERR "):
  946. raise GitProtocolError(pkt[4:].rstrip(b"\n").decode("utf-8", "replace"))
  947. else:
  948. raise AssertionError("invalid response %r" % pkt)
  949. ret = proto.read_pkt_line()
  950. if ret is not None:
  951. raise AssertionError("expected pkt tail")
  952. self._read_side_band64k_data(
  953. proto,
  954. {
  955. SIDE_BAND_CHANNEL_DATA: write_data,
  956. SIDE_BAND_CHANNEL_PROGRESS: progress,
  957. SIDE_BAND_CHANNEL_FATAL: write_error,
  958. },
  959. )
  960. class TCPGitClient(TraditionalGitClient):
  961. """A Git Client that works over TCP directly (i.e. git://)."""
  962. def __init__(self, host, port=None, **kwargs):
  963. if port is None:
  964. port = TCP_GIT_PORT
  965. self._host = host
  966. self._port = port
  967. super(TCPGitClient, self).__init__(**kwargs)
  968. @classmethod
  969. def from_parsedurl(cls, parsedurl, **kwargs):
  970. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  971. def get_url(self, path):
  972. netloc = self._host
  973. if self._port is not None and self._port != TCP_GIT_PORT:
  974. netloc += ":%d" % self._port
  975. return urlunsplit(("git", netloc, path, "", ""))
  976. def _connect(self, cmd, path):
  977. if not isinstance(cmd, bytes):
  978. raise TypeError(cmd)
  979. if not isinstance(path, bytes):
  980. path = path.encode(self._remote_path_encoding)
  981. sockaddrs = socket.getaddrinfo(
  982. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM
  983. )
  984. s = None
  985. err = socket.error("no address found for %s" % self._host)
  986. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  987. s = socket.socket(family, socktype, proto)
  988. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  989. try:
  990. s.connect(sockaddr)
  991. break
  992. except socket.error as e:
  993. err = e
  994. if s is not None:
  995. s.close()
  996. s = None
  997. if s is None:
  998. raise err
  999. # -1 means system default buffering
  1000. rfile = s.makefile("rb", -1)
  1001. # 0 means unbuffered
  1002. wfile = s.makefile("wb", 0)
  1003. def close():
  1004. rfile.close()
  1005. wfile.close()
  1006. s.close()
  1007. proto = Protocol(
  1008. rfile.read,
  1009. wfile.write,
  1010. close,
  1011. report_activity=self._report_activity,
  1012. )
  1013. if path.startswith(b"/~"):
  1014. path = path[1:]
  1015. # TODO(jelmer): Alternative to ascii?
  1016. proto.send_cmd(b"git-" + cmd, path, b"host=" + self._host.encode("ascii"))
  1017. return proto, lambda: _fileno_can_read(s), None
  1018. class SubprocessWrapper(object):
  1019. """A socket-like object that talks to a subprocess via pipes."""
  1020. def __init__(self, proc):
  1021. self.proc = proc
  1022. self.read = BufferedReader(proc.stdout).read
  1023. self.write = proc.stdin.write
  1024. @property
  1025. def stderr(self):
  1026. return self.proc.stderr
  1027. def can_read(self):
  1028. if sys.platform == "win32":
  1029. from msvcrt import get_osfhandle
  1030. handle = get_osfhandle(self.proc.stdout.fileno())
  1031. return _win32_peek_avail(handle) != 0
  1032. else:
  1033. return _fileno_can_read(self.proc.stdout.fileno())
  1034. def close(self):
  1035. self.proc.stdin.close()
  1036. self.proc.stdout.close()
  1037. if self.proc.stderr:
  1038. self.proc.stderr.close()
  1039. self.proc.wait()
  1040. def find_git_command():
  1041. """Find command to run for system Git (usually C Git)."""
  1042. if sys.platform == "win32": # support .exe, .bat and .cmd
  1043. try: # to avoid overhead
  1044. import win32api
  1045. except ImportError: # run through cmd.exe with some overhead
  1046. return ["cmd", "/c", "git"]
  1047. else:
  1048. status, git = win32api.FindExecutable("git")
  1049. return [git]
  1050. else:
  1051. return ["git"]
  1052. class SubprocessGitClient(TraditionalGitClient):
  1053. """Git client that talks to a server using a subprocess."""
  1054. @classmethod
  1055. def from_parsedurl(cls, parsedurl, **kwargs):
  1056. return cls(**kwargs)
  1057. git_command = None
  1058. def _connect(self, service, path):
  1059. if not isinstance(service, bytes):
  1060. raise TypeError(service)
  1061. if isinstance(path, bytes):
  1062. path = path.decode(self._remote_path_encoding)
  1063. if self.git_command is None:
  1064. git_command = find_git_command()
  1065. argv = git_command + [service.decode("ascii"), path]
  1066. p = subprocess.Popen(
  1067. argv,
  1068. bufsize=0,
  1069. stdin=subprocess.PIPE,
  1070. stdout=subprocess.PIPE,
  1071. stderr=subprocess.PIPE,
  1072. )
  1073. pw = SubprocessWrapper(p)
  1074. return (
  1075. Protocol(
  1076. pw.read,
  1077. pw.write,
  1078. pw.close,
  1079. report_activity=self._report_activity,
  1080. ),
  1081. pw.can_read,
  1082. p.stderr,
  1083. )
  1084. class LocalGitClient(GitClient):
  1085. """Git Client that just uses a local Repo."""
  1086. def __init__(self, thin_packs=True, report_activity=None, config=None):
  1087. """Create a new LocalGitClient instance.
  1088. Args:
  1089. thin_packs: Whether or not thin packs should be retrieved
  1090. report_activity: Optional callback for reporting transport
  1091. activity.
  1092. """
  1093. self._report_activity = report_activity
  1094. # Ignore the thin_packs argument
  1095. def get_url(self, path):
  1096. return urlunsplit(("file", "", path, "", ""))
  1097. @classmethod
  1098. def from_parsedurl(cls, parsedurl, **kwargs):
  1099. return cls(**kwargs)
  1100. @classmethod
  1101. def _open_repo(cls, path):
  1102. from dulwich.repo import Repo
  1103. if not isinstance(path, str):
  1104. path = os.fsdecode(path)
  1105. return closing(Repo(path))
  1106. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1107. """Upload a pack to a remote repository.
  1108. Args:
  1109. path: Repository path (as bytestring)
  1110. update_refs: Function to determine changes to remote refs.
  1111. Receive dict with existing remote refs, returns dict with
  1112. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1113. with number of items and pack data to upload.
  1114. progress: Optional progress function
  1115. Returns:
  1116. SendPackResult
  1117. Raises:
  1118. SendPackError: if server rejects the pack data
  1119. """
  1120. if not progress:
  1121. def progress(x):
  1122. pass
  1123. with self._open_repo(path) as target:
  1124. old_refs = target.get_refs()
  1125. new_refs = update_refs(dict(old_refs))
  1126. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  1127. want = []
  1128. for refname, new_sha1 in new_refs.items():
  1129. if (
  1130. new_sha1 not in have
  1131. and new_sha1 not in want
  1132. and new_sha1 != ZERO_SHA
  1133. ):
  1134. want.append(new_sha1)
  1135. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1136. return SendPackResult(new_refs, ref_status={})
  1137. target.object_store.add_pack_data(
  1138. *generate_pack_data(have, want, ofs_delta=True)
  1139. )
  1140. ref_status = {}
  1141. for refname, new_sha1 in new_refs.items():
  1142. old_sha1 = old_refs.get(refname, ZERO_SHA)
  1143. if new_sha1 != ZERO_SHA:
  1144. if not target.refs.set_if_equals(refname, old_sha1, new_sha1):
  1145. msg = "unable to set %s to %s" % (refname, new_sha1)
  1146. progress(msg)
  1147. ref_status[refname] = msg
  1148. else:
  1149. if not target.refs.remove_if_equals(refname, old_sha1):
  1150. progress("unable to remove %s" % refname)
  1151. ref_status[refname] = "unable to remove"
  1152. return SendPackResult(new_refs, ref_status=ref_status)
  1153. def fetch(self, path, target, determine_wants=None, progress=None, depth=None):
  1154. """Fetch into a target repository.
  1155. Args:
  1156. path: Path to fetch from (as bytestring)
  1157. target: Target repository to fetch into
  1158. determine_wants: Optional function determine what refs
  1159. to fetch. Receives dictionary of name->sha, should return
  1160. list of shas to fetch. Defaults to all shas.
  1161. progress: Optional progress function
  1162. depth: Shallow fetch depth
  1163. Returns:
  1164. FetchPackResult object
  1165. """
  1166. with self._open_repo(path) as r:
  1167. refs = r.fetch(
  1168. target,
  1169. determine_wants=determine_wants,
  1170. progress=progress,
  1171. depth=depth,
  1172. )
  1173. return FetchPackResult(refs, r.refs.get_symrefs(), agent_string())
  1174. def fetch_pack(
  1175. self,
  1176. path,
  1177. determine_wants,
  1178. graph_walker,
  1179. pack_data,
  1180. progress=None,
  1181. depth=None,
  1182. ):
  1183. """Retrieve a pack from a git smart server.
  1184. Args:
  1185. path: Remote path to fetch from
  1186. determine_wants: Function determine what refs
  1187. to fetch. Receives dictionary of name->sha, should return
  1188. list of shas to fetch.
  1189. graph_walker: Object with next() and ack().
  1190. pack_data: Callback called for each bit of data in the pack
  1191. progress: Callback for progress reports (strings)
  1192. depth: Shallow fetch depth
  1193. Returns:
  1194. FetchPackResult object
  1195. """
  1196. with self._open_repo(path) as r:
  1197. objects_iter = r.fetch_objects(
  1198. determine_wants, graph_walker, progress=progress, depth=depth
  1199. )
  1200. symrefs = r.refs.get_symrefs()
  1201. agent = agent_string()
  1202. # Did the process short-circuit (e.g. in a stateless RPC call)?
  1203. # Note that the client still expects a 0-object pack in most cases.
  1204. if objects_iter is None:
  1205. return FetchPackResult(None, symrefs, agent)
  1206. protocol = ProtocolFile(None, pack_data)
  1207. write_pack_objects(protocol, objects_iter)
  1208. return FetchPackResult(r.get_refs(), symrefs, agent)
  1209. def get_refs(self, path):
  1210. """Retrieve the current refs from a git smart server."""
  1211. with self._open_repo(path) as target:
  1212. return target.get_refs()
  1213. # What Git client to use for local access
  1214. default_local_git_client_cls = LocalGitClient
  1215. class SSHVendor(object):
  1216. """A client side SSH implementation."""
  1217. def connect_ssh(
  1218. self,
  1219. host,
  1220. command,
  1221. username=None,
  1222. port=None,
  1223. password=None,
  1224. key_filename=None,
  1225. ):
  1226. # This function was deprecated in 0.9.1
  1227. import warnings
  1228. warnings.warn(
  1229. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  1230. DeprecationWarning,
  1231. )
  1232. return self.run_command(
  1233. host,
  1234. command,
  1235. username=username,
  1236. port=port,
  1237. password=password,
  1238. key_filename=key_filename,
  1239. )
  1240. def run_command(
  1241. self,
  1242. host,
  1243. command,
  1244. username=None,
  1245. port=None,
  1246. password=None,
  1247. key_filename=None,
  1248. ):
  1249. """Connect to an SSH server.
  1250. Run a command remotely and return a file-like object for interaction
  1251. with the remote command.
  1252. Args:
  1253. host: Host name
  1254. command: Command to run (as argv array)
  1255. username: Optional ame of user to log in as
  1256. port: Optional SSH port to use
  1257. password: Optional ssh password for login or private key
  1258. key_filename: Optional path to private keyfile
  1259. Returns:
  1260. """
  1261. raise NotImplementedError(self.run_command)
  1262. class StrangeHostname(Exception):
  1263. """Refusing to connect to strange SSH hostname."""
  1264. def __init__(self, hostname):
  1265. super(StrangeHostname, self).__init__(hostname)
  1266. class SubprocessSSHVendor(SSHVendor):
  1267. """SSH vendor that shells out to the local 'ssh' command."""
  1268. def run_command(
  1269. self,
  1270. host,
  1271. command,
  1272. username=None,
  1273. port=None,
  1274. password=None,
  1275. key_filename=None,
  1276. ):
  1277. if password is not None:
  1278. raise NotImplementedError(
  1279. "Setting password not supported by SubprocessSSHVendor."
  1280. )
  1281. args = ["ssh", "-x"]
  1282. if port:
  1283. args.extend(["-p", str(port)])
  1284. if key_filename:
  1285. args.extend(["-i", str(key_filename)])
  1286. if username:
  1287. host = "%s@%s" % (username, host)
  1288. if host.startswith("-"):
  1289. raise StrangeHostname(hostname=host)
  1290. args.append(host)
  1291. proc = subprocess.Popen(
  1292. args + [command],
  1293. bufsize=0,
  1294. stdin=subprocess.PIPE,
  1295. stdout=subprocess.PIPE,
  1296. stderr=subprocess.PIPE,
  1297. )
  1298. return SubprocessWrapper(proc)
  1299. class PLinkSSHVendor(SSHVendor):
  1300. """SSH vendor that shells out to the local 'plink' command."""
  1301. def run_command(
  1302. self,
  1303. host,
  1304. command,
  1305. username=None,
  1306. port=None,
  1307. password=None,
  1308. key_filename=None,
  1309. ):
  1310. if sys.platform == "win32":
  1311. args = ["plink.exe", "-ssh"]
  1312. else:
  1313. args = ["plink", "-ssh"]
  1314. if password is not None:
  1315. import warnings
  1316. warnings.warn(
  1317. "Invoking PLink with a password exposes the password in the "
  1318. "process list."
  1319. )
  1320. args.extend(["-pw", str(password)])
  1321. if port:
  1322. args.extend(["-P", str(port)])
  1323. if key_filename:
  1324. args.extend(["-i", str(key_filename)])
  1325. if username:
  1326. host = "%s@%s" % (username, host)
  1327. if host.startswith("-"):
  1328. raise StrangeHostname(hostname=host)
  1329. args.append(host)
  1330. proc = subprocess.Popen(
  1331. args + [command],
  1332. bufsize=0,
  1333. stdin=subprocess.PIPE,
  1334. stdout=subprocess.PIPE,
  1335. stderr=subprocess.PIPE,
  1336. )
  1337. return SubprocessWrapper(proc)
  1338. def ParamikoSSHVendor(**kwargs):
  1339. import warnings
  1340. warnings.warn(
  1341. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  1342. DeprecationWarning,
  1343. )
  1344. from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
  1345. return ParamikoSSHVendor(**kwargs)
  1346. # Can be overridden by users
  1347. get_ssh_vendor = SubprocessSSHVendor
  1348. class SSHGitClient(TraditionalGitClient):
  1349. def __init__(
  1350. self,
  1351. host,
  1352. port=None,
  1353. username=None,
  1354. vendor=None,
  1355. config=None,
  1356. password=None,
  1357. key_filename=None,
  1358. **kwargs
  1359. ):
  1360. self.host = host
  1361. self.port = port
  1362. self.username = username
  1363. self.password = password
  1364. self.key_filename = key_filename
  1365. super(SSHGitClient, self).__init__(**kwargs)
  1366. self.alternative_paths = {}
  1367. if vendor is not None:
  1368. self.ssh_vendor = vendor
  1369. else:
  1370. self.ssh_vendor = get_ssh_vendor()
  1371. def get_url(self, path):
  1372. netloc = self.host
  1373. if self.port is not None:
  1374. netloc += ":%d" % self.port
  1375. if self.username is not None:
  1376. netloc = urlquote(self.username, "@/:") + "@" + netloc
  1377. return urlunsplit(("ssh", netloc, path, "", ""))
  1378. @classmethod
  1379. def from_parsedurl(cls, parsedurl, **kwargs):
  1380. return cls(
  1381. host=parsedurl.hostname,
  1382. port=parsedurl.port,
  1383. username=parsedurl.username,
  1384. **kwargs
  1385. )
  1386. def _get_cmd_path(self, cmd):
  1387. cmd = self.alternative_paths.get(cmd, b"git-" + cmd)
  1388. assert isinstance(cmd, bytes)
  1389. return cmd
  1390. def _connect(self, cmd, path):
  1391. if not isinstance(cmd, bytes):
  1392. raise TypeError(cmd)
  1393. if isinstance(path, bytes):
  1394. path = path.decode(self._remote_path_encoding)
  1395. if path.startswith("/~"):
  1396. path = path[1:]
  1397. argv = (
  1398. self._get_cmd_path(cmd).decode(self._remote_path_encoding)
  1399. + " '"
  1400. + path
  1401. + "'"
  1402. )
  1403. kwargs = {}
  1404. if self.password is not None:
  1405. kwargs["password"] = self.password
  1406. if self.key_filename is not None:
  1407. kwargs["key_filename"] = self.key_filename
  1408. con = self.ssh_vendor.run_command(
  1409. self.host, argv, port=self.port, username=self.username, **kwargs
  1410. )
  1411. return (
  1412. Protocol(
  1413. con.read,
  1414. con.write,
  1415. con.close,
  1416. report_activity=self._report_activity,
  1417. ),
  1418. con.can_read,
  1419. getattr(con, "stderr", None),
  1420. )
  1421. def default_user_agent_string():
  1422. # Start user agent with "git/", because GitHub requires this. :-( See
  1423. # https://github.com/jelmer/dulwich/issues/562 for details.
  1424. return "git/dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  1425. def default_urllib3_manager( # noqa: C901
  1426. config, pool_manager_cls=None, proxy_manager_cls=None, **override_kwargs
  1427. ):
  1428. """Return `urllib3` connection pool manager.
  1429. Honour detected proxy configurations.
  1430. Args:
  1431. config: dulwich.config.ConfigDict` instance with Git configuration.
  1432. kwargs: Additional arguments for urllib3.ProxyManager
  1433. Returns:
  1434. `pool_manager_cls` (defaults to `urllib3.ProxyManager`) instance for
  1435. proxy configurations, `proxy_manager_cls` (defaults to
  1436. `urllib3.PoolManager`) instance otherwise.
  1437. """
  1438. proxy_server = user_agent = None
  1439. ca_certs = ssl_verify = None
  1440. if proxy_server is None:
  1441. for proxyname in ("https_proxy", "http_proxy", "all_proxy"):
  1442. proxy_server = os.environ.get(proxyname)
  1443. if proxy_server is not None:
  1444. break
  1445. if config is not None:
  1446. if proxy_server is None:
  1447. try:
  1448. proxy_server = config.get(b"http", b"proxy")
  1449. except KeyError:
  1450. pass
  1451. try:
  1452. user_agent = config.get(b"http", b"useragent")
  1453. except KeyError:
  1454. pass
  1455. # TODO(jelmer): Support per-host settings
  1456. try:
  1457. ssl_verify = config.get_boolean(b"http", b"sslVerify")
  1458. except KeyError:
  1459. ssl_verify = True
  1460. try:
  1461. ca_certs = config.get(b"http", b"sslCAInfo")
  1462. except KeyError:
  1463. ca_certs = None
  1464. if user_agent is None:
  1465. user_agent = default_user_agent_string()
  1466. headers = {"User-agent": user_agent}
  1467. kwargs = {}
  1468. if ssl_verify is True:
  1469. kwargs["cert_reqs"] = "CERT_REQUIRED"
  1470. elif ssl_verify is False:
  1471. kwargs["cert_reqs"] = "CERT_NONE"
  1472. else:
  1473. # Default to SSL verification
  1474. kwargs["cert_reqs"] = "CERT_REQUIRED"
  1475. if ca_certs is not None:
  1476. kwargs["ca_certs"] = ca_certs
  1477. kwargs.update(override_kwargs)
  1478. # Try really hard to find a SSL certificate path
  1479. if "ca_certs" not in kwargs and kwargs.get("cert_reqs") != "CERT_NONE":
  1480. try:
  1481. import certifi
  1482. except ImportError:
  1483. pass
  1484. else:
  1485. kwargs["ca_certs"] = certifi.where()
  1486. import urllib3
  1487. if proxy_server is not None:
  1488. if proxy_manager_cls is None:
  1489. proxy_manager_cls = urllib3.ProxyManager
  1490. if not isinstance(proxy_server, str):
  1491. proxy_server = proxy_server.decode()
  1492. manager = proxy_manager_cls(proxy_server, headers=headers, **kwargs)
  1493. else:
  1494. if pool_manager_cls is None:
  1495. pool_manager_cls = urllib3.PoolManager
  1496. manager = pool_manager_cls(headers=headers, **kwargs)
  1497. return manager
  1498. class AbstractHttpGitClient(GitClient):
  1499. """Abstract base class for HTTP Git Clients.
  1500. This is agonistic of the actual HTTP implementation.
  1501. Subclasses should provide an implementation of the
  1502. _http_request method.
  1503. """
  1504. def __init__(self, base_url, dumb=False, **kwargs):
  1505. self._base_url = base_url.rstrip("/") + "/"
  1506. self.dumb = dumb
  1507. GitClient.__init__(self, **kwargs)
  1508. def _http_request(self, url, headers=None, data=None, allow_compression=False):
  1509. """Perform HTTP request.
  1510. Args:
  1511. url: Request URL.
  1512. headers: Optional custom headers to override defaults.
  1513. data: Request data.
  1514. allow_compression: Allow GZipped communication.
  1515. Returns:
  1516. Tuple (`response`, `read`), where response is an `urllib3`
  1517. response object with additional `content_type` and
  1518. `redirect_location` properties, and `read` is a consumable read
  1519. method for the response data.
  1520. """
  1521. raise NotImplementedError(self._http_request)
  1522. def _discover_references(self, service, base_url):
  1523. assert base_url[-1] == "/"
  1524. tail = "info/refs"
  1525. headers = {"Accept": "*/*"}
  1526. if self.dumb is not True:
  1527. tail += "?service=%s" % service.decode("ascii")
  1528. url = urljoin(base_url, tail)
  1529. resp, read = self._http_request(url, headers, allow_compression=True)
  1530. if resp.redirect_location:
  1531. # Something changed (redirect!), so let's update the base URL
  1532. if not resp.redirect_location.endswith(tail):
  1533. raise GitProtocolError(
  1534. "Redirected from URL %s to URL %s without %s"
  1535. % (url, resp.redirect_location, tail)
  1536. )
  1537. base_url = resp.redirect_location[: -len(tail)]
  1538. try:
  1539. self.dumb = not resp.content_type.startswith("application/x-git-")
  1540. if not self.dumb:
  1541. proto = Protocol(read, None)
  1542. # The first line should mention the service
  1543. try:
  1544. [pkt] = list(proto.read_pkt_seq())
  1545. except ValueError:
  1546. raise GitProtocolError("unexpected number of packets received")
  1547. if pkt.rstrip(b"\n") != (b"# service=" + service):
  1548. raise GitProtocolError(
  1549. "unexpected first line %r from smart server" % pkt
  1550. )
  1551. return read_pkt_refs(proto) + (base_url,)
  1552. else:
  1553. return read_info_refs(resp), set(), base_url
  1554. finally:
  1555. resp.close()
  1556. def _smart_request(self, service, url, data):
  1557. """Send a 'smart' HTTP request.
  1558. This is a simple wrapper around _http_request that sets
  1559. a couple of extra headers.
  1560. """
  1561. assert url[-1] == "/"
  1562. url = urljoin(url, service)
  1563. result_content_type = "application/x-%s-result" % service
  1564. headers = {
  1565. "Content-Type": "application/x-%s-request" % service,
  1566. "Accept": result_content_type,
  1567. "Content-Length": str(len(data)),
  1568. }
  1569. resp, read = self._http_request(url, headers, data)
  1570. if resp.content_type != result_content_type:
  1571. raise GitProtocolError(
  1572. "Invalid content-type from server: %s" % resp.content_type
  1573. )
  1574. return resp, read
  1575. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1576. """Upload a pack to a remote repository.
  1577. Args:
  1578. path: Repository path (as bytestring)
  1579. update_refs: Function to determine changes to remote refs.
  1580. Receives dict with existing remote refs, returns dict with
  1581. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1582. generate_pack_data: Function that can return a tuple
  1583. with number of elements and pack data to upload.
  1584. progress: Optional progress function
  1585. Returns:
  1586. SendPackResult
  1587. Raises:
  1588. SendPackError: if server rejects the pack data
  1589. """
  1590. url = self._get_url(path)
  1591. old_refs, server_capabilities, url = self._discover_references(
  1592. b"git-receive-pack", url
  1593. )
  1594. (
  1595. negotiated_capabilities,
  1596. agent,
  1597. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  1598. negotiated_capabilities.add(capability_agent())
  1599. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1600. self._report_status_parser = ReportStatusParser()
  1601. new_refs = update_refs(dict(old_refs))
  1602. if new_refs is None:
  1603. # Determine wants function is aborting the push.
  1604. return SendPackResult(old_refs, agent=agent, ref_status={})
  1605. if set(new_refs.items()).issubset(set(old_refs.items())):
  1606. return SendPackResult(new_refs, agent=agent, ref_status={})
  1607. if self.dumb:
  1608. raise NotImplementedError(self.fetch_pack)
  1609. req_data = BytesIO()
  1610. req_proto = Protocol(None, req_data.write)
  1611. (have, want) = self._handle_receive_pack_head(
  1612. req_proto, negotiated_capabilities, old_refs, new_refs
  1613. )
  1614. pack_data_count, pack_data = generate_pack_data(
  1615. have,
  1616. want,
  1617. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  1618. )
  1619. if self._should_send_pack(new_refs):
  1620. write_pack_data(req_proto.write_file(), pack_data_count, pack_data)
  1621. resp, read = self._smart_request(
  1622. "git-receive-pack", url, data=req_data.getvalue()
  1623. )
  1624. try:
  1625. resp_proto = Protocol(read, None)
  1626. ref_status = self._handle_receive_pack_tail(
  1627. resp_proto, negotiated_capabilities, progress
  1628. )
  1629. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  1630. finally:
  1631. resp.close()
  1632. def fetch_pack(
  1633. self,
  1634. path,
  1635. determine_wants,
  1636. graph_walker,
  1637. pack_data,
  1638. progress=None,
  1639. depth=None,
  1640. ):
  1641. """Retrieve a pack from a git smart server.
  1642. Args:
  1643. path: Path to fetch from
  1644. determine_wants: Callback that returns list of commits to fetch
  1645. graph_walker: Object with next() and ack().
  1646. pack_data: Callback called for each bit of data in the pack
  1647. progress: Callback for progress reports (strings)
  1648. depth: Depth for request
  1649. Returns:
  1650. FetchPackResult object
  1651. """
  1652. url = self._get_url(path)
  1653. refs, server_capabilities, url = self._discover_references(
  1654. b"git-upload-pack", url
  1655. )
  1656. (
  1657. negotiated_capabilities,
  1658. symrefs,
  1659. agent,
  1660. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1661. if depth is not None:
  1662. wants = determine_wants(refs, depth=depth)
  1663. else:
  1664. wants = determine_wants(refs)
  1665. if wants is not None:
  1666. wants = [cid for cid in wants if cid != ZERO_SHA]
  1667. if not wants:
  1668. return FetchPackResult(refs, symrefs, agent)
  1669. if self.dumb:
  1670. raise NotImplementedError(self.fetch_pack)
  1671. req_data = BytesIO()
  1672. req_proto = Protocol(None, req_data.write)
  1673. (new_shallow, new_unshallow) = self._handle_upload_pack_head(
  1674. req_proto,
  1675. negotiated_capabilities,
  1676. graph_walker,
  1677. wants,
  1678. can_read=None,
  1679. depth=depth,
  1680. )
  1681. resp, read = self._smart_request(
  1682. "git-upload-pack", url, data=req_data.getvalue()
  1683. )
  1684. try:
  1685. resp_proto = Protocol(read, None)
  1686. if new_shallow is None and new_unshallow is None:
  1687. (new_shallow, new_unshallow) = _read_shallow_updates(resp_proto)
  1688. self._handle_upload_pack_tail(
  1689. resp_proto,
  1690. negotiated_capabilities,
  1691. graph_walker,
  1692. pack_data,
  1693. progress,
  1694. )
  1695. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  1696. finally:
  1697. resp.close()
  1698. def get_refs(self, path):
  1699. """Retrieve the current refs from a git smart server."""
  1700. url = self._get_url(path)
  1701. refs, _, _ = self._discover_references(b"git-upload-pack", url)
  1702. return refs
  1703. def get_url(self, path):
  1704. return self._get_url(path).rstrip("/")
  1705. def _get_url(self, path):
  1706. return urljoin(self._base_url, path).rstrip("/") + "/"
  1707. @classmethod
  1708. def from_parsedurl(cls, parsedurl, **kwargs):
  1709. password = parsedurl.password
  1710. if password is not None:
  1711. kwargs["password"] = urlunquote(password)
  1712. username = parsedurl.username
  1713. if username is not None:
  1714. kwargs["username"] = urlunquote(username)
  1715. netloc = parsedurl.hostname
  1716. if parsedurl.port:
  1717. netloc = "%s:%s" % (netloc, parsedurl.port)
  1718. if parsedurl.username:
  1719. netloc = "%s@%s" % (parsedurl.username, netloc)
  1720. parsedurl = parsedurl._replace(netloc=netloc)
  1721. return cls(urlunparse(parsedurl), **kwargs)
  1722. def __repr__(self):
  1723. return "%s(%r, dumb=%r)" % (
  1724. type(self).__name__,
  1725. self._base_url,
  1726. self.dumb,
  1727. )
  1728. class Urllib3HttpGitClient(AbstractHttpGitClient):
  1729. def __init__(
  1730. self,
  1731. base_url,
  1732. dumb=None,
  1733. pool_manager=None,
  1734. config=None,
  1735. username=None,
  1736. password=None,
  1737. **kwargs
  1738. ):
  1739. self._username = username
  1740. self._password = password
  1741. if pool_manager is None:
  1742. self.pool_manager = default_urllib3_manager(config)
  1743. else:
  1744. self.pool_manager = pool_manager
  1745. if username is not None:
  1746. # No escaping needed: ":" is not allowed in username:
  1747. # https://tools.ietf.org/html/rfc2617#section-2
  1748. credentials = "%s:%s" % (username, password)
  1749. import urllib3.util
  1750. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  1751. self.pool_manager.headers.update(basic_auth)
  1752. super(Urllib3HttpGitClient, self).__init__(
  1753. base_url=base_url, dumb=dumb, **kwargs)
  1754. def _get_url(self, path):
  1755. if not isinstance(path, str):
  1756. # urllib3.util.url._encode_invalid_chars() converts the path back
  1757. # to bytes using the utf-8 codec.
  1758. path = path.decode("utf-8")
  1759. return urljoin(self._base_url, path).rstrip("/") + "/"
  1760. def _http_request(self, url, headers=None, data=None, allow_compression=False):
  1761. req_headers = self.pool_manager.headers.copy()
  1762. if headers is not None:
  1763. req_headers.update(headers)
  1764. req_headers["Pragma"] = "no-cache"
  1765. if allow_compression:
  1766. req_headers["Accept-Encoding"] = "gzip"
  1767. else:
  1768. req_headers["Accept-Encoding"] = "identity"
  1769. if data is None:
  1770. resp = self.pool_manager.request("GET", url, headers=req_headers)
  1771. else:
  1772. resp = self.pool_manager.request(
  1773. "POST", url, headers=req_headers, body=data
  1774. )
  1775. if resp.status == 404:
  1776. raise NotGitRepository()
  1777. if resp.status == 401:
  1778. raise HTTPUnauthorized(resp.getheader("WWW-Authenticate"), url)
  1779. if resp.status == 407:
  1780. raise HTTPProxyUnauthorized(resp.getheader("Proxy-Authenticate"), url)
  1781. if resp.status != 200:
  1782. raise GitProtocolError(
  1783. "unexpected http resp %d for %s" % (resp.status, url)
  1784. )
  1785. # TODO: Optimization available by adding `preload_content=False` to the
  1786. # request and just passing the `read` method on instead of going via
  1787. # `BytesIO`, if we can guarantee that the entire response is consumed
  1788. # before issuing the next to still allow for connection reuse from the
  1789. # pool.
  1790. read = BytesIO(resp.data).read
  1791. resp.content_type = resp.getheader("Content-Type")
  1792. # Check if geturl() is available (urllib3 version >= 1.23)
  1793. try:
  1794. resp_url = resp.geturl()
  1795. except AttributeError:
  1796. # get_redirect_location() is available for urllib3 >= 1.1
  1797. resp.redirect_location = resp.get_redirect_location()
  1798. else:
  1799. resp.redirect_location = resp_url if resp_url != url else ""
  1800. return resp, read
  1801. HttpGitClient = Urllib3HttpGitClient
  1802. def get_transport_and_path_from_url(url, config=None, **kwargs):
  1803. """Obtain a git client from a URL.
  1804. Args:
  1805. url: URL to open (a unicode string)
  1806. config: Optional config object
  1807. thin_packs: Whether or not thin packs should be retrieved
  1808. report_activity: Optional callback for reporting transport
  1809. activity.
  1810. Returns:
  1811. Tuple with client instance and relative path.
  1812. """
  1813. parsed = urlparse(url)
  1814. if parsed.scheme == "git":
  1815. return (TCPGitClient.from_parsedurl(parsed, **kwargs), parsed.path)
  1816. elif parsed.scheme in ("git+ssh", "ssh"):
  1817. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  1818. elif parsed.scheme in ("http", "https"):
  1819. return (
  1820. HttpGitClient.from_parsedurl(parsed, config=config, **kwargs),
  1821. parsed.path,
  1822. )
  1823. elif parsed.scheme == "file":
  1824. return (
  1825. default_local_git_client_cls.from_parsedurl(parsed, **kwargs),
  1826. parsed.path,
  1827. )
  1828. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  1829. def parse_rsync_url(location):
  1830. """Parse a rsync-style URL."""
  1831. if ":" in location and "@" not in location:
  1832. # SSH with no user@, zero or one leading slash.
  1833. (host, path) = location.split(":", 1)
  1834. user = None
  1835. elif ":" in location:
  1836. # SSH with user@host:foo.
  1837. user_host, path = location.split(":", 1)
  1838. if "@" in user_host:
  1839. user, host = user_host.rsplit("@", 1)
  1840. else:
  1841. user = None
  1842. host = user_host
  1843. else:
  1844. raise ValueError("not a valid rsync-style URL")
  1845. return (user, host, path)
  1846. def get_transport_and_path(location, **kwargs):
  1847. """Obtain a git client from a URL.
  1848. Args:
  1849. location: URL or path (a string)
  1850. config: Optional config object
  1851. thin_packs: Whether or not thin packs should be retrieved
  1852. report_activity: Optional callback for reporting transport
  1853. activity.
  1854. Returns:
  1855. Tuple with client instance and relative path.
  1856. """
  1857. # First, try to parse it as a URL
  1858. try:
  1859. return get_transport_and_path_from_url(location, **kwargs)
  1860. except ValueError:
  1861. pass
  1862. if sys.platform == "win32" and location[0].isalpha() and location[1:3] == ":\\":
  1863. # Windows local path
  1864. return default_local_git_client_cls(**kwargs), location
  1865. try:
  1866. (username, hostname, path) = parse_rsync_url(location)
  1867. except ValueError:
  1868. # Otherwise, assume it's a local path.
  1869. return default_local_git_client_cls(**kwargs), location
  1870. else:
  1871. return SSHGitClient(hostname, username=username, **kwargs), path
  1872. DEFAULT_GIT_CREDENTIALS_PATHS = [
  1873. os.path.expanduser("~/.git-credentials"),
  1874. get_xdg_config_home_path("git", "credentials"),
  1875. ]
  1876. def get_credentials_from_store(
  1877. scheme, hostname, username=None, fnames=DEFAULT_GIT_CREDENTIALS_PATHS
  1878. ):
  1879. for fname in fnames:
  1880. try:
  1881. with open(fname, "rb") as f:
  1882. for line in f:
  1883. parsed_line = urlparse(line.strip())
  1884. if (
  1885. parsed_line.scheme == scheme
  1886. and parsed_line.hostname == hostname
  1887. and (username is None or parsed_line.username == username)
  1888. ):
  1889. return parsed_line.username, parsed_line.password
  1890. except FileNotFoundError:
  1891. # If the file doesn't exist, try the next one.
  1892. continue