client.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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([
  296. ref for ref in ref_status if ref not in ok]) +
  297. b' failed to update', ref_status=ref_status)
  298. def _read_side_band64k_data(self, proto, channel_callbacks):
  299. """Read per-channel data.
  300. This requires the side-band-64k capability.
  301. :param proto: Protocol object to read from
  302. :param channel_callbacks: Dictionary mapping channels to packet
  303. handlers to use. None for a callback discards channel data.
  304. """
  305. for pkt in proto.read_pkt_seq():
  306. channel = ord(pkt[:1])
  307. pkt = pkt[1:]
  308. try:
  309. cb = channel_callbacks[channel]
  310. except KeyError:
  311. raise AssertionError('Invalid sideband channel %d' % channel)
  312. else:
  313. if cb is not None:
  314. cb(pkt)
  315. def _handle_receive_pack_head(self, proto, capabilities, old_refs,
  316. new_refs):
  317. """Handle the head of a 'git-receive-pack' request.
  318. :param proto: Protocol object to read from
  319. :param capabilities: List of negotiated capabilities
  320. :param old_refs: Old refs, as received from the server
  321. :param new_refs: Refs to change
  322. :return: (have, want) tuple
  323. """
  324. want = []
  325. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  326. sent_capabilities = False
  327. for refname in new_refs:
  328. if not isinstance(refname, bytes):
  329. raise TypeError('refname is not a bytestring: %r' % refname)
  330. old_sha1 = old_refs.get(refname, ZERO_SHA)
  331. if not isinstance(old_sha1, bytes):
  332. raise TypeError('old sha1 for %s is not a bytestring: %r' %
  333. (refname, old_sha1))
  334. new_sha1 = new_refs.get(refname, ZERO_SHA)
  335. if not isinstance(new_sha1, bytes):
  336. raise TypeError('old sha1 for %s is not a bytestring %r' %
  337. (refname, new_sha1))
  338. if old_sha1 != new_sha1:
  339. if sent_capabilities:
  340. proto.write_pkt_line(old_sha1 + b' ' + new_sha1 + b' ' +
  341. 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. def progress(x):
  360. pass
  361. channel_callbacks = {2: progress}
  362. if CAPABILITY_REPORT_STATUS in capabilities:
  363. channel_callbacks[1] = PktLineParser(
  364. self._report_status_parser.handle_packet).parse
  365. self._read_side_band64k_data(proto, channel_callbacks)
  366. else:
  367. if CAPABILITY_REPORT_STATUS in capabilities:
  368. for pkt in proto.read_pkt_seq():
  369. self._report_status_parser.handle_packet(pkt)
  370. if self._report_status_parser is not None:
  371. self._report_status_parser.check()
  372. def _handle_upload_pack_head(self, proto, capabilities, graph_walker,
  373. wants, can_read):
  374. """Handle the head of a 'git-upload-pack' request.
  375. :param proto: Protocol object to read from
  376. :param capabilities: List of negotiated capabilities
  377. :param graph_walker: GraphWalker instance to call .ack() on
  378. :param wants: List of commits to fetch
  379. :param can_read: function that returns a boolean that indicates
  380. whether there is extra graph data to read on proto
  381. """
  382. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  383. proto.write_pkt_line(COMMAND_WANT + b' ' + wants[0] + b' ' +
  384. b' '.join(capabilities) + b'\n')
  385. for want in wants[1:]:
  386. proto.write_pkt_line(COMMAND_WANT + b' ' + want + b'\n')
  387. proto.write_pkt_line(None)
  388. have = next(graph_walker)
  389. while have:
  390. proto.write_pkt_line(COMMAND_HAVE + b' ' + have + b'\n')
  391. if can_read():
  392. pkt = proto.read_pkt_line()
  393. parts = pkt.rstrip(b'\n').split(b' ')
  394. if parts[0] == b'ACK':
  395. graph_walker.ack(parts[1])
  396. if parts[2] in (b'continue', b'common'):
  397. pass
  398. elif parts[2] == b'ready':
  399. break
  400. else:
  401. raise AssertionError(
  402. "%s not in ('continue', 'ready', 'common)" %
  403. parts[2])
  404. have = next(graph_walker)
  405. proto.write_pkt_line(COMMAND_DONE + b'\n')
  406. def _handle_upload_pack_tail(self, proto, capabilities, graph_walker,
  407. pack_data, progress=None, rbufsize=_RBUFSIZE):
  408. """Handle the tail of a 'git-upload-pack' request.
  409. :param proto: Protocol object to read from
  410. :param capabilities: List of negotiated capabilities
  411. :param graph_walker: GraphWalker instance to call .ack() on
  412. :param pack_data: Function to call with pack data
  413. :param progress: Optional progress reporting function
  414. :param rbufsize: Read buffer size
  415. """
  416. pkt = proto.read_pkt_line()
  417. while pkt:
  418. parts = pkt.rstrip(b'\n').split(b' ')
  419. if parts[0] == b'ACK':
  420. graph_walker.ack(parts[1])
  421. if len(parts) < 3 or parts[2] not in (
  422. b'ready', b'continue', b'common'):
  423. break
  424. pkt = proto.read_pkt_line()
  425. if CAPABILITY_SIDE_BAND_64K in capabilities:
  426. if progress is None:
  427. # Just ignore progress data
  428. def progress(x):
  429. pass
  430. self._read_side_band64k_data(proto, {
  431. SIDE_BAND_CHANNEL_DATA: pack_data,
  432. SIDE_BAND_CHANNEL_PROGRESS: progress}
  433. )
  434. else:
  435. while True:
  436. data = proto.read(rbufsize)
  437. if data == b"":
  438. break
  439. pack_data(data)
  440. class TraditionalGitClient(GitClient):
  441. """Traditional Git client."""
  442. DEFAULT_ENCODING = 'utf-8'
  443. def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs):
  444. self._remote_path_encoding = path_encoding
  445. super(TraditionalGitClient, self).__init__(**kwargs)
  446. def _connect(self, cmd, path):
  447. """Create a connection to the server.
  448. This method is abstract - concrete implementations should
  449. implement their own variant which connects to the server and
  450. returns an initialized Protocol object with the service ready
  451. for use and a can_read function which may be used to see if
  452. reads would block.
  453. :param cmd: The git service name to which we should connect.
  454. :param path: The path we should pass to the service. (as bytestirng)
  455. """
  456. raise NotImplementedError()
  457. def send_pack(self, path, determine_wants, generate_pack_contents,
  458. progress=None, write_pack=write_pack_objects):
  459. """Upload a pack to a remote repository.
  460. :param path: Repository path (as bytestring)
  461. :param generate_pack_contents: Function that can return a sequence of
  462. the shas of the objects to upload.
  463. :param progress: Optional callback called with progress updates
  464. :param write_pack: Function called with (file, iterable of objects) to
  465. write the objects returned by generate_pack_contents to the server.
  466. :raises SendPackError: if server rejects the pack data
  467. :raises UpdateRefsError: if the server supports report-status
  468. and rejects ref updates
  469. :return: new_refs dictionary containing the changes that were made
  470. {refname: new_ref}, including deleted refs.
  471. """
  472. proto, unused_can_read = self._connect(b'receive-pack', path)
  473. with proto:
  474. old_refs, server_capabilities = read_pkt_refs(proto)
  475. negotiated_capabilities = (
  476. self._send_capabilities & server_capabilities)
  477. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  478. self._report_status_parser = ReportStatusParser()
  479. report_status_parser = self._report_status_parser
  480. try:
  481. new_refs = orig_new_refs = determine_wants(dict(old_refs))
  482. except:
  483. proto.write_pkt_line(None)
  484. raise
  485. if CAPABILITY_DELETE_REFS not in server_capabilities:
  486. # Server does not support deletions. Fail later.
  487. new_refs = dict(orig_new_refs)
  488. for ref, sha in orig_new_refs.items():
  489. if sha == ZERO_SHA:
  490. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  491. report_status_parser._ref_statuses.append(
  492. b'ng ' + sha +
  493. b' remote does not support deleting refs')
  494. report_status_parser._ref_status_ok = False
  495. del new_refs[ref]
  496. if new_refs is None:
  497. proto.write_pkt_line(None)
  498. return old_refs
  499. if len(new_refs) == 0 and len(orig_new_refs):
  500. # NOOP - Original new refs filtered out by policy
  501. proto.write_pkt_line(None)
  502. if report_status_parser is not None:
  503. report_status_parser.check()
  504. return old_refs
  505. (have, want) = self._handle_receive_pack_head(
  506. proto, negotiated_capabilities, old_refs, new_refs)
  507. if (not want and
  508. set(new_refs.items()).issubset(set(old_refs.items()))):
  509. return new_refs
  510. objects = generate_pack_contents(have, want)
  511. dowrite = len(objects) > 0
  512. dowrite = dowrite or any(old_refs.get(ref) != sha
  513. for (ref, sha) in new_refs.items()
  514. if sha != ZERO_SHA)
  515. if dowrite:
  516. write_pack(proto.write_file(), objects)
  517. self._handle_receive_pack_tail(
  518. proto, negotiated_capabilities, progress)
  519. return new_refs
  520. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  521. progress=None):
  522. """Retrieve a pack from a git smart server.
  523. :param determine_wants: Callback that returns list of commits to fetch
  524. :param graph_walker: Object with next() and ack().
  525. :param pack_data: Callback called for each bit of data in the pack
  526. :param progress: Callback for progress reports (strings)
  527. :return: Dictionary with all remote refs (not just those fetched)
  528. """
  529. proto, can_read = self._connect(b'upload-pack', path)
  530. with proto:
  531. refs, server_capabilities = read_pkt_refs(proto)
  532. negotiated_capabilities = (
  533. self._fetch_capabilities & server_capabilities)
  534. if refs is None:
  535. proto.write_pkt_line(None)
  536. return refs
  537. try:
  538. wants = determine_wants(refs)
  539. except:
  540. proto.write_pkt_line(None)
  541. raise
  542. if wants is not None:
  543. wants = [cid for cid in wants if cid != ZERO_SHA]
  544. if not wants:
  545. proto.write_pkt_line(None)
  546. return refs
  547. self._handle_upload_pack_head(
  548. proto, negotiated_capabilities, graph_walker, wants, can_read)
  549. self._handle_upload_pack_tail(
  550. proto, negotiated_capabilities, graph_walker, pack_data,
  551. progress)
  552. return refs
  553. def get_refs(self, path):
  554. """Retrieve the current refs from a git smart server."""
  555. # stock `git ls-remote` uses upload-pack
  556. proto, _ = self._connect(b'upload-pack', path)
  557. with proto:
  558. refs, _ = read_pkt_refs(proto)
  559. proto.write_pkt_line(None)
  560. return refs
  561. def archive(self, path, committish, write_data, progress=None,
  562. write_error=None):
  563. proto, can_read = self._connect(b'upload-archive', path)
  564. with proto:
  565. proto.write_pkt_line(b"argument " + committish)
  566. proto.write_pkt_line(None)
  567. pkt = proto.read_pkt_line()
  568. if pkt == b"NACK\n":
  569. return
  570. elif pkt == b"ACK\n":
  571. pass
  572. elif pkt.startswith(b"ERR "):
  573. raise GitProtocolError(pkt[4:].rstrip(b"\n"))
  574. else:
  575. raise AssertionError("invalid response %r" % pkt)
  576. ret = proto.read_pkt_line()
  577. if ret is not None:
  578. raise AssertionError("expected pkt tail")
  579. self._read_side_band64k_data(proto, {
  580. SIDE_BAND_CHANNEL_DATA: write_data,
  581. SIDE_BAND_CHANNEL_PROGRESS: progress,
  582. SIDE_BAND_CHANNEL_FATAL: write_error})
  583. class TCPGitClient(TraditionalGitClient):
  584. """A Git Client that works over TCP directly (i.e. git://)."""
  585. def __init__(self, host, port=None, **kwargs):
  586. if port is None:
  587. port = TCP_GIT_PORT
  588. self._host = host
  589. self._port = port
  590. super(TCPGitClient, self).__init__(**kwargs)
  591. @classmethod
  592. def from_parsedurl(cls, parsedurl, **kwargs):
  593. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  594. def get_url(self, path):
  595. netloc = self._host
  596. if self._port is not None and self._port != TCP_GIT_PORT:
  597. netloc += ":%d" % self._port
  598. return urlparse.urlunsplit(("git", netloc, path, '', ''))
  599. def _connect(self, cmd, path):
  600. if not isinstance(cmd, bytes):
  601. raise TypeError(cmd)
  602. if not isinstance(path, bytes):
  603. path = path.encode(self._remote_path_encoding)
  604. sockaddrs = socket.getaddrinfo(
  605. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  606. s = None
  607. err = socket.error("no address found for %s" % self._host)
  608. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  609. s = socket.socket(family, socktype, proto)
  610. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  611. try:
  612. s.connect(sockaddr)
  613. break
  614. except socket.error as err:
  615. if s is not None:
  616. s.close()
  617. s = None
  618. if s is None:
  619. raise err
  620. # -1 means system default buffering
  621. rfile = s.makefile('rb', -1)
  622. # 0 means unbuffered
  623. wfile = s.makefile('wb', 0)
  624. def close():
  625. rfile.close()
  626. wfile.close()
  627. s.close()
  628. proto = Protocol(rfile.read, wfile.write, close,
  629. report_activity=self._report_activity)
  630. if path.startswith(b"/~"):
  631. path = path[1:]
  632. # TODO(jelmer): Alternative to ascii?
  633. proto.send_cmd(
  634. b'git-' + cmd, path, b'host=' + self._host.encode('ascii'))
  635. return proto, lambda: _fileno_can_read(s)
  636. class SubprocessWrapper(object):
  637. """A socket-like object that talks to a subprocess via pipes."""
  638. def __init__(self, proc):
  639. self.proc = proc
  640. if sys.version_info[0] == 2:
  641. self.read = proc.stdout.read
  642. else:
  643. self.read = BufferedReader(proc.stdout).read
  644. self.write = proc.stdin.write
  645. def can_read(self):
  646. if sys.platform == 'win32':
  647. from msvcrt import get_osfhandle
  648. from win32pipe import PeekNamedPipe
  649. handle = get_osfhandle(self.proc.stdout.fileno())
  650. data, total_bytes_avail, msg_bytes_left = PeekNamedPipe(handle, 0)
  651. return total_bytes_avail != 0
  652. else:
  653. return _fileno_can_read(self.proc.stdout.fileno())
  654. def close(self):
  655. self.proc.stdin.close()
  656. self.proc.stdout.close()
  657. if self.proc.stderr:
  658. self.proc.stderr.close()
  659. self.proc.wait()
  660. def find_git_command():
  661. """Find command to run for system Git (usually C Git).
  662. """
  663. if sys.platform == 'win32': # support .exe, .bat and .cmd
  664. try: # to avoid overhead
  665. import win32api
  666. except ImportError: # run through cmd.exe with some overhead
  667. return ['cmd', '/c', 'git']
  668. else:
  669. status, git = win32api.FindExecutable('git')
  670. return [git]
  671. else:
  672. return ['git']
  673. class SubprocessGitClient(TraditionalGitClient):
  674. """Git client that talks to a server using a subprocess."""
  675. def __init__(self, **kwargs):
  676. self._connection = None
  677. self._stderr = None
  678. self._stderr = kwargs.get('stderr')
  679. if 'stderr' in kwargs:
  680. del kwargs['stderr']
  681. super(SubprocessGitClient, self).__init__(**kwargs)
  682. @classmethod
  683. def from_parsedurl(cls, parsedurl, **kwargs):
  684. return cls(**kwargs)
  685. git_command = None
  686. def _connect(self, service, path):
  687. if not isinstance(service, bytes):
  688. raise TypeError(service)
  689. if not isinstance(path, bytes):
  690. path = path.encode(self._remote_path_encoding)
  691. if self.git_command is None:
  692. git_command = find_git_command()
  693. argv = git_command + [service.decode('ascii'), path]
  694. p = SubprocessWrapper(
  695. subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  696. stdout=subprocess.PIPE,
  697. stderr=self._stderr))
  698. return Protocol(p.read, p.write, p.close,
  699. report_activity=self._report_activity), p.can_read
  700. class LocalGitClient(GitClient):
  701. """Git Client that just uses a local Repo."""
  702. def __init__(self, thin_packs=True, report_activity=None):
  703. """Create a new LocalGitClient instance.
  704. :param thin_packs: Whether or not thin packs should be retrieved
  705. :param report_activity: Optional callback for reporting transport
  706. activity.
  707. """
  708. self._report_activity = report_activity
  709. # Ignore the thin_packs argument
  710. def get_url(self, path):
  711. return urlparse.urlunsplit(('file', '', path, '', ''))
  712. @classmethod
  713. def from_parsedurl(cls, parsedurl, **kwargs):
  714. return cls(**kwargs)
  715. @classmethod
  716. def _open_repo(cls, path):
  717. from dulwich.repo import Repo
  718. if not isinstance(path, str):
  719. path = path.decode(sys.getfilesystemencoding())
  720. return closing(Repo(path))
  721. def send_pack(self, path, determine_wants, generate_pack_contents,
  722. progress=None, write_pack=write_pack_objects):
  723. """Upload a pack to a remote repository.
  724. :param path: Repository path (as bytestring)
  725. :param generate_pack_contents: Function that can return a sequence of
  726. the shas of the objects to upload.
  727. :param progress: Optional progress function
  728. :param write_pack: Function called with (file, iterable of objects) to
  729. write the objects returned by generate_pack_contents to the server.
  730. :raises SendPackError: if server rejects the pack data
  731. :raises UpdateRefsError: if the server supports report-status
  732. and rejects ref updates
  733. :return: new_refs dictionary containing the changes that were made
  734. {refname: new_ref}, including deleted refs.
  735. """
  736. if not progress:
  737. def progress(x):
  738. pass
  739. with self._open_repo(path) as target:
  740. old_refs = target.get_refs()
  741. new_refs = determine_wants(dict(old_refs))
  742. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  743. want = []
  744. for refname, new_sha1 in new_refs.items():
  745. if (new_sha1 not in have and
  746. new_sha1 not in want and
  747. new_sha1 != ZERO_SHA):
  748. want.append(new_sha1)
  749. if (not want and
  750. set(new_refs.items()).issubset(set(old_refs.items()))):
  751. return new_refs
  752. target.object_store.add_objects(generate_pack_contents(have, want))
  753. for refname, new_sha1 in new_refs.items():
  754. old_sha1 = old_refs.get(refname, ZERO_SHA)
  755. if new_sha1 != ZERO_SHA:
  756. if not target.refs.set_if_equals(
  757. refname, old_sha1, new_sha1):
  758. progress('unable to set %s to %s' %
  759. (refname, new_sha1))
  760. else:
  761. if not target.refs.remove_if_equals(refname, old_sha1):
  762. progress('unable to remove %s' % refname)
  763. return new_refs
  764. def fetch(self, path, target, determine_wants=None, progress=None):
  765. """Fetch into a target repository.
  766. :param path: Path to fetch from (as bytestring)
  767. :param target: Target repository to fetch into
  768. :param determine_wants: Optional function to determine what refs
  769. to fetch
  770. :param progress: Optional progress function
  771. :return: Dictionary with all remote refs (not just those fetched)
  772. """
  773. with self._open_repo(path) as r:
  774. return r.fetch(target, determine_wants=determine_wants,
  775. progress=progress)
  776. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  777. progress=None):
  778. """Retrieve a pack from a git smart server.
  779. :param determine_wants: Callback that returns list of commits to fetch
  780. :param graph_walker: Object with next() and ack().
  781. :param pack_data: Callback called for each bit of data in the pack
  782. :param progress: Callback for progress reports (strings)
  783. :return: Dictionary with all remote refs (not just those fetched)
  784. """
  785. with self._open_repo(path) as r:
  786. objects_iter = r.fetch_objects(
  787. determine_wants, graph_walker, progress)
  788. # Did the process short-circuit (e.g. in a stateless RPC call)?
  789. # Note that the client still expects a 0-object pack in most cases.
  790. if objects_iter is None:
  791. return
  792. write_pack_objects(ProtocolFile(None, pack_data), objects_iter)
  793. return r.get_refs()
  794. def get_refs(self, path):
  795. """Retrieve the current refs from a git smart server."""
  796. with self._open_repo(path) as target:
  797. return target.get_refs()
  798. # What Git client to use for local access
  799. default_local_git_client_cls = LocalGitClient
  800. class SSHVendor(object):
  801. """A client side SSH implementation."""
  802. def connect_ssh(self, host, command, username=None, port=None):
  803. # This function was deprecated in 0.9.1
  804. import warnings
  805. warnings.warn(
  806. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  807. DeprecationWarning)
  808. return self.run_command(host, command, username=username, port=port)
  809. def run_command(self, host, command, username=None, port=None):
  810. """Connect to an SSH server.
  811. Run a command remotely and return a file-like object for interaction
  812. with the remote command.
  813. :param host: Host name
  814. :param command: Command to run (as argv array)
  815. :param username: Optional ame of user to log in as
  816. :param port: Optional SSH port to use
  817. """
  818. raise NotImplementedError(self.run_command)
  819. class SubprocessSSHVendor(SSHVendor):
  820. """SSH vendor that shells out to the local 'ssh' command."""
  821. def run_command(self, host, command, username=None, port=None):
  822. if not isinstance(command, bytes):
  823. raise TypeError(command)
  824. # FIXME: This has no way to deal with passwords..
  825. args = ['ssh', '-x']
  826. if port is not None:
  827. args.extend(['-p', str(port)])
  828. if username is not None:
  829. host = '%s@%s' % (username, host)
  830. args.append(host)
  831. proc = subprocess.Popen(args + [command], bufsize=0,
  832. stdin=subprocess.PIPE,
  833. stdout=subprocess.PIPE)
  834. return SubprocessWrapper(proc)
  835. def ParamikoSSHVendor(**kwargs):
  836. import warnings
  837. warnings.warn(
  838. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  839. DeprecationWarning)
  840. from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
  841. return ParamikoSSHVendor(**kwargs)
  842. # Can be overridden by users
  843. get_ssh_vendor = SubprocessSSHVendor
  844. class SSHGitClient(TraditionalGitClient):
  845. def __init__(self, host, port=None, username=None, vendor=None, **kwargs):
  846. self.host = host
  847. self.port = port
  848. self.username = username
  849. super(SSHGitClient, self).__init__(**kwargs)
  850. self.alternative_paths = {}
  851. if vendor is not None:
  852. self.ssh_vendor = vendor
  853. else:
  854. self.ssh_vendor = get_ssh_vendor()
  855. def get_url(self, path):
  856. netloc = self.host
  857. if self.port is not None:
  858. netloc += ":%d" % self.port
  859. if self.username is not None:
  860. netloc = urlquote(self.username, '@/:') + "@" + netloc
  861. return urlparse.urlunsplit(('ssh', netloc, path, '', ''))
  862. @classmethod
  863. def from_parsedurl(cls, parsedurl, **kwargs):
  864. return cls(host=parsedurl.hostname, port=parsedurl.port,
  865. username=parsedurl.username, **kwargs)
  866. def _get_cmd_path(self, cmd):
  867. cmd = self.alternative_paths.get(cmd, b'git-' + cmd)
  868. assert isinstance(cmd, bytes)
  869. return cmd
  870. def _connect(self, cmd, path):
  871. if not isinstance(cmd, bytes):
  872. raise TypeError(cmd)
  873. if not isinstance(path, bytes):
  874. path = path.encode(self._remote_path_encoding)
  875. if path.startswith(b"/~"):
  876. path = path[1:]
  877. argv = self._get_cmd_path(cmd) + b" '" + path + b"'"
  878. con = self.ssh_vendor.run_command(
  879. self.host, argv, port=self.port, username=self.username)
  880. return (Protocol(con.read, con.write, con.close,
  881. report_activity=self._report_activity),
  882. con.can_read)
  883. def default_user_agent_string():
  884. return "dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  885. def default_urllib2_opener(config):
  886. if config is not None:
  887. proxy_server = config.get("http", "proxy")
  888. else:
  889. proxy_server = None
  890. handlers = []
  891. if proxy_server is not None:
  892. handlers.append(urllib2.ProxyHandler({"http": proxy_server}))
  893. opener = urllib2.build_opener(*handlers)
  894. if config is not None:
  895. user_agent = config.get("http", "useragent")
  896. else:
  897. user_agent = None
  898. if user_agent is None:
  899. user_agent = default_user_agent_string()
  900. opener.addheaders = [('User-agent', user_agent)]
  901. return opener
  902. class HttpGitClient(GitClient):
  903. def __init__(self, base_url, dumb=None, opener=None, config=None,
  904. username=None, password=None, **kwargs):
  905. self._base_url = base_url.rstrip("/") + "/"
  906. self._username = username
  907. self._password = password
  908. self.dumb = dumb
  909. if opener is None:
  910. self.opener = default_urllib2_opener(config)
  911. else:
  912. self.opener = opener
  913. if username is not None:
  914. pass_man = urllib2.HTTPPasswordMgrWithDefaultRealm()
  915. pass_man.add_password(None, base_url, username, password)
  916. self.opener.add_handler(urllib2.HTTPBasicAuthHandler(pass_man))
  917. GitClient.__init__(self, **kwargs)
  918. def get_url(self, path):
  919. return self._get_url(path).rstrip("/")
  920. @classmethod
  921. def from_parsedurl(cls, parsedurl, **kwargs):
  922. auth, host = urllib2.splituser(parsedurl.netloc)
  923. password = parsedurl.password
  924. if password is not None:
  925. password = urlunquote(password)
  926. username = parsedurl.username
  927. if username is not None:
  928. username = urlunquote(username)
  929. # TODO(jelmer): This also strips the username
  930. parsedurl = parsedurl._replace(netloc=host)
  931. return cls(urlparse.urlunparse(parsedurl),
  932. password=password, username=username, **kwargs)
  933. def __repr__(self):
  934. return "%s(%r, dumb=%r)" % (
  935. type(self).__name__, self._base_url, self.dumb)
  936. def _get_url(self, path):
  937. if not isinstance(path, str):
  938. # TODO(jelmer): this is unrelated to the local filesystem;
  939. # This is not necessarily the right encoding to decode the path
  940. # with.
  941. path = path.decode(sys.getfilesystemencoding())
  942. return urlparse.urljoin(self._base_url, path).rstrip("/") + "/"
  943. def _http_request(self, url, headers={}, data=None):
  944. req = urllib2.Request(url, headers=headers, data=data)
  945. try:
  946. resp = self.opener.open(req)
  947. except urllib2.HTTPError as e:
  948. if e.code == 404:
  949. raise NotGitRepository()
  950. if e.code != 200:
  951. raise GitProtocolError("unexpected http response %d" % e.code)
  952. return resp
  953. def _discover_references(self, service, url):
  954. assert url[-1] == "/"
  955. url = urlparse.urljoin(url, "info/refs")
  956. headers = {}
  957. if self.dumb is not False:
  958. url += "?service=%s" % service.decode('ascii')
  959. headers["Content-Type"] = "application/x-%s-request" % (
  960. service.decode('ascii'))
  961. resp = self._http_request(url, headers)
  962. try:
  963. content_type = resp.info().gettype()
  964. except AttributeError:
  965. content_type = resp.info().get_content_type()
  966. try:
  967. self.dumb = (not content_type.startswith("application/x-git-"))
  968. if not self.dumb:
  969. proto = Protocol(resp.read, None)
  970. # The first line should mention the service
  971. try:
  972. [pkt] = list(proto.read_pkt_seq())
  973. except ValueError:
  974. raise GitProtocolError(
  975. "unexpected number of packets received")
  976. if pkt.rstrip(b'\n') != (b'# service=' + service):
  977. raise GitProtocolError(
  978. "unexpected first line %r from smart server" % pkt)
  979. return read_pkt_refs(proto)
  980. else:
  981. return read_info_refs(resp), set()
  982. finally:
  983. resp.close()
  984. def _smart_request(self, service, url, data):
  985. assert url[-1] == "/"
  986. url = urlparse.urljoin(url, service)
  987. headers = {
  988. "Content-Type": "application/x-%s-request" % service
  989. }
  990. resp = self._http_request(url, headers, data)
  991. try:
  992. content_type = resp.info().gettype()
  993. except AttributeError:
  994. content_type = resp.info().get_content_type()
  995. if content_type != (
  996. "application/x-%s-result" % service):
  997. raise GitProtocolError("Invalid content-type from server: %s"
  998. % content_type)
  999. return resp
  1000. def send_pack(self, path, determine_wants, generate_pack_contents,
  1001. progress=None, write_pack=write_pack_objects):
  1002. """Upload a pack to a remote repository.
  1003. :param path: Repository path (as bytestring)
  1004. :param generate_pack_contents: Function that can return a sequence of
  1005. the shas of the objects to upload.
  1006. :param progress: Optional progress function
  1007. :param write_pack: Function called with (file, iterable of objects) to
  1008. write the objects returned by generate_pack_contents to the server.
  1009. :raises SendPackError: if server rejects the pack data
  1010. :raises UpdateRefsError: if the server supports report-status
  1011. and rejects ref updates
  1012. :return: new_refs dictionary containing the changes that were made
  1013. {refname: new_ref}, including deleted refs.
  1014. """
  1015. url = self._get_url(path)
  1016. old_refs, server_capabilities = self._discover_references(
  1017. b"git-receive-pack", url)
  1018. negotiated_capabilities = self._send_capabilities & server_capabilities
  1019. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1020. self._report_status_parser = ReportStatusParser()
  1021. new_refs = determine_wants(dict(old_refs))
  1022. if new_refs is None:
  1023. # Determine wants function is aborting the push.
  1024. return old_refs
  1025. if self.dumb:
  1026. raise NotImplementedError(self.fetch_pack)
  1027. req_data = BytesIO()
  1028. req_proto = Protocol(None, req_data.write)
  1029. (have, want) = self._handle_receive_pack_head(
  1030. req_proto, negotiated_capabilities, old_refs, new_refs)
  1031. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1032. return new_refs
  1033. objects = generate_pack_contents(have, want)
  1034. if len(objects) > 0:
  1035. write_pack(req_proto.write_file(), objects)
  1036. resp = self._smart_request("git-receive-pack", url,
  1037. data=req_data.getvalue())
  1038. try:
  1039. resp_proto = Protocol(resp.read, None)
  1040. self._handle_receive_pack_tail(
  1041. resp_proto, negotiated_capabilities, progress)
  1042. return new_refs
  1043. finally:
  1044. resp.close()
  1045. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  1046. progress=None):
  1047. """Retrieve a pack from a git smart server.
  1048. :param determine_wants: Callback that returns list of commits to fetch
  1049. :param graph_walker: Object with next() and ack().
  1050. :param pack_data: Callback called for each bit of data in the pack
  1051. :param progress: Callback for progress reports (strings)
  1052. :return: Dictionary with all remote refs (not just those fetched)
  1053. """
  1054. url = self._get_url(path)
  1055. refs, server_capabilities = self._discover_references(
  1056. b"git-upload-pack", url)
  1057. negotiated_capabilities = (
  1058. self._fetch_capabilities & server_capabilities)
  1059. wants = determine_wants(refs)
  1060. if wants is not None:
  1061. wants = [cid for cid in wants if cid != ZERO_SHA]
  1062. if not wants:
  1063. return refs
  1064. if self.dumb:
  1065. raise NotImplementedError(self.send_pack)
  1066. req_data = BytesIO()
  1067. req_proto = Protocol(None, req_data.write)
  1068. self._handle_upload_pack_head(
  1069. req_proto, negotiated_capabilities, graph_walker, wants,
  1070. lambda: False)
  1071. resp = self._smart_request(
  1072. "git-upload-pack", url, data=req_data.getvalue())
  1073. try:
  1074. resp_proto = Protocol(resp.read, None)
  1075. self._handle_upload_pack_tail(
  1076. resp_proto, negotiated_capabilities, graph_walker, pack_data,
  1077. progress)
  1078. return refs
  1079. finally:
  1080. resp.close()
  1081. def get_refs(self, path):
  1082. """Retrieve the current refs from a git smart server."""
  1083. url = self._get_url(path)
  1084. refs, _ = self._discover_references(
  1085. b"git-upload-pack", url)
  1086. return refs
  1087. def get_transport_and_path_from_url(url, config=None, **kwargs):
  1088. """Obtain a git client from a URL.
  1089. :param url: URL to open (a unicode string)
  1090. :param config: Optional config object
  1091. :param thin_packs: Whether or not thin packs should be retrieved
  1092. :param report_activity: Optional callback for reporting transport
  1093. activity.
  1094. :return: Tuple with client instance and relative path.
  1095. """
  1096. parsed = urlparse.urlparse(url)
  1097. if parsed.scheme == 'git':
  1098. return (TCPGitClient.from_parsedurl(parsed, **kwargs),
  1099. parsed.path)
  1100. elif parsed.scheme in ('git+ssh', 'ssh'):
  1101. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  1102. elif parsed.scheme in ('http', 'https'):
  1103. return HttpGitClient.from_parsedurl(
  1104. parsed, config=config, **kwargs), parsed.path
  1105. elif parsed.scheme == 'file':
  1106. return default_local_git_client_cls.from_parsedurl(
  1107. parsed, **kwargs), parsed.path
  1108. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  1109. def get_transport_and_path(location, **kwargs):
  1110. """Obtain a git client from a URL.
  1111. :param location: URL or path (a string)
  1112. :param config: Optional config object
  1113. :param thin_packs: Whether or not thin packs should be retrieved
  1114. :param report_activity: Optional callback for reporting transport
  1115. activity.
  1116. :return: Tuple with client instance and relative path.
  1117. """
  1118. # First, try to parse it as a URL
  1119. try:
  1120. return get_transport_and_path_from_url(location, **kwargs)
  1121. except ValueError:
  1122. pass
  1123. if (sys.platform == 'win32' and
  1124. location[0].isalpha() and location[1:3] == ':\\'):
  1125. # Windows local path
  1126. return default_local_git_client_cls(**kwargs), location
  1127. if ':' in location and '@' not in location:
  1128. # SSH with no user@, zero or one leading slash.
  1129. (hostname, path) = location.split(':', 1)
  1130. return SSHGitClient(hostname, **kwargs), path
  1131. elif ':' in location:
  1132. # SSH with user@host:foo.
  1133. user_host, path = location.split(':', 1)
  1134. if '@' in user_host:
  1135. user, host = user_host.rsplit('@', 1)
  1136. else:
  1137. user = None
  1138. host = user_host
  1139. return SSHGitClient(host, username=user, **kwargs), path
  1140. # Otherwise, assume it's a local path.
  1141. return default_local_git_client_cls(**kwargs), location