application.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. # encoding: utf-8
  2. """
  3. An application for IPython.
  4. All top-level applications should use the classes in this module for
  5. handling configuration and creating configurables.
  6. The job of an :class:`Application` is to create the master configuration
  7. object and then create the configurable objects, passing the config to them.
  8. """
  9. # Copyright (c) IPython Development Team.
  10. # Distributed under the terms of the Modified BSD License.
  11. import atexit
  12. from copy import deepcopy
  13. import logging
  14. import os
  15. import shutil
  16. import sys
  17. from pathlib import Path
  18. from traitlets.config.application import Application, catch_config_error
  19. from traitlets.config.loader import ConfigFileNotFound, PyFileConfigLoader
  20. from IPython.core import release, crashhandler
  21. from IPython.core.profiledir import ProfileDir, ProfileDirError
  22. from IPython.paths import get_ipython_dir, get_ipython_package_dir
  23. from IPython.utils.path import ensure_dir_exists
  24. from traitlets import (
  25. List, Unicode, Type, Bool, Set, Instance, Undefined,
  26. default, observe,
  27. )
  28. if os.name == "nt":
  29. # %PROGRAMDATA% is not safe by default, require opt-in to trust it
  30. programdata = os.environ.get("PROGRAMDATA", None)
  31. if os.environ.get("IPYTHON_USE_PROGRAMDATA") == "1" and programdata is not None:
  32. SYSTEM_CONFIG_DIRS = [str(Path(programdata) / "ipython")]
  33. else:
  34. SYSTEM_CONFIG_DIRS = []
  35. else:
  36. SYSTEM_CONFIG_DIRS = [
  37. "/usr/local/etc/ipython",
  38. "/etc/ipython",
  39. ]
  40. ENV_CONFIG_DIRS = []
  41. _env_config_dir = os.path.join(sys.prefix, 'etc', 'ipython')
  42. if _env_config_dir not in SYSTEM_CONFIG_DIRS:
  43. # only add ENV_CONFIG if sys.prefix is not already included
  44. ENV_CONFIG_DIRS.append(_env_config_dir)
  45. _envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS')
  46. if _envvar in {None, ''}:
  47. IPYTHON_SUPPRESS_CONFIG_ERRORS = None
  48. else:
  49. if _envvar.lower() in {'1','true'}:
  50. IPYTHON_SUPPRESS_CONFIG_ERRORS = True
  51. elif _envvar.lower() in {'0','false'} :
  52. IPYTHON_SUPPRESS_CONFIG_ERRORS = False
  53. else:
  54. sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
  55. # aliases and flags
  56. base_aliases = {}
  57. if isinstance(Application.aliases, dict):
  58. # traitlets 5
  59. base_aliases.update(Application.aliases)
  60. base_aliases.update(
  61. {
  62. "profile-dir": "ProfileDir.location",
  63. "profile": "BaseIPythonApplication.profile",
  64. "ipython-dir": "BaseIPythonApplication.ipython_dir",
  65. "log-level": "Application.log_level",
  66. "config": "BaseIPythonApplication.extra_config_file",
  67. }
  68. )
  69. base_flags = dict()
  70. if isinstance(Application.flags, dict):
  71. # traitlets 5
  72. base_flags.update(Application.flags)
  73. base_flags.update(
  74. dict(
  75. debug=(
  76. {"Application": {"log_level": logging.DEBUG}},
  77. "set log level to logging.DEBUG (maximize logging output)",
  78. ),
  79. quiet=(
  80. {"Application": {"log_level": logging.CRITICAL}},
  81. "set log level to logging.CRITICAL (minimize logging output)",
  82. ),
  83. init=(
  84. {
  85. "BaseIPythonApplication": {
  86. "copy_config_files": True,
  87. "auto_create": True,
  88. }
  89. },
  90. """Initialize profile with default config files. This is equivalent
  91. to running `ipython profile create <profile>` prior to startup.
  92. """,
  93. ),
  94. )
  95. )
  96. class ProfileAwareConfigLoader(PyFileConfigLoader):
  97. """A Python file config loader that is aware of IPython profiles."""
  98. def load_subconfig(self, fname, path=None, profile=None):
  99. if profile is not None:
  100. try:
  101. profile_dir = ProfileDir.find_profile_dir_by_name(
  102. get_ipython_dir(),
  103. profile,
  104. )
  105. except ProfileDirError:
  106. return
  107. path = profile_dir.location
  108. return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path)
  109. class BaseIPythonApplication(Application):
  110. name = "ipython"
  111. description = "IPython: an enhanced interactive Python shell."
  112. version = Unicode(release.version)
  113. aliases = base_aliases
  114. flags = base_flags
  115. classes = List([ProfileDir])
  116. # enable `load_subconfig('cfg.py', profile='name')`
  117. python_config_loader_class = ProfileAwareConfigLoader
  118. # Track whether the config_file has changed,
  119. # because some logic happens only if we aren't using the default.
  120. config_file_specified = Set()
  121. config_file_name = Unicode()
  122. @default('config_file_name')
  123. def _config_file_name_default(self):
  124. return self.name.replace('-','_') + u'_config.py'
  125. @observe('config_file_name')
  126. def _config_file_name_changed(self, change):
  127. if change['new'] != change['old']:
  128. self.config_file_specified.add(change['new'])
  129. # The directory that contains IPython's builtin profiles.
  130. builtin_profile_dir = Unicode(
  131. os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
  132. )
  133. config_file_paths = List(Unicode())
  134. @default('config_file_paths')
  135. def _config_file_paths_default(self):
  136. return []
  137. extra_config_file = Unicode(
  138. help="""Path to an extra config file to load.
  139. If specified, load this config file in addition to any other IPython config.
  140. """).tag(config=True)
  141. @observe('extra_config_file')
  142. def _extra_config_file_changed(self, change):
  143. old = change['old']
  144. new = change['new']
  145. try:
  146. self.config_files.remove(old)
  147. except ValueError:
  148. pass
  149. self.config_file_specified.add(new)
  150. self.config_files.append(new)
  151. profile = Unicode(u'default',
  152. help="""The IPython profile to use."""
  153. ).tag(config=True)
  154. @observe('profile')
  155. def _profile_changed(self, change):
  156. self.builtin_profile_dir = os.path.join(
  157. get_ipython_package_dir(), u'config', u'profile', change['new']
  158. )
  159. add_ipython_dir_to_sys_path = Bool(
  160. False,
  161. """Should the IPython profile directory be added to sys path ?
  162. This option was non-existing before IPython 8.0, and ipython_dir was added to
  163. sys path to allow import of extensions present there. This was historical
  164. baggage from when pip did not exist. This now default to false,
  165. but can be set to true for legacy reasons.
  166. """,
  167. ).tag(config=True)
  168. ipython_dir = Unicode(
  169. help="""
  170. The name of the IPython directory. This directory is used for logging
  171. configuration (through profiles), history storage, etc. The default
  172. is usually $HOME/.ipython. This option can also be specified through
  173. the environment variable IPYTHONDIR.
  174. """
  175. ).tag(config=True)
  176. @default('ipython_dir')
  177. def _ipython_dir_default(self):
  178. d = get_ipython_dir()
  179. self._ipython_dir_changed({
  180. 'name': 'ipython_dir',
  181. 'old': d,
  182. 'new': d,
  183. })
  184. return d
  185. _in_init_profile_dir = False
  186. profile_dir = Instance(ProfileDir, allow_none=True)
  187. @default('profile_dir')
  188. def _profile_dir_default(self):
  189. # avoid recursion
  190. if self._in_init_profile_dir:
  191. return
  192. # profile_dir requested early, force initialization
  193. self.init_profile_dir()
  194. return self.profile_dir
  195. overwrite = Bool(False,
  196. help="""Whether to overwrite existing config files when copying"""
  197. ).tag(config=True)
  198. auto_create = Bool(False,
  199. help="""Whether to create profile dir if it doesn't exist"""
  200. ).tag(config=True)
  201. config_files = List(Unicode())
  202. @default('config_files')
  203. def _config_files_default(self):
  204. return [self.config_file_name]
  205. copy_config_files = Bool(False,
  206. help="""Whether to install the default config files into the profile dir.
  207. If a new profile is being created, and IPython contains config files for that
  208. profile, then they will be staged into the new directory. Otherwise,
  209. default config files will be automatically generated.
  210. """).tag(config=True)
  211. verbose_crash = Bool(False,
  212. help="""Create a massive crash report when IPython encounters what may be an
  213. internal error. The default is to append a short message to the
  214. usual traceback""").tag(config=True)
  215. # The class to use as the crash handler.
  216. crash_handler_class = Type(crashhandler.CrashHandler)
  217. @catch_config_error
  218. def __init__(self, **kwargs):
  219. super(BaseIPythonApplication, self).__init__(**kwargs)
  220. # ensure current working directory exists
  221. try:
  222. os.getcwd()
  223. except:
  224. # exit if cwd doesn't exist
  225. self.log.error("Current working directory doesn't exist.")
  226. self.exit(1)
  227. #-------------------------------------------------------------------------
  228. # Various stages of Application creation
  229. #-------------------------------------------------------------------------
  230. def init_crash_handler(self):
  231. """Create a crash handler, typically setting sys.excepthook to it."""
  232. self.crash_handler = self.crash_handler_class(self)
  233. sys.excepthook = self.excepthook
  234. def unset_crashhandler():
  235. sys.excepthook = sys.__excepthook__
  236. atexit.register(unset_crashhandler)
  237. def excepthook(self, etype, evalue, tb):
  238. """this is sys.excepthook after init_crashhandler
  239. set self.verbose_crash=True to use our full crashhandler, instead of
  240. a regular traceback with a short message (crash_handler_lite)
  241. """
  242. if self.verbose_crash:
  243. return self.crash_handler(etype, evalue, tb)
  244. else:
  245. return crashhandler.crash_handler_lite(etype, evalue, tb)
  246. @observe('ipython_dir')
  247. def _ipython_dir_changed(self, change):
  248. old = change['old']
  249. new = change['new']
  250. if old is not Undefined:
  251. str_old = os.path.abspath(old)
  252. if str_old in sys.path:
  253. sys.path.remove(str_old)
  254. if self.add_ipython_dir_to_sys_path:
  255. str_path = os.path.abspath(new)
  256. sys.path.append(str_path)
  257. ensure_dir_exists(new)
  258. readme = os.path.join(new, "README")
  259. readme_src = os.path.join(
  260. get_ipython_package_dir(), "config", "profile", "README"
  261. )
  262. if not os.path.exists(readme) and os.path.exists(readme_src):
  263. shutil.copy(readme_src, readme)
  264. for d in ("extensions", "nbextensions"):
  265. path = os.path.join(new, d)
  266. try:
  267. ensure_dir_exists(path)
  268. except OSError as e:
  269. # this will not be EEXIST
  270. self.log.error("couldn't create path %s: %s", path, e)
  271. self.log.debug("IPYTHONDIR set to: %s", new)
  272. def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS):
  273. """Load the config file.
  274. By default, errors in loading config are handled, and a warning
  275. printed on screen. For testing, the suppress_errors option is set
  276. to False, so errors will make tests fail.
  277. `suppress_errors` default value is to be `None` in which case the
  278. behavior default to the one of `traitlets.Application`.
  279. The default value can be set :
  280. - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive).
  281. - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive).
  282. - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset.
  283. Any other value are invalid, and will make IPython exit with a non-zero return code.
  284. """
  285. self.log.debug("Searching path %s for config files", self.config_file_paths)
  286. base_config = 'ipython_config.py'
  287. self.log.debug("Attempting to load config file: %s" %
  288. base_config)
  289. try:
  290. if suppress_errors is not None:
  291. old_value = Application.raise_config_file_errors
  292. Application.raise_config_file_errors = not suppress_errors
  293. Application.load_config_file(
  294. self,
  295. base_config,
  296. path=self.config_file_paths
  297. )
  298. except ConfigFileNotFound:
  299. # ignore errors loading parent
  300. self.log.debug("Config file %s not found", base_config)
  301. pass
  302. if suppress_errors is not None:
  303. Application.raise_config_file_errors = old_value
  304. for config_file_name in self.config_files:
  305. if not config_file_name or config_file_name == base_config:
  306. continue
  307. self.log.debug("Attempting to load config file: %s" %
  308. self.config_file_name)
  309. try:
  310. Application.load_config_file(
  311. self,
  312. config_file_name,
  313. path=self.config_file_paths
  314. )
  315. except ConfigFileNotFound:
  316. # Only warn if the default config file was NOT being used.
  317. if config_file_name in self.config_file_specified:
  318. msg = self.log.warning
  319. else:
  320. msg = self.log.debug
  321. msg("Config file not found, skipping: %s", config_file_name)
  322. except Exception:
  323. # For testing purposes.
  324. if not suppress_errors:
  325. raise
  326. self.log.warning("Error loading config file: %s" %
  327. self.config_file_name, exc_info=True)
  328. def init_profile_dir(self):
  329. """initialize the profile dir"""
  330. self._in_init_profile_dir = True
  331. if self.profile_dir is not None:
  332. # already ran
  333. return
  334. if 'ProfileDir.location' not in self.config:
  335. # location not specified, find by profile name
  336. try:
  337. p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
  338. except ProfileDirError:
  339. # not found, maybe create it (always create default profile)
  340. if self.auto_create or self.profile == 'default':
  341. try:
  342. p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
  343. except ProfileDirError:
  344. self.log.fatal("Could not create profile: %r"%self.profile)
  345. self.exit(1)
  346. else:
  347. self.log.info("Created profile dir: %r"%p.location)
  348. else:
  349. self.log.fatal("Profile %r not found."%self.profile)
  350. self.exit(1)
  351. else:
  352. self.log.debug("Using existing profile dir: %r", p.location)
  353. else:
  354. location = self.config.ProfileDir.location
  355. # location is fully specified
  356. try:
  357. p = ProfileDir.find_profile_dir(location, self.config)
  358. except ProfileDirError:
  359. # not found, maybe create it
  360. if self.auto_create:
  361. try:
  362. p = ProfileDir.create_profile_dir(location, self.config)
  363. except ProfileDirError:
  364. self.log.fatal("Could not create profile directory: %r"%location)
  365. self.exit(1)
  366. else:
  367. self.log.debug("Creating new profile dir: %r"%location)
  368. else:
  369. self.log.fatal("Profile directory %r not found."%location)
  370. self.exit(1)
  371. else:
  372. self.log.debug("Using existing profile dir: %r", p.location)
  373. # if profile_dir is specified explicitly, set profile name
  374. dir_name = os.path.basename(p.location)
  375. if dir_name.startswith('profile_'):
  376. self.profile = dir_name[8:]
  377. self.profile_dir = p
  378. self.config_file_paths.append(p.location)
  379. self._in_init_profile_dir = False
  380. def init_config_files(self):
  381. """[optionally] copy default config files into profile dir."""
  382. self.config_file_paths.extend(ENV_CONFIG_DIRS)
  383. self.config_file_paths.extend(SYSTEM_CONFIG_DIRS)
  384. # copy config files
  385. path = Path(self.builtin_profile_dir)
  386. if self.copy_config_files:
  387. src = self.profile
  388. cfg = self.config_file_name
  389. if path and (path / cfg).exists():
  390. self.log.warning(
  391. "Staging %r from %s into %r [overwrite=%s]"
  392. % (cfg, src, self.profile_dir.location, self.overwrite)
  393. )
  394. self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
  395. else:
  396. self.stage_default_config_file()
  397. else:
  398. # Still stage *bundled* config files, but not generated ones
  399. # This is necessary for `ipython profile=sympy` to load the profile
  400. # on the first go
  401. files = path.glob("*.py")
  402. for fullpath in files:
  403. cfg = fullpath.name
  404. if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
  405. # file was copied
  406. self.log.warning("Staging bundled %s from %s into %r"%(
  407. cfg, self.profile, self.profile_dir.location)
  408. )
  409. def stage_default_config_file(self):
  410. """auto generate default config file, and stage it into the profile."""
  411. s = self.generate_config_file()
  412. config_file = Path(self.profile_dir.location) / self.config_file_name
  413. if self.overwrite or not config_file.exists():
  414. self.log.warning("Generating default config file: %r", (config_file))
  415. config_file.write_text(s, encoding="utf-8")
  416. @catch_config_error
  417. def initialize(self, argv=None):
  418. # don't hook up crash handler before parsing command-line
  419. self.parse_command_line(argv)
  420. self.init_crash_handler()
  421. if self.subapp is not None:
  422. # stop here if subapp is taking over
  423. return
  424. # save a copy of CLI config to re-load after config files
  425. # so that it has highest priority
  426. cl_config = deepcopy(self.config)
  427. self.init_profile_dir()
  428. self.init_config_files()
  429. self.load_config_file()
  430. # enforce cl-opts override configfile opts:
  431. self.update_config(cl_config)