client.py 41 KB

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