client.py 40 KB

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