Debian Codegraph @

mkdocs/commands/gh_deploy.py

raw
1 from __future__ import annotations
2
3 import logging
4 import os
5 import re
6 import subprocess
7 from typing import TYPE_CHECKING
8
9 import ghp_import # type: ignore
10 from packaging import version
11
12 import mkdocs
13 from mkdocs.exceptions import Abort
14
15 if TYPE_CHECKING:
16 from mkdocs.config.defaults import MkDocsConfig
17
18 log = logging.getLogger(__name__)
19
20 default_message = """Deployed {sha} with MkDocs version: {version}"""
21
22
23 def _is_cwd_git_repo() -> bool:
24 try:
25 proc = subprocess.Popen(
26 ['git', 'rev-parse', '--is-inside-work-tree'],
27 stdout=subprocess.PIPE,
28 stderr=subprocess.PIPE,
29 )
30 except FileNotFoundError:
31 log.error("Could not find git - is it installed and on your path?")
32 raise Abort('Deployment Aborted!')
33 proc.communicate()
34 return proc.wait() == 0
35
36
37 def _get_current_sha(repo_path) -> str:
38 proc = subprocess.Popen(
39 ['git', 'rev-parse', '--short', 'HEAD'],
40 cwd=repo_path or None,
41 stdout=subprocess.PIPE,
42 stderr=subprocess.PIPE,
43 )
44
45 stdout, _ = proc.communicate()
46 sha = stdout.decode('utf-8').strip()
47 return sha
48
49
50 def _get_remote_url(remote_name: str) -> tuple[str, str] | tuple[None, None]:
51 # No CNAME found. We will use the origin URL to determine the GitHub
52 # Pages location.
53 remote = f"remote.{remote_name}.url"
54 proc = subprocess.Popen(
55 ["git", "config", "--get", remote],
56 stdout=subprocess.PIPE,
57 stderr=subprocess.PIPE,
58 )
59
60 stdout, _ = proc.communicate()
61 url = stdout.decode('utf-8').strip()
62
63 if 'github.com/' in url:
64 host, path = url.split('github.com/', 1)
65 elif 'github.com:' in url:
66 host, path = url.split('github.com:', 1)
67 else:
68 return None, None
69 return host, path
70
71
72 def _check_version(branch: str) -> None:
73 proc = subprocess.Popen(
74 ['git', 'show', '-s', '--format=%s', f'refs/heads/{branch}'],
75 stdout=subprocess.PIPE,
76 stderr=subprocess.PIPE,
77 )
78
79 stdout, _ = proc.communicate()
80 msg = stdout.decode('utf-8').strip()
81 m = re.search(r'\d+(\.\d+)+((a|b|rc)\d+)?(\.post\d+)?(\.dev\d+)?', msg, re.X | re.I)
82 previousv = version.parse(m.group()) if m else None
83 currentv = version.parse(mkdocs.__version__)
84 if not previousv:
85 log.warning('Version check skipped: No version specified in previous deployment.')
86 elif currentv > previousv:
87 log.info(
88 f'Previous deployment was done with MkDocs version {previousv}; '
89 f'you are deploying with a newer version ({currentv})'
90 )
91 elif currentv < previousv:
92 log.error(
93 f'Deployment terminated: Previous deployment was made with MkDocs version {previousv}; '
94 f'you are attempting to deploy with an older version ({currentv}). Use --ignore-version '
95 'to deploy anyway.'
96 )
97 raise Abort('Deployment Aborted!')
98
99
100 def gh_deploy(
101 config: MkDocsConfig,
102 message: str | None = None,
103 force=False,
104 no_history=False,
105 ignore_version=False,
106 shell=False,
107 ) -> None:
108 if not _is_cwd_git_repo():
109 log.error('Cannot deploy - this directory does not appear to be a git repository')
110
111 remote_branch = config.remote_branch
112 remote_name = config.remote_name
113
114 if not ignore_version:
115 _check_version(remote_branch)
116
117 if message is None:
118 message = default_message
119 sha = _get_current_sha(os.path.dirname(config.config_file_path))
120 message = message.format(version=mkdocs.__version__, sha=sha)
121
122 log.info(
123 "Copying '%s' to '%s' branch and pushing to GitHub.",
124 config.site_dir,
125 config.remote_branch,
126 )
127
128 try:
129 ghp_import.ghp_import(
130 config.site_dir,
131 mesg=message,
132 remote=remote_name,
133 branch=remote_branch,
134 push=True,
135 force=force,
136 use_shell=shell,
137 no_history=no_history,
138 nojekyll=True,
139 )
140 except ghp_import.GhpError as e:
141 log.error(f"Failed to deploy to GitHub with error: \n{e.message}")
142 raise Abort('Deployment Aborted!')
143
144 cname_file = os.path.join(config.site_dir, 'CNAME')
145 # Does this repository have a CNAME set for GitHub Pages?
146 if os.path.isfile(cname_file):
147 # This GitHub Pages repository has a CNAME configured.
148 with open(cname_file) as f:
149 cname_host = f.read().strip()
150 log.info(
151 f'Based on your CNAME file, your documentation should be '
152 f'available shortly at: http://{cname_host}'
153 )
154 log.info(
155 'NOTE: Your DNS records must be configured appropriately for your CNAME URL to work.'
156 )
157 return
158
159 host, path = _get_remote_url(remote_name)
160
161 if host is None or path is None:
162 # This could be a GitHub Enterprise deployment.
163 log.info('Your documentation should be available shortly.')
164 else:
165 username, repo = path.split('/', 1)
166 if repo.endswith('.git'):
167 repo = repo[: -len('.git')]
168 url = f'https://{username}.github.io/{repo}/'
169 log.info(f"Your documentation should shortly be available at: {url}")