client.py 42 KB

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