Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

CI policy: pin .yaml and quoted uses:, cover all of sim/, read paths with -z (Fixes #2664) (#2682)

Eyal Golande4a1ce960f5
diff --git a/scripts/oss/changelog_check.py b/scripts/oss/changelog_check.py
index f651b6a73..cb119ee74 100755
--- a/scripts/oss/changelog_check.py
+++ b/scripts/oss/changelog_check.py
@@ -15,9 +15,9 @@ import sys
from collections.abc import Sequence
# translations/ ships beside the content to every player (#1618, step 2); its README.md is not a language (TranslationLoader).
-USER_VISIBLE = ("content/", "translations/", "sim/Statecraft.Sim/", "sim/Statecraft.Cli/", "unity/Assets/",
+USER_VISIBLE = ("content/", "translations/", "sim/", "unity/Assets/",
"unity/ProjectSettings/", "unity/Packages/")
-NOT_USER_VISIBLE = ("unity/Assets/Tests/", "translations/README.md")
+NOT_USER_VISIBLE = ("sim/Statecraft.Sim.Tests/", "unity/Assets/Tests/", "translations/README.md")
FRAGMENTS = "changelog.d/"
@@ -52,15 +52,16 @@ def verdict(paths: list[str], skip_label: bool, fragments: Sequence[str] = ()) -
def changed_paths(base: str, head: str) -> list[str]:
- out = subprocess.run(["git", "diff", "--name-only", f"{base}...{head}"], capture_output=True, text=True, check=True)
- return [p for p in out.stdout.splitlines() if p]
+ out = subprocess.run(["git", "diff", "--name-only", "-z", f"{base}...{head}"], capture_output=True, text=True,
+ check=True)
+ return [p for p in out.stdout.split("\0") if p]
def added_fragments(base: str, head: str) -> list[str]:
"""Fragments the PR adds with an entry in them. An edited, renamed or deleted fragment does not count."""
- out = subprocess.run(["git", "diff", "--name-only", "--find-renames", "--diff-filter=A", f"{base}...{head}", "--",
- FRAGMENTS], capture_output=True, text=True, check=True)
- return [p for p in out.stdout.splitlines() if is_fragment(p) and has_entry(
+ out = subprocess.run(["git", "diff", "--name-only", "-z", "--find-renames", "--diff-filter=A",
+ f"{base}...{head}", "--", FRAGMENTS], capture_output=True, text=True, check=True)
+ return [p for p in out.stdout.split("\0") if p and is_fragment(p) and has_entry(
subprocess.run(["git", "show", f"{head}:{p}"], capture_output=True, text=True, check=True).stdout)]
diff --git a/scripts/oss/pin_actions.py b/scripts/oss/pin_actions.py
index 52cd97503..8273ed3ad 100755
--- a/scripts/oss/pin_actions.py
+++ b/scripts/oss/pin_actions.py
@@ -1,11 +1,11 @@
# /// script
# requires-python = ">=3.11"
-# dependencies = []
+# dependencies = ["pyyaml==6.0.3"]
# ///
-"""Pin every `uses: owner/repo@ref` in .github/workflows/*.yml to the ref's full commit SHA, keeping the ref as a
-trailing comment. Anything already after the ref on the line, such as a note of why that action is used, is kept
-after the ref. Resolves with a read-only `gh api` GET. A tag can be moved by its owner; a SHA cannot (no_human
-5f99b7af3: unpinned third-party downloads in the release build).
+"""Pin every `uses: owner/repo@ref` in .github/workflows/*.yml and *.yaml to the ref's full commit SHA, keeping the
+ref as a trailing comment. Anything already after the ref on the line, such as a note of why that action is used,
+is kept after the ref. Resolves with a read-only `gh api` GET. A tag can be moved by its owner; a SHA cannot
+(no_human 5f99b7af3: unpinned third-party downloads in the release build).
Usage: uv run scripts/oss/pin_actions.py"""
from __future__ import annotations
@@ -16,8 +16,16 @@ import sys
from pathlib import Path
from typing import Callable
+import yaml
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) # tools/yaml12.py
+import yaml12 # noqa: E402
+
ROOT = Path(__file__).resolve().parents[2]
-USES = re.compile(r"^(?P<lead>\s*-?\s*uses:\s*)(?P<action>[\w.-]+/[\w./-]+)@(?P<ref>[^\s#]+)(?P<rest>.*)$")
+USES = re.compile(
+ r"""^(?P<lead>\s*-?\s*(?P<kq>["']?)uses(?P=kq)\s*:\s*)(?P<quote>["']?)(?P<action>[\w.-]+/[\w./-]+)"""
+ r"""@(?P<ref>[^\s#'"]+)(?P=quote)(?P<rest>.*)$"""
+)
def gh_resolve(action: str, ref: str) -> str:
@@ -29,21 +37,58 @@ def gh_resolve(action: str, ref: str) -> str:
return out
+def workflow_paths(root: Path) -> list[Path]:
+ folder = root / ".github/workflows"
+ return sorted((*folder.glob("*.yml"), *folder.glob("*.yaml")))
+
+
+def _uses_by_line(text: str) -> dict[int, str]:
+ """Return parsed scalar `uses` values keyed by their zero-based source line."""
+ found: dict[int, str] = {}
+ seen: set[int] = set()
+
+ def walk(node: yaml.nodes.Node) -> None:
+ # An alias can make the composed node graph share nodes (or even contain a cycle).
+ if id(node) in seen:
+ return
+ seen.add(id(node))
+ if isinstance(node, yaml.nodes.MappingNode):
+ for key, value in node.value:
+ if (isinstance(key, yaml.nodes.ScalarNode) and key.value == "uses"
+ and isinstance(value, yaml.nodes.ScalarNode)
+ and value.tag == "tag:yaml.org,2002:str"):
+ found[value.start_mark.line] = value.value
+ walk(value)
+ elif isinstance(node, yaml.nodes.SequenceNode):
+ for value in node.value:
+ walk(value)
+
+ document = yaml.compose(text, Loader=yaml12.Core12Loader) # YAML 1.2 tags, as tools/yaml12.py (#601)
+ if document is not None:
+ walk(document)
+ return found
+
+
def pin_text(text: str, resolve: Callable[[str, str], str]) -> str:
+ parsed_uses = _uses_by_line(text)
lines = []
- for line in text.splitlines(keepends=True):
+ for line_number, line in enumerate(text.splitlines(keepends=True)):
m = USES.match(line.rstrip("\n"))
- if m and not re.fullmatch(r"[0-9a-f]{40}", m["ref"]):
+ value = f"{m['action']}@{m['ref']}" if m else None
+ if (m and parsed_uses.get(line_number) == value
+ and not re.fullmatch(r"[0-9a-f]{40}", m["ref"])):
sha = resolve(m["action"], m["ref"])
# Whatever already followed the ref is kept after it, so a note on the line survives the pin (#1463).
kept = m["rest"].strip()
- line = f"{m['lead']}{m['action']}@{sha} # {m['ref']}{' ' + kept if kept else ''}\n"
+ quote = m["quote"]
+ line = (f"{m['lead']}{quote}{m['action']}@{sha}{quote} # {m['ref']}"
+ f"{' ' + kept if kept else ''}\n")
lines.append(line)
return "".join(lines)
def main() -> int:
- for wf in sorted((ROOT / ".github/workflows").glob("*.yml")):
+ for wf in workflow_paths(ROOT):
before = wf.read_text(encoding="utf-8")
after = pin_text(before, gh_resolve)
if after != before:
diff --git a/scripts/oss/tests/test_changelog_check.py b/scripts/oss/tests/test_changelog_check.py
index e39d1959c..80bd5fe24 100644
--- a/scripts/oss/tests/test_changelog_check.py
+++ b/scripts/oss/tests/test_changelog_check.py
@@ -1,5 +1,5 @@
import changelog_check as cc
-from conftest import commit_all
+from conftest import commit_all, git
def test_user_visible_change_without_changelog_fails_and_names_the_paths():
@@ -22,7 +22,8 @@ def test_tests_docs_tools_and_ci_need_no_entry():
def test_every_user_visible_root_is_named():
- for p in ("content/people.yaml", "sim/Statecraft.Sim/Rng.cs", "sim/Statecraft.Cli/Program.cs",
+ for p in ("content/people.yaml", "sim/Directory.Build.props", "sim/Statecraft.Sim/Rng.cs",
+ "sim/Statecraft.Cli/Program.cs",
"unity/Assets/UI/Game.uxml", "unity/ProjectSettings/ProjectSettings.asset", "unity/Packages/manifest.json",
"translations/he/events.yaml", "translations/ro/ui.yaml"):
assert cc.user_visible([p]) == [p], p
@@ -107,3 +108,23 @@ def test_a_changelog_line_still_passes_end_to_end(make_repo, capsys, monkeypatch
root, base, head = _pr(make_repo, {"content/a.yaml": "a: 1\n", "CHANGELOG.md": "## [Unreleased]\n"},
{"content/a.yaml": "a: 2\n", "CHANGELOG.md": "## [Unreleased]\n- Content: a is 2.\n"})
assert _run(root, base, head, capsys, monkeypatch) == (0, "CHANGELOG.md is updated.\n")
+
+
+def test_a_git_quoted_user_visible_path_fails_closed(make_repo, capsys, monkeypatch):
+ path = "content/אירוע.yaml"
+ root, base, head = _pr(make_repo, {path: "a: 1\n"}, {path: "a: 2\n"})
+ git(root, "config", "core.quotePath", "true")
+
+ code, out = _run(root, base, head, capsys, monkeypatch)
+ assert code == 1 and path in out
+
+
+def test_a_git_quoted_fragment_path_satisfies_the_rule(make_repo, capsys, monkeypatch):
+ fragment = "changelog.d/שינוי.md"
+ root, base, head = _pr(make_repo, {"content/a.yaml": "a: 1\n"},
+ {"content/a.yaml": "a: 2\n", fragment: "- Content: a is 2.\n"})
+ git(root, "config", "core.quotePath", "true")
+
+ assert _run(root, base, head, capsys, monkeypatch) == (
+ 0, f"A changelog fragment is added: {fragment}\n"
+ )
diff --git a/scripts/oss/tests/test_github_config.py b/scripts/oss/tests/test_github_config.py
index 48d2adc08..b95ee0bd1 100644
--- a/scripts/oss/tests/test_github_config.py
+++ b/scripts/oss/tests/test_github_config.py
@@ -8,6 +8,8 @@ from pathlib import Path
import pytest
import yaml
+import pin_actions
+
ROOT = Path(__file__).resolve().parents[3]
CI = ROOT / ".github/workflows/ci.yml"
RULESET = ROOT / "scripts/oss/github/ruleset-main-review.json"
@@ -64,16 +66,61 @@ SECRET_WORKFLOWS = {"steam-upload.yml"}
def test_the_secret_exception_names_only_steam_upload():
- users = {wf.name for wf in (ROOT / ".github/workflows").glob("*.yml") if "secrets." in wf.read_text(encoding="utf-8")}
+ users = {wf.name for wf in pin_actions.workflow_paths(ROOT) if "secrets." in wf.read_text(encoding="utf-8")}
assert users <= SECRET_WORKFLOWS, users
-def test_every_action_is_pinned_to_a_full_sha():
- for wf in (ROOT / ".github/workflows").glob("*.yml"):
- for ref in re.findall(r"uses:\s*[\w.-]+/[\w./-]+@(\S+)", wf.read_text(encoding="utf-8")):
+def _uses_values(node):
+ # Every value of a `uses` key in the parsed workflow (steps and reusable-workflow jobs), however the YAML is quoted;
+ # text in comments or run: blocks is not a key and is not read.
+ if isinstance(node, dict):
+ for key, value in node.items():
+ if key == "uses" and isinstance(value, str):
+ yield value
+ yield from _uses_values(value)
+ elif isinstance(node, list):
+ for item in node:
+ yield from _uses_values(item)
+
+
+def _assert_every_action_is_pinned(root: Path) -> None:
+ for wf in pin_actions.workflow_paths(root):
+ for uses in _uses_values(yaml.safe_load(wf.read_text(encoding="utf-8"))):
+ if uses.startswith(("./", "docker://")):
+ continue # local and docker actions are not pinned (pin_actions.USES needs owner/repo@ref)
+ ref = uses.partition("@")[2]
assert re.fullmatch(r"[0-9a-f]{40}", ref), f"{wf.name}: {ref}"
+def test_every_action_is_pinned_to_a_full_sha():
+ _assert_every_action_is_pinned(ROOT)
+
+
+def test_action_assertion_checks_quoted_uses_in_yaml(tmp_path):
+ workflow = tmp_path / ".github/workflows/check.yaml"
+ workflow.parent.mkdir(parents=True)
+ workflow.write_text('steps:\n - uses: "actions/checkout@v4"\n', encoding="utf-8")
+
+ with pytest.raises(AssertionError, match=r"check\.yaml: v4"):
+ _assert_every_action_is_pinned(tmp_path)
+
+ workflow.write_text(f'steps:\n - uses: "actions/checkout@{"a" * 40}"\n', encoding="utf-8")
+ _assert_every_action_is_pinned(tmp_path)
+
+
+def test_action_assertion_reads_a_quoted_key_but_not_comments_or_run_text(tmp_path):
+ workflow = tmp_path / ".github/workflows/check.yml"
+ workflow.parent.mkdir(parents=True)
+ workflow.write_text('steps:\n - "uses": "actions/checkout@v4"\n', encoding="utf-8")
+ with pytest.raises(AssertionError, match=r"check\.yml: v4"):
+ _assert_every_action_is_pinned(tmp_path)
+
+ workflow.write_text('jobs:\n a:\n steps:\n # uses: actions/checkout@v4\n'
+ ' - run: |\n echo "uses: actions/checkout@v4"\n - uses: ./local-action\n',
+ encoding="utf-8")
+ _assert_every_action_is_pinned(tmp_path)
+
+
def test_tools_job_installs_dotnet():
# Review C2: tools/tests/test_package_release.py runs the sim's release gate through dotnet.
tools = next(j for j in ci()["jobs"].values() if j["name"] == "Tools (pytest)")
diff --git a/scripts/oss/tests/test_pin_actions.py b/scripts/oss/tests/test_pin_actions.py
index 3502ab407..d5b68b20b 100644
--- a/scripts/oss/tests/test_pin_actions.py
+++ b/scripts/oss/tests/test_pin_actions.py
@@ -28,3 +28,51 @@ def test_trailing_whitespace_after_the_ref_does_not_become_a_comment():
text = " - uses: actions/checkout@v4 \n"
out = pin_actions.pin_text(text, lambda repo, ref: SHA)
assert out == f" - uses: actions/checkout@{SHA} # v4\n"
+
+
+def test_quoted_uses_are_pinned_and_keep_their_quotes():
+ for quote in ('"', "'"):
+ text = f" - uses: {quote}actions/checkout@v4{quote}\n"
+ out = pin_actions.pin_text(text, lambda repo, ref: SHA)
+ assert out == f" - uses: {quote}actions/checkout@{SHA}{quote} # v4\n"
+
+
+def test_main_pins_yaml_workflows(tmp_path, monkeypatch):
+ workflow = tmp_path / ".github/workflows/check.yaml"
+ workflow.parent.mkdir(parents=True)
+ workflow.write_text("steps:\n - uses: actions/checkout@v4\n", encoding="utf-8")
+ monkeypatch.setattr(pin_actions, "ROOT", tmp_path)
+ monkeypatch.setattr(pin_actions, "gh_resolve", lambda repo, ref: SHA)
+
+ assert pin_actions.main() == 0
+ assert workflow.read_text(encoding="utf-8") == f"steps:\n - uses: actions/checkout@{SHA} # v4\n"
+
+
+def test_a_quoted_uses_key_is_pinned():
+ text = ' - "uses": actions/checkout@v4\n'
+ assert pin_actions.pin_text(text, lambda repo, ref: SHA) == f' - "uses": actions/checkout@{SHA} # v4\n'
+
+
+def test_quoted_uses_keys_allow_separation_before_the_colon():
+ for quote in ('"', "'"):
+ text = f" - {quote}uses{quote} : actions/checkout@v4\n"
+ expected = f" - {quote}uses{quote} : actions/checkout@{SHA} # v4\n"
+ assert pin_actions.pin_text(text, lambda repo, ref: SHA) == expected
+
+
+def test_block_scalar_uses_text_is_not_pinned_or_resolved():
+ text = ("steps:\n"
+ " - uses: actions/checkout@v4\n"
+ " - run: |\n"
+ " cat <<'YAML'\n"
+ " uses: actions/checkout@v4\n"
+ " YAML\n")
+ resolved = []
+
+ def resolve(repo, ref):
+ resolved.append((repo, ref))
+ return SHA
+
+ assert pin_actions.pin_text(text, resolve) == text.replace(
+ " - uses: actions/checkout@v4\n", f" - uses: actions/checkout@{SHA} # v4\n")
+ assert resolved == [("actions/checkout", "v4")]