We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Warn users if they are using an old/different version
pip has a nice feature where they warn users if they are using an old version and prompt them to update. I think it would be neat to add something like this. The code they use for it is here: https://github.com/pypa/pip/blob/7.0.3/pip/utils/outdated.py#L95


--- 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/commands/gh_deploy.py`
Content:
```
1 from __future__ import unicode_literals
2 import logging
3 import subprocess
4 import os
5 
6 import mkdocs
7 from mkdocs.utils import ghp_import
8 
9 log = logging.getLogger(__name__)
10 
11 default_message = """Deployed {sha} with MkDocs version: {version}"""
12 
13 
14 def _is_cwd_git_repo():
15     proc = subprocess.Popen(['git', 'rev-parse', '--is-inside-work-tree'],
16                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
17     proc.communicate()
18     return proc.wait() == 0
19 
20 
21 def _get_current_sha(repo_path):
22 
23     proc = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], cwd=repo_path,
24                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
25 
26     stdout, _ = proc.communicate()
27     sha = stdout.decode('utf-8').strip()
28     return sha
29 
30 
31 def _get_remote_url(remote_name):
32 
33     # No CNAME found.  We will use the origin URL to determine the GitHub
34     # pages location.
35     remote = "remote.%s.url" % remote_name
36     proc = subprocess.Popen(["git", "config", "--get", remote],
37                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
38 
39     stdout, _ = proc.communicate()
40     url = stdout.decode('utf-8').strip()
41 
42     host = None
43     path = None
44     if 'github.com/' in url:
45         host, path = url.split('github.com/', 1)
46     elif 'github.com:' in url:
47         host, path = url.split('github.com:', 1)
48 
49     return host, path
50 
51 
52 def gh_deploy(config, message=None, force=False):
53 
54     if not _is_cwd_git_repo():
55         log.error('Cannot deploy - this directory does not appear to be a git '
56                   'repository')
57 
58     if message is None:
59         message = default_message
60     sha = _get_current_sha(os.path.dirname(config.config_file_path))
61     message = message.format(version=mkdocs.__version__, sha=sha)
62 
63     remote_branch = config['remote_branch']
64     remote_name = config['remote_name']
65 
66     log.info("Copying '%s' to '%s' branch and pushing to GitHub.",
67              config['site_dir'], config['remote_branch'])
68 
69     result, error = ghp_import.ghp_import(config['site_dir'], message, remote_name,
70                                           remote_branch, force)
71     if not result:
72         log.error("Failed to deploy to GitHub with error: \n%s", error)
73         raise SystemExit(1)
74     else:
75         cname_file = os.path.join(config['site_dir'], 'CNAME')
76         # Does this repository have a CNAME set for GitHub pages?
77         if os.path.isfile(cname_file):
78             # This GitHub pages repository has a CNAME configured.
79             with(open(cname_file, 'r')) as f:
80                 cname_host = f.read().strip()
81             log.info('Based on your CNAME file, your documentation should be '
82                      'available shortly at: http://%s', cname_host)
83             log.info('NOTE: Your DNS records must be configured appropriately for '
84                      'your CNAME URL to work.')
85             return
86 
87         host, path = _get_remote_url(remote_name)
88 
89         if host is None:
90             # This could be a GitHub Enterprise deployment.
91             log.info('Your documentation should be available shortly.')
92         else:
93             username, repo = path.split('/', 1)
94             if repo.endswith('.git'):
95                 repo = repo[:-len('.git')]
96             url = 'https://%s.github.io/%s/' % (username, repo)
97             log.info('Your documentation should shortly be available at: ' + url)
98
```

Path: `mkdocs/__main__.py`
Content:
```
1 #!/usr/bin/env python
2 # coding: utf-8
3 
4 from __future__ import unicode_literals
5 import os
6 import sys
7 import logging
8 import click
9 import socket
10 
11 from mkdocs import __version__
12 from mkdocs import utils
13 from mkdocs import exceptions
14 from mkdocs import config
15 from mkdocs.commands import build, gh_deploy, new, serve
16 
17 log = logging.getLogger(__name__)
18 
19 # Disable the warning that Click displays (as of Click version 5.0) when users
20 # use unicode_literals in Python 2.
21 # See http://click.pocoo.org/dev/python3/#unicode-literals for more details.
22 click.disable_unicode_literals_warning = True
23 
24 
25 class State(object):
26     ''' Maintain logging level.'''
27 
28     def __init__(self, log_name='mkdocs', level=logging.INFO):
29         self.logger = logging.getLogger(log_name)
30         self.logger.propagate = False
31         stream = logging.StreamHandler()
32         formatter = logging.Formatter("%(levelname)-7s -  %(message)s ")
33         stream.setFormatter(formatter)
34         self.logger.addHandler(stream)
35 
36         self.logger.setLevel(level)
37 
38 
39 pass_state = click.make_pass_decorator(State, ensure=True)
40 
41 
42 def verbose_option(f):
43     def callback(ctx, param, value):
44         state = ctx.ensure_object(State)
45         if value:
46             state.logger.setLevel(logging.DEBUG)
47     return click.option('-v', '--verbose',
48                         is_flag=True,
49                         expose_value=False,
50                         help='Enable verbose output',
51                         callback=callback)(f)
52 
53 
54 def quiet_option(f):
55     def callback(ctx, param, value):
56         state = ctx.ensure_object(State)
57         if value:
58             state.logger.setLevel(logging.ERROR)
59     return click.option('-q', '--quiet',
60                         is_flag=True,
61                         expose_value=False,
62                         help='Silence warnings',
63                         callback=callback)(f)
64 
65 
66 def common_options(f):
67     f = verbose_option(f)
68     f = quiet_option(f)
69     return f
70 
71 
72 clean_help = "Remove old files from the site_dir before building (the default)."
73 config_help = "Provide a specific MkDocs config"
74 dev_addr_help = ("IP address and port to serve documentation locally (default: "
75                  "localhost:8000)")
76 strict_help = ("Enable strict mode. This will cause MkDocs to abort the build "
77                "on any warnings.")
78 theme_dir_help = "The theme directory to use when building your documentation."
79 theme_help = "The theme to use when building your documentation."
80 theme_choices = utils.get_theme_names()
81 site_dir_help = "The directory to output the result of the documentation build."
82 reload_help = "Enable the live reloading in the development server (this is the default)"
83 no_reload_help = "Disable the live reloading in the development server."
84 dirty_reload_help = "Enable the live reloading in the development server, but only re-build files that have changed"
85 commit_message_help = ("A commit message to use when committing to the "
86                        "Github Pages remote branch. Commit {sha} and MkDocs {version} are available as expansions")
87 remote_branch_help = ("The remote branch to commit to for Github Pages. This "
88                       "overrides the value specified in config")
89 remote_name_help = ("The remote name to commit to for Github Pages. This "
90                     "overrides the value specified in config")
91 force_help = "Force the push to the repository."
92 
93 pgk_dir = os.path.dirname(os.path.abspath(__file__))
94 
95 
96 @click.group(context_settings={'help_option_names': ['-h', '--help']})
97 @click.version_option(
98     '{0} from {1} (Python {2})'.format(__version__, pgk_dir, sys.version[:3]),
99     '-V', '--version')
100 @common_options
101 def cli():
102     """
103     MkDocs - Project documentation with Markdown.
104     """
105 
106 
107 @cli.command(name="serve")
108 @click.option('-f', '--config-file', type=click.File('rb'), help=config_help)
109 @click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>')
110 @click.option('-s', '--strict', is_flag=True, help=strict_help)
111 @click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help)
112 @click.option('-e', '--theme-dir', type=click.Path(), help=theme_dir_help)
113 @click.option('--livereload', 'livereload', flag_value='livereload', help=reload_help, default=True)
114 @click.option('--no-livereload', 'livereload', flag_value='no-livereload', help=no_reload_help)
115 @click.option('--dirtyreload', 'livereload', flag_value='dirty', help=dirty_reload_help)
116 @common_options
117 def serve_command(dev_addr, config_file, strict, theme, theme_dir, livereload):
118     """Run the builtin development server"""
119 
120     logging.getLogger('tornado').setLevel(logging.WARNING)
121 
122     # Don't override config value if user did not specify --strict flag
123     # Conveniently, load_config drops None values
124     strict = strict or None
125 
126     try:
127         serve.serve(
128             config_file=config_file,
129             dev_addr=dev_addr,
130             strict=strict,
131             theme=theme,
132             theme_dir=theme_dir,
133             livereload=livereload
134         )
135     except (exceptions.ConfigurationError, socket.error) as e:  # pragma: no cover
136         # Avoid ugly, unhelpful traceback
137         raise SystemExit('\n' + str(e))
138 
139 
140 @cli.command(name="build")
141 @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)
142 @click.option('-f', '--config-file', type=click.File('rb'), help=config_help)
143 @click.option('-s', '--strict', is_flag=True, help=strict_help)
144 @click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help)
145 @click.option('-e', '--theme-dir', type=click.Path(), help=theme_dir_help)
146 @click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help)
147 @common_options
148 def build_command(clean, config_file, strict, theme, theme_dir, site_dir):
149     """Build the MkDocs documentation"""
150 
151     # Don't override config value if user did not specify --strict flag
152     # Conveniently, load_config drops None values
153     strict = strict or None
154 
155     try:
156         build.build(config.load_config(
157             config_file=config_file,
158             strict=strict,
159             theme=theme,
160             theme_dir=theme_dir,
161             site_dir=site_dir
162         ), dirty=not clean)
163     except exceptions.ConfigurationError as e:  # pragma: no cover
164         # Avoid ugly, unhelpful traceback
165         raise SystemExit('\n' + str(e))
166 
167 
168 @cli.command(name="gh-deploy")
169 @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)
170 @click.option('-f', '--config-file', type=click.File('rb'), help=config_help)
171 @click.option('-m', '--message', help=commit_message_help)
172 @click.option('-b', '--remote-branch', help=remote_branch_help)
173 @click.option('-r', '--remote-name', help=remote_name_help)
174 @click.option('--force', is_flag=True, help=force_help)
175 @common_options
176 def gh_deploy_command(config_file, clean, message, remote_branch, remote_name, force):
177     """Deploy your documentation to GitHub Pages"""
178     try:
179         cfg = config.load_config(
180             config_file=config_file,
181             remote_branch=remote_branch,
182             remote_name=remote_name
183         )
184         build.build(cfg, dirty=not clean)
185         gh_deploy.gh_deploy(cfg, message=message, force=force)
186     except exceptions.ConfigurationError as e:  # pragma: no cover
187         # Avoid ugly, unhelpful traceback
188         raise SystemExit('\n' + str(e))
189 
190 
191 @cli.command(name="new")
192 @click.argument("project_directory")
193 @common_options
194 def new_command(project_directory):
195     """Create a new MkDocs project"""
196     new.new(project_directory)
197 
198 
199 if __name__ == '__main__':  # pragma: no cover
200     cli()
201
```
--- 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
@@ -89,6 +89,7 @@
 remote_name_help = ("The remote name to commit to for Github Pages. This "
                     "overrides the value specified in config")
 force_help = "Force the push to the repository."
+ignore_version_help = "Ignore check that build is not being deployed with an older version of MkDocs."
 
 pgk_dir = os.path.dirname(os.path.abspath(__file__))
 
@@ -172,8 +173,9 @@
 @click.option('-b', '--remote-branch', help=remote_branch_help)
 @click.option('-r', '--remote-name', help=remote_name_help)
 @click.option('--force', is_flag=True, help=force_help)
+@click.option('--ignore-version', is_flag=True, help=ignore_version_help)
 @common_options
-def gh_deploy_command(config_file, clean, message, remote_branch, remote_name, force):
+def gh_deploy_command(config_file, clean, message, remote_branch, remote_name, force, ignore_version):
     """Deploy your documentation to GitHub Pages"""
     try:
         cfg = config.load_config(
@@ -182,7 +184,7 @@
             remote_name=remote_name
         )
         build.build(cfg, dirty=not clean)
-        gh_deploy.gh_deploy(cfg, message=message, force=force)
+        gh_deploy.gh_deploy(cfg, message=message, force=force, ignore_version=ignore_version)
     except exceptions.ConfigurationError as e:  # pragma: no cover
         # Avoid ugly, unhelpful traceback
         raise SystemExit('\n' + str(e))
diff --git a/mkdocs/commands/gh_deploy.py b/mkdocs/commands/gh_deploy.py
--- a/mkdocs/commands/gh_deploy.py
+++ b/mkdocs/commands/gh_deploy.py
@@ -2,6 +2,8 @@
 import logging
 import subprocess
 import os
+import re
+from pkg_resources import parse_version
 
 import mkdocs
 from mkdocs.utils import ghp_import
@@ -49,20 +51,49 @@
     return host, path
 
 
-def gh_deploy(config, message=None, force=False):
+def _check_version(branch):
+
+    proc = subprocess.Popen(['git', 'show', '-s', '--format=%s', 'refs/heads/{}'.format(branch)],
+                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+
+    stdout, _ = proc.communicate()
+    msg = stdout.decode('utf-8').strip()
+    m = re.search(r'\d+(\.\d+)+', msg, re.X | re.I)
+    previousv = parse_version(m.group()) if m else None
+    currentv = parse_version(mkdocs.__version__)
+    if not previousv:
+        log.warn('Version check skipped: No version specificed in previous deployment.')
+    elif currentv > previousv:
+        log.info(
+            'Previous deployment was done with MkDocs version {}; '
+            'you are deploying with a newer version ({})'.format(previousv, currentv)
+        )
+    elif currentv < previousv:
+        log.error(
+            'Deployment terminated: Previous deployment was made with MkDocs version {}; '
+            'you are attempting to deploy with an older version ({}). Use --ignore-version '
+            'to deploy anyway.'.format(previousv, currentv)
+        )
+        raise SystemExit(1)
+
+
+def gh_deploy(config, message=None, force=False, ignore_version=False):
 
     if not _is_cwd_git_repo():
         log.error('Cannot deploy - this directory does not appear to be a git '
                   'repository')
 
+    remote_branch = config['remote_branch']
+    remote_name = config['remote_name']
+
+    if not ignore_version:
+        _check_version(remote_branch)
+
     if message is None:
         message = default_message
     sha = _get_current_sha(os.path.dirname(config.config_file_path))
     message = message.format(version=mkdocs.__version__, sha=sha)
 
-    remote_branch = config['remote_branch']
-    remote_name = config['remote_name']
-
     log.info("Copying '%s' to '%s' branch and pushing to GitHub.",
              config['site_dir'], config['remote_branch'])

{"golden_diff": "diff --git a/mkdocs/__main__.py b/mkdocs/__main__.py\n--- a/mkdocs/__main__.py\n+++ b/mkdocs/__main__.py\n@@ -89,6 +89,7 @@\n remote_name_help = (\"The remote name to commit to for Github Pages. This \"\n                     \"overrides the value specified in config\")\n force_help = \"Force the push to the repository.\"\n+ignore_version_help = \"Ignore check that build is not being deployed with an older version of MkDocs.\"\n \n pgk_dir = os.path.dirname(os.path.abspath(__file__))\n \n@@ -172,8 +173,9 @@\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('--ignore-version', is_flag=True, help=ignore_version_help)\n @common_options\n-def gh_deploy_command(config_file, clean, message, remote_branch, remote_name, force):\n+def gh_deploy_command(config_file, clean, message, remote_branch, remote_name, force, ignore_version):\n     \"\"\"Deploy your documentation to GitHub Pages\"\"\"\n     try:\n         cfg = config.load_config(\n@@ -182,7 +184,7 @@\n             remote_name=remote_name\n         )\n         build.build(cfg, dirty=not clean)\n-        gh_deploy.gh_deploy(cfg, message=message, force=force)\n+        gh_deploy.gh_deploy(cfg, message=message, force=force, ignore_version=ignore_version)\n     except exceptions.ConfigurationError as e:  # pragma: no cover\n         # Avoid ugly, unhelpful traceback\n         raise SystemExit('\\n' + str(e))\ndiff --git a/mkdocs/commands/gh_deploy.py b/mkdocs/commands/gh_deploy.py\n--- a/mkdocs/commands/gh_deploy.py\n+++ b/mkdocs/commands/gh_deploy.py\n@@ -2,6 +2,8 @@\n import logging\n import subprocess\n import os\n+import re\n+from pkg_resources import parse_version\n \n import mkdocs\n from mkdocs.utils import ghp_import\n@@ -49,20 +51,49 @@\n     return host, path\n \n \n-def gh_deploy(config, message=None, force=False):\n+def _check_version(branch):\n+\n+    proc = subprocess.Popen(['git', 'show', '-s', '--format=%s', 'refs/heads/{}'.format(branch)],\n+                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n+\n+    stdout, _ = proc.communicate()\n+    msg = stdout.decode('utf-8').strip()\n+    m = re.search(r'\\d+(\\.\\d+)+', msg, re.X | re.I)\n+    previousv = parse_version(m.group()) if m else None\n+    currentv = parse_version(mkdocs.__version__)\n+    if not previousv:\n+        log.warn('Version check skipped: No version specificed in previous deployment.')\n+    elif currentv > previousv:\n+        log.info(\n+            'Previous deployment was done with MkDocs version {}; '\n+            'you are deploying with a newer version ({})'.format(previousv, currentv)\n+        )\n+    elif currentv < previousv:\n+        log.error(\n+            'Deployment terminated: Previous deployment was made with MkDocs version {}; '\n+            'you are attempting to deploy with an older version ({}). Use --ignore-version '\n+            'to deploy anyway.'.format(previousv, currentv)\n+        )\n+        raise SystemExit(1)\n+\n+\n+def gh_deploy(config, message=None, force=False, ignore_version=False):\n \n     if not _is_cwd_git_repo():\n         log.error('Cannot deploy - this directory does not appear to be a git '\n                   'repository')\n \n+    remote_branch = config['remote_branch']\n+    remote_name = config['remote_name']\n+\n+    if not ignore_version:\n+        _check_version(remote_branch)\n+\n     if message is None:\n         message = default_message\n     sha = _get_current_sha(os.path.dirname(config.config_file_path))\n     message = message.format(version=mkdocs.__version__, sha=sha)\n \n-    remote_branch = config['remote_branch']\n-    remote_name = config['remote_name']\n-\n     log.info(\"Copying '%s' to '%s' branch and pushing to GitHub.\",\n              config['site_dir'], config['remote_branch'])\n", "issue": "Warn users if they are using an old/different version\npip has a nice feature where they warn users if they are using an old version and prompt them to update. I think it would be neat to add something like this. The code they use for it is here: https://github.com/pypa/pip/blob/7.0.3/pip/utils/outdated.py#L95\n\n", "before_files": [{"content": "from __future__ import unicode_literals\nimport logging\nimport subprocess\nimport os\n\nimport mkdocs\nfrom mkdocs.utils import ghp_import\n\nlog = logging.getLogger(__name__)\n\ndefault_message = \"\"\"Deployed {sha} with MkDocs version: {version}\"\"\"\n\n\ndef _is_cwd_git_repo():\n    proc = subprocess.Popen(['git', 'rev-parse', '--is-inside-work-tree'],\n                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    proc.communicate()\n    return proc.wait() == 0\n\n\ndef _get_current_sha(repo_path):\n\n    proc = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], cwd=repo_path,\n                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n    stdout, _ = proc.communicate()\n    sha = stdout.decode('utf-8').strip()\n    return sha\n\n\ndef _get_remote_url(remote_name):\n\n    # No CNAME found.  We will use the origin URL to determine the GitHub\n    # pages location.\n    remote = \"remote.%s.url\" % remote_name\n    proc = subprocess.Popen([\"git\", \"config\", \"--get\", remote],\n                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n    stdout, _ = proc.communicate()\n    url = stdout.decode('utf-8').strip()\n\n    host = None\n    path = None\n    if 'github.com/' in url:\n        host, path = url.split('github.com/', 1)\n    elif 'github.com:' in url:\n        host, path = url.split('github.com:', 1)\n\n    return host, path\n\n\ndef gh_deploy(config, message=None, force=False):\n\n    if not _is_cwd_git_repo():\n        log.error('Cannot deploy - this directory does not appear to be a git '\n                  'repository')\n\n    if message is None:\n        message = default_message\n    sha = _get_current_sha(os.path.dirname(config.config_file_path))\n    message = message.format(version=mkdocs.__version__, sha=sha)\n\n    remote_branch = config['remote_branch']\n    remote_name = config['remote_name']\n\n    log.info(\"Copying '%s' to '%s' branch and pushing to GitHub.\",\n             config['site_dir'], config['remote_branch'])\n\n    result, error = ghp_import.ghp_import(config['site_dir'], message, remote_name,\n                                          remote_branch, force)\n    if not result:\n        log.error(\"Failed to deploy to GitHub with error: \\n%s\", error)\n        raise SystemExit(1)\n    else:\n        cname_file = os.path.join(config['site_dir'], 'CNAME')\n        # Does this repository have a CNAME set for GitHub pages?\n        if os.path.isfile(cname_file):\n            # This GitHub pages repository has a CNAME configured.\n            with(open(cname_file, 'r')) as f:\n                cname_host = f.read().strip()\n            log.info('Based on your CNAME file, your documentation should be '\n                     'available shortly at: http://%s', cname_host)\n            log.info('NOTE: Your DNS records must be configured appropriately for '\n                     'your CNAME URL to work.')\n            return\n\n        host, path = _get_remote_url(remote_name)\n\n        if host is None:\n            # This could be a GitHub Enterprise deployment.\n            log.info('Your documentation should be available shortly.')\n        else:\n            username, repo = path.split('/', 1)\n            if repo.endswith('.git'):\n                repo = repo[:-len('.git')]\n            url = 'https://%s.github.io/%s/' % (username, repo)\n            log.info('Your documentation should shortly be available at: ' + url)\n", "path": "mkdocs/commands/gh_deploy.py"}, {"content": "#!/usr/bin/env python\n# coding: utf-8\n\nfrom __future__ import unicode_literals\nimport os\nimport sys\nimport logging\nimport click\nimport socket\n\nfrom mkdocs import __version__\nfrom mkdocs import utils\nfrom mkdocs import exceptions\nfrom mkdocs import config\nfrom mkdocs.commands import build, gh_deploy, new, serve\n\nlog = logging.getLogger(__name__)\n\n# Disable the warning that Click displays (as of Click version 5.0) when users\n# use unicode_literals in Python 2.\n# See http://click.pocoo.org/dev/python3/#unicode-literals for more details.\nclick.disable_unicode_literals_warning = True\n\n\nclass State(object):\n    ''' Maintain logging level.'''\n\n    def __init__(self, log_name='mkdocs', level=logging.INFO):\n        self.logger = logging.getLogger(log_name)\n        self.logger.propagate = False\n        stream = logging.StreamHandler()\n        formatter = logging.Formatter(\"%(levelname)-7s -  %(message)s \")\n        stream.setFormatter(formatter)\n        self.logger.addHandler(stream)\n\n        self.logger.setLevel(level)\n\n\npass_state = click.make_pass_decorator(State, ensure=True)\n\n\ndef verbose_option(f):\n    def callback(ctx, param, value):\n        state = ctx.ensure_object(State)\n        if value:\n            state.logger.setLevel(logging.DEBUG)\n    return click.option('-v', '--verbose',\n                        is_flag=True,\n                        expose_value=False,\n                        help='Enable verbose output',\n                        callback=callback)(f)\n\n\ndef quiet_option(f):\n    def callback(ctx, param, value):\n        state = ctx.ensure_object(State)\n        if value:\n            state.logger.setLevel(logging.ERROR)\n    return click.option('-q', '--quiet',\n                        is_flag=True,\n                        expose_value=False,\n                        help='Silence warnings',\n                        callback=callback)(f)\n\n\ndef common_options(f):\n    f = verbose_option(f)\n    f = quiet_option(f)\n    return f\n\n\nclean_help = \"Remove old files from the site_dir before building (the default).\"\nconfig_help = \"Provide a specific MkDocs config\"\ndev_addr_help = (\"IP address and port to serve documentation locally (default: \"\n                 \"localhost:8000)\")\nstrict_help = (\"Enable strict mode. This will cause MkDocs to abort the build \"\n               \"on any warnings.\")\ntheme_dir_help = \"The theme directory to use when building your documentation.\"\ntheme_help = \"The theme to use when building your documentation.\"\ntheme_choices = utils.get_theme_names()\nsite_dir_help = \"The directory to output the result of the documentation build.\"\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.\"\ndirty_reload_help = \"Enable the live reloading in the development server, but only re-build files that have changed\"\ncommit_message_help = (\"A commit message to use when committing to the \"\n                       \"Github Pages remote branch. Commit {sha} and MkDocs {version} are available as expansions\")\nremote_branch_help = (\"The remote branch to commit to for Github Pages. This \"\n                      \"overrides the value specified in config\")\nremote_name_help = (\"The remote name to commit to for Github Pages. This \"\n                    \"overrides the value specified in config\")\nforce_help = \"Force the push to the repository.\"\n\npgk_dir = os.path.dirname(os.path.abspath(__file__))\n\n\n@click.group(context_settings={'help_option_names': ['-h', '--help']})\n@click.version_option(\n    '{0} from {1} (Python {2})'.format(__version__, pgk_dir, sys.version[:3]),\n    '-V', '--version')\n@common_options\ndef cli():\n    \"\"\"\n    MkDocs - Project documentation with Markdown.\n    \"\"\"\n\n\n@cli.command(name=\"serve\")\n@click.option('-f', '--config-file', type=click.File('rb'), help=config_help)\n@click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>')\n@click.option('-s', '--strict', is_flag=True, help=strict_help)\n@click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help)\n@click.option('-e', '--theme-dir', type=click.Path(), help=theme_dir_help)\n@click.option('--livereload', 'livereload', flag_value='livereload', help=reload_help, default=True)\n@click.option('--no-livereload', 'livereload', flag_value='no-livereload', help=no_reload_help)\n@click.option('--dirtyreload', 'livereload', flag_value='dirty', help=dirty_reload_help)\n@common_options\ndef serve_command(dev_addr, config_file, strict, theme, theme_dir, livereload):\n    \"\"\"Run the builtin development server\"\"\"\n\n    logging.getLogger('tornado').setLevel(logging.WARNING)\n\n    # Don't override config value if user did not specify --strict flag\n    # Conveniently, load_config drops None values\n    strict = strict or None\n\n    try:\n        serve.serve(\n            config_file=config_file,\n            dev_addr=dev_addr,\n            strict=strict,\n            theme=theme,\n            theme_dir=theme_dir,\n            livereload=livereload\n        )\n    except (exceptions.ConfigurationError, socket.error) as e:  # pragma: no cover\n        # Avoid ugly, unhelpful traceback\n        raise SystemExit('\\n' + str(e))\n\n\n@cli.command(name=\"build\")\n@click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)\n@click.option('-f', '--config-file', type=click.File('rb'), help=config_help)\n@click.option('-s', '--strict', is_flag=True, help=strict_help)\n@click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help)\n@click.option('-e', '--theme-dir', type=click.Path(), help=theme_dir_help)\n@click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help)\n@common_options\ndef build_command(clean, config_file, strict, theme, theme_dir, site_dir):\n    \"\"\"Build the MkDocs documentation\"\"\"\n\n    # Don't override config value if user did not specify --strict flag\n    # Conveniently, load_config drops None values\n    strict = strict or None\n\n    try:\n        build.build(config.load_config(\n            config_file=config_file,\n            strict=strict,\n            theme=theme,\n            theme_dir=theme_dir,\n            site_dir=site_dir\n        ), dirty=not clean)\n    except exceptions.ConfigurationError as e:  # pragma: no cover\n        # Avoid ugly, unhelpful traceback\n        raise SystemExit('\\n' + str(e))\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('-f', '--config-file', type=click.File('rb'), help=config_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@common_options\ndef gh_deploy_command(config_file, clean, message, remote_branch, remote_name, force):\n    \"\"\"Deploy your documentation to GitHub Pages\"\"\"\n    try:\n        cfg = config.load_config(\n            config_file=config_file,\n            remote_branch=remote_branch,\n            remote_name=remote_name\n        )\n        build.build(cfg, dirty=not clean)\n        gh_deploy.gh_deploy(cfg, message=message, force=force)\n    except exceptions.ConfigurationError as e:  # pragma: no cover\n        # Avoid ugly, unhelpful traceback\n        raise SystemExit('\\n' + str(e))\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    new.new(project_directory)\n\n\nif __name__ == '__main__':  # pragma: no cover\n    cli()\n", "path": "mkdocs/__main__.py"}], "after_files": [{"content": "from __future__ import unicode_literals\nimport logging\nimport subprocess\nimport os\nimport re\nfrom pkg_resources import parse_version\n\nimport mkdocs\nfrom mkdocs.utils import ghp_import\n\nlog = logging.getLogger(__name__)\n\ndefault_message = \"\"\"Deployed {sha} with MkDocs version: {version}\"\"\"\n\n\ndef _is_cwd_git_repo():\n    proc = subprocess.Popen(['git', 'rev-parse', '--is-inside-work-tree'],\n                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    proc.communicate()\n    return proc.wait() == 0\n\n\ndef _get_current_sha(repo_path):\n\n    proc = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], cwd=repo_path,\n                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n    stdout, _ = proc.communicate()\n    sha = stdout.decode('utf-8').strip()\n    return sha\n\n\ndef _get_remote_url(remote_name):\n\n    # No CNAME found.  We will use the origin URL to determine the GitHub\n    # pages location.\n    remote = \"remote.%s.url\" % remote_name\n    proc = subprocess.Popen([\"git\", \"config\", \"--get\", remote],\n                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n    stdout, _ = proc.communicate()\n    url = stdout.decode('utf-8').strip()\n\n    host = None\n    path = None\n    if 'github.com/' in url:\n        host, path = url.split('github.com/', 1)\n    elif 'github.com:' in url:\n        host, path = url.split('github.com:', 1)\n\n    return host, path\n\n\ndef _check_version(branch):\n\n    proc = subprocess.Popen(['git', 'show', '-s', '--format=%s', 'refs/heads/{}'.format(branch)],\n                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n    stdout, _ = proc.communicate()\n    msg = stdout.decode('utf-8').strip()\n    m = re.search(r'\\d+(\\.\\d+)+', msg, re.X | re.I)\n    previousv = parse_version(m.group()) if m else None\n    currentv = parse_version(mkdocs.__version__)\n    if not previousv:\n        log.warn('Version check skipped: No version specificed in previous deployment.')\n    elif currentv > previousv:\n        log.info(\n            'Previous deployment was done with MkDocs version {}; '\n            'you are deploying with a newer version ({})'.format(previousv, currentv)\n        )\n    elif currentv < previousv:\n        log.error(\n            'Deployment terminated: Previous deployment was made with MkDocs version {}; '\n            'you are attempting to deploy with an older version ({}). Use --ignore-version '\n            'to deploy anyway.'.format(previousv, currentv)\n        )\n        raise SystemExit(1)\n\n\ndef gh_deploy(config, message=None, force=False, ignore_version=False):\n\n    if not _is_cwd_git_repo():\n        log.error('Cannot deploy - this directory does not appear to be a git '\n                  'repository')\n\n    remote_branch = config['remote_branch']\n    remote_name = config['remote_name']\n\n    if not ignore_version:\n        _check_version(remote_branch)\n\n    if message is None:\n        message = default_message\n    sha = _get_current_sha(os.path.dirname(config.config_file_path))\n    message = message.format(version=mkdocs.__version__, sha=sha)\n\n    log.info(\"Copying '%s' to '%s' branch and pushing to GitHub.\",\n             config['site_dir'], config['remote_branch'])\n\n    result, error = ghp_import.ghp_import(config['site_dir'], message, remote_name,\n                                          remote_branch, force)\n    if not result:\n        log.error(\"Failed to deploy to GitHub with error: \\n%s\", error)\n        raise SystemExit(1)\n    else:\n        cname_file = os.path.join(config['site_dir'], 'CNAME')\n        # Does this repository have a CNAME set for GitHub pages?\n        if os.path.isfile(cname_file):\n            # This GitHub pages repository has a CNAME configured.\n            with(open(cname_file, 'r')) as f:\n                cname_host = f.read().strip()\n            log.info('Based on your CNAME file, your documentation should be '\n                     'available shortly at: http://%s', cname_host)\n            log.info('NOTE: Your DNS records must be configured appropriately for '\n                     'your CNAME URL to work.')\n            return\n\n        host, path = _get_remote_url(remote_name)\n\n        if host is None:\n            # This could be a GitHub Enterprise deployment.\n            log.info('Your documentation should be available shortly.')\n        else:\n            username, repo = path.split('/', 1)\n            if repo.endswith('.git'):\n                repo = repo[:-len('.git')]\n            url = 'https://%s.github.io/%s/' % (username, repo)\n            log.info('Your documentation should shortly be available at: ' + url)\n", "path": "mkdocs/commands/gh_deploy.py"}, {"content": "#!/usr/bin/env python\n# coding: utf-8\n\nfrom __future__ import unicode_literals\nimport os\nimport sys\nimport logging\nimport click\nimport socket\n\nfrom mkdocs import __version__\nfrom mkdocs import utils\nfrom mkdocs import exceptions\nfrom mkdocs import config\nfrom mkdocs.commands import build, gh_deploy, new, serve\n\nlog = logging.getLogger(__name__)\n\n# Disable the warning that Click displays (as of Click version 5.0) when users\n# use unicode_literals in Python 2.\n# See http://click.pocoo.org/dev/python3/#unicode-literals for more details.\nclick.disable_unicode_literals_warning = True\n\n\nclass State(object):\n    ''' Maintain logging level.'''\n\n    def __init__(self, log_name='mkdocs', level=logging.INFO):\n        self.logger = logging.getLogger(log_name)\n        self.logger.propagate = False\n        stream = logging.StreamHandler()\n        formatter = logging.Formatter(\"%(levelname)-7s -  %(message)s \")\n        stream.setFormatter(formatter)\n        self.logger.addHandler(stream)\n\n        self.logger.setLevel(level)\n\n\npass_state = click.make_pass_decorator(State, ensure=True)\n\n\ndef verbose_option(f):\n    def callback(ctx, param, value):\n        state = ctx.ensure_object(State)\n        if value:\n            state.logger.setLevel(logging.DEBUG)\n    return click.option('-v', '--verbose',\n                        is_flag=True,\n                        expose_value=False,\n                        help='Enable verbose output',\n                        callback=callback)(f)\n\n\ndef quiet_option(f):\n    def callback(ctx, param, value):\n        state = ctx.ensure_object(State)\n        if value:\n            state.logger.setLevel(logging.ERROR)\n    return click.option('-q', '--quiet',\n                        is_flag=True,\n                        expose_value=False,\n                        help='Silence warnings',\n                        callback=callback)(f)\n\n\ndef common_options(f):\n    f = verbose_option(f)\n    f = quiet_option(f)\n    return f\n\n\nclean_help = \"Remove old files from the site_dir before building (the default).\"\nconfig_help = \"Provide a specific MkDocs config\"\ndev_addr_help = (\"IP address and port to serve documentation locally (default: \"\n                 \"localhost:8000)\")\nstrict_help = (\"Enable strict mode. This will cause MkDocs to abort the build \"\n               \"on any warnings.\")\ntheme_dir_help = \"The theme directory to use when building your documentation.\"\ntheme_help = \"The theme to use when building your documentation.\"\ntheme_choices = utils.get_theme_names()\nsite_dir_help = \"The directory to output the result of the documentation build.\"\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.\"\ndirty_reload_help = \"Enable the live reloading in the development server, but only re-build files that have changed\"\ncommit_message_help = (\"A commit message to use when committing to the \"\n                       \"Github Pages remote branch. Commit {sha} and MkDocs {version} are available as expansions\")\nremote_branch_help = (\"The remote branch to commit to for Github Pages. This \"\n                      \"overrides the value specified in config\")\nremote_name_help = (\"The remote name to commit to for Github Pages. This \"\n                    \"overrides the value specified in config\")\nforce_help = \"Force the push to the repository.\"\nignore_version_help = \"Ignore check that build is not being deployed with an older version of MkDocs.\"\n\npgk_dir = os.path.dirname(os.path.abspath(__file__))\n\n\n@click.group(context_settings={'help_option_names': ['-h', '--help']})\n@click.version_option(\n    '{0} from {1} (Python {2})'.format(__version__, pgk_dir, sys.version[:3]),\n    '-V', '--version')\n@common_options\ndef cli():\n    \"\"\"\n    MkDocs - Project documentation with Markdown.\n    \"\"\"\n\n\n@cli.command(name=\"serve\")\n@click.option('-f', '--config-file', type=click.File('rb'), help=config_help)\n@click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>')\n@click.option('-s', '--strict', is_flag=True, help=strict_help)\n@click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help)\n@click.option('-e', '--theme-dir', type=click.Path(), help=theme_dir_help)\n@click.option('--livereload', 'livereload', flag_value='livereload', help=reload_help, default=True)\n@click.option('--no-livereload', 'livereload', flag_value='no-livereload', help=no_reload_help)\n@click.option('--dirtyreload', 'livereload', flag_value='dirty', help=dirty_reload_help)\n@common_options\ndef serve_command(dev_addr, config_file, strict, theme, theme_dir, livereload):\n    \"\"\"Run the builtin development server\"\"\"\n\n    logging.getLogger('tornado').setLevel(logging.WARNING)\n\n    # Don't override config value if user did not specify --strict flag\n    # Conveniently, load_config drops None values\n    strict = strict or None\n\n    try:\n        serve.serve(\n            config_file=config_file,\n            dev_addr=dev_addr,\n            strict=strict,\n            theme=theme,\n            theme_dir=theme_dir,\n            livereload=livereload\n        )\n    except (exceptions.ConfigurationError, socket.error) as e:  # pragma: no cover\n        # Avoid ugly, unhelpful traceback\n        raise SystemExit('\\n' + str(e))\n\n\n@cli.command(name=\"build\")\n@click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)\n@click.option('-f', '--config-file', type=click.File('rb'), help=config_help)\n@click.option('-s', '--strict', is_flag=True, help=strict_help)\n@click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help)\n@click.option('-e', '--theme-dir', type=click.Path(), help=theme_dir_help)\n@click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help)\n@common_options\ndef build_command(clean, config_file, strict, theme, theme_dir, site_dir):\n    \"\"\"Build the MkDocs documentation\"\"\"\n\n    # Don't override config value if user did not specify --strict flag\n    # Conveniently, load_config drops None values\n    strict = strict or None\n\n    try:\n        build.build(config.load_config(\n            config_file=config_file,\n            strict=strict,\n            theme=theme,\n            theme_dir=theme_dir,\n            site_dir=site_dir\n        ), dirty=not clean)\n    except exceptions.ConfigurationError as e:  # pragma: no cover\n        # Avoid ugly, unhelpful traceback\n        raise SystemExit('\\n' + str(e))\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('-f', '--config-file', type=click.File('rb'), help=config_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('--ignore-version', is_flag=True, help=ignore_version_help)\n@common_options\ndef gh_deploy_command(config_file, clean, message, remote_branch, remote_name, force, ignore_version):\n    \"\"\"Deploy your documentation to GitHub Pages\"\"\"\n    try:\n        cfg = config.load_config(\n            config_file=config_file,\n            remote_branch=remote_branch,\n            remote_name=remote_name\n        )\n        build.build(cfg, dirty=not clean)\n        gh_deploy.gh_deploy(cfg, message=message, force=force, ignore_version=ignore_version)\n    except exceptions.ConfigurationError as e:  # pragma: no cover\n        # Avoid ugly, unhelpful traceback\n        raise SystemExit('\\n' + str(e))\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    new.new(project_directory)\n\n\nif __name__ == '__main__':  # pragma: no cover\n    cli()\n", "path": "mkdocs/__main__.py"}]}