Skip to content

Instantly share code, notes, and snippets.

@GaryLee
Created February 20, 2024 10:18
Show Gist options
  • Save GaryLee/ba3b262c458c68d90d8adc0550832c11 to your computer and use it in GitHub Desktop.
Save GaryLee/ba3b262c458c68d90d8adc0550832c11 to your computer and use it in GitHub Desktop.
A Python script to generate template YAML file for mkdocs.
#!python
# coding: utf-8
import sys
import os
from mako.template import Template
yml_content = r'''site_name: "${site_name}"
nav:
- ${index_page_name}: ${index_filename}.md
- ${about_page_name}: ${about_filename}.md
plugins:
- search
theme:
name: readthedocs
markdown_extensions:
- tables
- admonition
- pymdownx.details
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
- pymdownx.inlinehilite
- pymdownx.snippets
- pymdownx.arithmatex:
generic: true
- pymdownx.highlight:
anchor_linenums: true
line_spans: __span
pygments_lang_class: true
extra_javascript:
- javascripts/mathjax.js
- https://polyfill.io/v3/polyfill.min.js?features=es6
- https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
'''
class MkdocsTmpl:
MKDOCS_YML = 'mkdocs.yml'
def __init__(self, **cfg):
self.cfg = cfg
...
def generate(self, folder):
if os.path.isdir(folder):
raise Exception(f"Folder {folder} already exists")
os.makedirs(folder, exist_ok=True)
if not os.path.isdir(folder):
raise Exception(f"Folder {folder} can't be created.")
yml_file = os.path.join(folder, self.MKDOCS_YML)
if os.path.isdir(yml_file):
raise Exception(f'File {yml_file} already exists and it is a folder.')
if os.path.isfile(yml_file):
raise Exception(f'File {yml_file} already exists')
tmpl = Template(yml_content)
content = tmpl.render(**self.cfg)
with open(yml_file, 'w') as f:
f.write(content)
print(f'File {yml_file} created.')
def no_check(_):
return True
def main():
if len(sys.argv) <= 1:
print(f'Usage: {sys.argv[0]} <folder>')
sys.exit(1)
items = {
'site_name' : ('Input your side name: ', 'My site', no_check),
'index_page_name': ("Input name of the index page: ", "Index", no_check),
'index_filename' : ("Input name of the index file: ", "index", no_check),
'about_page_name': ("Input name of the about page: ", "About", no_check),
'about_filename' : ("Input name of the about file: ", "about", no_check),
}
cfg = {k: v[1] for k, v in items.items()}
for k, v in items.items():
try:
value = input(v[0]).strip()
if not value:
print(f"--> Usage default value `{v[1]}`")
continue
if callable(v[2]) and not v[2](cfg[k]):
break
cfg[k] = value
except Exception as e:
print(f'Error: {e}')
tmpl = MkdocsTmpl(**cfg)
tmpl.generate(f'{sys.argv[1]}')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment