Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
bharel committed Oct 7, 2023
1 parent a6a587d commit 981232f
Show file tree
Hide file tree
Showing 9 changed files with 221 additions and 38 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,4 @@ dmypy.json
# Pyre type checker
.pyre/
.idea
example_project/site
17 changes: 17 additions & 0 deletions example_project/docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Welcome to MkDocs

This is a simple test project.

## Commands

* `mkdocs new [dir-name]` - Create a new project.
* `mkdocs serve` - Start the live-reloading docs server.
* `mkdocs build` - Build the documentation site.
* `mkdocs -h` - Print help message and exit.

## Project layout

mkdocs.yml # The configuration file.
docs/
index.md # The documentation homepage.
openapi_example.md # Plugin example
48 changes: 48 additions & 0 deletions example_project/docs/openapi.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
openapi: 3.0.0
info:
title: Example API
version: 1.0.0
servers:
- url: http://localhost:8000
paths:
/users:
get:
summary: Get a list of users
responses:
'200':
description: A list of users
content:
application/json:
schema:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: string
post:
summary: Create a new user
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
responses:
'201':
description: The created user
content:
application/json:
schema:
type: object
properties:
id:
type: integer
name:
type: string

5 changes: 5 additions & 0 deletions example_project/docs/openapi_example.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# OpenAPI example

This is a rendered OpenAPI file:

!!swagger openapi.yml!!
4 changes: 4 additions & 0 deletions example_project/mkdocs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
site_name: My Docs

plugins:
- render_swagger
36 changes: 29 additions & 7 deletions render_swagger.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import os
import re
import string
import urllib.parse
from pathlib import Path
from xml.sax.saxutils import escape

import mkdocs.plugins
from pathlib import Path
from mkdocs.config import config_options
from mkdocs.structure.files import File
import string
import re
from xml.sax.saxutils import escape

USAGE_MSG = ("Usage: '!!swagger <filename>!!' or '!!swagger-http <url>!!'. "
"File must either exist locally and be placed next to the .md that contains "
Expand Down Expand Up @@ -50,17 +51,40 @@ def swagger_lib(config) -> dict:
extra_css = config.get('extra_css', [])
for lib in extra_javascript:
if os.path.basename(urllib.parse.urlparse(lib).path) == 'swagger-ui-bundle.js':
import warnings
warnings.warn(
"Please use the javascript configuration option for "
"mkdocs-render-swagger-plugin instead of extra_javascript.",
DeprecationWarning)
lib_swagger['js'] = lib
break

for css in extra_css:
if os.path.basename(urllib.parse.urlparse(css).path) == 'swagger-ui.css':
warnings.warn(
"Please use the css configuration option for "
"mkdocs-render-swagger-plugin instead of extra_css.",
DeprecationWarning)
lib_swagger['css'] = css
break
return lib_swagger


class SwaggerPlugin(mkdocs.plugins.BasePlugin):
config_scheme = (
("javascript",
config_options.Optional(config_options.File(exists=True))),
("css",
config_options.Optional(config_options.File(exists=True))),
("allow_arbitrary_locations", config_options.Type(bool, default=False)),
)

def on_config(self, config, **kwargs):
lib = swagger_lib(config)
config.javascript = config.javascript or lib['js']
config.css = config.css or lib['css']
return super().on_config(config, **kwargs)

def on_page_markdown(self, markdown, page, config, files):
is_http = False
match = TOKEN.search(markdown)
Expand Down Expand Up @@ -102,10 +126,8 @@ def _error(message):
files.append(new_file)
url = Path(new_file.abs_dest_path).name

lib = swagger_lib(config)

markdown = pre_token + TEMPLATE.substitute(
path=url, swagger_lib_js=lib['js'], swagger_lib_css=lib['css']
path=url, swagger_lib_js=config.javascript, swagger_lib_css=config.css
) + post_token

# If multiple swaggers exist.
Expand Down
28 changes: 28 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
[metadata]
name = mkdocs-render-swagger-plugin
version = 0.1.0
author = Bar Harel
author_email = bzvi7919@gmail.com
description = MKDocs plugin for rendering swagger & openapi files.
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/bharel/mkdocs-render-swagger-plugin
classifiers =
Programming Language :: Python :: 3
License :: OSI Approved :: MIT License
Operating System :: OS Independent

[options]
py_modules = render_swagger
python_requires = >=3.6
install_requires =
mkdocs >= 1.0
extras_require =
dev =
flake8
mypy
pyyaml

[options.entry_points]
mkdocs.plugins =
render_swagger = render_swagger:SwaggerPlugin
31 changes: 0 additions & 31 deletions setup.py

This file was deleted.

89 changes: 89 additions & 0 deletions tests/test_plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import os
import tempfile
import mkdocs
from mkdocs.config import Config
from mkdocs.structure.files import File
import unittest
from mkdocs.structure.pages import Page
from yaml import dump


DEFAULT_CONFIG = {
"site_name": 'My Site',
"plugins": [
{
"render_swagger": {}
},
],
}


def render_markdown(markdown, config_options=None):
# Create a temporary directory for the Mkdocs site
config_options = config_options or {}
with tempfile.TemporaryDirectory() as temp_dir:
# Create a mock Mkdocs config
config = Config([])
config.load_dict(dict(
site_name='My Site',
theme={
'name': 'mkdocs',
'custom_dir': 'custom_theme',
'static_templates': ['404.html']
},
extra_javascript=[js] if (
js := config_options.pop('extra_javascript', None)) else [],
extra_css=[css] if (
css := config_options.pop('extra_css', None)) else [],
plugins=[{'render_swagger': config_options or {}}],
))

# Create a mock Mkdocs page
page = Page(title='My Page', file=File(
'my_page.md', temp_dir, temp_dir, False), config=config)

# # Create a mock Mkdocs TOC
# toc = Toc([
# {'title': 'Home', 'url': 'index.html', 'children': []},
# {'title': 'My Page', 'url': 'my_page.html', 'children': []}
# ])

# Create a mock Mkdocs files collection
files = {
'index.md': '',
'my_page.md': markdown
}

# # Create a mock Mkdocs site navigation
# nav = mkdocs.structure.nav.Navigation(
# pages=[page],
# config=config,
# files=files,
# toc=toc
# )

# Create a mock Mkdocs site
site = mkdocs.structure.site.Site(
config=config,
files=files,
pages=[page],
nav=nav,
theme=mkdocs.themes.get_theme_instance(config),
template_context={},
use_directory_urls=False
)

# Build the Mkdocs site
mkdocs.commands.build.build(config, dump_config=False, clean_site_dir=False,
strict=False, use_directory_urls=False, site_dir=temp_dir)

# Render the page and return the HTML output
with open(os.path.join(temp_dir, page.url), 'r') as f:
html = f.read()

return html

class SwaggerPluginTestCase(unittest.TestCase):
def test_sanity(self):
result = render_markdown("")

0 comments on commit 981232f

Please sign in to comment.