forked from vemel/handsdown
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_parser.py
More file actions
294 lines (249 loc) · 8.04 KB
/
Copy pathcli_parser.py
File metadata and controls
294 lines (249 loc) · 8.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""CLI Parser."""
import argparse
import contextlib
import logging
import re
from collections.abc import Iterable
from dataclasses import dataclass
from importlib import metadata
from pathlib import Path
from urllib.parse import urlparse, urlunparse
from handsdown.constants import ENCODING, EXCLUDE_EXPRS, PACKAGE_NAME, Theme
@dataclass
class CLINamespace:
"""Main CLI Namespace."""
panic: bool
input_path: Path
output_path: Path
toc_depth: int
log_level: int
include: list[str]
exclude: list[str]
source_code_url: str
source_code_path: Path
branch: str
project_name: str
files: list[Path]
cleanup: bool
encoding: str
create_configs: bool
theme: Theme
def get_source_code_url(self) -> str:
"""
Get URL to source code.
Returns:
URL as a string.
"""
if not self.source_code_url:
return ""
result = self.source_code_url.rstrip("/")
if self.branch:
result = f"{result}/blob/{self.branch}"
if self.source_code_path != Path():
result = f"{result}/{self.source_code_path.as_posix()}".rstrip("/")
result = urlunparse(urlparse(result.rstrip("/")))
return f"{result}/"
def git_repo(git_repo_url: str) -> str:
"""
Validate `git_repo_url` to be a GitHub repo and converts SSH urls to HTTPS.
Arguments:
git_repo_url -- GitHub URL or `remote.origin.url`
Returns:
A GitHub URL.
"""
if not git_repo_url:
return git_repo_url
https_repo_re = re.compile(r"^https://github.com/(?P<user>[^/]+)/(?P<repo>[^/]+)\.git$")
ssh_repo_re = re.compile(r"^git@github\.com:(?P<user>[^/]+)/(?P<repo>[^/]+)\.git$")
short_https_repo_re = re.compile(r"^https://github.com/(?P<user>[^/]+)/(?P<repo>[^/]+)/?$")
match = https_repo_re.match(git_repo_url)
if not match:
match = ssh_repo_re.match(git_repo_url)
if not match:
match = short_https_repo_re.match(git_repo_url)
if not match:
msg = f"Cannot parse Git URL {git_repo_url}"
raise argparse.ArgumentTypeError(msg)
user = match.groupdict()["user"]
repo = match.groupdict()["repo"]
return f"https://github.com/{user}/{repo}/"
def abs_path(path_str: str) -> Path:
"""
Validate `path_str` and make it absolute.
Arguments:
path_str -- A path to check.
Returns:
An absolute path.
"""
return Path(path_str).absolute()
def dir_abs_path(path_str: str) -> Path:
"""
Validate directory `path_str` and make it absolute.
Arguments:
path_str -- A path to check.
Returns:
An absolute path.
Raises:
argparse.ArgumentTypeError -- If path is not a directory.
"""
path = Path(path_str).absolute()
if path.exists() and not path.is_dir():
msg = f"Path {path} is not a directory"
raise argparse.ArgumentTypeError(msg)
return path
def existing_dir_abs_path(path_str: str) -> Path:
"""
Validate existing directory `path_str` and make it absolute.
Arguments:
path_str -- A path to check.
Returns:
An absolute path.
Raises:
argparse.ArgumentTypeError -- If path does not exist or is not a directory.
"""
path = Path(path_str).absolute()
if not path.exists():
msg = f"Path {path} does not exist"
raise argparse.ArgumentTypeError(msg)
if not path.is_dir():
msg = f"Path {path} is not a directory"
raise argparse.ArgumentTypeError(msg)
return path
def parse_theme(name: str) -> Theme:
"""Cast theme name to `Theme`."""
try:
return Theme(name)
except ValueError:
choices = ", ".join([i.value for i in Theme])
msg = f"Invalid theme {name}, choices are: {choices}"
raise argparse.ArgumentTypeError(msg) from None
def _get_package_version() -> str:
with contextlib.suppress(metadata.PackageNotFoundError):
return metadata.version(PACKAGE_NAME)
return "0.0.0"
def parse_args(args: Iterable[str]) -> CLINamespace:
"""
Get CLI arguments parser.
Returns:
An `argparse.ArgumentParser` instance.
"""
version = _get_package_version()
exclude_exprs_str = " ".join([f"'{i}'" for i in EXCLUDE_EXPRS])
parser = argparse.ArgumentParser(
PACKAGE_NAME, description="Docstring-based python documentation generator.",
)
parser.add_argument(
"include", nargs="*", help="Path expressions to include source files", default=[],
)
parser.add_argument(
"--exclude",
nargs="*",
help=f"Path expressions to exclude source files (default: {exclude_exprs_str})",
default=EXCLUDE_EXPRS,
)
parser.add_argument(
"-i",
"--input-path",
help="Path to project root folder",
default=Path.cwd(),
type=existing_dir_abs_path,
)
parser.add_argument(
"-f",
"--files",
nargs="*",
default=[],
type=abs_path,
help="List of source files to use for generation. If empty - all are used.",
)
parser.add_argument(
"-o",
"--output-path",
help="Path to output folder (default: <cwd>/docs)",
default=Path.cwd() / "docs",
type=dir_abs_path,
)
parser.add_argument(
"--external",
help=(
"Build docs and config for external hosting, GitHub Pages or Read the Docs."
" Provide the project GitHub URL here."
),
dest="source_code_url",
metavar="REPO_URL",
default="",
type=git_repo,
)
parser.add_argument(
"--source-code-path",
help="Path to source code in the project.",
dest="source_code_path",
metavar="REPO_PATH",
default=Path(),
type=Path,
)
parser.add_argument(
"--branch",
help="Main branch name, extends external URL with `/blob/<branch>` (default: main)",
default="main",
)
parser.add_argument(
"--toc-depth", help="Maximum depth of child modules ToC (default: 3)", default=3, type=int,
)
parser.add_argument(
"--cleanup", action="store_true", help="Remove orphaned auto-generated docs",
)
parser.add_argument(
"-n",
"--name",
dest="project_name",
help="Project name",
default=Path.cwd().stem.capitalize(),
)
parser.add_argument(
"-e",
"--encoding",
help=f"Input and output file encoding (default: {ENCODING})",
default=ENCODING,
)
parser.add_argument(
"--create-configs",
help="Create config files for deployment to RtD and GitHub Pages",
action="store_true",
)
parser.add_argument(
"-t",
"--theme",
choices=list(Theme),
default=Theme.RTD,
type=parse_theme,
help=f"Output mkdocs theme (default: {Theme.RTD.value})",
)
parser.add_argument("--panic", action="store_true", help="Panic and die on import error")
parser.add_argument("-d", "--debug", action="store_true", help="Show debug messages")
parser.add_argument("-q", "--quiet", action="store_true", help="Hide log output")
parser.add_argument("-V", "--version", action="version", version=version)
namespace = parser.parse_args(list(args))
log_level = logging.INFO
if namespace.debug:
log_level = logging.DEBUG
if namespace.quiet:
log_level = logging.CRITICAL
return CLINamespace(
panic=namespace.panic,
input_path=namespace.input_path,
output_path=namespace.output_path,
toc_depth=namespace.toc_depth,
log_level=log_level,
exclude=list(namespace.exclude),
include=list(namespace.include),
source_code_url=namespace.source_code_url,
source_code_path=namespace.source_code_path,
branch=namespace.branch,
project_name=namespace.project_name,
files=list(namespace.files),
cleanup=namespace.cleanup,
encoding=namespace.encoding,
create_configs=namespace.create_configs,
theme=namespace.theme,
)