client.py 44 KB

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