We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Disable color output in terminal when NO_COLOR is set
It would be nice to turn off terminal colors sometimes, but there currently is no option to do that.

https://no-color.org/ is the closest thing to a standard I could find, and they recommend disabling color if the `NO_COLOR` environment variable is set (to any value).

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mkdocs/__main__.py`
Content:
```
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     from mkdocs.commands import build
50 
51     build.log.addFilter(utils.DuplicateFilter())
52 
53     warnings.simplefilter('module', DeprecationWarning)
54     warnings.showwarning = _showwarning
55 
56 
57 class ColorFormatter(logging.Formatter):
58     colors = {
59         'CRITICAL': 'red',
60         'ERROR': 'red',
61         'WARNING': 'yellow',
62         'DEBUG': 'blue',
63     }
64 
65     text_wrapper = textwrap.TextWrapper(
66         width=shutil.get_terminal_size(fallback=(0, 0)).columns,
67         replace_whitespace=False,
68         break_long_words=False,
69         break_on_hyphens=False,
70         initial_indent=' ' * 12,
71         subsequent_indent=' ' * 12,
72     )
73 
74     def format(self, record):
75         message = super().format(record)
76         prefix = f'{record.levelname:<8} -  '
77         if record.levelname in self.colors:
78             prefix = click.style(prefix, fg=self.colors[record.levelname])
79         if self.text_wrapper.width:
80             # Only wrap text if a terminal width was detected
81             msg = '\n'.join(self.text_wrapper.fill(line) for line in message.splitlines())
82             # Prepend prefix after wrapping so that color codes don't affect length
83             return prefix + msg[12:]
84         return prefix + message
85 
86 
87 class State:
88     """Maintain logging level."""
89 
90     def __init__(self, log_name='mkdocs', level=logging.INFO):
91         self.logger = logging.getLogger(log_name)
92         # Don't restrict level on logger; use handler
93         self.logger.setLevel(1)
94         self.logger.propagate = False
95 
96         self.stream = logging.StreamHandler()
97         self.stream.setFormatter(ColorFormatter())
98         self.stream.setLevel(level)
99         self.stream.name = 'MkDocsStreamHandler'
100         self.logger.addHandler(self.stream)
101 
102     def __del__(self):
103         self.logger.removeHandler(self.stream)
104 
105 
106 pass_state = click.make_pass_decorator(State, ensure=True)
107 
108 clean_help = "Remove old files from the site_dir before building (the default)."
109 config_help = (
110     "Provide a specific MkDocs config. This can be a file name, or '-' to read from stdin."
111 )
112 dev_addr_help = "IP address and port to serve documentation locally (default: localhost:8000)"
113 strict_help = "Enable strict mode. This will cause MkDocs to abort the build on any warnings."
114 theme_help = "The theme to use when building your documentation."
115 theme_choices = sorted(utils.get_theme_names())
116 site_dir_help = "The directory to output the result of the documentation build."
117 use_directory_urls_help = "Use directory URLs when building pages (the default)."
118 reload_help = "Enable the live reloading in the development server (this is the default)"
119 no_reload_help = "Disable the live reloading in the development server."
120 serve_dirty_help = "Only re-build files that have changed."
121 serve_clean_help = (
122     "Build the site without any effects of `mkdocs serve` - pure `mkdocs build`, then serve."
123 )
124 commit_message_help = (
125     "A commit message to use when committing to the "
126     "GitHub Pages remote branch. Commit {sha} and MkDocs {version} are available as expansions"
127 )
128 remote_branch_help = (
129     "The remote branch to commit to for GitHub Pages. This "
130     "overrides the value specified in config"
131 )
132 remote_name_help = (
133     "The remote name to commit to for GitHub Pages. This overrides the value specified in config"
134 )
135 force_help = "Force the push to the repository."
136 no_history_help = "Replace the whole Git history with one new commit."
137 ignore_version_help = (
138     "Ignore check that build is not being deployed with an older version of MkDocs."
139 )
140 watch_theme_help = (
141     "Include the theme in list of files to watch for live reloading. "
142     "Ignored when live reload is not used."
143 )
144 shell_help = "Use the shell when invoking Git."
145 watch_help = "A directory or file to watch for live reloading. Can be supplied multiple times."
146 projects_file_help = (
147     "URL or local path of the registry file that declares all known MkDocs-related projects."
148 )
149 
150 
151 def add_options(*opts):
152     def inner(f):
153         for i in reversed(opts):
154             f = i(f)
155         return f
156 
157     return inner
158 
159 
160 def verbose_option(f):
161     def callback(ctx, param, value):
162         state = ctx.ensure_object(State)
163         if value:
164             state.stream.setLevel(logging.DEBUG)
165 
166     return click.option(
167         '-v',
168         '--verbose',
169         is_flag=True,
170         expose_value=False,
171         help='Enable verbose output',
172         callback=callback,
173     )(f)
174 
175 
176 def quiet_option(f):
177     def callback(ctx, param, value):
178         state = ctx.ensure_object(State)
179         if value:
180             state.stream.setLevel(logging.ERROR)
181 
182     return click.option(
183         '-q',
184         '--quiet',
185         is_flag=True,
186         expose_value=False,
187         help='Silence warnings',
188         callback=callback,
189     )(f)
190 
191 
192 common_options = add_options(quiet_option, verbose_option)
193 common_config_options = add_options(
194     click.option('-f', '--config-file', type=click.File('rb'), help=config_help),
195     # Don't override config value if user did not specify --strict flag
196     # Conveniently, load_config drops None values
197     click.option('-s', '--strict/--no-strict', is_flag=True, default=None, help=strict_help),
198     click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help),
199     # As with --strict, set the default to None so that this doesn't incorrectly
200     # override the config file
201     click.option(
202         '--use-directory-urls/--no-directory-urls',
203         is_flag=True,
204         default=None,
205         help=use_directory_urls_help,
206     ),
207 )
208 
209 PYTHON_VERSION = f"{sys.version_info.major}.{sys.version_info.minor}"
210 
211 PKG_DIR = os.path.dirname(os.path.abspath(__file__))
212 
213 
214 @click.group(context_settings=dict(help_option_names=['-h', '--help'], max_content_width=120))
215 @click.version_option(
216     __version__,
217     '-V',
218     '--version',
219     message=f'%(prog)s, version %(version)s from { PKG_DIR } (Python { PYTHON_VERSION })',
220 )
221 @common_options
222 def cli():
223     """
224     MkDocs - Project documentation with Markdown.
225     """
226 
227 
228 @cli.command(name="serve")
229 @click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>')
230 @click.option('--livereload', 'livereload', flag_value='livereload', default=True, hidden=True)
231 @click.option('--no-livereload', 'livereload', flag_value='no-livereload', help=no_reload_help)
232 @click.option('--dirtyreload', 'build_type', flag_value='dirty', hidden=True)
233 @click.option('--dirty', 'build_type', flag_value='dirty', help=serve_dirty_help)
234 @click.option('-c', '--clean', 'build_type', flag_value='clean', help=serve_clean_help)
235 @click.option('--watch-theme', help=watch_theme_help, is_flag=True)
236 @click.option(
237     '-w', '--watch', help=watch_help, type=click.Path(exists=True), multiple=True, default=[]
238 )
239 @common_config_options
240 @common_options
241 def serve_command(**kwargs):
242     """Run the builtin development server"""
243     from mkdocs.commands import serve
244 
245     _enable_warnings()
246     serve.serve(**kwargs)
247 
248 
249 @cli.command(name="build")
250 @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)
251 @common_config_options
252 @click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help)
253 @common_options
254 def build_command(clean, **kwargs):
255     """Build the MkDocs documentation"""
256     from mkdocs.commands import build
257 
258     _enable_warnings()
259     cfg = config.load_config(**kwargs)
260     cfg.plugins.on_startup(command='build', dirty=not clean)
261     try:
262         build.build(cfg, dirty=not clean)
263     finally:
264         cfg.plugins.on_shutdown()
265 
266 
267 @cli.command(name="gh-deploy")
268 @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)
269 @click.option('-m', '--message', help=commit_message_help)
270 @click.option('-b', '--remote-branch', help=remote_branch_help)
271 @click.option('-r', '--remote-name', help=remote_name_help)
272 @click.option('--force', is_flag=True, help=force_help)
273 @click.option('--no-history', is_flag=True, help=no_history_help)
274 @click.option('--ignore-version', is_flag=True, help=ignore_version_help)
275 @click.option('--shell', is_flag=True, help=shell_help)
276 @common_config_options
277 @click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help)
278 @common_options
279 def gh_deploy_command(
280     clean, message, remote_branch, remote_name, force, no_history, ignore_version, shell, **kwargs
281 ):
282     """Deploy your documentation to GitHub Pages"""
283     from mkdocs.commands import build, gh_deploy
284 
285     _enable_warnings()
286     cfg = config.load_config(remote_branch=remote_branch, remote_name=remote_name, **kwargs)
287     cfg.plugins.on_startup(command='gh-deploy', dirty=not clean)
288     try:
289         build.build(cfg, dirty=not clean)
290     finally:
291         cfg.plugins.on_shutdown()
292     gh_deploy.gh_deploy(
293         cfg,
294         message=message,
295         force=force,
296         no_history=no_history,
297         ignore_version=ignore_version,
298         shell=shell,
299     )
300 
301 
302 @cli.command(name="get-deps")
303 @verbose_option
304 @click.option('-f', '--config-file', type=click.File('rb'), help=config_help)
305 @click.option(
306     '-p',
307     '--projects-file',
308     default='https://raw.githubusercontent.com/mkdocs/catalog/main/projects.yaml',
309     help=projects_file_help,
310     show_default=True,
311 )
312 def get_deps_command(config_file, projects_file):
313     """Show required PyPI packages inferred from plugins in mkdocs.yml"""
314     from mkdocs.commands import get_deps
315 
316     warning_counter = utils.CountHandler()
317     warning_counter.setLevel(logging.WARNING)
318     logging.getLogger('mkdocs').addHandler(warning_counter)
319 
320     get_deps.get_deps(projects_file_url=projects_file, config_file_path=config_file)
321 
322     if warning_counter.get_counts():
323         sys.exit(1)
324 
325 
326 @cli.command(name="new")
327 @click.argument("project_directory")
328 @common_options
329 def new_command(project_directory):
330     """Create a new MkDocs project"""
331     from mkdocs.commands import new
332 
333     new.new(project_directory)
334 
335 
336 if __name__ == '__main__':  # pragma: no cover
337     cli()
338
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mkdocs/__main__.py b/mkdocs/__main__.py
--- a/mkdocs/__main__.py
+++ b/mkdocs/__main__.py
@@ -67,20 +67,20 @@
         replace_whitespace=False,
         break_long_words=False,
         break_on_hyphens=False,
