How to use the mkdocs.config.config_options.OptionallyRequired function in mkdocs

To help you get started, we’ve selected a few mkdocs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mkdocs / mkdocs / mkdocs / config / config_options.py View on Github external
target_key = self.moved_to
        else:
            move_to, target_key = self.moved_to.rsplit('.', 1)

            target = config
            for key in move_to.split('.'):
                target = target.setdefault(key, {})

                if not isinstance(target, dict):
                    # We can't move it for the user
                    return

        target[target_key] = config.pop(key_name)


class IpAddress(OptionallyRequired):
    """
    IpAddress Config Option

    Validate that an IP address is in an apprioriate format
    """

    def run_validation(self, value):
        try:
            host, port = value.rsplit(':', 1)
        except Exception:
            raise ValidationError("Must be a string of format 'IP:PORT'")

        try:
            port = int(port)
        except Exception:
            raise ValidationError("'{}' is not a valid port".format(port))
github mkdocs / mkdocs / mkdocs / contrib / search / __init__.py View on Github external
import os
import logging
from mkdocs import utils
from mkdocs.plugins import BasePlugin
from mkdocs.config import config_options
from mkdocs.contrib.search.search_index import SearchIndex


log = logging.getLogger(__name__)
base_path = os.path.dirname(os.path.abspath(__file__))


class LangOption(config_options.OptionallyRequired):
    """ Validate Language(s) provided in config are known languages. """

    def lang_file_exists(self, lang):
        path = os.path.join(base_path, 'lunr-language', 'lunr.{}.js'.format(lang))
        return os.path.isfile(path)

    def run_validation(self, value):
        if isinstance(value, str):
            value = [value]
        elif not isinstance(value, (list, tuple)):
            raise config_options.ValidationError('Expected a list of language codes.')
        for lang in value:
            if lang != 'en' and not self.lang_file_exists(lang):
                raise config_options.ValidationError(
                    '"{}" is not a supported language code.'.format(lang)
                )
github mkdocs / mkdocs / mkdocs / config / config_options.py View on Github external
raise ValidationError("Invalid pages config. {} {}".format(
            config_types, {str, dict}
        ))

    def post_validation(self, config, key_name):
        # TODO: remove this when `pages` config setting is fully deprecated.
        if key_name == 'pages' and config['pages'] is not None:
            if config['nav'] is None:
                # copy `pages` config to new 'nav' config setting
                config['nav'] = config['pages']
            warning = ("The 'pages' configuration option has been deprecated and will "
                       "be removed in a future release of MkDocs. Use 'nav' instead.")
            self.warnings.append(warning)


class Private(OptionallyRequired):
    """
    Private Config Option

    A config option only for internal use. Raises an error if set by the user.
    """

    def run_validation(self, value):
        raise ValidationError('For internal use only.')


