client.py 48 KB

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