-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcmd.py
More file actions
338 lines (298 loc) · 10.4 KB
/
cmd.py
File metadata and controls
338 lines (298 loc) · 10.4 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
from collections import deque
import json
from os import linesep
from pathlib import Path
import tomllib
from typing import Annotated, TypeAlias, cast
import typer
from sphinx_codelinks.analyse.projects import AnalyseProjects
from sphinx_codelinks.config import (
CodeLinksConfig,
CodeLinksConfigType,
CodeLinksProjectConfigType,
generate_project_configs,
)
from sphinx_codelinks.logger import logger
from sphinx_codelinks.needextend_write import MarkedObjType, convert_marked_content
from sphinx_codelinks.source_discover.config import (
CommentType,
SourceDiscoverConfig,
SourceDiscoverConfigType,
)
from sphinx_codelinks.source_discover.source_discover import SourceDiscover
app = typer.Typer(
no_args_is_help=True, context_settings={"help_option_names": ["-h", "--help"]}
)
write_app = typer.Typer(
help="Export marked content to other formats", no_args_is_help=True
)
app.add_typer(write_app, name="write", rich_help_panel="Sub-menus")
OptVerbose: TypeAlias = Annotated[ # noqa: UP040 # has to be TypeAlias
bool,
typer.Option(
...,
"-v",
"--verbose",
is_flag=True,
help="Show debug information",
rich_help_panel="Logging",
),
]
OptQuiet: TypeAlias = Annotated[ # noqa: UP040 # has to be TypeAlias
bool,
typer.Option(
...,
"-q",
"--quiet",
is_flag=True,
help="Only show errors and warnings",
rich_help_panel="Logging",
),
]
@app.command(no_args_is_help=True)
def analyse( # noqa: PLR0912 # for CLI, so it needs the branches
config: Annotated[
Path,
typer.Argument(
help="The toml config file",
show_default=False,
dir_okay=False,
file_okay=True,
exists=True,
),
],
projects: Annotated[
list[str] | None,
typer.Option(
"--project",
"-p",
help="Specify the project name of the config. If not specified, take all",
show_default=True,
),
] = None,
outdir: Annotated[
Path | None,
typer.Option(
"--outdir",
"-o",
help="The output directory. When given, this overwrites the config's outdir",
show_default=True,
dir_okay=True,
file_okay=False,
exists=True,
),
] = None,
) -> None:
"""Analyse marked content in source code."""
# @CLI command to analyse source code and extract traceability markers, IMPL_CLI_ANALYZE, impl, [FE_CLI_ANALYZE]
data: CodeLinksConfigType = load_config_from_toml(config)
try:
codelinks_config = CodeLinksConfig(**data)
generate_project_configs(codelinks_config.projects)
except TypeError as e:
raise typer.BadParameter(str(e)) from e
errors: deque[str] = deque()
if outdir:
codelinks_config.outdir = outdir
project_errors: list[str] = []
if projects:
for project in projects:
if project not in codelinks_config.projects:
if not project_errors:
project_errors.append("The following projects are not found:")
project_errors.append(project)
if project_errors:
raise typer.BadParameter(f"{linesep.join(project_errors)}")
specifed_project_configs: dict[str, CodeLinksProjectConfigType] = {}
for project, _config in codelinks_config.projects.items():
if projects and project not in projects:
continue
# Get source_discover configuration
src_discover_config = _config["source_discover_config"]
src_discover_errors = src_discover_config.check_schema()
if src_discover_errors:
errors.appendleft("Invalid source discovery configuration:")
errors.extend(src_discover_errors)
if errors:
raise typer.BadParameter(f"{linesep.join(errors)}")
# src dir shall be relevant to the config file's location
src_discover_config.src_dir = (
config.parent / src_discover_config.src_dir
).resolve()
src_discover = SourceDiscover(src_discover_config)
# Init source analyse config
analyse_config = _config["analyse_config"]
analyse_config.src_files = src_discover.source_paths
analyse_config.src_dir = Path(src_discover.src_discover_config.src_dir)
# git_root shall be relative to the config file's location (like src_dir)
if analyse_config.git_root is not None:
analyse_config.git_root = (
config.parent / analyse_config.git_root
).resolve()
analyse_errors = analyse_config.check_fields_configuration()
errors.extend(analyse_errors)
if errors:
raise typer.BadParameter(f"{linesep.join(errors)}")
specifed_project_configs[project] = {"analyse_config": analyse_config}
codelinks_config.projects = specifed_project_configs
analyse_projects = AnalyseProjects(codelinks_config)
analyse_projects.run()
# Output warnings to console for CLI users
for src_analyse in analyse_projects.projects_analyse.values():
for warning in src_analyse.oneline_warnings:
logger.warning(
f"Oneline parser warning in {warning.file_path}:{warning.lineno} "
f"- {warning.sub_type}: {warning.msg}",
)
analyse_projects.dump_markers()
@app.command(no_args_is_help=True)
def discover( # noqa: PLR0913 # CLI command requires multiple parameters
src_dir: Annotated[
Path,
typer.Argument(
...,
help="Root directory for discovery",
show_default=False,
dir_okay=True,
file_okay=False,
exists=True,
resolve_path=True,
),
],
exclude: Annotated[
list[str],
typer.Option(
"--excludes",
"-e",
help="Glob patterns to be excluded.",
),
] = [], # noqa: B006 # to show the default value on CLI
include: Annotated[
list[str],
typer.Option(
"--includes",
"-i",
help="Glob patterns to be included.",
),
] = [], # noqa: B006 # to show the default value on CLI
# @CLI command to discover source files recursively with gitignore support, IMPL_CLI_DISCOVER, impl, [FE_CLI_DISCOVER]
gitignore: Annotated[
bool,
typer.Option(
help="Respect .gitignore files in the given directory and its parents"
),
] = True,
follow_links: Annotated[
bool,
typer.Option(help="Follow symbolic links during file discovery"),
] = False,
comment_type: Annotated[
CommentType,
typer.Option(
"--comment-type",
"-c",
help="The relevant file extensions which use the specified the comment type will be discovered.",
),
] = CommentType.cpp,
) -> None:
"""Discover the filepaths from the given root directory."""
src_discover_dict: SourceDiscoverConfigType = {
"src_dir": src_dir,
"exclude": exclude,
"include": include,
"gitignore": gitignore,
"follow_links": follow_links,
"comment_type": comment_type,
}
src_discover_config = SourceDiscoverConfig(**src_discover_dict)
errors = src_discover_config.check_schema()
if errors:
raise typer.BadParameter(f"{linesep.join(errors)}")
source_discover = SourceDiscover(src_discover_config)
typer.echo(f"{len(source_discover.source_paths)} files discovered")
for file_path in source_discover.source_paths:
typer.echo(file_path)
@write_app.command("rst", no_args_is_help=True)
def write_rst( # noqa: PLR0913 # for CLI, so it takes as many as it requires
jsonpath: Annotated[
Path,
typer.Argument(
...,
help="Path of the JSON file which contains the extracted markers",
show_default=False,
dir_okay=False,
file_okay=True,
exists=True,
resolve_path=True,
),
],
# @CLI command to generate needextend RST file from extracted markers, IMPL_CLI_WRITE, impl, [FE_CLI_WRITE]
outpath: Annotated[
Path,
typer.Option(
"--outpath",
"-o",
help="The output path for generated rst file",
show_default=True,
dir_okay=False,
file_okay=True,
exists=False,
),
] = Path("needextend.rst"),
remote_url_field: Annotated[
str,
typer.Option(
"--remote-url-field",
"-r",
help="The field name for the remote url",
show_default=True,
),
] = "remote_url", # to show default value in this CLI
title: Annotated[
str | None,
typer.Option(
"--title",
"-t",
help="Give the title to the generated RST file",
show_default=True,
),
] = None, # to show default value in this CLI
verbose: OptVerbose = False,
quiet: OptQuiet = False,
) -> None:
"""Generate needextend.rst from the extracted obj in JSON."""
logger.configure(verbose, quiet)
try:
with jsonpath.open("r") as f:
marked_content = json.load(f)
except Exception as e:
raise typer.BadParameter(
f"Failed to load marked content from {jsonpath}: {e}"
) from e
marked_objs: list[MarkedObjType] = [
obj for objs in marked_content.values() for obj in objs
]
needextend_texts, errors = convert_marked_content(
marked_objs, remote_url_field, title
)
if errors:
raise typer.BadParameter(
f"Errors occurred during conversion: {linesep.join(errors)}"
)
with outpath.open("w") as f:
f.writelines(needextend_texts)
typer.echo(f"Generated {outpath}")
def load_config_from_toml(toml_file: Path) -> CodeLinksConfigType:
try:
with toml_file.open("rb") as f:
toml_data = tomllib.load(f)
except Exception as e:
raise typer.BadParameter(
f"Failed to load CodeLinks configuration from {toml_file}"
) from e
codelink_dict = toml_data.get("codelinks")
if not codelink_dict:
raise typer.BadParameter(f"No 'codelinks' section found in {toml_file}")
return cast(CodeLinksConfigType, codelink_dict)
if __name__ == "__main__":
app()