class MarkdownExtensions(OptionallyRequired):
    """
    Markdown Extensions Config Option

    A list of extensions. If a list item contains extension configs,
    those are set on the private  setting passed to `configkey`. The
github mkdocs / mkdocs / mkdocs / config / config_options.py View on Github external
if value is None:
            if self.default is not None:
                if hasattr(self.default, 'copy'):
                    # ensure no mutable values are assigned
                    value = self.default.copy()
                else:
                    value = self.default
            elif not self.required:
                return
            elif self.required:
                raise ValidationError("Required configuration not provided.")

        return self.run_validation(value)


class Type(OptionallyRequired):
    """
    Type Config Option

    Validate the type of a config option against a given Python type.
    """

    def __init__(self, type_, length=None, **kwargs):
        super().__init__(**kwargs)
        self._type = type_
        self.length = length

    def run_validation(self, value):

        if not isinstance(value, self._type):
            msg = ("Expected type: {} but received: {}"
                   .format(self._type, type(value)))
github mkdocs / mkdocs / mkdocs / config / config_options.py View on Github external
"be removed in a future release of MkDocs. Use 'nav' instead.")
            self.warnings.append(warning)


class Private(OptionallyRequired):
    """
    Private Config Option

    A config option only for internal use. Raises an error if set by the user.
    """

    def run_validation(self, value):
        raise ValidationError('For internal use only.')


class MarkdownExtensions(OptionallyRequired):
    """
    Markdown Extensions Config Option

    A list of extensions. If a list item contains extension configs,
    those are set on the private  setting passed to `configkey`. The
    `builtins` keyword accepts a list of extensions which cannot be
    overriden by the user. However, builtins can be duplicated to define
    config options for them if desired.
    """
    def __init__(self, builtins=None, configkey='mdx_configs', **kwargs):
        super().__init__(**kwargs)
        self.builtins = builtins or []
        self.configkey = configkey
        self.configdata = {}

    def run_validation(self, value):
github mkdocs / mkdocs / mkdocs / config / config_options.py View on Github external
except Exception:
            raise ValidationError("Must be a string of format 'IP:PORT'")

        try:
            port = int(port)
        except Exception:
            raise ValidationError("'{}' is not a valid port".format(port))

        class Address(namedtuple('Address', 'host port')):
            def __str__(self):
                return '{}:{}'.format(self.host, self.port)

        return Address(host, port)


class URL(OptionallyRequired):
    """
    URL Config Option

    Validate a URL by requiring a scheme is present.
    """

    def __init__(self, default='', required=False):
        super().__init__(default, required)

    def run_validation(self, value):
        if value == '':
            return value

        try:
            parsed_url = urlparse(value)
        except (AttributeError, TypeError):
github mkdocs / mkdocs / mkdocs / config / config_options.py View on Github external
extensions = utils.reduce_list(self.builtins + extensions)

        # Confirm that Markdown considers extensions to be valid
        try:
            markdown.Markdown(extensions=extensions, extension_configs=self.configdata)
        except Exception as e:
            raise ValidationError(e.args[0])

        return extensions

    def post_validation(self, config, key_name):
        config[self.configkey] = self.configdata


class Plugins(OptionallyRequired):
    """
    Plugins config option.

    A list of plugins. If a plugin defines config options those are used when
    initializing the plugin class.
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.installed_plugins = plugins.get_plugins()
        self.config_file_path = None

    def pre_validation(self, config, key_name):
        self.config_file_path = config.config_file_path

    def run_validation(self, value):
github mkdocs / mkdocs / mkdocs / config / config_options.py View on Github external
def run_validation(self, value):

        if not isinstance(value, self._type):
            msg = ("Expected type: {} but received: {}"
                   .format(self._type, type(value)))
        elif self.length is not None and len(value) != self.length:
            msg = ("Expected type: {0} with length {2} but received: {1} with "
                   "length {3}").format(self._type, value, self.length,
                                        len(value))
        else:
            return value

        raise ValidationError(msg)


class Choice(OptionallyRequired):
    """
    Choice Config Option

    Validate the config option against a strict set of values.
    """

    def __init__(self, choices, **kwargs):
        super().__init__(**kwargs)
        try:
            length = len(choices)
        except TypeError:
            length = 0

        if not length or isinstance(choices, str):
            raise ValueError('Expected iterable of choices, got {}', choices)
github mkdocs / mkdocs / mkdocs / config / config_options.py View on Github external
if not theme_config['name'] and 'custom_dir' not in theme_config:
            raise ValidationError("At least one of 'theme.name' or 'theme.custom_dir' must be defined.")

        # Ensure custom_dir is an absolute path
        if 'custom_dir' in theme_config and not os.path.isabs(theme_config['custom_dir']):
            config_dir = os.path.dirname(config.config_file_path)
            theme_config['custom_dir'] = os.path.join(config_dir, theme_config['custom_dir'])

        if 'custom_dir' in theme_config and not os.path.isdir(theme_config['custom_dir']):
            raise ValidationError("The path set in {name}.custom_dir ('{path}') does not exist.".
                                  format(path=theme_config['custom_dir'], name=key_name))

        config[key_name] = theme.Theme(**theme_config)


class Nav(OptionallyRequired):
    """
    Nav Config Option

    Validate the Nav config. Automatically add all markdown files if empty.
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.file_match = utils.is_markdown_file

    def run_validation(self, value):

        if not isinstance(value, list):
            raise ValidationError(
                "Expected a list, got {}".format(type(value)))