-
Notifications
You must be signed in to change notification settings - Fork 129
feat: ops.testing autoload support for charmcraft extensions #2367
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
tonyandrewmeyer
merged 20 commits into
canonical:main
from
tonyandrewmeyer:autoload-paas-charm
Mar 12, 2026
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
241dfff
feat: autoload support for charmcraft extensions
tonyandrewmeyer 7fb5c23
Load extension list from charmcraft.
tonyandrewmeyer 1ea90f8
Improve the type annotations.
tonyandrewmeyer ff2140a
Don't lazy import.
tonyandrewmeyer 04a296d
Make the warning more user-focused.
tonyandrewmeyer 85bc524
Make the warning more user-focused.
tonyandrewmeyer 48359d6
Remove unnecessary skip.
tonyandrewmeyer 6177283
Minor cleanup.
tonyandrewmeyer 1f46d6b
Also update the docs.
tonyandrewmeyer 572a70f
Avoid 'autoload'.
tonyandrewmeyer 44103c0
Apply suggestion from @james-garner-canonical
tonyandrewmeyer 88853be
Suggestion from review.
tonyandrewmeyer c064515
Apply suggestions from code review
tonyandrewmeyer 174601a
Apply suggestion from @james-garner-canonical
tonyandrewmeyer c95768b
More closely match the charmcraft behaviour of clashing values.
tonyandrewmeyer b173a90
Address review comments.
tonyandrewmeyer 9b19669
More refiew adjustments.
tonyandrewmeyer 235cbc2
Add an explicit else as per code review.
tonyandrewmeyer 6a99e9b
Merge remote-tracking branch 'origin/main' into autoload-paas-charm
tonyandrewmeyer 3a633db
Scenario tests get type checked now :)
tonyandrewmeyer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| #!/usr/bin/env -S uv run --script --no-project | ||
| # /// script | ||
| # requires-python = ">=3.10" | ||
| # dependencies = ["pyyaml"] | ||
| # /// | ||
|
|
||
| # Copyright 2026 Canonical Ltd. | ||
| # See LICENSE file for licensing details. | ||
|
|
||
| """Generate testing/src/scenario/_charmcraft_extensions.py. | ||
|
|
||
| For each charmcraft extension profile (django-framework, fastapi-framework, etc.), | ||
| this script runs `charmcraft init` and `charmcraft expand-extensions` in a temp | ||
| directory, then extracts the metadata, config, and actions that the extension adds. | ||
|
|
||
| The output module contains three dictionaries per extension: | ||
| METADATA: dict[str, dict] - containers, peers, provides, requires, resources, assumes | ||
| CONFIG: dict[str, dict] - config options added by each extension | ||
| ACTIONS: dict[str, dict] - actions added by each extension | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import pathlib | ||
| import subprocess | ||
| import sys | ||
| import tempfile | ||
| from typing import Any | ||
|
|
||
| import yaml | ||
|
|
||
| # Keys from the expanded YAML that belong to "metadata" (the charm's metadata.yaml equivalent). | ||
| METADATA_KEYS = { | ||
| 'assumes', | ||
| 'containers', | ||
| 'peers', | ||
| 'provides', | ||
| 'requires', | ||
| 'resources', | ||
| } | ||
|
|
||
| # Keys that are user-provided or build-related (not extension-contributed metadata). | ||
| IGNORED_KEYS = { | ||
| 'name', | ||
| 'summary', | ||
| 'description', | ||
| 'type', | ||
| 'bases', | ||
| 'base', | ||
| 'platforms', | ||
| 'extensions', | ||
| 'parts', | ||
| 'charm-libs', | ||
| } | ||
|
|
||
| OUTPUT_FILE = ( | ||
| pathlib.Path(__file__).resolve().parent.parent | ||
| / 'testing' | ||
| / 'src' | ||
| / 'scenario' | ||
| / '_charmcraft_extensions.py' | ||
| ) | ||
|
|
||
|
|
||
| def get_extensions() -> list[str]: | ||
| """Get the list of available charmcraft extensions via ``charmcraft list-extensions``.""" | ||
| result = subprocess.check_output(['charmcraft', 'list-extensions'], text=True) | ||
| extensions = [] | ||
| for line in result.splitlines(): | ||
| # Skip header and separator lines. | ||
| if not line or line.startswith('Extension') or line.startswith('---'): | ||
| continue | ||
| name = line.split()[0] | ||
| extensions.append(name) | ||
| return sorted(extensions) | ||
|
|
||
|
|
||
| def run_charmcraft(profile: str, workdir: pathlib.Path) -> dict[str, Any]: | ||
| """Run charmcraft init + expand-extensions and return the expanded YAML as a dict.""" | ||
| subprocess.check_call( | ||
| ['charmcraft', 'init', '--profile', profile, '--name', 'test-charm'], | ||
| cwd=workdir, | ||
| ) | ||
| output = subprocess.check_output( | ||
| ['charmcraft', 'expand-extensions'], | ||
| cwd=workdir, | ||
| text=True, | ||
| ) | ||
| return yaml.safe_load(output) | ||
|
|
||
|
|
||
| def extract_extension_data( | ||
| expanded: dict[str, Any], | ||
| ) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: | ||
| """Extract metadata, config options, and actions from expanded charmcraft YAML.""" | ||
| metadata = {key: expanded[key] for key in METADATA_KEYS if key in expanded} | ||
| config = expanded.get('config', {}).get('options', {}) | ||
| actions: dict[str, Any] = expanded.get('actions', {}) | ||
|
|
||
| return metadata, config, actions | ||
|
|
||
|
|
||
| def generate_module( | ||
| all_data: dict[str, tuple[dict[str, Any], dict[str, Any], dict[str, Any]]], | ||
| ) -> str: | ||
| """Generate the Python module source code.""" | ||
| lines = [ | ||
| '# Copyright 2026 Canonical Ltd.', | ||
| '# See LICENSE file for licensing details.', | ||
| '"""Charmcraft extension metadata, config, and actions.', | ||
| '', | ||
| 'Auto-generated by .github/generate_charmcraft_extensions.py', | ||
| 'Do not edit manually.', | ||
| '"""', | ||
| '', | ||
| 'from __future__ import annotations', | ||
| '', | ||
| 'from typing import Any, TypedDict', | ||
| '', | ||
| '', | ||
| 'class _ExtensionMetadata(TypedDict, total=False):', | ||
| ' assumes: list[str]', | ||
| ' containers: dict[str, Any]', | ||
| ' peers: dict[str, Any]', | ||
| ' provides: dict[str, Any]', | ||
| ' requires: dict[str, Any]', | ||
| ' resources: dict[str, Any]', | ||
| '', | ||
| '', | ||
| ] | ||
|
|
||
| # Build the three top-level dicts, pre-sorting keys. | ||
| metadata_entries: dict[str, dict[str, Any]] = {} | ||
| config_entries: dict[str, dict[str, Any]] = {} | ||
| action_entries: dict[str, dict[str, Any]] = {} | ||
| for profile, (metadata, config, actions) in sorted(all_data.items()): | ||
| metadata_entries[profile] = {k: metadata[k] for k in sorted(metadata)} | ||
| config_entries[profile] = {k: config[k] for k in sorted(config)} | ||
| action_entries[profile] = {k: actions[k] for k in sorted(actions)} | ||
|
|
||
| for var_name, data, type_str, doc_name in [ | ||
| ('METADATA', metadata_entries, 'dict[str, _ExtensionMetadata]', 'Metadata'), | ||
| ('CONFIG', config_entries, 'dict[str, dict[str, Any]]', 'Config options'), | ||
| ('ACTIONS', action_entries, 'dict[str, dict[str, Any]]', 'Actions'), | ||
| ]: | ||
| lines.append(f'# {doc_name} added by each charmcraft extension.') | ||
| lines.append(f'{var_name}: {type_str} = {data!r}') | ||
| lines.append('') | ||
|
|
||
| return '\n'.join(lines) | ||
|
|
||
|
|
||
| def main() -> int: # noqa: D103 | ||
| extensions = get_extensions() | ||
| print(f'Found extensions: {", ".join(extensions)}') | ||
|
|
||
| all_data: dict[str, tuple[dict[str, Any], dict[str, Any], dict[str, Any]]] = {} | ||
|
|
||
| for profile in extensions: | ||
| print(f'Processing {profile}...') | ||
| with tempfile.TemporaryDirectory() as tmpdir: | ||
| expanded = run_charmcraft(profile, pathlib.Path(tmpdir)) | ||
| all_data[profile] = extract_extension_data(expanded) | ||
|
|
||
| module_source = generate_module(all_data) | ||
| OUTPUT_FILE.write_text(module_source) | ||
| print(f'Written to {OUTPUT_FILE}') | ||
|
|
||
| print('Running tox -e format...') | ||
| subprocess.run( | ||
| ['tox', '-e', 'format', '--', str(OUTPUT_FILE)], | ||
| cwd=OUTPUT_FILE.parent, | ||
| check=True, | ||
| ) | ||
|
|
||
| return 0 | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| sys.exit(main()) | ||
|
tonyandrewmeyer marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.