How to use the mkdocs.plugins.BasePlugin 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
def load_plugin(self, name, config):
        if name not in self.installed_plugins:
            raise ValidationError('The "{}" plugin is not installed'.format(name))

        Plugin = self.installed_plugins[name].load()

        if not issubclass(Plugin, plugins.BasePlugin):
            raise ValidationError('{}.{} must be a subclass of {}.{}'.format(
                Plugin.__module__, Plugin.__name__, plugins.BasePlugin.__module__,
                plugins.BasePlugin.__name__))

        plugin = Plugin()
        errors, warnings = plugin.load_config(config, self.config_file_path)
        self.warnings.extend(warnings)
        errors_message = '\n'.join(
            "Plugin value: '{}'. Error: {}".format(x, y)
            for x, y in errors
        )
        if errors_message:
            raise ValidationError(errors_message)
        return plugin
github dhis2 / dhis2-docs / tools / python / edit_url / edit_url / plugin.py View on Github external
from mkdocs.plugins import BasePlugin


class EditUrlPlugin(BasePlugin):
    def on_page_context(self, context, page, config, **kwargs):
        page.edit_url = ""
        if 'edit_url' in page.meta:
            page.edit_url = page.meta['edit_url']
        return context
github mkdocs / mkdocs / mkdocs / plugins.py View on Github external
def __setitem__(self, key, value, **kwargs):
        if not isinstance(value, BasePlugin):
            raise TypeError(
                '{0}.{1} only accepts values which are instances of {3}.{4} '
                'sublcasses'.format(self.__module__, self.__name__,
                                    BasePlugin.__module__, BasePlugin.__name__))
        super().__setitem__(key, value, **kwargs)
        # Register all of the event methods defined for this Plugin.
        for event_name in (x for x in dir(value) if x.startswith('on_')):
            method = getattr(value, event_name)
            if callable(method):
                self._register_event(event_name[3:], method)
github byrnereese / mkdocs-minify-plugin / mkdocs_minify_plugin / plugin.py View on Github external
import os
import sys
import fnmatch
from timeit import default_timer as timer
from datetime import datetime, timedelta

from mkdocs import utils as mkdocs_utils
from mkdocs.config import config_options, Config
from mkdocs.plugins import BasePlugin
import mkdocs.structure.files

from jsmin import jsmin
from htmlmin import minify

class MinifyPlugin(BasePlugin):

    config_scheme = (
        ('minify_html', mkdocs.config.config_options.Type(bool, default=False)),
        ('htmlmin_opts', mkdocs.config.config_options.Type((str, dict), default=None)),
        ('minify_js', mkdocs.config.config_options.Type(bool, default=False)),
        ('js_files', mkdocs.config.config_options.Type((str, list), default=None))
    )

    def __init__(self):
        self.enabled = True
        self.total_time = 0

    def on_post_page(self, output_content, page, config):
        if self.config['minify_html']:
            opts = self.config['htmlmin_opts'] or {}
            for key in opts:
github lukasgeiter / mkdocs-awesome-pages-plugin / mkdocs_awesome_pages_plugin / plugin.py View on Github external
from mkdocs.config import config_options, Config
from mkdocs.plugins import BasePlugin
from mkdocs.structure.files import Files
from mkdocs.structure.nav import Navigation as MkDocsNavigation

from .navigation import AwesomeNavigation
from .options import Options


class AwesomePagesPlugin(BasePlugin):

    DEFAULT_META_FILENAME = '.pages'

    config_scheme = (
        ('filename', config_options.Type(str, default=DEFAULT_META_FILENAME)),
        ('collapse_single_pages', config_options.Type(bool, default=False)),
        ('strict', config_options.Type(bool, default=True))
    )

    def on_nav(self, nav: MkDocsNavigation, config: Config, files: Files):
        return AwesomeNavigation(nav, Options(**self.config)).to_mkdocs()
github allevo / mkdocs-swagger-plugin / swagger / swagger.py View on Github external
from mkdocs import plugins
import re
import os

regex = '!!([^\s]+) ([^!]+)!!'
def replace_all_occurence(text):
    return re.sub(regex, r'<div data-path="\2" data-method="\1">\1 \2</div>', text)

