Files
github-action/tests/workflow_source.py
T
Tirsvad c4bbea4a2b
Validate workflows / validate (pull_request) Successful in 12s
Make the wiki publisher a scoped workflow with an opt-in gate
Embed the publish script in .gitea/scoped_workflows/publish-wiki.yml and
remove the repository workflow and tools/publish_wiki.py. A repository
publishes only when wiki/.publish exists; the word prune in it is the only
thing that lets the workflow delete pages. The organisation's
TOKEN_FOR_GITEA_WIKI is used with no fallback. This repository opts in with
prune. Tests run the embedded script against a fake Gitea.

Task: MIL-006#2
Task: MIL-006#3
2026-10-10 11:39:11 +08:00

71 lines
2.3 KiB
Python

"""Helpers that read workflow files and the Python embedded in them."""
import re
import textwrap
from pathlib import Path
from typing import Any
REPO_ROOT = Path(__file__).resolve().parent.parent
WORKFLOW_DIRS = (
REPO_ROOT / ".gitea" / "scoped_workflows",
REPO_ROOT / ".gitea" / "workflows",
)
SYNC_WORKFLOW = WORKFLOW_DIRS[0] / "sync-github-metadata.yml"
PUBLISH_WORKFLOW = WORKFLOW_DIRS[0] / "publish-wiki.yml"
_HEREDOC = re.compile(
r"^[ \t]*python3 - <<'PY'\r?\n(?P<code>.*?)^[ \t]*PY[ \t]*\r?$",
re.DOTALL | re.MULTILINE,
)
def workflow_files() -> list[Path]:
"""Return every workflow file in the known workflow directories."""
files: list[Path] = []
for directory in WORKFLOW_DIRS:
if directory.is_dir():
files += sorted(directory.glob("*.yml")) + sorted(directory.glob("*.yaml"))
return files
def embedded_python(path: Path) -> list[str]:
"""Return the source of each `python3 - <<'PY'` heredoc in a workflow."""
text = path.read_text(encoding="utf-8")
return [
textwrap.dedent(match.group("code").replace("\r\n", "\n"))
for match in _HEREDOC.finditer(text)
]
def load_sync_module(name: str = "embedded_sync") -> dict[str, Any]:
"""Execute the embedded sync script without running `main`."""
(source,) = embedded_python(SYNC_WORKFLOW)
namespace: dict[str, Any] = {"__name__": name}
exec(compile(source, str(SYNC_WORKFLOW), "exec"), namespace)
return namespace
class ScriptNamespace(dict):
"""The globals of an embedded script, readable and writable as attributes.
Functions of the script look names up in this dict, so a test that sets
`namespace.request_json = fake` changes what the script calls.
"""
def __getattr__(self, name: str) -> Any:
try:
return self[name]
except KeyError:
raise AttributeError(name) from None
def __setattr__(self, name: str, value: Any) -> None:
self[name] = value
def load_publish_module(name: str = "embedded_publish") -> ScriptNamespace:
"""Execute the embedded publish script without running `main`."""
(source,) = embedded_python(PUBLISH_WORKFLOW)
namespace = ScriptNamespace({"__name__": name})
exec(compile(source, str(PUBLISH_WORKFLOW), "exec"), namespace)
return namespace