-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
191 lines (161 loc) · 6.71 KB
/
Copy pathcli.py
File metadata and controls
191 lines (161 loc) · 6.71 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
"""Command-line interface: ``python -m profile_diff {run,compare,comment}``."""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import List, Optional
from . import __version__
from .diff import compare, render_json, render_markdown, render_text
from .profiler import build_run_fn, profile
# --------------------------------------------------------------------------- #
# Argument parsing
# --------------------------------------------------------------------------- #
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="python -m profile_diff",
description="Profile a target and diff CPU/memory hotspots across branches.",
)
parser.add_argument("--version", action="version", version=f"profile_diff {__version__}")
sub = parser.add_subparsers(dest="command", required=True)
# --- run --------------------------------------------------------------- #
run = sub.add_parser("run", help="Profile a target and write a JSON report.")
target = run.add_mutually_exclusive_group(required=True)
target.add_argument(
"--pytest",
nargs=argparse.REMAINDER,
metavar="PYTEST_ARG",
help="Profile an in-process 'pytest' run. Must be LAST: every token "
"after it (including flags like -q) is forwarded to pytest.",
)
target.add_argument("--script", metavar="PATH", help="Profile a Python script by path.")
target.add_argument(
"--callable",
dest="callable_ref",
metavar="pkg.mod:func",
help="Profile a zero-argument importable callable.",
)
run.add_argument(
"--script-arg",
dest="script_args",
action="append",
default=[],
metavar="ARG",
help="Argument passed to --script (repeatable).",
)
run.add_argument("--out", metavar="PATH", help="Write JSON report here (default: stdout).")
run.add_argument("--top", type=int, default=30, help="Keep top N functions by cumtime (default 30).")
run.add_argument("--label", default="run", help="Human label stored in the report (e.g. base/head).")
# --- compare ----------------------------------------------------------- #
comp = sub.add_parser("compare", help="Diff two JSON reports.")
comp.add_argument("base", help="Base-branch report JSON.")
comp.add_argument("head", help="Head-branch report JSON.")
comp.add_argument("--threshold-pct", type=float, default=5.0, help="Ignore moves below this %% (default 5).")
comp.add_argument("--min-abs-ms", type=float, default=0.0, help="Ignore moves below this many ms (default 0).")
comp.add_argument("--top", type=int, default=10, help="Movers to show each direction (default 10).")
comp.add_argument(
"--format",
choices=("markdown", "text", "json"),
default="markdown",
help="Output format (default markdown).",
)
comp.add_argument("--out", metavar="PATH", help="Write the report here (default: stdout).")
comp.add_argument(
"--fail-on-regression",
action="store_true",
help="Exit 2 if any hotspot regresses beyond the threshold.",
)
# --- comment ----------------------------------------------------------- #
com = sub.add_parser("comment", help="Post/update a PR comment with a diff body.")
com.add_argument("body", help="Path to the Markdown body, or '-' to read stdin.")
com.add_argument("--repo", help="owner/name (default: $GITHUB_REPOSITORY).")
com.add_argument("--pr", type=int, help="PR number (default: $PR_NUMBER).")
com.add_argument("--token", help="GitHub token (default: $GITHUB_TOKEN).")
return parser
# --------------------------------------------------------------------------- #
# Subcommand handlers
# --------------------------------------------------------------------------- #
def _write(text: str, out: Optional[str]) -> None:
if out:
with open(out, "w", encoding="utf-8") as handle:
handle.write(text)
else:
sys.stdout.write(text)
def cmd_run(args: argparse.Namespace) -> int:
run_fn, target = build_run_fn(
pytest_args=args.pytest,
script=args.script,
script_args=args.script_args,
callable_ref=args.callable_ref,
)
report = profile(run_fn, label=args.label, target=target, top_n=args.top)
_write(json.dumps(report, indent=2) + "\n", args.out)
return 0
def cmd_compare(args: argparse.Namespace) -> int:
with open(args.base, encoding="utf-8") as handle:
base = json.load(handle)
with open(args.head, encoding="utf-8") as handle:
head = json.load(handle)
result = compare(
base,
head,
threshold_pct=args.threshold_pct,
min_abs_ms=args.min_abs_ms,
top=args.top,
)
if args.format == "markdown":
text = render_markdown(result)
elif args.format == "text":
text = render_text(result)
else:
text = json.dumps(render_json(result), indent=2) + "\n"
_write(text, args.out)
if args.fail_on_regression and result.has_regression:
return 2
return 0
def cmd_comment(args: argparse.Namespace) -> int:
# Imported lazily so `run`/`compare` never touch the network stack.
from .comment import GitHubClient, post_or_update
repo = args.repo or os.environ.get("GITHUB_REPOSITORY")
pr = args.pr if args.pr is not None else _env_int("PR_NUMBER")
token = args.token or os.environ.get("GITHUB_TOKEN")
missing = [
name
for name, value in (("repo", repo), ("pr", pr), ("token", token))
if not value
]
if missing:
sys.stderr.write(
"error: missing required value(s): "
+ ", ".join(missing)
+ " (set via flag or env)\n"
)
return 1
if args.body == "-":
body = sys.stdin.read()
else:
with open(args.body, encoding="utf-8") as handle:
body = handle.read()
client = GitHubClient(repo=repo, token=token) # type: ignore[arg-type]
result = post_or_update(client, int(pr), body) # type: ignore[arg-type]
sys.stderr.write(f"comment {result.get('_action', 'posted')}\n")
return 0
def _env_int(name: str) -> Optional[int]:
raw = os.environ.get(name)
if raw is None or raw == "":
return None
try:
return int(raw)
except ValueError:
return None
def main(argv: Optional[List[str]] = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
if args.command == "run":
return cmd_run(args)
if args.command == "compare":
return cmd_compare(args)
if args.command == "comment":
return cmd_comment(args)
parser.error("unknown command") # pragma: no cover
return 1 # pragma: no cover