From 9a313faaa4164f94d354cbefe95e5f9e022b3f56 Mon Sep 17 00:00:00 2001 From: mrunalC27 Date: Wed, 2 Dec 2026 21:47:15 +0530 Subject: [PATCH 1/2] Align Python profiler CLI with rc-cli conventions --- runtimeconditions_profiler/cli.py | 43 +++++++++++++++-- runtimeconditions_profiler/errors.py | 13 +++++- .../project/installed.py | 10 +++- runtimeconditions_profiler/project/verify.py | 5 +- tests/test_installed_binding_discovery.py | 46 +++++++++++++++++++ 5 files changed, 109 insertions(+), 8 deletions(-) diff --git a/runtimeconditions_profiler/cli.py b/runtimeconditions_profiler/cli.py index fd26ac4..3bbe96e 100644 --- a/runtimeconditions_profiler/cli.py +++ b/runtimeconditions_profiler/cli.py @@ -18,6 +18,24 @@ NAME = "runtimeconditions-python-profiler" COMMANDS = ("generate", "verify-bindings") +class RuntimeConditionsArgumentParser(argparse.ArgumentParser): + def error(self, message: str) -> None: + usage = USAGE.replace(NAME, get_command_prefix()) + self.exit( + 2, + f"usage: {usage}\n" + f"runtimeconditions: error: {message}\n", + ) + +USAGE = ( + f"{NAME} [profile] verify-bindings --project DIR [--json]\n" + f" {NAME} [profile] generate --project DIR --name NAME " + "--workload-uri URI [--workload-version VERSION] [--out FILE] [--json]\n" + f" {NAME} --version [--json]" +) + +def get_command_prefix() -> str: + return os.environ.get("RC_COMMAND_PREFIX", NAME) def version() -> str: try: @@ -38,20 +56,28 @@ def main(argv: list[str] | None = None) -> int: if argv[:1] and argv[0] in COMMANDS: # The profile prefix is optional, so rc can pass the subcommand straight through. argv = ["profile", *argv] - parser = argparse.ArgumentParser(prog=NAME) + usage = USAGE.replace(NAME, get_command_prefix()) + parser = RuntimeConditionsArgumentParser(prog=get_command_prefix(), usage=usage) subparsers = parser.add_subparsers(dest="command", required=True) - profile = subparsers.add_parser("profile") profile_commands = profile.add_subparsers(dest="profile_command", required=True) - profile_generate = profile_commands.add_parser("generate") + profile_generate = profile_commands.add_parser( + "generate", + usage=f"{get_command_prefix()} [profile] generate --project DIR --name NAME --workload-uri URI [--workload-version VERSION] [--out FILE] [--json]", + ) profile_generate.add_argument("--project", default=".") profile_generate.add_argument("--name", required=True) profile_generate.add_argument("--workload-uri", required=True) profile_generate.add_argument("--workload-version") profile_generate.add_argument("--out") + profile_generate.add_argument("--json", action="store_true") profile_verify = profile_commands.add_parser( "verify-bindings", help="verify installed generated bindings without running application or binding code", + usage=( + f"{get_command_prefix()} [profile] " + "verify-bindings --project DIR [--json]" + ), ) profile_verify.add_argument("--project", default=".") profile_verify.add_argument("--json", action="store_true") @@ -64,7 +90,16 @@ def main(argv: list[str] | None = None) -> int: if command == "profile" and args.profile_command == "verify-bindings": return run_profile_verify_bindings(args) except RuntimeConditionsError as exc: - print(f"runtimeconditions: {exc}", file=sys.stderr) + if getattr(args, "json", False): + error = { + "stage": exc.stage, + "message": exc.args[0], + } + if exc.location: + error["location"] = exc.location + print(json.dumps({"error": error}, separators=(",", ":")), file=sys.stderr) + else: + print(f"runtimeconditions: {exc}", file=sys.stderr) return 1 return 0 diff --git a/runtimeconditions_profiler/errors.py b/runtimeconditions_profiler/errors.py index 378cd85..4c17d1c 100644 --- a/runtimeconditions_profiler/errors.py +++ b/runtimeconditions_profiler/errors.py @@ -1,3 +1,14 @@ class RuntimeConditionsError(Exception): - pass + def __init__( + self, + message: str, + stage: str = "profile", + location: str | None = None, + ) -> None: + super().__init__(message) + self.stage = stage + self.location = location + def __str__(self) -> str: + location = f"{self.location}: " if self.location else "" + return f"error: {self.stage}: {location}{self.args[0]}" diff --git a/runtimeconditions_profiler/project/installed.py b/runtimeconditions_profiler/project/installed.py index 20540c3..c1a7d96 100644 --- a/runtimeconditions_profiler/project/installed.py +++ b/runtimeconditions_profiler/project/installed.py @@ -67,10 +67,16 @@ class InstalledBindingDiscovery: def discover(self, project_root: Path) -> InstalledBindingDiscoveryResult: root = project_root.absolute().resolve() if not root.is_dir(): - raise RuntimeConditionsError(f"workload directory does not exist: {root}") + raise RuntimeConditionsError( + f"workload directory does not exist: {root}. " + "Check that --project points to an existing directory." + ) source_files = workload_source_files(root) if not source_files: - raise RuntimeConditionsError(f"no Python source files found under {root}") + raise RuntimeConditionsError( + f"no Python source files found under {root}. " + "Add Python source files to the workload directory or check the --project path." + ) imports = _source_imports(source_files) imports_by_root: dict[str, list[SourceImport]] = {} for item in imports: diff --git a/runtimeconditions_profiler/project/verify.py b/runtimeconditions_profiler/project/verify.py index 1926659..93282b3 100644 --- a/runtimeconditions_profiler/project/verify.py +++ b/runtimeconditions_profiler/project/verify.py @@ -396,7 +396,10 @@ def resolve_marker_declaration( class InstalledBindingVerifier: def verify(self, discovery: InstalledBindingDiscoveryResult) -> VerifiedBindingSet: if not discovery.packages: - raise RuntimeConditionsError("no installed generated binding imports found in workload") + raise RuntimeConditionsError( + "no installed generated binding imports found in workload. " + "Install the generated binding package and import it in your Python source files." + ) schemas = _schemas() pending = list(discovery.packages) verified: dict[str, VerifiedBindingPackage] = {} diff --git a/tests/test_installed_binding_discovery.py b/tests/test_installed_binding_discovery.py index cb77ae0..7570f5e 100644 --- a/tests/test_installed_binding_discovery.py +++ b/tests/test_installed_binding_discovery.py @@ -975,3 +975,49 @@ def test_verify_bindings_says_which_packages_the_workload_imports_and_which_only status, out, _ = run_cli(["verify-bindings", "--project", str(tmp_path), "--json"], capsys) assert {item["distribution"]: item["direct"] for item in json.loads(out)["packages"]} == { "extra_binding": True, base.installed.distribution: False} + +def test_generate_json_returns_structured_error( + tmp_path: Path, capsys: pytest.CaptureFixture[str], +) -> None: + (tmp_path / "app.py").write_text("print('hello')\n", encoding="utf-8") + status = cli.main([ + "generate", "--project", str(tmp_path), + "--name", "sample", "--workload-uri", "example/sample", "--json", + ]) + + captured = capsys.readouterr() + assert status == 1 + assert json.loads(captured.err) == { + "error": { + "stage": "profile", + "message": ( + "no installed generated binding imports found in workload. " + "Install the generated binding package and import it in your Python source files." + ), + } + } + +def test_command_prefix_is_used_in_usage( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], +) -> None: + monkeypatch.setenv("RC_COMMAND_PREFIX", "rc profile python") + + with pytest.raises(SystemExit) as exc: + cli.main(["--help"]) + + assert exc.value.code == 0 + assert "usage: rc profile python" in capsys.readouterr().out + +def test_missing_project_directory_returns_actionable_error( + tmp_path: Path, +) -> None: + missing = tmp_path / "missing" + with pytest.raises(RuntimeConditionsError, match="workload directory does not exist"): + installed.InstalledBindingDiscovery().discover(missing) + + +def test_empty_project_returns_actionable_error( + tmp_path: Path, +) -> None: + with pytest.raises(RuntimeConditionsError, match="no Python source files found"): + installed.InstalledBindingDiscovery().discover(tmp_path) From 175f68e8a418bccaa1385fc64f8acafbc4052c31 Mon Sep 17 00:00:00 2001 From: mrunalC27 Date: Fri, 4 Dec 2026 22:49:03 +0530 Subject: [PATCH 2/2] Align Python profiler CLI with rc-cli conventions --- CONFORMANCE.md | 5 ++- README.md | 4 +-- runtimeconditions_profiler/cli.py | 33 ++++++++++---------- runtimeconditions_profiler/project/verify.py | 3 +- tests/test_installed_binding_discovery.py | 25 +++++++-------- 5 files changed, 34 insertions(+), 36 deletions(-) diff --git a/CONFORMANCE.md b/CONFORMANCE.md index e1f0524..c4ffa21 100644 --- a/CONFORMANCE.md +++ b/CONFORMANCE.md @@ -92,9 +92,8 @@ checked the `pip --report` URLs for HTTP retrieval. It removed ambient profiler runtime environment. The workload sources use absolute imports from those installed distributions; they contain a sentinel that raises if executed. The installed `runtimeconditions-python-profiler` console script, -not source code from this repository, ran `profile verify-bindings` and -`profile generate` for every case. - +not source code from this repository, ran `verify-bindings` and +`generate` for every case. | Check | Final result | | --- | --- | | Positive profiles | **19/19** successful; full YAML matches the independently reviewed bytes and repeats identically. Emitted extension IDs match direct contributors. | diff --git a/README.md b/README.md index 475d95d..b52797d 100644 --- a/README.md +++ b/README.md @@ -65,10 +65,10 @@ where the profiler or binding packages were built: ```sh "$PROFILE_ENV/bin/runtimeconditions-python-profiler" \ - profile verify-bindings --project "$PROJECT_DIR" + verify-bindings --project "$PROJECT_DIR" "$PROFILE_ENV/bin/runtimeconditions-python-profiler" \ - profile generate \ + generate \ --project "$PROJECT_DIR" \ --name orders \ --workload-uri https://services.example.com/orders \ diff --git a/runtimeconditions_profiler/cli.py b/runtimeconditions_profiler/cli.py index 3bbe96e..c12dbf2 100644 --- a/runtimeconditions_profiler/cli.py +++ b/runtimeconditions_profiler/cli.py @@ -16,7 +16,7 @@ from .profile.semantic import CORE_VERSION, GeneratedProfileValidator NAME = "runtimeconditions-python-profiler" -COMMANDS = ("generate", "verify-bindings") + class RuntimeConditionsArgumentParser(argparse.ArgumentParser): def error(self, message: str) -> None: @@ -28,8 +28,8 @@ def error(self, message: str) -> None: ) USAGE = ( - f"{NAME} [profile] verify-bindings --project DIR [--json]\n" - f" {NAME} [profile] generate --project DIR --name NAME " + f"{NAME} verify-bindings --project DIR [--json]\n" + f" {NAME} generate --project DIR --name NAME " "--workload-uri URI [--workload-version VERSION] [--out FILE] [--json]\n" f" {NAME} --version [--json]" ) @@ -53,17 +53,17 @@ def main(argv: list[str] | None = None) -> int: else: print(version()) return 0 - if argv[:1] and argv[0] in COMMANDS: - # The profile prefix is optional, so rc can pass the subcommand straight through. - argv = ["profile", *argv] + usage = USAGE.replace(NAME, get_command_prefix()) parser = RuntimeConditionsArgumentParser(prog=get_command_prefix(), usage=usage) subparsers = parser.add_subparsers(dest="command", required=True) - profile = subparsers.add_parser("profile") - profile_commands = profile.add_subparsers(dest="profile_command", required=True) - profile_generate = profile_commands.add_parser( + + profile_generate = subparsers.add_parser( "generate", - usage=f"{get_command_prefix()} [profile] generate --project DIR --name NAME --workload-uri URI [--workload-version VERSION] [--out FILE] [--json]", + usage=( + f"{get_command_prefix()} generate --project DIR --name NAME " + "--workload-uri URI [--workload-version VERSION] [--out FILE] [--json]" + ), ) profile_generate.add_argument("--project", default=".") profile_generate.add_argument("--name", required=True) @@ -71,23 +71,22 @@ def main(argv: list[str] | None = None) -> int: profile_generate.add_argument("--workload-version") profile_generate.add_argument("--out") profile_generate.add_argument("--json", action="store_true") - profile_verify = profile_commands.add_parser( + + profile_verify = subparsers.add_parser( "verify-bindings", help="verify installed generated bindings without running application or binding code", - usage=( - f"{get_command_prefix()} [profile] " - "verify-bindings --project DIR [--json]" - ), + usage=f"{get_command_prefix()} verify-bindings --project DIR [--json]", ) profile_verify.add_argument("--project", default=".") profile_verify.add_argument("--json", action="store_true") args = parser.parse_args(argv) command = args.command + try: - if command == "profile" and args.profile_command == "generate": + if command == "generate": return run_profile_generate(args) - if command == "profile" and args.profile_command == "verify-bindings": + if command == "verify-bindings": return run_profile_verify_bindings(args) except RuntimeConditionsError as exc: if getattr(args, "json", False): diff --git a/runtimeconditions_profiler/project/verify.py b/runtimeconditions_profiler/project/verify.py index 93282b3..be505f7 100644 --- a/runtimeconditions_profiler/project/verify.py +++ b/runtimeconditions_profiler/project/verify.py @@ -398,7 +398,8 @@ def verify(self, discovery: InstalledBindingDiscoveryResult) -> VerifiedBindingS if not discovery.packages: raise RuntimeConditionsError( "no installed generated binding imports found in workload. " - "Install the generated binding package and import it in your Python source files." + "Ensure the required generated binding packages are installed " + "and imported in your Python source files." ) schemas = _schemas() pending = list(discovery.packages) diff --git a/tests/test_installed_binding_discovery.py b/tests/test_installed_binding_discovery.py index 7570f5e..5a3a317 100644 --- a/tests/test_installed_binding_discovery.py +++ b/tests/test_installed_binding_discovery.py @@ -121,7 +121,7 @@ def test_missing_package_resource_fails_before_profile_output( status = cli.main( [ - "profile", "generate", "--project", str(workload), "--name", "sample", + "generate", "--project", str(workload), "--name", "sample", "--workload-uri", "example/sample", "--workload-version", "1", "--out", str(output), ] ) @@ -142,7 +142,7 @@ def test_profile_command_rejects_placeholder_core_identity( status = cli.main( [ - "profile", "generate", "--project", str(workload), "--name", "sample", + "generate", "--project", str(workload), "--name", "sample", "--workload-uri", "example/sample", "--workload-version", "1", "--out", str(output), ] ) @@ -163,7 +163,7 @@ def test_profile_command_reports_unresolved_declaration_without_writing_output( set_distributions(monkeypatch, verified_distribution(tmp_path)) output = tmp_path / "profile.yaml" status = cli.main([ - "profile", "generate", "--project", str(workload), "--name", "sample", + "generate", "--project", str(workload), "--name", "sample", "--workload-uri", "example/sample", "--workload-version", "1", "--out", str(output), ]) assert status == 1 @@ -364,7 +364,7 @@ def test_installed_cli_verifies_binding_from_unrelated_workload( (workload / "app.py").write_text("import example_binding as binding\n") record = verified_distribution(tmp_path) set_distributions(monkeypatch, record) - assert cli.main(["profile", "verify-bindings", "--project", str(workload), "--json"]) == 0 + assert cli.main(["verify-bindings", "--project", str(workload), "--json"]) == 0 output = json.loads(capsys.readouterr().out) assert output["packages"][0]["distribution"] == "example-binding" assert output["packages"][0]["extensionId"] == "https://example.test/extension:1.0.0" @@ -439,7 +439,7 @@ def test_unlisted_import_fails_before_profile_output( set_distributions(monkeypatch, record) output = tmp_path / "profile.yaml" status = cli.main([ - "profile", "generate", "--project", str(workload), "--name", "sample", + "generate", "--project", str(workload), "--name", "sample", "--workload-uri", "example/sample", "--workload-version", "1", "--out", str(output), ]) assert status == 1 @@ -852,7 +852,7 @@ def test_cli_writes_validated_profile_and_preserves_existing_output_on_failure( monkeypatch.setattr(cli, "verified_installed_bindings", lambda project: bindings) output = tmp_path / "profile.yaml" args = [ - "profile", "generate", "--project", str(workload), "--name", "sample", + "generate", "--project", str(workload), "--name", "sample", "--workload-uri", "example/sample", "--workload-version", "1", "--out", str(output), ] assert cli.main(args) == 0 @@ -885,7 +885,7 @@ def fail_replace(source: Path, destination: Path) -> None: monkeypatch.setattr(cli.os, "replace", fail_replace) status = cli.main([ - "profile", "generate", "--project", str(workload), "--name", "sample", + "generate", "--project", str(workload), "--name", "sample", "--workload-uri", "example/sample", "--workload-version", "1", "--out", str(output), ]) assert status == 1 @@ -922,13 +922,11 @@ def generated_profile(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, args: lis SERVICE = "import example_binding as b\nb.service(b.Http())\n" -def test_the_profile_prefix_is_optional_so_rc_can_pass_subcommands_straight_through( +def test_cli_accepts_subcommands_directly_as_rc_passes_them_through( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - with_prefix = generated_profile(tmp_path, monkeypatch, ["profile", "generate"], SERVICE, "a") - without = generated_profile(tmp_path, monkeypatch, ["generate"], SERVICE, "b") - assert with_prefix == without and "kind: service" in with_prefix - + profile = generated_profile(tmp_path, monkeypatch, ["generate"], SERVICE) + assert "kind: service" in profile def test_the_workload_version_is_optional_and_left_out_when_not_given(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: without = yaml.safe_load(generated_profile(tmp_path, monkeypatch, ["generate"], SERVICE, "a")) @@ -992,7 +990,8 @@ def test_generate_json_returns_structured_error( "stage": "profile", "message": ( "no installed generated binding imports found in workload. " - "Install the generated binding package and import it in your Python source files." + "Ensure the required generated binding packages are installed " + "and imported in your Python source files." ), } }