client.py 42 KB

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