client.py 51 KB

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