client.py 55 KB

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