client.py 52 KB

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