Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions CONFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down
58 changes: 46 additions & 12 deletions runtimeconditions_profiler/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,27 @@
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:
usage = USAGE.replace(NAME, get_command_prefix())
self.exit(
2,
f"usage: {usage}\n"
f"runtimeconditions: error: {message}\n",
)

USAGE = (
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]"
)

def get_command_prefix() -> str:
return os.environ.get("RC_COMMAND_PREFIX", NAME)

def version() -> str:
try:
return metadata.version("runtimeconditions-profiler")
Expand All @@ -35,36 +53,52 @@ 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]
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 = subparsers.add_parser(
"generate",
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)
profile_generate.add_argument("--workload-uri", required=True)
profile_generate.add_argument("--workload-version")
profile_generate.add_argument("--out")
profile_verify = profile_commands.add_parser(
profile_generate.add_argument("--json", action="store_true")

profile_verify = subparsers.add_parser(
"verify-bindings",
help="verify installed generated bindings without running application or binding code",
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:
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

Expand Down
13 changes: 12 additions & 1 deletion runtimeconditions_profiler/errors.py
Original file line number Diff line number Diff line change
@@ -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]}"
10 changes: 8 additions & 2 deletions runtimeconditions_profiler/project/installed.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 5 additions & 1 deletion runtimeconditions_profiler/project/verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,11 @@ 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. "
"Ensure the required generated binding packages are installed "
"and imported in your Python source files."
)
schemas = _schemas()
pending = list(discovery.packages)
verified: dict[str, VerifiedBindingPackage] = {}
Expand Down
69 changes: 57 additions & 12 deletions tests/test_installed_binding_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
]
)
Expand All @@ -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),
]
)
Expand All @@ -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
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"))
Expand Down Expand Up @@ -975,3 +973,50 @@ 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. "
"Ensure the required generated binding packages are installed "
"and imported 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)