-        initial_indent=' ' * 12,
-        subsequent_indent=' ' * 12,
+        initial_indent=' ' * 11,
+        subsequent_indent=' ' * 11,
     )
 
     def format(self, record):
         message = super().format(record)
-        prefix = f'{record.levelname:<8} -  '
+        prefix = f'{record.levelname:<8}-  '
         if record.levelname in self.colors:
             prefix = click.style(prefix, fg=self.colors[record.levelname])
         if self.text_wrapper.width:
             # Only wrap text if a terminal width was detected
             msg = '\n'.join(self.text_wrapper.fill(line) for line in message.splitlines())
             # Prepend prefix after wrapping so that color codes don't affect length
-            return prefix + msg[12:]
+            return prefix + msg[11:]
         return prefix + message
 
 
@@ -189,6 +189,29 @@
     )(f)
 
 
+def color_option(f):
+    def callback(ctx, param, value):
+        state = ctx.ensure_object(State)
+        if value is False or (
+            value is None
+            and (
+                not sys.stdout.isatty()
+                or os.environ.get('NO_COLOR')
+                or os.environ.get('TERM') == 'dumb'
+            )
+        ):
+            state.stream.setFormatter(logging.Formatter('%(levelname)-8s-  %(message)s'))
+
+    return click.option(
+        '--color/--no-color',
+        is_flag=True,
+        default=None,
+        expose_value=False,
+        help="Force enable or disable color and wrapping for the output. Default is auto-detect.",
+        callback=callback,
+    )(f)
+
+
 common_options = add_options(quiet_option, verbose_option)
 common_config_options = add_options(
     click.option('-f', '--config-file', type=click.File('rb'), help=config_help),
@@ -219,6 +242,7 @@
     message=f'%(prog)s, version %(version)s from { PKG_DIR } (Python { PYTHON_VERSION })',
 )
 @common_options
