Skip to content

Commit 803300a

Browse files
committed
feat(cli): add -j and --jobs 0 for one process per core instead of an --async mode (#205)
1 parent ee70aca commit 803300a

3 files changed

Lines changed: 133 additions & 7 deletions

File tree

‎docs/usage.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ coretrace-python-analyzer [--check | --emit-ir [--ssa]] [options] [path]
4848
| `--plugins DIR` | Load the plugins found under `DIR` on top of the bundled ones. Repeatable. |
4949
| `--no-bundled-plugins` | Do not load the plugins shipped with the package. |
5050
| `--cache DIR` | Keep per-module results under `DIR` and reuse them for unchanged modules. |
51-
| `--jobs N` | Analyse independent modules in `N` processes. |
51+
| `-j N`, `--jobs N` | Analyse independent modules in `N` processes, `0` for one per available core. Default: `1`. |
5252
| `--sbom PATH` | Write a CycloneDX bill of materials of the dependencies to `PATH`. |
5353
| `--vex PATH` | Write an OpenVEX document to `PATH`: whether each advisory affecting a requirement affects the project. |
5454
| `--advisories FILE` | Read a local advisory file in addition to `advisories.json` at the root. Repeatable. |
@@ -730,8 +730,12 @@ graph and the modules it imports. On the next run an unchanged
730730
module is served from the cache, so editing one file re-analyses that file and its
731731
importers only. Entries are plain data; an unreadable entry is recomputed.
732732

733-
`--jobs N` analyses independent modules in `N` processes. Modules are scheduled imports
734-
first, so the result is the same whatever `N`.
733+
`--jobs N` (`-j N`) analyses independent modules in `N` processes; `0` takes one per core
734+
the process may run on, as `runtime.jobs` of `ctrace` does, and the default is one.
735+
Modules are scheduled imports first, so the result is the same whatever `N`: the report,
736+
the order of its findings, `--fail-on`, the cache, the baseline and the SBOM and VEX
737+
documents. The command always waits for the complete report. There is no `--async`
738+
option: `ctrace` deprecated its own for `-j`/`--jobs`, which this follows.
735739

736740
```bash
737741
coretrace-python-analyzer --check src/ --cache .coretrace --jobs 4

‎src/coretrace_python/cli.py‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,13 @@ def build_parser() -> argparse.ArgumentParser:
109109
"them for modules unchanged since the previous run",
110110
)
111111
parser.add_argument(
112+
"-j",
112113
"--jobs",
113114
type=int,
114115
default=None,
115116
metavar="N",
116-
help="with --check on a directory, analyse independent modules in N processes",
117+
help="with --check on a directory, analyse independent modules in N processes, "
118+
"0 for one per available core; default: 1",
117119
)
118120
parser.add_argument(
119121
"--sbom",
@@ -214,8 +216,8 @@ def main(argv: list[str] | None = None) -> int:
214216
if args.jobs is not None and not (args.check and args.path.is_dir()):
215217
print("error: --jobs only applies to --check on a directory", file=sys.stderr)
216218
return EXIT_ERROR
217-
if args.jobs is not None and args.jobs < 1:
218-
print("error: --jobs must be at least 1", file=sys.stderr)
219+
if args.jobs is not None and args.jobs < 0:
220+
print("error: --jobs must be 0 (one per available core) or more", file=sys.stderr)
219221
return EXIT_ERROR
220222
if args.sbom is not None and not (args.check and args.path.is_dir()):
221223
print("error: --sbom only applies to --check on a directory", file=sys.stderr)
@@ -270,7 +272,7 @@ def main(argv: list[str] | None = None) -> int:
270272
args.path,
271273
plugin_roots,
272274
cache=cache,
273-
jobs=args.jobs or 1,
275+
jobs=_processes(args.jobs),
274276
advisory_files=args.advisories,
275277
policy_file=args.policy,
276278
)
@@ -331,5 +333,16 @@ def main(argv: list[str] | None = None) -> int:
331333
return EXIT_CLEAN
332334

333335

336+
def _processes(jobs: int | None) -> int:
337+
"""The number of processes ``--jobs`` asks for: 0 is one per core the process may run
338+
on, as ``runtime.jobs`` of ``ctrace``; none is one."""
339+
340+
if jobs is None:
341+
return 1
342+
if jobs == 0:
343+
return getattr(os, "process_cpu_count", os.cpu_count)() or 1
344+
return jobs
345+
346+
334347
if __name__ == "__main__":
335348
raise SystemExit(main())

‎tests/test_jobs_option.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
"""Acceptance tests for issue #205: the concurrency contract of the command line.
2+
3+
``ctrace`` deprecated ``--async`` for ``-j``/``--jobs`` (CoreTrace/coretrace#158): the
4+
analyzer follows it rather than adding an ``--async`` mode. ``-j N`` is ``--jobs N``;
5+
``0`` analyses in one process per available core, as ``runtime.jobs`` of ``ctrace``;
6+
the default stays one process. The command always waits for the complete report, which
7+
is the same whatever the number of processes.
8+
"""
9+
10+
from __future__ import annotations
11+
12+
import os
13+
import re
14+
from pathlib import Path
15+
16+
import pytest
17+
18+
from coretrace_python import engine
19+
from coretrace_python.cli import EXIT_ERROR, main
20+
21+
PROJECT = {
22+
"app/__init__.py": "",
23+
"app/a.py": "import os\n\n\ndef run(cmd):\n os.system(cmd)\n",
24+
"app/b.py": "def handle(code):\n eval(code)\n",
25+
"app/c.py": "import hashlib\n\n\ndef digest(data):\n return hashlib.md5(data)\n",
26+
}
27+
28+
29+
@pytest.fixture
30+
def project(tmp_path: Path) -> Path:
31+
root = tmp_path / "proj"
32+
for name, text in PROJECT.items():
33+
(root / name).parent.mkdir(parents=True, exist_ok=True)
34+
(root / name).write_text(text, encoding="utf-8")
35+
return root
36+
37+
38+
def report(capsys: pytest.CaptureFixture[str], *options: str) -> tuple[int, str]:
39+
status = main(["--check", *options, "--format", "json"])
40+
out = capsys.readouterr().out
41+
return status, out
42+
43+
44+
def test_j_is_jobs_and_the_report_does_not_depend_on_it(
45+
project: Path, capsys: pytest.CaptureFixture[str]
46+
) -> None:
47+
sequential = report(capsys, str(project))
48+
49+
assert report(capsys, str(project), "-j", "2") == sequential
50+
assert report(capsys, str(project), "--jobs", "2") == sequential
51+
52+
53+
def test_zero_jobs_is_one_process_per_available_core(
54+
project: Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
55+
) -> None:
56+
sequential = report(capsys, str(project))
57+
used: list[int] = []
58+
analyze = engine.analyze_project
59+
60+
def recording(*args: object, jobs: int = 1, **kwargs: object) -> engine.ProjectAnalysis:
61+
used.append(jobs)
62+
return analyze(*args, jobs=jobs, **kwargs) # type: ignore[arg-type]
63+
64+
monkeypatch.setattr(engine, "analyze_project", recording)
65+
cores = getattr(os, "process_cpu_count", os.cpu_count)() or 1
66+
67+
assert report(capsys, str(project), "-j", "0") == sequential
68+
assert used == [cores]
69+
70+
71+
def test_the_default_stays_one_process(
72+
project: Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
73+
) -> None:
74+
used: list[int] = []
75+
analyze = engine.analyze_project
76+
77+
def recording(*args: object, jobs: int = 1, **kwargs: object) -> engine.ProjectAnalysis:
78+
used.append(jobs)
79+
return analyze(*args, jobs=jobs, **kwargs) # type: ignore[arg-type]
80+
81+
monkeypatch.setattr(engine, "analyze_project", recording)
82+
report(capsys, str(project))
83+
84+
assert used == [1]
85+
86+
87+
@pytest.mark.parametrize("value", ["-1", "-8"])
88+
def test_a_negative_number_of_jobs_is_an_error(
89+
project: Path, capsys: pytest.CaptureFixture[str], value: str
90+
) -> None:
91+
assert main(["--check", str(project), "-j", value]) == EXIT_ERROR
92+
assert "--jobs" in capsys.readouterr().err
93+
94+
95+
def test_there_is_no_async_option(project: Path, capsys: pytest.CaptureFixture[str]) -> None:
96+
with pytest.raises(SystemExit) as exit:
97+
main(["--check", str(project), "--async"])
98+
99+
assert exit.value.code == EXIT_ERROR
100+
assert "--async" in capsys.readouterr().err
101+
102+
103+
def test_help_names_j_and_zero(capsys: pytest.CaptureFixture[str]) -> None:
104+
with pytest.raises(SystemExit):
105+
main(["--help"])
106+
text = " ".join(capsys.readouterr().out.split())
107+
108+
# Python 3.13 prints "-j, --jobs N", earlier versions "-j N, --jobs N".
109+
assert re.search(r"-j( N)?, --jobs N", text) and "0 for one per available core" in text

0 commit comments

Comments
 (0)