client.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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. class SSHVendor(object):
  562. """A client side SSH implementation."""
  563. def connect_ssh(self, host, command, username=None, port=None):
  564. import warnings
  565. warnings.warn(
  566. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  567. DeprecationWarning)
  568. return self.run_command(host, command, username=username, port=port)
  569. def run_command(self, host, command, username=None, port=None):
  570. """Connect to an SSH server.
  571. Run a command remotely and return a file-like object for interaction
  572. with the remote command.
  573. :param host: Host name
  574. :param command: Command to run
  575. :param username: Optional ame of user to log in as
  576. :param port: Optional SSH port to use
  577. """
  578. raise NotImplementedError(self.run_command)
  579. class SubprocessSSHVendor(SSHVendor):
  580. """SSH vendor that shells out to the local 'ssh' command."""
  581. def run_command(self, host, command, username=None, port=None):
  582. import subprocess
  583. #FIXME: This has no way to deal with passwords..
  584. args = ['ssh', '-x']
  585. if port is not None:
  586. args.extend(['-p', str(port)])
  587. if username is not None:
  588. host = '%s@%s' % (username, host)
  589. args.append(host)
  590. proc = subprocess.Popen(args + command,
  591. stdin=subprocess.PIPE,
  592. stdout=subprocess.PIPE)
  593. return SubprocessWrapper(proc)
  594. try:
  595. import paramiko
  596. except ImportError:
  597. pass
  598. else:
  599. import threading
  600. class ParamikoWrapper(object):
  601. STDERR_READ_N = 2048 # 2k
  602. def __init__(self, client, channel, progress_stderr=None):
  603. self.client = client
  604. self.channel = channel
  605. self.progress_stderr = progress_stderr
  606. self.should_monitor = bool(progress_stderr) or True
  607. self.monitor_thread = None
  608. self.stderr = ''
  609. # Channel must block
  610. self.channel.setblocking(True)
  611. # Start
  612. if self.should_monitor:
  613. self.monitor_thread = threading.Thread(target=self.monitor_stderr)
  614. self.monitor_thread.start()
  615. def monitor_stderr(self):
  616. while self.should_monitor:
  617. # Block and read
  618. data = self.read_stderr(self.STDERR_READ_N)
  619. # Socket closed
  620. if not data:
  621. self.should_monitor = False
  622. break
  623. # Emit data
  624. if self.progress_stderr:
  625. self.progress_stderr(data)
  626. # Append to buffer
  627. self.stderr += data
  628. def stop_monitoring(self):
  629. # Stop StdErr thread
  630. if self.should_monitor:
  631. self.should_monitor = False
  632. self.monitor_thread.join()
  633. # Get left over data
  634. data = self.channel.in_stderr_buffer.empty()
  635. self.stderr += data
  636. def can_read(self):
  637. return self.channel.recv_ready()
  638. def write(self, data):
  639. return self.channel.sendall(data)
  640. def read_stderr(self, n):
  641. return self.channel.recv_stderr(n)
  642. def read(self, n=None):
  643. data = self.channel.recv(n)
  644. data_len = len(data)
  645. # Closed socket
  646. if not data:
  647. return
  648. # Read more if needed
  649. if n and data_len < n:
  650. diff_len = n - data_len
  651. return data + self.read(diff_len)
  652. return data
  653. def close(self):
  654. self.channel.close()
  655. self.stop_monitoring()
  656. def __del__(self):
  657. self.close()
  658. class ParamikoSSHVendor(object):
  659. def __init__(self):
  660. self.ssh_kwargs = {}
  661. def run_command(self, host, command, username=None, port=None,
  662. progress_stderr=None):
  663. # Paramiko needs an explicit port. None is not valid
  664. if port is None:
  665. port = 22
  666. client = paramiko.SSHClient()
  667. policy = paramiko.client.MissingHostKeyPolicy()
  668. client.set_missing_host_key_policy(policy)
  669. client.connect(host, username=username, port=port,
  670. **self.ssh_kwargs)
  671. # Open SSH session
  672. channel = client.get_transport().open_session()
  673. # Run commands
  674. apply(channel.exec_command, command)
  675. return ParamikoWrapper(client, channel,
  676. progress_stderr=progress_stderr)
  677. # Can be overridden by users
  678. get_ssh_vendor = SubprocessSSHVendor
  679. class SSHGitClient(TraditionalGitClient):
  680. def __init__(self, host, port=None, username=None, *args, **kwargs):
  681. self.host = host
  682. self.port = port
  683. self.username = username
  684. TraditionalGitClient.__init__(self, *args, **kwargs)
  685. self.alternative_paths = {}
  686. def _get_cmd_path(self, cmd):
  687. return self.alternative_paths.get(cmd, 'git-%s' % cmd)
  688. def _connect(self, cmd, path):
  689. if path.startswith("/~"):
  690. path = path[1:]
  691. con = get_ssh_vendor().run_command(
  692. self.host, ["%s '%s'" % (self._get_cmd_path(cmd), path)],
  693. port=self.port, username=self.username)
  694. return (Protocol(con.read, con.write, report_activity=self._report_activity),
  695. con.can_read)
  696. class HttpGitClient(GitClient):
  697. def __init__(self, base_url, dumb=None, *args, **kwargs):
  698. self.base_url = base_url.rstrip("/") + "/"
  699. self.dumb = dumb
  700. GitClient.__init__(self, *args, **kwargs)
  701. def _get_url(self, path):
  702. return urlparse.urljoin(self.base_url, path).rstrip("/") + "/"
  703. def _http_request(self, url, headers={}, data=None):
  704. req = urllib2.Request(url, headers=headers, data=data)
  705. try:
  706. resp = self._perform(req)
  707. except urllib2.HTTPError, e:
  708. if e.code == 404:
  709. raise NotGitRepository()
  710. if e.code != 200:
  711. raise GitProtocolError("unexpected http response %d" % e.code)
  712. return resp
  713. def _perform(self, req):
  714. """Perform a HTTP request.
  715. This is provided so subclasses can provide their own version.
  716. :param req: urllib2.Request instance
  717. :return: matching response
  718. """
  719. return urllib2.urlopen(req)
  720. def _discover_references(self, service, url):
  721. assert url[-1] == "/"
  722. url = urlparse.urljoin(url, "info/refs")
  723. headers = {}
  724. if self.dumb != False:
  725. url += "?service=%s" % service
  726. headers["Content-Type"] = "application/x-%s-request" % service
  727. resp = self._http_request(url, headers)
  728. self.dumb = (not resp.info().gettype().startswith("application/x-git-"))
  729. if not self.dumb:
  730. proto = Protocol(resp.read, None)
  731. # The first line should mention the service
  732. pkts = list(proto.read_pkt_seq())
  733. if pkts != [('# service=%s\n' % service)]:
  734. raise GitProtocolError(
  735. "unexpected first line %r from smart server" % pkts)
  736. return read_pkt_refs(proto)
  737. else:
  738. return read_info_refs(resp), set()
  739. def _smart_request(self, service, url, data):
  740. assert url[-1] == "/"
  741. url = urlparse.urljoin(url, service)
  742. headers = {"Content-Type": "application/x-%s-request" % service}
  743. resp = self._http_request(url, headers, data)
  744. if resp.info().gettype() != ("application/x-%s-result" % service):
  745. raise GitProtocolError("Invalid content-type from server: %s"
  746. % resp.info().gettype())
  747. return resp
  748. def send_pack(self, path, determine_wants, generate_pack_contents,
  749. progress=None):
  750. """Upload a pack to a remote repository.
  751. :param path: Repository path
  752. :param generate_pack_contents: Function that can return a sequence of the
  753. shas of the objects to upload.
  754. :param progress: Optional progress function
  755. :raises SendPackError: if server rejects the pack data
  756. :raises UpdateRefsError: if the server supports report-status
  757. and rejects ref updates
  758. """
  759. url = self._get_url(path)
  760. old_refs, server_capabilities = self._discover_references(
  761. "git-receive-pack", url)
  762. negotiated_capabilities = self._send_capabilities & server_capabilities
  763. if 'report-status' in negotiated_capabilities:
  764. self._report_status_parser = ReportStatusParser()
  765. new_refs = determine_wants(dict(old_refs))
  766. if new_refs is None:
  767. return old_refs
  768. if self.dumb:
  769. raise NotImplementedError(self.fetch_pack)
  770. req_data = StringIO()
  771. req_proto = Protocol(None, req_data.write)
  772. (have, want) = self._handle_receive_pack_head(
  773. req_proto, negotiated_capabilities, old_refs, new_refs)
  774. if not want and old_refs == new_refs:
  775. return new_refs
  776. objects = generate_pack_contents(have, want)
  777. if len(objects) > 0:
  778. entries, sha = write_pack_objects(req_proto.write_file(), objects)
  779. resp = self._smart_request("git-receive-pack", url,
  780. data=req_data.getvalue())
  781. resp_proto = Protocol(resp.read, None)
  782. self._handle_receive_pack_tail(resp_proto, negotiated_capabilities,
  783. progress)
  784. return new_refs
  785. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  786. progress=None):
  787. """Retrieve a pack from a git smart server.
  788. :param determine_wants: Callback that returns list of commits to fetch
  789. :param graph_walker: Object with next() and ack().
  790. :param pack_data: Callback called for each bit of data in the pack
  791. :param progress: Callback for progress reports (strings)
  792. :return: Dictionary with the refs of the remote repository
  793. """
  794. url = self._get_url(path)
  795. refs, server_capabilities = self._discover_references(
  796. "git-upload-pack", url)
  797. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  798. wants = determine_wants(refs)
  799. if wants is not None:
  800. wants = [cid for cid in wants if cid != ZERO_SHA]
  801. if not wants:
  802. return refs
  803. if self.dumb:
  804. raise NotImplementedError(self.send_pack)
  805. req_data = StringIO()
  806. req_proto = Protocol(None, req_data.write)
  807. self._handle_upload_pack_head(req_proto,
  808. negotiated_capabilities, graph_walker, wants,
  809. lambda: False)
  810. resp = self._smart_request("git-upload-pack", url,
  811. data=req_data.getvalue())
  812. resp_proto = Protocol(resp.read, None)
  813. self._handle_upload_pack_tail(resp_proto, negotiated_capabilities,
  814. graph_walker, pack_data, progress)
  815. return refs
  816. def get_transport_and_path(uri, **kwargs):
  817. """Obtain a git client from a URI or path.
  818. :param uri: URI or path
  819. :param thin_packs: Whether or not thin packs should be retrieved
  820. :param report_activity: Optional callback for reporting transport
  821. activity.
  822. :return: Tuple with client instance and relative path.
  823. """
  824. parsed = urlparse.urlparse(uri)
  825. if parsed.scheme == 'git':
  826. return (TCPGitClient(parsed.hostname, port=parsed.port, **kwargs),
  827. parsed.path)
  828. elif parsed.scheme == 'git+ssh':
  829. path = parsed.path
  830. if path.startswith('/'):
  831. path = parsed.path[1:]
  832. return SSHGitClient(parsed.hostname, port=parsed.port,
  833. username=parsed.username, **kwargs), path
  834. elif parsed.scheme in ('http', 'https'):
  835. return HttpGitClient(urlparse.urlunparse(parsed), **kwargs), parsed.path
  836. if parsed.scheme and not parsed.netloc:
  837. # SSH with no user@, zero or one leading slash.
  838. return SSHGitClient(parsed.scheme, **kwargs), parsed.path
  839. elif parsed.scheme:
  840. raise ValueError('Unknown git protocol scheme: %s' % parsed.scheme)
  841. elif '@' in parsed.path and ':' in parsed.path:
  842. # SSH with user@host:foo.
  843. user_host, path = parsed.path.split(':')
  844. user, host = user_host.rsplit('@')
  845. return SSHGitClient(host, username=user, **kwargs), path
  846. # Otherwise, assume it's a local path.
  847. return SubprocessGitClient(**kwargs), uri