+@color_option
 def cli():
     """
     MkDocs - Project documentation with Markdown.

{"golden_diff": "diff --git a/mkdocs/__main__.py b/mkdocs/__main__.py\n--- a/mkdocs/__main__.py\n+++ b/mkdocs/__main__.py\n@@ -67,20 +67,20 @@\n         replace_whitespace=False,\n         break_long_words=False,\n         break_on_hyphens=False,\n-        initial_indent=' ' * 12,\n-        subsequent_indent=' ' * 12,\n+        initial_indent=' ' * 11,\n+        subsequent_indent=' ' * 11,\n     )\n \n     def format(self, record):\n         message = super().format(record)\n-        prefix = f'{record.levelname:<8} -  '\n+        prefix = f'{record.levelname:<8}-  '\n         if record.levelname in self.colors:\n             prefix = click.style(prefix, fg=self.colors[record.levelname])\n         if self.text_wrapper.width:\n             # Only wrap text if a terminal width was detected\n             msg = '\\n'.join(self.text_wrapper.fill(line) for line in message.splitlines())\n             # Prepend prefix after wrapping so that color codes don't affect length\n-            return prefix + msg[12:]\n+            return prefix + msg[11:]\n         return prefix + message\n \n \n@@ -189,6 +189,29 @@\n     )(f)\n \n \n+def color_option(f):\n+    def callback(ctx, param, value):\n+        state = ctx.ensure_object(State)\n+        if value is False or (\n+            value is None\n+            and (\n+                not sys.stdout.isatty()\n+                or os.environ.get('NO_COLOR')\n+                or os.environ.get('TERM') == 'dumb'\n+            )\n+        ):\n+            state.stream.setFormatter(logging.Formatter('%(levelname)-8s-  %(message)s'))\n+\n+    return click.option(\n+        '--color/--no-color',\n+        is_flag=True,\n+        default=None,\n+        expose_value=False,\n+        help=\"Force enable or disable color and wrapping for the output. Default is auto-detect.\",\n+        callback=callback,\n+    )(f)\n+\n+\n common_options = add_options(quiet_option, verbose_option)\n common_config_options = add_options(\n     click.option('-f', '--config-file', type=click.File('rb'), help=config_help),\n@@ -219,6 +242,7 @@\n     message=f'%(prog)s, version %(version)s from { PKG_DIR } (Python { PYTHON_VERSION })',\n )\n @common_options\n+@color_option\n def cli():\n     \"\"\"\n     MkDocs - Project documentation with Markdown.\n", "issue": "Disable color output in terminal when NO_COLOR is set\nIt would be nice to turn off terminal colors sometimes, but there currently is no option to do that.\r\n\r\nhttps://no-color.org/ is the closest thing to a standard I could find, and they recommend disabling color if the `NO_COLOR` environment variable is set (to any value).\n", "before_files": [{"content": "#!/usr/bin/env python\n\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport shutil\nimport sys\nimport textwrap\nimport traceback\nimport warnings\n\nimport click\n\nfrom mkdocs import __version__, config, utils\n\nif sys.platform.startswith(\"win\"):\n    try:\n        import colorama\n    except ImportError:\n        pass\n    else:\n        colorama.init()\n\nlog = logging.getLogger(__name__)\n\n\ndef _showwarning(message, category, filename, lineno, file=None, line=None):\n    try:\n        # Last stack frames:\n        # * ...\n        # * Location of call to deprecated function   <-- include this\n        # * Location of call to warn()                <-- include this\n        # * (stdlib) Location of call to showwarning function\n        # * (this function) Location of call to extract_stack()\n        stack = [frame for frame in traceback.extract_stack() if frame.line][-4:-2]\n        # Make sure the actual affected file's name is still present (the case of syntax warning):\n        if not any(frame.filename == filename for frame in stack):\n            stack = stack[-1:] + [traceback.FrameSummary(filename, lineno, '')]\n\n        tb = ''.join(traceback.format_list(stack))\n    except Exception:\n        tb = f'  File \"{filename}\", line {lineno}'\n\n    log.info(f'{category.__name__}: {message}\\n{tb}')\n\n\ndef _enable_warnings():\n    from mkdocs.commands import build\n\n    build.log.addFilter(utils.DuplicateFilter())\n\n    warnings.simplefilter('module', DeprecationWarning)\n    warnings.showwarning = _showwarning\n\n\nclass ColorFormatter(logging.Formatter):\n    colors = {\n        'CRITICAL': 'red',\n        'ERROR': 'red',\n        'WARNING': 'yellow',\n        'DEBUG': 'blue',\n    }\n\n    text_wrapper = textwrap.TextWrapper(\n        width=shutil.get_terminal_size(fallback=(0, 0)).columns,\n        replace_whitespace=False,\n        break_long_words=False,\n        break_on_hyphens=False,\n        initial_indent=' ' * 12,\n        subsequent_indent=' ' * 12,\n    )\n\n    def format(self, record):\n        message = super().format(record)\n        prefix = f'{record.levelname:<8} -  '\n        if record.levelname in self.colors:\n            prefix = click.style(prefix, fg=self.colors[record.levelname])\n        if self.text_wrapper.width:\n            # Only wrap text if a terminal width was detected\n            msg = '\\n'.join(self.text_wrapper.fill(line) for line in message.splitlines())\n            # Prepend prefix after wrapping so that color codes don't affect length\n            return prefix + msg[12:]\n        return prefix + message\n\n\nclass State:\n    \"\"\"Maintain logging level.\"\"\"\n\n    def __init__(self, log_name='mkdocs', level=logging.INFO):\n        self.logger = logging.getLogger(log_name)\n        # Don't restrict level on logger; use handler\n        self.logger.setLevel(1)\n        self.logger.propagate = False\n\n        self.stream = logging.StreamHandler()\n        self.stream.setFormatter(ColorFormatter())\n        self.stream.setLevel(level)\n        self.stream.name = 'MkDocsStreamHandler'\n        self.logger.addHandler(self.stream)\n\n    def __del__(self):\n        self.logger.removeHandler(self.stream)\n\n\npass_state = click.make_pass_decorator(State, ensure=True)\n\nclean_help = \"Remove old files from the site_dir before building (the default).\"\nconfig_help = (\n    \"Provide a specific MkDocs config. This can be a file name, or '-' to read from stdin.\"\n)\ndev_addr_help = \"IP address and port to serve documentation locally (default: localhost:8000)\"\nstrict_help = \"Enable strict mode. This will cause MkDocs to abort the build on any warnings.\"\ntheme_help = \"The theme to use when building your documentation.\"\ntheme_choices = sorted(utils.get_theme_names())\nsite_dir_help = \"The directory to output the result of the documentation build.\"\nuse_directory_urls_help = \"Use directory URLs when building pages (the default).\"\nreload_help = \"Enable the live reloading in the development server (this is the default)\"\nno_reload_help = \"Disable the live reloading in the development server.\"\nserve_dirty_help = \"Only re-build files that have changed.\"\nserve_clean_help = (\n    \"Build the site without any effects of `mkdocs serve` - pure `mkdocs build`, then serve.\"\n)\ncommit_message_help = (\n    \"A commit message to use when committing to the \"\n    \"GitHub Pages remote branch. Commit {sha} and MkDocs {version} are available as expansions\"\n)\nremote_branch_help = (\n    \"The remote branch to commit to for GitHub Pages. This \"\n    \"overrides the value specified in config\"\n)\nremote_name_help = (\n    \"The remote name to commit to for GitHub Pages. This overrides the value specified in config\"\n)\nforce_help = \"Force the push to the repository.\"\nno_history_help = \"Replace the whole Git history with one new commit.\"\nignore_version_help = (\n    \"Ignore check that build is not being deployed with an older version of MkDocs.\"\n)\nwatch_theme_help = (\n    \"Include the theme in list of files to watch for live reloading. \"\n    \"Ignored when live reload is not used.\"\n)\nshell_help = \"Use the shell when invoking Git.\"\nwatch_help = \"A directory or file to watch for live reloading. Can be supplied multiple times.\"\nprojects_file_help = (\n    \"URL or local path of the registry file that declares all known MkDocs-related projects.\"\n)\n\n\ndef add_options(*opts):\n    def inner(f):\n        for i in reversed(opts):\n            f = i(f)\n        return f\n\n    return inner\n\n\ndef verbose_option(f):\n    def callback(ctx, param, value):\n        state = ctx.ensure_object(State)\n        if value:\n            state.stream.setLevel(logging.DEBUG)\n\n    return click.option(\n        '-v',\n        '--verbose',\n        is_flag=True,\n        expose_value=False,\n        help='Enable verbose output',\n        callback=callback,\n    )(f)\n\n\ndef quiet_option(f):\n    def callback(ctx, param, value):\n        state = ctx.ensure_object(State)\n        if value:\n            state.stream.setLevel(logging.ERROR)\n\n    return click.option(\n        '-q',\n        '--quiet',\n        is_flag=True,\n        expose_value=False,\n        help='Silence warnings',\n        callback=callback,\n    )(f)\n\n\ncommon_options = add_options(quiet_option, verbose_option)\ncommon_config_options = add_options(\n    click.option('-f', '--config-file', type=click.File('rb'), help=config_help),\n    # Don't override config value if user did not specify --strict flag\n    # Conveniently, load_config drops None values\n    click.option('-s', '--strict/--no-strict', is_flag=True, default=None, help=strict_help),\n    click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help),\n    # As with --strict, set the default to None so that this doesn't incorrectly\n    # override the config file\n    click.option(\n        '--use-directory-urls/--no-directory-urls',\n        is_flag=True,\n        default=None,\n        help=use_directory_urls_help,\n    ),\n)\n\nPYTHON_VERSION = f\"{sys.version_info.major}.{sys.version_info.minor}\"\n\nPKG_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\n@click.group(context_settings=dict(help_option_names=['-h', '--help'], max_content_width=120))\n@click.version_option(\n    __version__,\n    '-V',\n    '--version',\n    message=f'%(prog)s, version %(version)s from { PKG_DIR } (Python { PYTHON_VERSION })',\n)\n@common_options\ndef cli():\n    \"\"\"\n    MkDocs - Project documentation with Markdown.\n    \"\"\"\n\n\n@cli.command(name=\"serve\")\n@click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>')\n@click.option('--livereload', 'livereload', flag_value='livereload', default=True, hidden=True)\n@click.option('--no-livereload', 'livereload', flag_value='no-livereload', help=no_reload_help)\n@click.option('--dirtyreload', 'build_type', flag_value='dirty', hidden=True)\n@click.option('--dirty', 'build_type', flag_value='dirty', help=serve_dirty_help)\n@click.option('-c', '--clean', 'build_type', flag_value='clean', help=serve_clean_help)\n@click.option('--watch-theme', help=watch_theme_help, is_flag=True)\n@click.option(\n    '-w', '--watch', help=watch_help, type=click.Path(exists=True), multiple=True, default=[]\n)\n@common_config_options\n@common_options\ndef serve_command(**kwargs):\n    \"\"\"Run the builtin development server\"\"\"\n    from mkdocs.commands import serve\n\n    _enable_warnings()\n    serve.serve(**kwargs)\n\n\n@cli.command(name=\"build\")\n@click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)\n@common_config_options\n@click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help)\n@common_options\ndef build_command(clean, **kwargs):\n    \"\"\"Build the MkDocs documentation\"\"\"\n    from mkdocs.commands import build\n\n    _enable_warnings()\n    cfg = config.load_config(**kwargs)\n    cfg.plugins.on_startup(command='build', dirty=not clean)\n    try:\n        build.build(cfg, dirty=not clean)\n    finally:\n        cfg.plugins.on_shutdown()\n\n\n@cli.command(name=\"gh-deploy\")\n@click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)\n@click.option('-m', '--message', help=commit_message_help)\n@click.option('-b', '--remote-branch', help=remote_branch_help)\n@click.option('-r', '--remote-name', help=remote_name_help)\n@click.option('--force', is_flag=True, help=force_help)\n@click.option('--no-history', is_flag=True, help=no_history_help)\n@click.option('--ignore-version', is_flag=True, help=ignore_version_help)\n@click.option('--shell', is_flag=True, help=shell_help)\n@common_config_options\n@click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help)\n@common_options\ndef gh_deploy_command(\n    clean, message, remote_branch, remote_name, force, no_history, ignore_version, shell, **kwargs\n):\n    \"\"\"Deploy your documentation to GitHub Pages\"\"\"\n    from mkdocs.commands import build, gh_deploy\n\n    _enable_warnings()\n    cfg = config.load_config(remote_branch=remote_branch, remote_name=remote_name, **kwargs)\n    cfg.plugins.on_startup(command='gh-deploy', dirty=not clean)\n    try:\n        build.build(cfg, dirty=not clean)\n    finally:\n        cfg.plugins.on_shutdown()\n    gh_deploy.gh_deploy(\n        cfg,\n        message=message,\n        force=force,\n        no_history=no_history,\n        ignore_version=ignore_version,\n        shell=shell,\n    )\n\n\n@cli.command(name=\"get-deps\")\n@verbose_option\n@click.option('-f', '--config-file', type=click.File('rb'), help=config_help)\n@click.option(\n    '-p',\n    '--projects-file',\n    default='https://raw.githubusercontent.com/mkdocs/catalog/main/projects.yaml',\n    help=projects_file_help,\n    show_default=True,\n)\ndef get_deps_command(config_file, projects_file):\n    \"\"\"Show required PyPI packages inferred from plugins in mkdocs.yml\"\"\"\n    from mkdocs.commands import get_deps\n\n    warning_counter = utils.CountHandler()\n    warning_counter.setLevel(logging.WARNING)\n    logging.getLogger('mkdocs').addHandler(warning_counter)\n\n    get_deps.get_deps(projects_file_url=projects_file, config_file_path=config_file)\n\n    if warning_counter.get_counts():\n        sys.exit(1)\n\n\n@cli.command(name=\"new\")\n@click.argument(\"project_directory\")\n@common_options\ndef new_command(project_directory):\n    \"\"\"Create a new MkDocs project\"\"\"\n    from mkdocs.commands import new\n\n    new.new(project_directory)\n\n\nif __name__ == '__main__':  # pragma: no cover\n    cli()\n", "path": "mkdocs/__main__.py"}], "after_files": [{"content": "#!/usr/bin/env python\n\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport shutil\nimport sys\nimport textwrap\nimport traceback\nimport warnings\n\nimport click\n\nfrom mkdocs import __version__, config, utils\n\nif sys.platform.startswith(\"win\"):\n    try:\n        import colorama\n    except ImportError:\n        pass\n    else:\n        colorama.init()\n\nlog = logging.getLogger(__name__)\n\n\ndef _showwarning(message, category, filename, lineno, file=None, line=None):\n    try:\n        # Last stack frames:\n        # * ...\n        # * Location of call to deprecated function   <-- include this\n        # * Location of call to warn()                <-- include this\n        # * (stdlib) Location of call to showwarning function\n        # * (this function) Location of call to extract_stack()\n        stack = [frame for frame in traceback.extract_stack() if frame.line][-4:-2]\n        # Make sure the actual affected file's name is still present (the case of syntax warning):\n        if not any(frame.filename == filename for frame in stack):\n            stack = stack[-1:] + [traceback.FrameSummary(filename, lineno, '')]\n\n        tb = ''.join(traceback.format_list(stack))\n    except Exception:\n        tb = f'  File \"{filename}\", line {lineno}'\n\n    log.info(f'{category.__name__}: {message}\\n{tb}')\n\n\ndef _enable_warnings():\n    from mkdocs.commands import build\n\n    build.log.addFilter(utils.DuplicateFilter())\n\n    warnings.simplefilter('module', DeprecationWarning)\n    warnings.showwarning = _showwarning\n\n\nclass ColorFormatter(logging.Formatter):\n    colors = {\n        'CRITICAL': 'red',\n        'ERROR': 'red',\n        'WARNING': 'yellow',\n        'DEBUG': 'blue',\n    }\n\n    text_wrapper = textwrap.TextWrapper(\n        width=shutil.get_terminal_size(fallback=(0, 0)).columns,\n        replace_whitespace=False,\n        break_long_words=False,\n        break_on_hyphens=False,\n        initial_indent=' ' * 11,\n        subsequent_indent=' ' * 11,\n    )\n\n    def format(self, record):\n        message = super().format(record)\n        prefix = f'{record.levelname:<8}-  '\n        if record.levelname in self.colors:\n            prefix = click.style(prefix, fg=self.colors[record.levelname])\n        if self.text_wrapper.width:\n            # Only wrap text if a terminal width was detected\n            msg = '\\n'.join(self.text_wrapper.fill(line) for line in message.splitlines())\n            # Prepend prefix after wrapping so that color codes don't affect length\n            return prefix + msg[11:]\n        return prefix + message\n\n\nclass State:\n    \"\"\"Maintain logging level.\"\"\"\n\n    def __init__(self, log_name='mkdocs', level=logging.INFO):\n        self.logger = logging.getLogger(log_name)\n        # Don't restrict level on logger; use handler\n        self.logger.setLevel(1)\n        self.logger.propagate = False\n\n        self.stream = logging.StreamHandler()\n        self.stream.setFormatter(ColorFormatter())\n        self.stream.setLevel(level)\n        self.stream.name = 'MkDocsStreamHandler'\n        self.logger.addHandler(self.stream)\n\n    def __del__(self):\n        self.logger.removeHandler(self.stream)\n\n\npass_state = click.make_pass_decorator(State, ensure=True)\n\nclean_help = \"Remove old files from the site_dir before building (the default).\"\nconfig_help = (\n    \"Provide a specific MkDocs config. This can be a file name, or '-' to read from stdin.\"\n)\ndev_addr_help = \"IP address and port to serve documentation locally (default: localhost:8000)\"\nstrict_help = \"Enable strict mode. This will cause MkDocs to abort the build on any warnings.\"\ntheme_help = \"The theme to use when building your documentation.\"\ntheme_choices = sorted(utils.get_theme_names())\nsite_dir_help = \"The directory to output the result of the documentation build.\"\nuse_directory_urls_help = \"Use directory URLs when building pages (the default).\"\nreload_help = \"Enable the live reloading in the development server (this is the default)\"\nno_reload_help = \"Disable the live reloading in the development server.\"\nserve_dirty_help = \"Only re-build files that have changed.\"\nserve_clean_help = (\n    \"Build the site without any effects of `mkdocs serve` - pure `mkdocs build`, then serve.\"\n)\ncommit_message_help = (\n    \"A commit message to use when committing to the \"\n    \"GitHub Pages remote branch. Commit {sha} and MkDocs {version} are available as expansions\"\n)\nremote_branch_help = (\n    \"The remote branch to commit to for GitHub Pages. This \"\n    \"overrides the value specified in config\"\n)\nremote_name_help = (\n    \"The remote name to commit to for GitHub Pages. This overrides the value specified in config\"\n)\nforce_help = \"Force the push to the repository.\"\nno_history_help = \"Replace the whole Git history with one new commit.\"\nignore_version_help = (\n    \"Ignore check that build is not being deployed with an older version of MkDocs.\"\n)\nwatch_theme_help = (\n    \"Include the theme in list of files to watch for live reloading. \"\n    \"Ignored when live reload is not used.\"\n)\nshell_help = \"Use the shell when invoking Git.\"\nwatch_help = \"A directory or file to watch for live reloading. Can be supplied multiple times.\"\nprojects_file_help = (\n    \"URL or local path of the registry file that declares all known MkDocs-related projects.\"\n)\n\n\ndef add_options(*opts):\n    def inner(f):\n        for i in reversed(opts):\n            f = i(f)\n        return f\n\n    return inner\n\n\ndef verbose_option(f):\n    def callback(ctx, param, value):\n        state = ctx.ensure_object(State)\n        if value:\n            state.stream.setLevel(logging.DEBUG)\n\n    return click.option(\n        '-v',\n        '--verbose',\n        is_flag=True,\n        expose_value=False,\n        help='Enable verbose output',\n        callback=callback,\n    )(f)\n\n\ndef quiet_option(f):\n    def callback(ctx, param, value):\n        state = ctx.ensure_object(State)\n        if value:\n            state.stream.setLevel(logging.ERROR)\n\n    return click.option(\n        '-q',\n        '--quiet',\n        is_flag=True,\n        expose_value=False,\n        help='Silence warnings',\n        callback=callback,\n    )(f)\n\n\ndef color_option(f):\n    def callback(ctx, param, value):\n        state = ctx.ensure_object(State)\n        if value is False or (\n            value is None\n            and (\n                not sys.stdout.isatty()\n                or os.environ.get('NO_COLOR')\n                or os.environ.get('TERM') == 'dumb'\n            )\n        ):\n            state.stream.setFormatter(logging.Formatter('%(levelname)-8s-  %(message)s'))\n\n    return click.option(\n        '--color/--no-color',\n        is_flag=True,\n        default=None,\n        expose_value=False,\n        help=\"Force enable or disable color and wrapping for the output. Default is auto-detect.\",\n        callback=callback,\n    )(f)\n\n\ncommon_options = add_options(quiet_option, verbose_option)\ncommon_config_options = add_options(\n    click.option('-f', '--config-file', type=click.File('rb'), help=config_help),\n    # Don't override config value if user did not specify --strict flag\n    # Conveniently, load_config drops None values\n    click.option('-s', '--strict/--no-strict', is_flag=True, default=None, help=strict_help),\n    click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help),\n    # As with --strict, set the default to None so that this doesn't incorrectly\n    # override the config file\n    click.option(\n        '--use-directory-urls/--no-directory-urls',\n        is_flag=True,\n        default=None,\n        help=use_directory_urls_help,\n    ),\n)\n\nPYTHON_VERSION = f\"{sys.version_info.major}.{sys.version_info.minor}\"\n\nPKG_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\n@click.group(context_settings=dict(help_option_names=['-h', '--help'], max_content_width=120))\n@click.version_option(\n    __version__,\n    '-V',\n    '--version',\n    message=f'%(prog)s, version %(version)s from { PKG_DIR } (Python { PYTHON_VERSION })',\n)\n@common_options\n@color_option\ndef cli():\n    \"\"\"\n    MkDocs - Project documentation with Markdown.\n    \"\"\"\n\n\n@cli.command(name=\"serve\")\n@click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>')\n@click.option('--livereload', 'livereload', flag_value='livereload', default=True, hidden=True)\n@click.option('--no-livereload', 'livereload', flag_value='no-livereload', help=no_reload_help)\n@click.option('--dirtyreload', 'build_type', flag_value='dirty', hidden=True)\n@click.option('--dirty', 'build_type', flag_value='dirty', help=serve_dirty_help)\n@click.option('-c', '--clean', 'build_type', flag_value='clean', help=serve_clean_help)\n@click.option('--watch-theme', help=watch_theme_help, is_flag=True)\n@click.option(\n    '-w', '--watch', help=watch_help, type=click.Path(exists=True), multiple=True, default=[]\n)\n@common_config_options\n@common_options\ndef serve_command(**kwargs):\n    \"\"\"Run the builtin development server\"\"\"\n    from mkdocs.commands import serve\n\n    _enable_warnings()\n    serve.serve(**kwargs)\n\n\n@cli.command(name=\"build\")\n@click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)\n@common_config_options\n@click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help)\n@common_options\ndef build_command(clean, **kwargs):\n    \"\"\"Build the MkDocs documentation\"\"\"\n    from mkdocs.commands import build\n\n    _enable_warnings()\n    cfg = config.load_config(**kwargs)\n    cfg.plugins.on_startup(command='build', dirty=not clean)\n    try:\n        build.build(cfg, dirty=not clean)\n    finally:\n        cfg.plugins.on_shutdown()\n\n\n@cli.command(name=\"gh-deploy\")\n@click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)\n@click.option('-m', '--message', help=commit_message_help)\n@click.option('-b', '--remote-branch', help=remote_branch_help)\n@click.option('-r', '--remote-name', help=remote_name_help)\n@click.option('--force', is_flag=True, help=force_help)\n@click.option('--no-history', is_flag=True, help=no_history_help)\n@click.option('--ignore-version', is_flag=True, help=ignore_version_help)\n@click.option('--shell', is_flag=True, help=shell_help)\n@common_config_options\n@click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help)\n@common_options\ndef gh_deploy_command(\n    clean, message, remote_branch, remote_name, force, no_history, ignore_version, shell, **kwargs\n):\n    \"\"\"Deploy your documentation to GitHub Pages\"\"\"\n    from mkdocs.commands import build, gh_deploy\n\n    _enable_warnings()\n    cfg = config.load_config(remote_branch=remote_branch, remote_name=remote_name, **kwargs)\n    cfg.plugins.on_startup(command='gh-deploy', dirty=not clean)\n    try:\n        build.build(cfg, dirty=not clean)\n    finally:\n        cfg.plugins.on_shutdown()\n    gh_deploy.gh_deploy(\n        cfg,\n        message=message,\n        force=force,\n        no_history=no_history,\n        ignore_version=ignore_version,\n        shell=shell,\n    )\n\n\n@cli.command(name=\"get-deps\")\n@verbose_option\n@click.option('-f', '--config-file', type=click.File('rb'), help=config_help)\n@click.option(\n    '-p',\n    '--projects-file',\n    default='https://raw.githubusercontent.com/mkdocs/catalog/main/projects.yaml',\n    help=projects_file_help,\n    show_default=True,\n)\ndef get_deps_command(config_file, projects_file):\n    \"\"\"Show required PyPI packages inferred from plugins in mkdocs.yml\"\"\"\n    from mkdocs.commands import get_deps\n\n    warning_counter = utils.CountHandler()\n    warning_counter.setLevel(logging.WARNING)\n    logging.getLogger('mkdocs').addHandler(warning_counter)\n\n    get_deps.get_deps(projects_file_url=projects_file, config_file_path=config_file)\n\n    if warning_counter.get_counts():\n        sys.exit(1)\n\n\n@cli.command(name=\"new\")\n@click.argument(\"project_directory\")\n@common_options\ndef new_command(project_directory):\n    \"\"\"Create a new MkDocs project\"\"\"\n    from mkdocs.commands import new\n\n    new.new(project_directory)\n\n\nif __name__ == '__main__':  # pragma: no cover\n    cli()\n", "path": "mkdocs/__main__.py"}]}