class Swagger(plugins.BasePlugin):
    def on_config(self, config):
        swagger_url = config[u'extra'].data.get(u'swagger_url', 'https://petstore.swagger.io/v2/swagger.json')

        js_relative_path = 'javascript_swagger/swagger_plugin.js'
        dirname = os.path.dirname(__file__)
        js_filepath = os.path.join(dirname, js_relative_path)

        data = ''
        with open(js_filepath, 'r') as file:
            data = file.read()
        data = re.sub('\{\{swagger_url\}\}', swagger_url, data)
        with open(js_filepath, 'w') as file:
            file.write(data)

        # Add javascript to every pages
        config[u'extra_javascript'].append(js_relative_path)
github mkdocs / mkdocs / mkdocs / config / config_options.py View on Github external
def load_plugin(self, name, config):
        if name not in self.installed_plugins:
            raise ValidationError('The "{}" plugin is not installed'.format(name))

        Plugin = self.installed_plugins[name].load()

        if not issubclass(Plugin, plugins.BasePlugin):
            raise ValidationError('{}.{} must be a subclass of {}.{}'.format(
                Plugin.__module__, Plugin.__name__, plugins.BasePlugin.__module__,
                plugins.BasePlugin.__name__))

        plugin = Plugin()
        errors, warnings = plugin.load_config(config, self.config_file_path)
        self.warnings.extend(warnings)
        errors_message = '\n'.join(
            "Plugin value: '{}'. Error: {}".format(x, y)
            for x, y in errors
        )
        if errors_message:
            raise ValidationError(errors_message)
        return plugin
github spotify / mkdocs-monorepo-plugin / mkdocs_monorepo_plugin / plugin.py View on Github external
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from mkdocs.plugins import BasePlugin
from .parser import Parser
from .merger import Merger


class MonorepoPlugin(BasePlugin):
    def __init__(self):
        self.parser = None
        self.merger = None
        self.originalDocsDir = None
        self.resolvedPaths = []
        self.files_source_dir = {}

    def on_config(self, config):
        # If no 'nav' defined, we don't need to run.
        if not config.get('nav'):
            return config

        # Handle !import statements
        self.parser = Parser(config)
        resolvedNav = self.parser.resolve()
        resolvedPaths = self.parser.getResolvedPaths()
github zhaoterryy / mkdocs-git-revision-date-plugin / mkdocs_git_revision_date_plugin / plugin.py View on Github external
from os import environ
from datetime import datetime

from mkdocs.config import config_options
from mkdocs.plugins import BasePlugin
from jinja2 import Template
from .util import Util


class GitRevisionDatePlugin(BasePlugin):
    config_scheme = (
        ('enabled_if_env', config_options.Type(str)),
        ('modify_md', config_options.Type(bool, default=True)),
        ('as_datetime', config_options.Type(bool, default=False)),
    )

    def __init__(self):
        self.enabled = True
        self.util = Util()

    def on_config(self, config):
        env_name = self.config['enabled_if_env']
        if env_name:
            self.enabled = environ.get(env_name) == '1'
            if not self.enabled:
                print('PDF export is disabled (set environment variable %s to 1 to enable)' % env_name)
github mkdocs / mkdocs / mkdocs / config / config_options.py View on Github external
def load_plugin(self, name, config):
        if name not in self.installed_plugins:
            raise ValidationError('The "{}" plugin is not installed'.format(name))

        Plugin = self.installed_plugins[name].load()

        if not issubclass(Plugin, plugins.BasePlugin):
            raise ValidationError('{}.{} must be a subclass of {}.{}'.format(
                Plugin.__module__, Plugin.__name__, plugins.BasePlugin.__module__,
                plugins.BasePlugin.__name__))

        plugin = Plugin()
        errors, warnings = plugin.load_config(config, self.config_file_path)
        self.warnings.extend(warnings)
        errors_message = '\n'.join(
            "Plugin value: '{}'. Error: {}".format(x, y)
            for x, y in errors
        )
        if errors_message:
            raise ValidationError(errors_message)
        return plugin