How to use Nikola - 10 common examples

To help you get started, we’ve selected a few Nikola 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 diegosarmentero / documentor / docdump.py View on Github external
def _add_function(self, symbol, htmlpath, docpath):
        """Add the function with the function content and style."""
        content = ''
        name_to_slugy = os.path.splitext(htmlpath)[0]
        slugy = utils.slugify(name_to_slugy.decode('utf-8'))
        function_name = templates.FUNCTION % {
            'name': "%s [at ln:%d]" % (symbol['name'], symbol['lineno']),
            'link': '%s#%s-%s' % (htmlpath, slugy, symbol['lineno'])
        }
        content += function_name + ('~' * len(function_name)) + '\n'

        content += templates.CODE % {
            'code': "def %s:" % symbol['name']
        }

        docstring = symbol['docstring']
        if docstring:
            docstring = '| %s' % docstring.replace(
                '*', '\\*').replace('`', '\\`').replace('_', '\_')
            doc = '| '.join([line + '\n'
                             for line in docstring.split('\n')]) + '\n'
github undertherain / pycontextfree / site / plugins / pdoc / pdoc.py View on Github external
def __init__(self):
        plugin_path = os.path.dirname(os.path.realpath(__file__))
        base_path = plugin_path.split("plugins")[0]
        LOGGER.info(f"!!!!!!!!!!!!!!!!base path = {base_path}")
        sys.path.insert(0, os.path.join(base_path, "../"))
github undertherain / pycontextfree / site / plugins / copy_pics / copy_pics.py View on Github external
from nikola.plugin_categories import Task
from nikola import utils
from nikola.utils import LOGGER

plugin_path = os.path.dirname(os.path.realpath(__file__))
base_path = plugin_path.split("plugins")[0]


def get_entries(path):
    for dirName, _, fileList in os.walk(path, topdown=False):
        for fname in fileList:
            if fname.endswith(".png"):
                yield(os.path.join(dirName, fname))


class CopyPics(Task):
    """Render code listings."""

    name = "copy_pics"

    def register_output_name(self, input_folder, rel_name, rel_output_name):
        """Register proper and improper file mappings."""
        self.improper_input_file_mapping[rel_name].add(rel_output_name)
        self.proper_input_file_mapping[os.path.join(input_folder, rel_name)] = rel_output_name
        self.proper_input_file_mapping[rel_output_name] = rel_output_name

    def set_site(self, site):
        """Set Nikola site."""

    def gen_tasks(self):
        for in_name in get_entries(os.path.join(base_path, "../examples")):
            name_image = os.path.basename(in_name)
github undertherain / pycontextfree / site / plugins / pdoc / pdoc.py View on Github external
def compile_string(self, data, source_path=None, is_two_file=True, post=None, lang=None):
        """Compile docstrings into HTML strings, with shortcode support."""
        if not is_two_file:
            _, data = self.split_metadata(data, None, lang)
        new_data, shortcodes = sc.extract_shortcodes(data)
        # The way pdoc generates output is a bit inflexible
        with tempfile.TemporaryDirectory() as tmpdir:
            subprocess.check_call(['pdoc', '--html', '--html-dir', tmpdir] + shlex.split(new_data.strip()))
            fname = os.listdir(tmpdir)[0]
            with open(os.path.join(tmpdir, fname), 'r', encoding='utf8') as inf:
                output = inf.read()
        return self.site.apply_shortcodes_uuid(output, shortcodes, filename=source_path, extra_context={'post': post})
github undertherain / pycontextfree / site / plugins / pdoc / pdoc.py View on Github external
import io
import os
import shlex
import subprocess
import sys
import tempfile


from nikola import shortcodes as sc
from nikola.plugin_categories import PageCompiler
from nikola.utils import makedirs, write_metadata
from nikola.utils import LOGGER


class CompilePdoc(PageCompiler):
    """Compile docstrings into HTML."""

    name = "pdoc"
    friendly_name = "PDoc"
    supports_metadata = False

    def __init__(self):
        plugin_path = os.path.dirname(os.path.realpath(__file__))
        base_path = plugin_path.split("plugins")[0]
        LOGGER.info(f"!!!!!!!!!!!!!!!!base path = {base_path}")
        sys.path.insert(0, os.path.join(base_path, "../"))

    def compile_string(self, data, source_path=None, is_two_file=True, post=None, lang=None):
        """Compile docstrings into HTML strings, with shortcode support."""
        if not is_two_file:
            _, data = self.split_metadata(data, None, lang)
github diegosarmentero / documentor / docdump.py View on Github external
'year': str(datetime.date.today().year),
            'projectname': self.projectname
        }

        path = os.path.join(self.files_folder, 'documentor_classes.html')
        with open(path, 'w') as f:
            f.write(html)

        # Functions
        html = templates.HTML_FILES_HEADER % {
            'projectname': self.projectname,
            'type': 'Functions'
        }
        for fun in sorted(self.__functions, key=lambda x: x[0]):
            name_to_slugy = os.path.splitext(fun[1])[0]
            slugy = utils.slugify(name_to_slugy.decode('utf-8'))
            html += templates.HTML_FILES_BODY % {
                'link': "%s#%s-%d" % (fun[1], slugy, fun[2]),
                'name': fun[0]
            }
        html += templates.HTML_FILES_FOOTER % {
            'year': str(datetime.date.today().year),
            'projectname': self.projectname
        }

        path = os.path.join(self.files_folder, 'documentor_functions.html')
        with open(path, 'w') as f:
            f.write(html)
