client.py 40 KB

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