-
Notifications
You must be signed in to change notification settings - Fork 10
/
generator.py
169 lines (136 loc) · 4.94 KB
/
generator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""md
# Mkdocs Simple Generator
`mkdocs_simple_gen` is a program that will automatically create a `mkdocs.yml`
configuration file (only if needed) and optionally install dependencies, build,
and serve the site.
## Installation
Install the plugin with pip.
```bash
pip install mkdocs-simple-plugin
```
{% include "versions.snippet" %}
"""
import click
import tempfile
import os
import yaml
def default_config():
"""Get default configuration for mkdocs.yml file."""
config = {}
config['site_name'] = os.path.basename(os.path.abspath("."))
# Set the docs dir to temporary directory, or docs if the folder exists
default_docs = os.path.join(os.getcwd(), "docs")
temp_docs = os.path.join(
tempfile.gettempdir(),
'mkdocs-simple',
os.path.basename(
os.getcwd()),
"docs")
config['docs_dir'] = default_docs if os.path.exists(
default_docs) else temp_docs
config['plugins'] = ("simple", "search")
# Set the default edit uri to empty since doc files are built from source
# and may not exist.
config['edit_uri'] = ''
config['site_url'] = 'http://localhost'
def maybe_set_string(name):
env_variable = "INPUT_" + name.upper()
config_variable = name.lower()
if env_variable in os.environ.keys() and os.environ[env_variable]:
config[config_variable] = os.environ[env_variable]
def maybe_set_dict(name, key):
env_variable = "INPUT_" + name.upper()
config_variable = name.lower()
if env_variable in os.environ.keys() and os.environ[env_variable]:
config[config_variable] = {key: os.environ[env_variable]}
# Set the config variables via environment if exist
maybe_set_string("site_name")
maybe_set_string("site_url")
maybe_set_string("site_dir")
maybe_set_string("repo_url")
maybe_set_dict("theme", "name")
return config
class MkdocsConfigDumper(yaml.Dumper):
"""Format yaml files better."""
def increase_indent(self, flow=False, indentless=False):
"""Indent lists."""
return super(MkdocsConfigDumper, self).increase_indent(flow, False)
def write_config(config_file, config):
"""Write configuration file."""
if os.path.dirname(config_file):
os.makedirs(os.path.dirname(config_file), exist_ok=True)
with open(config_file, 'w+') as file:
try:
yaml.dump(
data=config,
stream=file,
sort_keys=False,
default_flow_style=False,
Dumper=MkdocsConfigDumper)
except yaml.YAMLError as exc:
print(exc)
def setup_config(config_file="mkdocs.yml"):
"""Create the mkdocs.yml file with defaults for params that don't exist."""
config = default_config()
if not os.path.exists(config_file):
# If config file doesn't exit, create a simple one, guess the site name
# from the folder name.
write_config(config_file, config)
# Open the config file to verify settings.
with open(config_file, 'r') as stream:
try:
local_config = yaml.load(stream, yaml.Loader)
if local_config:
# Overwrite default config values with local mkdocs.yml
config.update(local_config)
print(config)
if not os.path.exists(config["docs_dir"]):
# Ensure docs directory exists.
print("making docs_dir {}".format(config["docs_dir"]))
os.makedirs(config["docs_dir"], exist_ok=True)
except yaml.YAMLError as exc:
print(exc)
raise
write_config(config_file, config)
return config
@click.command()
@click.option("--config-file", default="mkdocs.yml",
help="set the configuration file")
@click.option('--build/--no-build', default=False,
help="build the site using mkdocs build")
@click.option('--serve/--no-serve', default=False,
help="serve the site using mkdocs serve")
@click.argument('mkdocs-args', nargs=-1)
def main(config_file, build, serve, mkdocs_args):
"""Generate and build a mkdocs site."""
setup_config(config_file)
args = mkdocs_args + ("-f", config_file)
if build:
os.system("mkdocs build " + " ".join(args))
if serve:
os.system("mkdocs serve " + " ".join(args))
""" md
## Usage
```bash
mkdocs_simple_gen
```
### Command line options
See `--help`
```txt
Usage: mkdocs_simple_gen [OPTIONS]
Options:
--config-file set the configuration file
--build / --no-build build the site using mkdocs build
--serve / --no-serve serve the site using mkdocs serve
--help Show this message and exit.
```
default flags:
```bash
mkdocs_simple_gen --no-build --no-serve
```
"""
if __name__ == "__main__":
# pylint doesn't know how to parse the click decorators,
# so disable no-value-for-parameter on main
# pylint: disable=no-value-for-parameter
main(['--help'])