github undertherain / pycontextfree / site / plugins / copy_pics / copy_pics.py View on Github external
def gen_tasks(self):
        for in_name in get_entries(os.path.join(base_path, "../examples")):
            name_image = os.path.basename(in_name)
            out_name = "output/gallery/" + name_image

        # in_name = "/home/blackbird/Projects_heavy/pycontextfree/examples/paper/paper.png"
        # out_name = "output/gallery/paper.png"
        # out_name = "gallery/paper.png"
            LOGGER.info(f"emiting copyi task {in_name} to {out_name}")
            yield utils.apply_filters({
                'basename': self.name,
                'name': out_name,
                'file_dep': [in_name],
                'targets': [out_name],
                'actions': [(utils.copy_file, [in_name, out_name])],
                'clean': True,
                }, {})
github openframeworks / ofSite / plugins / documentation / documentation / __init__.py View on Github external
index_block_template_dep = self.site.template_system.template_deps(index_block_template_name)
        module_intro_template_name = "documentation_module_intro.mako"
        module_intro_template_dep = self.site.template_system.template_deps(module_intro_template_name)
        tdst = []
        for lang in self.kw['translations']:
            short_tdst = os.path.join(self.kw['translations'][lang], "documentation", "index.html")
            tdst.append(os.path.normpath(os.path.join(self.kw['output_folder'], short_tdst)))

        docs_md = []
        directory = os.path.join(self.site.original_cwd, "documentation")
        for root, subFolders, files in os.walk(directory):
            for file in files:
                f = os.path.join(root,file)
                docs_md.append(f)

        yield utils.apply_filters({
            'basename': self.name,
            'name': "documentation",
            'file_dep': template_dep + docs_md + class_template_dep + index_block_template_dep + module_intro_template_dep + [__file__, 'conf.py'] ,
            'targets': tdst,
            'actions': [
                (self.create_docs, ())
            ],
            'clean': True,
            'uptodate': [utils.config_changed({
                1: self.kw,
            })],
        }, self.kw['filters'])
github openframeworks / ofSite / plugins / tutorials / tutorials / __init__.py View on Github external
if not is_translation:
                        articles.append(articleobj)
                    else:
                        translations.append(articleobj)
                elif os.path.isdir(folder):
                    for lang in self.kw['translations']:
                        if lang == self.site.config['DEFAULT_LANG']: 
                            out_folder = os.path.join(self.site.original_cwd, 'output',folder_name,catfolder,article.lower())
                        else:
                            out_folder = os.path.join(self.site.original_cwd, 'output',lang,folder_name,catfolder,article.lower())
                            
                        for root, dirs, file_ins in os.walk(folder):
                            for f in file_ins:
                                in_path = os.path.join(root,f)
                                out_path = os.path.join(out_folder, f)
                                yield utils.apply_filters({
                                    'basename': self.name,
                                    'name': in_path + "." + lang,
                                    'file_dep': [in_path, __file__],
                                    'targets': [out_path],
                                    'actions': [
                                        (create_file, (in_path, out_path))
                                    ],
                                    'clean': True,
                                    'uptodate': [utils.config_changed({
                                        1: self.kw,
                                    })],
                                }, self.kw['filters'])
            
                
            def find_translations(article):
                article_file_name = os.path.splitext(article.file)[0]
github openframeworks / ofSite / plugins / tutorials / tutorials / __init__.py View on Github external
of_book_path = os.path.join(directory, "of_book.md")
            if lang != self.site.config['DEFAULT_LANG']:
                of_book_lang_path = utils.get_translation_candidate(self.site.config, of_book_path, lang)
                p = pathlib.Path(of_book_lang_path)
                if p.exists():
                    of_book_path = of_book_lang_path
            of_book = open(of_book_path).read()
            

            ### -----------------------------------
            ### 4) BOTTOM SECTION: how to improve the doc ###

            contributing_to_docs_path = os.path.join(directory, "contributing_to_docs.md")
            if lang != self.site.config['DEFAULT_LANG']:
                contributing_to_docs_lang_path = utils.get_translation_candidate(self.site.config, contributing_to_docs_path, lang)
                p = pathlib.Path(contributing_to_docs_lang_path)
                if p.exists():
                    contributing_to_docs_path = contributing_to_docs_lang_path
            contributing_to_docs = markdown.markdown(open(contributing_to_docs_path).read())


            context = {}
            context["lang"] = lang
            if lang == self.site.config['DEFAULT_LANG']: 
                context["permalink"] = '/' + folder_name + '/'
            else:
                context["permalink"] = '/' + lang + '/' + folder_name + '/'
            context["of_book"] = of_book
            context["contributing_to_docs"] = contributing_to_docs
            context["title"] = "learning"
            context['categories'] = categories