| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import logging |
| 6 |
import os |
| 7 |
import shutil |
| 8 |
import sys |
| 9 |
import textwrap |
| 10 |
import traceback |
| 11 |
import warnings |
| 12 |
|
| 13 |
import click |
| 14 |
|
| 15 |
from mkdocs import __version__, config, utils |
| 16 |
|
| 17 |
if sys.platform.startswith("win"): |
| 18 |
try: |
| 19 |
import colorama |
| 20 |
except ImportError: |
| 21 |
pass |
| 22 |
else: |
| 23 |
colorama.init() |
| 24 |
|
| 25 |
log = logging.getLogger(__name__) |
| 26 |
|
| 27 |
|
| 28 |
def _showwarning(message, category, filename, lineno, file=None, line=None): |
| 29 |
try: |
| 30 |
# Last stack frames: |
| 31 |
# * ... |
| 32 |
# * Location of call to deprecated function <-- include this |
| 33 |
# * Location of call to warn() <-- include this |
| 34 |
# * (stdlib) Location of call to showwarning function |
| 35 |
# * (this function) Location of call to extract_stack() |
| 36 |
stack = [frame for frame in traceback.extract_stack() if frame.line][-4:-2] |
| 37 |
# Make sure the actual affected file's name is still present (the case of syntax warning): |
| 38 |
if not any(frame.filename == filename for frame in stack): |
| 39 |
stack = stack[-1:] + [traceback.FrameSummary(filename, lineno, '')] |
| 40 |
|
| 41 |
tb = ''.join(traceback.format_list(stack)) |
| 42 |
except Exception: |
| 43 |
tb = f' File "{filename}", line {lineno}' |
| 44 |
|
| 45 |
log.info(f'{category.__name__}: {message}\n{tb}') |
| 46 |
|
| 47 |
|
| 48 |
def _enable_warnings(): |
| 49 |
# When `python -W...` or `PYTHONWARNINGS` are used, `sys.warnoptions` is set. |
| 50 |
# In that case, we skip warnings configuration since |
| 51 |
# we don't want to overwrite the user configuration. |
| 52 |
if not sys.warnoptions: |
| 53 |
from mkdocs.commands import build |
| 54 |
|
| 55 |
build.log.addFilter(utils.DuplicateFilter()) |
| 56 |
|
| 57 |
warnings.simplefilter('module', DeprecationWarning) |
| 58 |
warnings.showwarning = _showwarning |
| 59 |
|
| 60 |
|
| 61 |
class ColorFormatter(logging.Formatter): |
| 62 |
colors = { |
| 63 |
'CRITICAL': 'red', |
| 64 |
'ERROR': 'red', |
| 65 |
'WARNING': 'yellow', |
| 66 |
'DEBUG': 'blue', |
| 67 |
} |
| 68 |
|
| 69 |
text_wrapper = textwrap.TextWrapper( |
| 70 |
width=shutil.get_terminal_size(fallback=(0, 0)).columns, |
| 71 |
replace_whitespace=False, |
| 72 |
break_long_words=False, |
| 73 |
break_on_hyphens=False, |
| 74 |
initial_indent=' ' * 11, |
| 75 |
subsequent_indent=' ' * 11, |
| 76 |
) |
| 77 |
|
| 78 |
def format(self, record): |
| 79 |
message = super().format(record) |
| 80 |
prefix = f'{record.levelname:<8}- ' |
| 81 |
if record.levelname in self.colors: |
| 82 |
prefix = click.style(prefix, fg=self.colors[record.levelname]) |
| 83 |
if self.text_wrapper.width: |
| 84 |
# Only wrap text if a terminal width was detected |
| 85 |
msg = '\n'.join(self.text_wrapper.fill(line) for line in message.splitlines()) |
| 86 |
# Prepend prefix after wrapping so that color codes don't affect length |
| 87 |
return prefix + msg[11:] |
| 88 |
return prefix + message |
| 89 |
|
| 90 |
|
| 91 |
class State: |
| 92 |
"""Maintain logging level.""" |
| 93 |
|
| 94 |
def __init__(self, log_name='mkdocs', level=logging.INFO): |
| 95 |
self.logger = logging.getLogger(log_name) |
| 96 |
self.logger.setLevel(level) |
| 97 |
self.logger.propagate = False |
| 98 |
|
| 99 |
self.stream = logging.StreamHandler() |
| 100 |
self.stream.setFormatter(ColorFormatter()) |
| 101 |
self.stream.name = 'MkDocsStreamHandler' |
| 102 |
self.logger.addHandler(self.stream) |
| 103 |
|
| 104 |
def __del__(self): |
| 105 |
self.logger.removeHandler(self.stream) |
| 106 |
|
| 107 |
|
| 108 |
pass_state = click.make_pass_decorator(State, ensure=True) |
| 109 |
|
| 110 |
clean_help = "Remove old files from the site_dir before building (the default)." |
| 111 |
config_help = ( |
| 112 |
"Provide a specific MkDocs config. This can be a file name, or '-' to read from stdin." |
| 113 |
) |
| 114 |
dev_addr_help = "IP address and port to serve documentation locally (default: localhost:8000)" |
| 115 |
serve_open_help = "Open the website in a Web browser after the initial build finishes." |
| 116 |
strict_help = "Enable strict mode. This will cause MkDocs to abort the build on any warnings." |
| 117 |
theme_help = "The theme to use when building your documentation." |
| 118 |
theme_choices = sorted(utils.get_theme_names()) |
| 119 |
site_dir_help = "The directory to output the result of the documentation build." |
| 120 |
use_directory_urls_help = "Use directory URLs when building pages (the default)." |
| 121 |
reload_help = "Enable the live reloading in the development server (this is the default)" |
| 122 |
no_reload_help = "Disable the live reloading in the development server." |
| 123 |
serve_dirty_help = "Only re-build files that have changed." |
| 124 |
serve_clean_help = ( |
| 125 |
"Build the site without any effects of `mkdocs serve` - pure `mkdocs build`, then serve." |
| 126 |
) |
| 127 |
commit_message_help = ( |
| 128 |
"A commit message to use when committing to the " |
| 129 |
"GitHub Pages remote branch. Commit {sha} and MkDocs {version} are available as expansions" |
| 130 |
) |
| 131 |
remote_branch_help = ( |
| 132 |
"The remote branch to commit to for GitHub Pages. This " |
| 133 |
"overrides the value specified in config" |
| 134 |
) |
| 135 |
remote_name_help = ( |
| 136 |
"The remote name to commit to for GitHub Pages. This overrides the value specified in config" |
| 137 |
) |
| 138 |
force_help = "Force the push to the repository." |
| 139 |
no_history_help = "Replace the whole Git history with one new commit." |
| 140 |
ignore_version_help = ( |
| 141 |
"Ignore check that build is not being deployed with an older version of MkDocs." |
| 142 |
) |
| 143 |
watch_theme_help = ( |
| 144 |
"Include the theme in list of files to watch for live reloading. " |
| 145 |
"Ignored when live reload is not used." |
| 146 |
) |
| 147 |
shell_help = "Use the shell when invoking Git." |
| 148 |
watch_help = "A directory or file to watch for live reloading. Can be supplied multiple times." |
| 149 |
projects_file_help = ( |
| 150 |
"URL or local path of the registry file that declares all known MkDocs-related projects." |
| 151 |
) |
| 152 |
|
| 153 |
|
| 154 |
def add_options(*opts): |
| 155 |
def inner(f): |
| 156 |
for i in reversed(opts): |
| 157 |
f = i(f) |
| 158 |
return f |
| 159 |
|
| 160 |
return inner |
| 161 |
|
| 162 |
|
| 163 |
def verbose_option(f): |
| 164 |
def callback(ctx, param, value): |
| 165 |
state = ctx.ensure_object(State) |
| 166 |
if value: |
| 167 |
state.logger.setLevel(logging.DEBUG) |
| 168 |
|
| 169 |
return click.option( |
| 170 |
'-v', |
| 171 |
'--verbose', |
| 172 |
is_flag=True, |
| 173 |
expose_value=False, |
| 174 |
help='Enable verbose output', |
| 175 |
callback=callback, |
| 176 |
)(f) |
| 177 |
|
| 178 |
|
| 179 |
def quiet_option(f): |
| 180 |
def callback(ctx, param, value): |
| 181 |
state = ctx.ensure_object(State) |
| 182 |
if value: |
| 183 |
state.logger.setLevel(logging.ERROR) |
| 184 |
|
| 185 |
return click.option( |
| 186 |
'-q', |
| 187 |
'--quiet', |
| 188 |
is_flag=True, |
| 189 |
expose_value=False, |
| 190 |
help='Silence warnings', |
| 191 |
callback=callback, |
| 192 |
)(f) |
| 193 |
|
| 194 |
|
| 195 |
def color_option(f): |
| 196 |
def callback(ctx, param, value): |
| 197 |
state = ctx.ensure_object(State) |
| 198 |
if value is False or ( |
| 199 |
value is None |
| 200 |
and ( |
| 201 |
not sys.stdout.isatty() |
| 202 |
or os.environ.get('NO_COLOR') |
| 203 |
or os.environ.get('TERM') == 'dumb' |
| 204 |
) |
| 205 |
): |
| 206 |
state.stream.setFormatter(logging.Formatter('%(levelname)-8s- %(message)s')) |
| 207 |
|
| 208 |
return click.option( |
| 209 |
'--color/--no-color', |
| 210 |
is_flag=True, |
| 211 |
default=None, |
| 212 |
expose_value=False, |
| 213 |
help="Force enable or disable color and wrapping for the output. Default is auto-detect.", |
| 214 |
callback=callback, |
| 215 |
)(f) |
| 216 |
|
| 217 |
|
| 218 |
common_options = add_options(quiet_option, verbose_option) |
| 219 |
common_config_options = add_options( |
| 220 |
click.option('-f', '--config-file', type=click.File('rb'), help=config_help), |
| 221 |
# Don't override config value if user did not specify --strict flag |
| 222 |
# Conveniently, load_config drops None values |
| 223 |
click.option('-s', '--strict/--no-strict', is_flag=True, default=None, help=strict_help), |
| 224 |
click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help), |
| 225 |
# As with --strict, set the default to None so that this doesn't incorrectly |
| 226 |
# override the config file |
| 227 |
click.option( |
| 228 |
'--use-directory-urls/--no-directory-urls', |
| 229 |
is_flag=True, |
| 230 |
default=None, |
| 231 |
help=use_directory_urls_help, |
| 232 |
), |
| 233 |
) |
| 234 |
|
| 235 |
PYTHON_VERSION = f"{sys.version_info.major}.{sys.version_info.minor}" |
| 236 |
|
| 237 |
PKG_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 238 |
|
| 239 |
|
| 240 |
@click.group(context_settings=dict(help_option_names=['-h', '--help'], max_content_width=120)) |
| 241 |
@click.version_option( |
| 242 |
__version__, |
| 243 |
'-V', |
| 244 |
'--version', |
| 245 |
message=f'%(prog)s, version %(version)s from { PKG_DIR } (Python { PYTHON_VERSION })', |
| 246 |
) |
| 247 |
@common_options |
| 248 |
@color_option |
| 249 |
def cli(): |
| 250 |
"""MkDocs - Project documentation with Markdown.""" |
| 251 |
|
| 252 |
|
| 253 |
@cli.command(name="serve") |
| 254 |
@click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>') |
| 255 |
@click.option('-o', '--open', 'open_in_browser', help=serve_open_help, is_flag=True) |
| 256 |
@click.option('--no-livereload', 'livereload', flag_value=False, help=no_reload_help) |
| 257 |
@click.option('--livereload', 'livereload', flag_value=True, default=True, hidden=True) |
| 258 |
@click.option('--dirtyreload', 'build_type', flag_value='dirty', hidden=True) |
| 259 |
@click.option('--dirty', 'build_type', flag_value='dirty', help=serve_dirty_help) |
| 260 |
@click.option('-c', '--clean', 'build_type', flag_value='clean', help=serve_clean_help) |
| 261 |
@click.option('--watch-theme', help=watch_theme_help, is_flag=True) |
| 262 |
@click.option( |
| 263 |
'-w', '--watch', help=watch_help, type=click.Path(exists=True), multiple=True, default=[] |
| 264 |
) |
| 265 |
@common_config_options |
| 266 |
@common_options |
| 267 |
def serve_command(**kwargs): |
| 268 |
"""Run the builtin development server.""" |
| 269 |
from mkdocs.commands import serve |
| 270 |
|
| 271 |
_enable_warnings() |
| 272 |
serve.serve(**kwargs) |
| 273 |
|
| 274 |
|
| 275 |
@cli.command(name="build") |
| 276 |
@click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) |
| 277 |
@common_config_options |
| 278 |
@click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help) |
| 279 |
@common_options |
| 280 |
def build_command(clean, **kwargs): |
| 281 |
"""Build the MkDocs documentation.""" |
| 282 |
from mkdocs.commands import build |
| 283 |
|
| 284 |
_enable_warnings() |
| 285 |
cfg = config.load_config(**kwargs) |
| 286 |
cfg.plugins.on_startup(command='build', dirty=not clean) |
| 287 |
try: |
| 288 |
build.build(cfg, dirty=not clean) |
| 289 |
finally: |
| 290 |
cfg.plugins.on_shutdown() |
| 291 |
|
| 292 |
|
| 293 |
@cli.command(name="gh-deploy") |
| 294 |
@click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) |
| 295 |
@click.option('-m', '--message', help=commit_message_help) |
| 296 |
@click.option('-b', '--remote-branch', help=remote_branch_help) |
| 297 |
@click.option('-r', '--remote-name', help=remote_name_help) |
| 298 |
@click.option('--force', is_flag=True, help=force_help) |
| 299 |
@click.option('--no-history', is_flag=True, help=no_history_help) |
| 300 |
@click.option('--ignore-version', is_flag=True, help=ignore_version_help) |
| 301 |
@click.option('--shell', is_flag=True, help=shell_help) |
| 302 |
@common_config_options |
| 303 |
@click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help) |
| 304 |
@common_options |
| 305 |
def gh_deploy_command( |
| 306 |
clean, message, remote_branch, remote_name, force, no_history, ignore_version, shell, **kwargs |
| 307 |
): |
| 308 |
"""Deploy your documentation to GitHub Pages.""" |
| 309 |
from mkdocs.commands import build, gh_deploy |
| 310 |
|
| 311 |
_enable_warnings() |
| 312 |
cfg = config.load_config(remote_branch=remote_branch, remote_name=remote_name, **kwargs) |
| 313 |
cfg.plugins.on_startup(command='gh-deploy', dirty=not clean) |
| 314 |
try: |
| 315 |
build.build(cfg, dirty=not clean) |
| 316 |
finally: |
| 317 |
cfg.plugins.on_shutdown() |
| 318 |
gh_deploy.gh_deploy( |
| 319 |
cfg, |
| 320 |
message=message, |
| 321 |
force=force, |
| 322 |
no_history=no_history, |
| 323 |
ignore_version=ignore_version, |
| 324 |
shell=shell, |
| 325 |
) |
| 326 |
|
| 327 |
|
| 328 |
@cli.command(name="get-deps") |
| 329 |
@verbose_option |
| 330 |
@click.option('-f', '--config-file', type=click.File('rb'), help=config_help) |
| 331 |
@click.option( |
| 332 |
'-p', |
| 333 |
'--projects-file', |
| 334 |
default=None, |
| 335 |
help=projects_file_help, |
| 336 |
show_default=True, |
| 337 |
) |
| 338 |
def get_deps_command(config_file, projects_file): |
| 339 |
"""Show required PyPI packages inferred from plugins in mkdocs.yml.""" |
| 340 |
from mkdocs_get_deps import get_deps, get_projects_file |
| 341 |
|
| 342 |
from mkdocs.config.base import _open_config_file |
| 343 |
|
| 344 |
warning_counter = utils.CountHandler() |
| 345 |
warning_counter.setLevel(logging.WARNING) |
| 346 |
logging.getLogger('mkdocs').addHandler(warning_counter) |
| 347 |
|
| 348 |
with get_projects_file(projects_file) as p: |
| 349 |
with _open_config_file(config_file) as f: |
| 350 |
deps = get_deps(config_file=f, projects_file=p) |
| 351 |
|
| 352 |
for dep in deps: |
| 353 |
print(dep) # noqa: T201 |
| 354 |
|
| 355 |
if warning_counter.get_counts(): |
| 356 |
sys.exit(1) |
| 357 |
|
| 358 |
|
| 359 |
@cli.command(name="new") |
| 360 |
@click.argument("project_directory") |
| 361 |
@common_options |
| 362 |
def new_command(project_directory): |
| 363 |
"""Create a new MkDocs project.""" |
| 364 |
from mkdocs.commands import new |
| 365 |
|
| 366 |
new.new(project_directory) |
| 367 |
|
| 368 |
|
| 369 |
if __name__ == '__main__': # pragma: no cover |
| 370 |
cli() |