-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__main__.py
More file actions
367 lines (343 loc) · 12.5 KB
/
Copy path__main__.py
File metadata and controls
367 lines (343 loc) · 12.5 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
from importlib.metadata import version as _pkg_version, PackageNotFoundError
from pathlib import Path
from typing import Optional, Annotated
import typer
from codeanalyzer.core import Codeanalyzer
from codeanalyzer.utils import _set_log_level, logger
from codeanalyzer.config import OutputFormat
from codeanalyzer.schema import model_dump_json
from codeanalyzer.options import AnalysisOptions, EmitTarget, ShardStrategy
def _version_callback(value: bool) -> None:
"""Print the installed ``codeanalyzer-python`` version and exit.
Eager so it fires before the rest of the CLI callback (no -i/--input
required). Reads the version from package metadata so it always reflects
what is actually installed rather than a hardcoded string."""
if not value:
return
try:
installed = _pkg_version("codeanalyzer-python")
except PackageNotFoundError:
installed = "unknown"
typer.echo(f"canpy {installed}")
raise typer.Exit()
def main(
version: Annotated[
Optional[bool],
typer.Option(
"--version",
help="Show the canpy version and exit.",
callback=_version_callback,
is_eager=True,
),
] = None,
input: Annotated[
Optional[Path],
typer.Option(
"-i",
"--input",
help="Path to the project root directory (not required for --emit schema).",
),
] = None,
output: Annotated[
Optional[Path],
typer.Option("-o", "--output", help="Output directory for artifacts."),
] = None,
format: Annotated[
OutputFormat,
typer.Option(
"-f",
"--format",
help="Output format for --emit json: json or msgpack.",
case_sensitive=False,
),
] = OutputFormat.JSON,
emit: Annotated[
EmitTarget,
typer.Option(
"--emit",
help="Output target: json (analysis.json, default) | neo4j (graph.cypher or live "
"Bolt push) | schema (the Neo4j schema.json contract).",
case_sensitive=False,
),
] = EmitTarget.JSON,
app_name: Annotated[
Optional[str],
typer.Option(
"--app-name",
help="Logical application name for the graph :PyApplication anchor "
"(default: input dir name).",
),
] = None,
neo4j_uri: Annotated[
Optional[str],
typer.Option(
"--neo4j-uri",
envvar="NEO4J_URI",
help="Push the graph to a live Neo4j over Bolt (incremental); omit to write "
"graph.cypher. [env: NEO4J_URI]",
),
] = None,
neo4j_user: Annotated[
str,
typer.Option(
"--neo4j-user",
envvar="NEO4J_USERNAME",
help="Neo4j username. [env: NEO4J_USERNAME]",
),
] = "neo4j",
neo4j_password: Annotated[
str,
typer.Option(
"--neo4j-password",
envvar="NEO4J_PASSWORD",
help="Neo4j password. Prefer the env var over the flag (the flag is visible in shell "
"history / process list). [env: NEO4J_PASSWORD]",
),
] = "neo4j",
neo4j_database: Annotated[
Optional[str],
typer.Option(
"--neo4j-database",
envvar="NEO4J_DATABASE",
help="Neo4j database name (default: server default). [env: NEO4J_DATABASE]",
),
] = None,
analysis_level: Annotated[
int,
typer.Option(
"-a",
"--analysis-level",
help="Analysis depth: 1=symbol table+Jedi call graph, 2=+PyCG call graph.",
min=1,
max=2,
),
] = 1,
using_ray: Annotated[
bool,
typer.Option("--ray/--no-ray", help="Enable Ray for distributed analysis."),
] = False,
rebuild_analysis: Annotated[
bool,
typer.Option(
"--eager/--lazy",
help="Enable eager or lazy analysis. Defaults to lazy.",
),
] = False,
skip_tests: Annotated[
bool,
typer.Option(
"--skip-tests/--include-tests",
help="Skip test files in analysis.",
),
] = True,
no_venv: Annotated[
bool,
typer.Option(
"--no-venv/--venv",
help="Skip virtualenv creation and dependency installation; resolve "
"imports against the ambient Python environment instead.",
),
] = False,
file_name: Annotated[
Optional[Path],
typer.Option(
"--file-name",
help="Analyze only the specified file (relative to input directory).",
),
] = None,
cache_dir: Annotated[
Optional[Path],
typer.Option(
"-c",
"--cache-dir",
help="Directory to store analysis cache. Defaults to '.codeanalyzer' in the input directory.",
),
] = None,
clear_cache: Annotated[
bool,
typer.Option(
"--clear-cache/--keep-cache",
help="Clear cache after analysis. By default, cache is retained.",
),
] = False,
verbosity: Annotated[
int, typer.Option("-v", count=True, help="Increase verbosity: -v, -vv, -vvv")
] = 0,
pycg_shard: Annotated[
bool,
typer.Option(
"--pycg-shard/--no-pycg-shard",
help=(
"Shard PyCG call-graph analysis by Python package (level 2 only). "
"When the project exceeds the 500-file ceiling, PyCG is run "
"independently per top-level package with cross-package imports "
"treated as ghost nodes. Without this flag, projects over the "
"ceiling fall back to Jedi-only edges."
),
),
] = False,
pycg_shard_ceiling: Annotated[
int,
typer.Option(
"--pycg-shard-ceiling",
help=(
"Maximum files per shard when --pycg-shard is active (default 100). "
"Shards exceeding this limit are skipped; their call edges are "
"omitted from the call graph (Jedi edges for those packages are "
"still included). Lower values are safer for packages with deep "
"class hierarchies or heavy import graphs."
),
min=1,
),
] = 100,
pycg_shard_timeout: Annotated[
int,
typer.Option(
"--pycg-shard-timeout",
help=(
"Per-shard wall-clock timeout in seconds when --pycg-shard is "
"active (default 120). A shard that exceeds this limit is skipped "
"gracefully. PyCG's fixpoint is bimodal: it either converges "
"quickly or diverges indefinitely, so the timeout acts as a final "
"safety net after the file-count ceiling. Set to 0 to disable. "
"POSIX only (macOS / Linux); ignored on Windows."
),
min=0,
),
] = 120,
pycg_shard_strategy: Annotated[
ShardStrategy,
typer.Option(
"--pycg-shard-strategy",
help=(
"How --pycg-shard groups files (level 2 only). 'jedi' (default) "
"partitions the Jedi module-dependency graph (SCC + Louvain) so "
"tightly-coupled modules co-compute and few call edges are "
"severed between shards; import cycles are never split. "
"'package' uses the legacy one-shard-per-package-directory "
"grouping."
),
),
] = ShardStrategy.JEDI,
pycg_max_iter: Annotated[
int,
typer.Option(
"--pycg-max-iter",
help=(
"Cap on PyCG's fixpoint passes per shard/project (level 2; "
"default 50). PyCG iterates until its points-to state stops "
"changing, but its access-path domain has no convergence bound, "
"so heavy metaclass/mixin code (e.g. an ORM) can loop with each "
"pass costing seconds. The cap returns a sound-but-incomplete "
"call graph instead of looping until the timeout kills it. "
"Set to -1 for PyCG's unbounded run-to-convergence behaviour."
),
min=-1,
),
] = 50,
):
options = AnalysisOptions(
input=input,
output=output,
format=format,
emit=emit,
app_name=app_name,
neo4j_uri=neo4j_uri,
neo4j_user=neo4j_user,
neo4j_password=neo4j_password,
neo4j_database=neo4j_database,
analysis_level=analysis_level,
using_ray=using_ray,
rebuild_analysis=rebuild_analysis,
skip_tests=skip_tests,
no_venv=no_venv,
file_name=file_name,
cache_dir=cache_dir,
clear_cache=clear_cache,
verbosity=verbosity,
pycg_shard=pycg_shard,
pycg_shard_ceiling=pycg_shard_ceiling,
pycg_shard_timeout=pycg_shard_timeout,
pycg_shard_strategy=pycg_shard_strategy,
pycg_max_iter=pycg_max_iter,
)
_set_log_level(options.verbosity)
# The schema contract is a static artifact — no project analysis required.
if options.emit == EmitTarget.SCHEMA:
from codeanalyzer.neo4j.emit import emit_schema
emit_schema(options.output)
return
# Every other target requires an input project.
if options.input is None:
logger.error("Missing option '-i' / '--input' (required for --emit json | neo4j).")
raise typer.Exit(code=1)
if not options.input.exists():
logger.error(f"Input path '{options.input}' does not exist.")
raise typer.Exit(code=1)
if options.file_name is not None:
full_file_path = options.input / options.file_name
if not full_file_path.exists():
logger.error(
f"Specified file '{options.file_name}' does not exist in '{options.input}'."
)
raise typer.Exit(code=1)
if not full_file_path.is_file():
logger.error(f"Specified path '{options.file_name}' is not a file.")
raise typer.Exit(code=1)
if not str(options.file_name).endswith(".py"):
logger.error(
f"Specified file '{options.file_name}' is not a Python file (.py)."
)
raise typer.Exit(code=1)
with Codeanalyzer(options) as analyzer:
artifacts = analyzer.analyze()
if options.emit == EmitTarget.NEO4J:
from codeanalyzer.neo4j.emit import emit_neo4j
emit_neo4j(artifacts, options)
elif options.output is None:
print(model_dump_json(artifacts, separators=(",", ":")))
else:
options.output.mkdir(parents=True, exist_ok=True)
_write_output(artifacts, options.output, options.format)
def _write_output(artifacts, output_dir: Path, format: OutputFormat):
"""Write artifacts to file in the specified format."""
if format == OutputFormat.JSON:
output_file = output_dir / "analysis.json"
# Use Pydantic's model_dump_json() for compact output
json_str = model_dump_json(artifacts, indent=None)
with output_file.open("w") as f:
f.write(json_str)
logger.info(f"Analysis saved to {output_file}")
elif format == OutputFormat.MSGPACK:
output_file = output_dir / "analysis.msgpack"
msgpack_data = artifacts.to_msgpack_bytes()
with output_file.open("wb") as f:
f.write(msgpack_data)
logger.info(f"Analysis saved to {output_file}")
logger.info(
f"Compression ratio: {artifacts.get_compression_ratio():.1%} of JSON size"
)
app = typer.Typer(
callback=main,
name="canpy",
help="Static Analysis on Python source code using Jedi, PyCG and Tree sitter.",
invoke_without_command=True,
no_args_is_help=True,
add_completion=False,
rich_markup_mode="rich",
pretty_exceptions_show_locals=False,
)
def deprecated_main() -> None:
"""Entry point for the legacy ``codeanalyzer`` command. Prints a one-line
deprecation notice to stderr (so piped stdout — e.g. ``--emit schema`` — stays
clean) and then runs the CLI unchanged. Kept for backwards compatibility; will
be removed in a future release."""
import sys
print(
"codeanalyzer: this command has been renamed to `canpy`. The `codeanalyzer` "
"alias is deprecated and will be removed in a future release — please use `canpy`.",
file=sys.stderr,
)
app()
if __name__ == "__main__":
app()