config_options.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. import os
  2. from collections import Sequence, namedtuple
  3. from urllib.parse import urlparse
  4. import ipaddress
  5. import markdown
  6. from mkdocs import utils, theme, plugins
  7. from mkdocs.config.base import Config, ValidationError
  8. class BaseConfigOption:
  9. def __init__(self):
  10. self.warnings = []
  11. self.default = None
  12. def is_required(self):
  13. return False
  14. def validate(self, value):
  15. return self.run_validation(value)
  16. def reset_warnings(self):
  17. self.warnings = []
  18. def pre_validation(self, config, key_name):
  19. """
  20. Before all options are validated, perform a pre-validation process.
  21. The pre-validation process method should be implemented by subclasses.
  22. """
  23. def run_validation(self, value):
  24. """
  25. Perform validation for a value.
  26. The run_validation method should be implemented by subclasses.
  27. """
  28. return value
  29. def post_validation(self, config, key_name):
  30. """
  31. After all options have passed validation, perform a post-validation
  32. process to do any additional changes dependant on other config values.
  33. The post-validation process method should be implemented by subclasses.
  34. """
  35. class SubConfig(BaseConfigOption, Config):
  36. def __init__(self, *config_options):
  37. BaseConfigOption.__init__(self)
  38. Config.__init__(self, config_options)
  39. self.default = {}
  40. def validate(self, value):
  41. self.load_dict(value)
  42. return self.run_validation(value)
  43. def run_validation(self, value):
  44. Config.validate(self)
  45. return self
  46. class ConfigItems(BaseConfigOption):
  47. """
  48. Config Items Option
  49. Validates a list of mappings that all must match the same set of
  50. options.
  51. """
  52. def __init__(self, *config_options, **kwargs):
  53. BaseConfigOption.__init__(self)
  54. self.item_config = SubConfig(*config_options)
  55. self.required = kwargs.get('required', False)
  56. def __repr__(self):
  57. return '{}: {}'.format(self.__class__.__name__, self.item_config)
  58. def run_validation(self, value):
  59. if value is None:
  60. if self.required:
  61. raise ValidationError("Required configuration not provided.")
  62. else:
  63. return ()
  64. if not isinstance(value, Sequence):
  65. raise ValidationError('Expected a sequence of mappings, but a %s '
  66. 'was given.' % type(value))
  67. result = []
  68. for item in value:
  69. result.append(self.item_config.validate(item))
  70. return result
  71. class OptionallyRequired(BaseConfigOption):
  72. """
  73. A subclass of BaseConfigOption that adds support for default values and
  74. required values. It is a base class for config options.
  75. """
  76. def __init__(self, default=None, required=False):
  77. super().__init__()
  78. self.default = default
  79. self.required = required
  80. def is_required(self):
  81. return self.required
  82. def validate(self, value):
  83. """
  84. Perform some initial validation.
  85. If the option is empty (None) and isn't required, leave it as such. If
  86. it is empty but has a default, use that. Finally, call the
  87. run_validation method on the subclass unless.
  88. """
  89. if value is None:
  90. if self.default is not None:
  91. if hasattr(self.default, 'copy'):
  92. # ensure no mutable values are assigned
  93. value = self.default.copy()
  94. else:
  95. value = self.default
  96. elif not self.required:
  97. return
  98. elif self.required:
  99. raise ValidationError("Required configuration not provided.")
  100. return self.run_validation(value)
  101. class Type(OptionallyRequired):
  102. """
  103. Type Config Option
  104. Validate the type of a config option against a given Python type.
  105. """
  106. def __init__(self, type_, length=None, **kwargs):
  107. super().__init__(**kwargs)
  108. self._type = type_
  109. self.length = length
  110. def run_validation(self, value):
  111. if not isinstance(value, self._type):
  112. msg = ("Expected type: {} but received: {}"
  113. .format(self._type, type(value)))
  114. elif self.length is not None and len(value) != self.length:
  115. msg = ("Expected type: {0} with length {2} but received: {1} with "
  116. "length {3}").format(self._type, value, self.length,
  117. len(value))
  118. else:
  119. return value
  120. raise ValidationError(msg)
  121. class Choice(OptionallyRequired):
  122. """
  123. Choice Config Option
  124. Validate the config option against a strict set of values.
  125. """
  126. def __init__(self, choices, **kwargs):
  127. super().__init__(**kwargs)
  128. try:
  129. length = len(choices)
  130. except TypeError:
  131. length = 0
  132. if not length or isinstance(choices, str):
  133. raise ValueError('Expected iterable of choices, got {}', choices)
  134. self.choices = choices
  135. def run_validation(self, value):
  136. if value not in self.choices:
  137. msg = ("Expected one of: {} but received: {}"
  138. .format(self.choices, value))
  139. else:
  140. return value
  141. raise ValidationError(msg)
  142. class Deprecated(BaseConfigOption):
  143. def __init__(self, moved_to=None):
  144. super().__init__()
  145. self.default = None
  146. self.moved_to = moved_to
  147. def pre_validation(self, config, key_name):
  148. if config.get(key_name) is None or self.moved_to is None:
  149. return
  150. warning = ('The configuration option {} has been deprecated and '
  151. 'will be removed in a future release of MkDocs.'
  152. ''.format(key_name))
  153. self.warnings.append(warning)
  154. if '.' not in self.moved_to:
  155. target = config
  156. target_key = self.moved_to
  157. else:
  158. move_to, target_key = self.moved_to.rsplit('.', 1)
  159. target = config
  160. for key in move_to.split('.'):
  161. target = target.setdefault(key, {})
  162. if not isinstance(target, dict):
  163. # We can't move it for the user
  164. return
  165. target[target_key] = config.pop(key_name)
  166. class IpAddress(OptionallyRequired):
  167. """
  168. IpAddress Config Option
  169. Validate that an IP address is in an apprioriate format
  170. """
  171. def run_validation(self, value):
  172. try:
  173. host, port = value.rsplit(':', 1)
  174. except Exception:
  175. raise ValidationError("Must be a string of format 'IP:PORT'")
  176. if host != 'localhost':
  177. try:
  178. # Validate and normalize IP Address
  179. host = str(ipaddress.ip_address(host))
  180. except ValueError as e:
  181. raise ValidationError(e)
  182. try:
  183. port = int(port)
  184. except Exception:
  185. raise ValidationError("'{}' is not a valid port".format(port))
  186. class Address(namedtuple('Address', 'host port')):
  187. def __str__(self):
  188. return '{}:{}'.format(self.host, self.port)
  189. return Address(host, port)
  190. def post_validation(self, config, key_name):
  191. host = config[key_name].host
  192. if key_name == 'dev_addr' and host in ['0.0.0.0', '::']:
  193. self.warnings.append(
  194. ("The use of the IP address '{}' suggests a production environment "
  195. "or the use of a proxy to connect to the MkDocs server. However, "
  196. "the MkDocs' server is intended for local development purposes only. "
  197. "Please use a third party production-ready server instead.").format(host)
  198. )
  199. class URL(OptionallyRequired):
  200. """
  201. URL Config Option
  202. Validate a URL by requiring a scheme is present.
  203. """
  204. def __init__(self, default='', required=False):
  205. super().__init__(default, required)
  206. def run_validation(self, value):
  207. if value == '':
  208. return value
  209. try:
  210. parsed_url = urlparse(value)
  211. except (AttributeError, TypeError):
  212. raise ValidationError("Unable to parse the URL.")
  213. if parsed_url.scheme:
  214. return value
  215. raise ValidationError(
  216. "The URL isn't valid, it should include the http:// (scheme)")
  217. class RepoURL(URL):
  218. """
  219. Repo URL Config Option
  220. A small extension to the URL config that sets the repo_name and edit_uri,
  221. based on the url if they haven't already been provided.
  222. """
  223. def post_validation(self, config, key_name):
  224. repo_host = urlparse(config['repo_url']).netloc.lower()
  225. edit_uri = config.get('edit_uri')
  226. # derive repo_name from repo_url if unset
  227. if config['repo_url'] is not None and config.get('repo_name') is None:
  228. if repo_host == 'github.com':
  229. config['repo_name'] = 'GitHub'
  230. elif repo_host == 'bitbucket.org':
  231. config['repo_name'] = 'Bitbucket'
  232. elif repo_host == 'gitlab.com':
  233. config['repo_name'] = 'GitLab'
  234. else:
  235. config['repo_name'] = repo_host.split('.')[0].title()
  236. # derive edit_uri from repo_name if unset
  237. if config['repo_url'] is not None and edit_uri is None:
  238. if repo_host == 'github.com' or repo_host == 'gitlab.com':
  239. edit_uri = 'edit/master/docs/'
  240. elif repo_host == 'bitbucket.org':
  241. edit_uri = 'src/default/docs/'
  242. else:
  243. edit_uri = ''
  244. # ensure a well-formed edit_uri
  245. if edit_uri:
  246. if not edit_uri.startswith(('?', '#')) \
  247. and not config['repo_url'].endswith('/'):
  248. config['repo_url'] += '/'
  249. if not edit_uri.endswith('/'):
  250. edit_uri += '/'
  251. config['edit_uri'] = edit_uri
  252. class FilesystemObject(Type):
  253. """
  254. Base class for options that point to filesystem objects.
  255. """
  256. def __init__(self, exists=False, **kwargs):
  257. super().__init__(type_=str, **kwargs)
  258. self.exists = exists
  259. self.config_dir = None
  260. def pre_validation(self, config, key_name):
  261. self.config_dir = os.path.dirname(config.config_file_path) if config.config_file_path else None
  262. def run_validation(self, value):
  263. value = super().run_validation(value)
  264. if self.config_dir and not os.path.isabs(value):
  265. value = os.path.join(self.config_dir, value)
  266. if self.exists and not self.existence_test(value):
  267. raise ValidationError("The path {path} isn't an existing {name}.".
  268. format(path=value, name=self.name))
  269. value = os.path.abspath(value)
  270. assert isinstance(value, str)
  271. return value
  272. class Dir(FilesystemObject):
  273. """
  274. Dir Config Option
  275. Validate a path to a directory, optionally verifying that it exists.
  276. """
  277. existence_test = staticmethod(os.path.isdir)
  278. name = 'directory'
  279. def post_validation(self, config, key_name):
  280. if config.config_file_path is None:
  281. return
  282. # Validate that the dir is not the parent dir of the config file.
  283. if os.path.dirname(config.config_file_path) == config[key_name]:
  284. raise ValidationError(
  285. ("The '{0}' should not be the parent directory of the config "
  286. "file. Use a child directory instead so that the '{0}' "
  287. "is a sibling of the config file.").format(key_name))
  288. class File(FilesystemObject):
  289. """
  290. File Config Option
  291. Validate a path to a file, optionally verifying that it exists.
  292. """
  293. existence_test = staticmethod(os.path.isfile)
  294. name = 'file'
  295. class SiteDir(Dir):
  296. """
  297. SiteDir Config Option
  298. Validates the site_dir and docs_dir directories do not contain each other.
  299. """
  300. def post_validation(self, config, key_name):
  301. super().post_validation(config, key_name)
  302. # Validate that the docs_dir and site_dir don't contain the
  303. # other as this will lead to copying back and forth on each
  304. # and eventually make a deep nested mess.
  305. if (config['docs_dir'] + os.sep).startswith(config['site_dir'].rstrip(os.sep) + os.sep):
  306. raise ValidationError(
  307. ("The 'docs_dir' should not be within the 'site_dir' as this "
  308. "can mean the source files are overwritten by the output or "
  309. "it will be deleted if --clean is passed to mkdocs build."
  310. "(site_dir: '{}', docs_dir: '{}')"
  311. ).format(config['site_dir'], config['docs_dir']))
  312. elif (config['site_dir'] + os.sep).startswith(config['docs_dir'].rstrip(os.sep) + os.sep):
  313. raise ValidationError(
  314. ("The 'site_dir' should not be within the 'docs_dir' as this "
  315. "leads to the build directory being copied into itself and "
  316. "duplicate nested files in the 'site_dir'."
  317. "(site_dir: '{}', docs_dir: '{}')"
  318. ).format(config['site_dir'], config['docs_dir']))
  319. class Theme(BaseConfigOption):
  320. """
  321. Theme Config Option
  322. Validate that the theme exists and build Theme instance.
  323. """
  324. def __init__(self, default=None):
  325. super().__init__()
  326. self.default = default
  327. def validate(self, value):
  328. if value is None and self.default is not None:
  329. value = {'name': self.default}
  330. if isinstance(value, str):
  331. value = {'name': value}
  332. themes = utils.get_theme_names()
  333. if isinstance(value, dict):
  334. if 'name' in value:
  335. if value['name'] is None or value['name'] in themes:
  336. return value
  337. raise ValidationError(
  338. "Unrecognised theme name: '{}'. The available installed themes "
  339. "are: {}".format(value['name'], ', '.join(themes))
  340. )
  341. raise ValidationError("No theme name set.")
  342. raise ValidationError('Invalid type "{}". Expected a string or key/value pairs.'.format(type(value)))
  343. def post_validation(self, config, key_name):
  344. theme_config = config[key_name]
  345. if not theme_config['name'] and 'custom_dir' not in theme_config:
  346. raise ValidationError("At least one of 'theme.name' or 'theme.custom_dir' must be defined.")
  347. # Ensure custom_dir is an absolute path
  348. if 'custom_dir' in theme_config and not os.path.isabs(theme_config['custom_dir']):
  349. config_dir = os.path.dirname(config.config_file_path)
  350. theme_config['custom_dir'] = os.path.join(config_dir, theme_config['custom_dir'])
  351. if 'custom_dir' in theme_config and not os.path.isdir(theme_config['custom_dir']):
  352. raise ValidationError("The path set in {name}.custom_dir ('{path}') does not exist.".
  353. format(path=theme_config['custom_dir'], name=key_name))
  354. config[key_name] = theme.Theme(**theme_config)
  355. class Nav(OptionallyRequired):
  356. """
  357. Nav Config Option
  358. Validate the Nav config. Automatically add all markdown files if empty.
  359. """
  360. def __init__(self, **kwargs):
  361. super().__init__(**kwargs)
  362. self.file_match = utils.is_markdown_file
  363. def run_validation(self, value):
  364. if not isinstance(value, list):
  365. raise ValidationError(
  366. "Expected a list, got {}".format(type(value)))
  367. if len(value) == 0:
  368. return
  369. config_types = {type(item) for item in value}
  370. if config_types.issubset({str, dict}):
  371. return value
  372. raise ValidationError("Invalid pages config. {} {}".format(
  373. config_types, {str, dict}
  374. ))
  375. def post_validation(self, config, key_name):
  376. # TODO: remove this when `pages` config setting is fully deprecated.
  377. if key_name == 'pages' and config['pages'] is not None:
  378. if config['nav'] is None:
  379. # copy `pages` config to new 'nav' config setting
  380. config['nav'] = config['pages']
  381. warning = ("The 'pages' configuration option has been deprecated and will "
  382. "be removed in a future release of MkDocs. Use 'nav' instead.")
  383. self.warnings.append(warning)
  384. class Private(OptionallyRequired):
  385. """
  386. Private Config Option
  387. A config option only for internal use. Raises an error if set by the user.
  388. """
  389. def run_validation(self, value):
  390. raise ValidationError('For internal use only.')
  391. class MarkdownExtensions(OptionallyRequired):
  392. """
  393. Markdown Extensions Config Option
  394. A list of extensions. If a list item contains extension configs,
  395. those are set on the private setting passed to `configkey`. The
  396. `builtins` keyword accepts a list of extensions which cannot be
  397. overriden by the user. However, builtins can be duplicated to define
  398. config options for them if desired.
  399. """
  400. def __init__(self, builtins=None, configkey='mdx_configs', **kwargs):
  401. super().__init__(**kwargs)
  402. self.builtins = builtins or []
  403. self.configkey = configkey
  404. self.configdata = {}
  405. def run_validation(self, value):
  406. if not isinstance(value, (list, tuple)):
  407. raise ValidationError('Invalid Markdown Extensions configuration')
  408. extensions = []
  409. for item in value:
  410. if isinstance(item, dict):
  411. if len(item) > 1:
  412. raise ValidationError('Invalid Markdown Extensions configuration')
  413. ext, cfg = item.popitem()
  414. extensions.append(ext)
  415. if cfg is None:
  416. continue
  417. if not isinstance(cfg, dict):
  418. raise ValidationError('Invalid config options for Markdown '
  419. "Extension '{}'.".format(ext))
  420. self.configdata[ext] = cfg
  421. elif isinstance(item, str):
  422. extensions.append(item)
  423. else:
  424. raise ValidationError('Invalid Markdown Extensions configuration')
  425. extensions = utils.reduce_list(self.builtins + extensions)
  426. # Confirm that Markdown considers extensions to be valid
  427. try:
  428. markdown.Markdown(extensions=extensions, extension_configs=self.configdata)
  429. except Exception as e:
  430. raise ValidationError(e.args[0])
  431. return extensions
  432. def post_validation(self, config, key_name):
  433. config[self.configkey] = self.configdata
  434. class Plugins(OptionallyRequired):
  435. """
  436. Plugins config option.
  437. A list of plugins. If a plugin defines config options those are used when
  438. initializing the plugin class.
  439. """
  440. def __init__(self, **kwargs):
  441. super().__init__(**kwargs)
  442. self.installed_plugins = plugins.get_plugins()
  443. self.config_file_path = None
  444. def pre_validation(self, config, key_name):
  445. self.config_file_path = config.config_file_path
  446. def run_validation(self, value):
  447. if not isinstance(value, (list, tuple)):
  448. raise ValidationError('Invalid Plugins configuration. Expected a list of plugins')
  449. plgins = plugins.PluginCollection()
  450. for item in value:
  451. if isinstance(item, dict):
  452. if len(item) > 1:
  453. raise ValidationError('Invalid Plugins configuration')
  454. name, cfg = item.popitem()
  455. cfg = cfg or {} # Users may define a null (None) config
  456. if not isinstance(cfg, dict):
  457. raise ValidationError('Invalid config options for '
  458. 'the "{}" plugin.'.format(name))
  459. item = name
  460. else:
  461. cfg = {}
  462. if not isinstance(item, str):
  463. raise ValidationError('Invalid Plugins configuration')
  464. plgins[item] = self.load_plugin(item, cfg)
  465. return plgins
  466. def load_plugin(self, name, config):
  467. if name not in self.installed_plugins:
  468. raise ValidationError('The "{}" plugin is not installed'.format(name))
  469. Plugin = self.installed_plugins[name].load()
  470. if not issubclass(Plugin, plugins.BasePlugin):
  471. raise ValidationError('{}.{} must be a subclass of {}.{}'.format(
  472. Plugin.__module__, Plugin.__name__, plugins.BasePlugin.__module__,
  473. plugins.BasePlugin.__name__))
  474. plugin = Plugin()
  475. errors, warnings = plugin.load_config(config, self.config_file_path)
  476. self.warnings.extend(warnings)
  477. errors_message = '\n'.join(
  478. "Plugin value: '{}'. Error: {}".format(x, y)
  479. for x, y in errors
  480. )
  481. if errors_message:
  482. raise ValidationError(errors_message)
  483. return plugin