client.py 36 KB

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