Compare commits

...

2 Commits

12 changed files with 185 additions and 25 deletions
+63
View File
@@ -0,0 +1,63 @@
"""Require every submodule commit of the candidate to be on its repository's `dev` branch.
Reads the gitlinks from the index, so it runs on the merged candidate before it is committed, and descends into each
initialized submodule. A commit that `origin/dev` of its repository doesn't contain fails the run: the pull request
that moves a submodule goes in after the submodule's own pull request into `dev`.
"""
import subprocess
import sys
from pathlib import Path
BRANCH = "dev"
REMOTE_REF = "refs/remotes/origin/ci-dev"
def git(repo, *args, check=True):
return subprocess.run(["git", "-C", str(repo), *args], check=check, capture_output=True, text=True)
def gitlinks(repo):
"""Path and commit of each submodule the index records."""
found = {}
for line in git(repo, "ls-files", "--stage").stdout.splitlines():
metadata, path = line.split("\t", 1)
mode, sha, _ = metadata.split(" ")
if mode == "160000":
found[path] = sha
return found
def off_dev(repo, prefix=""):
"""The submodules, at any depth, whose recorded commit isn't on their `dev`, each with the reason."""
problems = []
for path, sha in sorted(gitlinks(repo).items()):
full = f"{prefix}/{path}" if prefix else path
child = repo / path
if not (child / ".git").exists():
problems.append(f"{full}: not initialized")
continue
if git(child, "fetch", "--no-recurse-submodules", "origin", f"refs/heads/{BRANCH}:{REMOTE_REF}",
check=False).returncode:
problems.append(f"{full}: its repository has no {BRANCH} branch to compare with")
continue
if git(child, "merge-base", "--is-ancestor", sha, REMOTE_REF, check=False).returncode:
problems.append(f"{full}: {sha} is not on {BRANCH}")
continue
print(f"{full}: {sha} is on {BRANCH}")
problems += off_dev(child, full)
return problems
def main():
problems = off_dev(Path.cwd())
for problem in problems:
print(problem, file=sys.stderr)
if problems:
print(f"Merge each submodule's pull request into {BRANCH} first, then point this one at that commit.",
file=sys.stderr)
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main())
+11 -5
View File
@@ -5,22 +5,24 @@ import subprocess
import sys
from pathlib import Path
CHECKS = ("Core", "Persistance", "Extraction", "Transformation", "models", "indicadores_kit", "WebApi", "WebApp")
CHECKS = ("Core", "Persistance", "Extraction", "Transformation", "models", "WebApi", "WebApp")
IMPACT = {
"Core": {"Core", "Persistance", "Transformation", "models", "indicadores_kit", "WebApi"},
"Persistance": {"Persistance", "Transformation", "models", "indicadores_kit", "WebApi"},
"Core": {"Core", "Persistance", "Transformation", "models", "WebApi"},
"Persistance": {"Persistance", "Transformation", "models", "WebApi"},
"Extraction": {"Extraction", "models", "WebApi"},
"Transformation": {"Transformation", "Persistance", "models", "WebApi"},
"models": {"models", "WebApi"},
"indicadores_kit": {"indicadores_kit", "WebApi"},
"WebApi": {"WebApi"},
"WebApp": {"WebApp"},
}
# Submodules that left the tree for good: removing one runs every check; anything else about it still fails.
RETIRED_SUBMODULES = {"ISSSTELEON/indicadores_kit"}
DEPLOY_FILES = {".gitea/deploy/dev.py", ".gitea/deploy/host.py", ".gitea/deploy/test_dev.py",
".gitea/workflows/deploy-dev.yml", ".gitea/workflows/deploy-dev-diagnostic.yml"}
PROBE_FILES = {".gitea/probe/README.md", ".gitea/probe/docker_probe.py", ".gitea/probe/test_docker_probe.py",
".gitea/workflows/docker-persistence-probe.yml"}
CI_SELF_TESTED = {".gitea/ci/select.py", ".gitea/ci/test_select.py", ".gitea/workflows/ci.yml"}
CI_SELF_TESTED = {".gitea/ci/select.py", ".gitea/ci/test_select.py", ".gitea/ci/on_dev.py", ".gitea/ci/test_on_dev.py",
".gitea/workflows/ci.yml"}
def deploy_file(path):
@@ -55,6 +57,10 @@ def compare(repo, old, new, prefix, changed):
full = f"{prefix}/{path}" if prefix else path
if (left and left[0] == "160000") or (right and right[0] == "160000"):
print(f"Changed submodule: {full}: {left} -> {right}")
if full in RETIRED_SUBMODULES and left and left[0] == "160000" and right is None:
print(f"Retired submodule removed: {full}; every check runs")
changed.add(full)
continue
if not left or not right or left[0] != "160000" or right[0] != "160000":
raise RuntimeError(f"Submodule added, removed or replaced: {full}; manual CI mapping required")
child = repo / path
+68
View File
@@ -0,0 +1,68 @@
"""Check that a submodule commit outside its repository's `dev` branch fails the run.
Covers `on_dev.off_dev` over throwaway repositories: a parent with one submodule cloned from a local origin that has a
`dev` branch and a feature branch.
"""
import importlib.util
import subprocess
import tempfile
import unittest
from pathlib import Path
spec = importlib.util.spec_from_file_location("ci_on_dev", Path(__file__).with_name("on_dev.py"))
on_dev = importlib.util.module_from_spec(spec)
spec.loader.exec_module(on_dev)
def run(repo, *args):
return subprocess.check_output(["git", "-C", str(repo), "-c", "protocol.file.allow=always", *args],
stderr=subprocess.DEVNULL).decode().strip()
class OnDevTests(unittest.TestCase):
"""Pin down which recorded submodule commits pass."""
def setUp(self):
"""An origin with `dev` and a commit only on `feature`, and a parent whose submodule `child` is its clone."""
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
base = Path(self.temp.name)
self.origin, self.root = base / "origin", base / "root"
for repo in (self.origin, self.root):
repo.mkdir()
run(repo, "init", "-q", "-b", "dev")
run(repo, "config", "user.email", "ci@example.invalid")
run(repo, "config", "user.name", "CI")
(self.origin / "file").write_text("dev", encoding="utf-8")
run(self.origin, "add", "file")
run(self.origin, "commit", "-qm", "dev")
self.on_dev = run(self.origin, "rev-parse", "HEAD")
run(self.origin, "checkout", "-q", "-b", "feature")
(self.origin / "file").write_text("feature", encoding="utf-8")
run(self.origin, "commit", "-qam", "feature")
self.on_feature = run(self.origin, "rev-parse", "HEAD")
run(self.root, "clone", "-q", str(self.origin), "child")
def record(self, sha):
run(self.root, "update-index", "--add", "--cacheinfo", f"160000,{sha},child")
def test_a_commit_on_dev_passes(self):
"""A gitlink at a commit of `dev` reports nothing. Fails if the check rejects a merged submodule."""
self.record(self.on_dev)
self.assertEqual(on_dev.off_dev(self.root), [])
def test_a_commit_only_on_a_feature_branch_fails(self):
"""A gitlink at a commit that only a feature branch has is reported by path. Fails if the ancestry test is
dropped or compares against another branch."""
self.record(self.on_feature)
self.assertEqual(on_dev.off_dev(self.root), [f"child: {self.on_feature} is not on dev"])
def test_an_uninitialized_submodule_fails(self):
"""A gitlink without a checkout can't be verified, so it is reported. Fails if it is skipped as if on dev."""
run(self.root, "update-index", "--add", "--cacheinfo", f"160000,{self.on_dev},missing")
self.assertIn("missing: not initialized", on_dev.off_dev(self.root))
if __name__ == "__main__":
unittest.main()
+33 -1
View File
@@ -73,7 +73,7 @@ class SelectionTests(unittest.TestCase):
script = "\n".join(line[10:] for line in block.splitlines())
for outcome, expected in (("failure", 1), ("skipped", 1), ("success", 0)):
env = {**os.environ, "CORE": outcome, "CORE_REQUIRED": "true"}
for name in ("PERSISTANCE", "EXTRACTION", "TRANSFORMATION", "MODELS", "INDICADORES", "WEBAPI", "WEBAPP"):
for name in ("PERSISTANCE", "EXTRACTION", "TRANSFORMATION", "MODELS", "WEBAPI", "WEBAPP"):
env[name] = "skipped"
env[name + "_REQUIRED"] = "false"
result = subprocess.run([bash, "-c", script], env=env, capture_output=True, text=True)
@@ -103,6 +103,38 @@ class SelectionTests(unittest.TestCase):
with self.assertRaisesRegex(RuntimeError, "not initialized"):
selector.compare(root, old, new, "", set())
def test_only_a_retired_submodule_may_leave_the_tree(self):
"""Removing the retired kit's gitlink runs every check; removing any other gitlink still fails.
Fails if the removal of `ISSSTELEON/indicadores_kit` stops the selection again, or if the exception starts
covering a submodule that isn't in `RETIRED_SUBMODULES`."""
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
subprocess.run(["git", "init", "-q", str(root)], check=True)
for key, value in (("user.email", "ci@example.invalid"), ("user.name", "CI")):
subprocess.run(["git", "-C", str(root), "config", key, value], check=True)
(root / "file").write_text("a", encoding="utf-8")
subprocess.run(["git", "-C", str(root), "add", "file"], check=True)
subprocess.run(["git", "-C", str(root), "commit", "-qm", "base"], check=True)
sha = selector.git(root, "rev-parse", "HEAD").decode().strip()
for path in ("indicadores_kit", "models"):
subprocess.run(["git", "-C", str(root), "update-index", "--add", "--cacheinfo",
f"160000,{sha},{path}"], check=True)
subprocess.run(["git", "-C", str(root), "commit", "-qm", "links"], check=True)
linked = selector.git(root, "rev-parse", "HEAD").decode().strip()
commits = {}
for path in ("indicadores_kit", "models"):
subprocess.run(["git", "-C", str(root), "rm", "-q", "--cached", path], check=True)
subprocess.run(["git", "-C", str(root), "commit", "-qm", "without " + path], check=True)
commits[path] = selector.git(root, "rev-parse", "HEAD").decode().strip()
changed = set()
selector.compare(root, linked, commits["indicadores_kit"], "ISSSTELEON", changed)
self.assertEqual(changed, {"ISSSTELEON/indicadores_kit"})
self.assertEqual(selector.select(changed), set(selector.CHECKS))
self.assertNotIn("indicadores_kit", selector.CHECKS)
with self.assertRaisesRegex(RuntimeError, "ISSSTELEON/models"):
selector.compare(root, commits["indicadores_kit"], commits["models"], "ISSSTELEON", set())
def test_recursive_submodule_comparison(self):
"""Changes inside a gitlink are read from both fixed commits, including docs-only changes."""
with tempfile.TemporaryDirectory() as temp:
+1 -1
View File
@@ -10,7 +10,7 @@ import tempfile
import source
APPLICATION_COMPONENTS = {'Core', 'Persistance', 'Extraction', 'WebApi', 'WebApp', 'models', 'indicadores_kit'}
APPLICATION_COMPONENTS = {'Core', 'Persistance', 'Extraction', 'WebApi', 'WebApp', 'models'}
def safe_member(member):
+1 -2
View File
@@ -24,8 +24,7 @@ SAFE_PATH = re.compile(r'^/[A-Za-z0-9_./-]+$')
DOCKER_ROOT = Path('/srv/workingnarrative-dev')
DOMAINS = ('cacu', 'cama', 'tea', 'governance')
INSTALLER_FILES = {'install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'}
REQUIRED_LINKS = {'ISSSTELEON', 'ISSSTELEON/WebApi', 'ISSSTELEON/WebApp',
'ISSSTELEON/models', 'ISSSTELEON/indicadores_kit'}
REQUIRED_LINKS = {'ISSSTELEON', 'ISSSTELEON/WebApi', 'ISSSTELEON/WebApp', 'ISSSTELEON/models'}
def validate_record(record):
-1
View File
@@ -11,7 +11,6 @@ ORIGINS = {
'ISSSTELEON/WebApi': 'WebApi',
'ISSSTELEON/WebApp': 'WebApp',
'ISSSTELEON/models': 'models',
'ISSSTELEON/indicadores_kit': 'indicadores_kit',
}
SHA = re.compile(r'^[0-9a-f]{40}$')
+2 -2
View File
@@ -78,8 +78,8 @@ the selected commit. Builds still execute code from the application branch;
choose trusted code and retain existing Actions authorization.
The installer verifies the workflow event and checkout, then uses the exact
recursive application gitlinks. Supported paths are ISSSTELEON, WebApp, WebApi,
models and indicadores_kit at their institutional origins; unknown paths and
recursive application gitlinks. Supported paths are ISSSTELEON, WebApp, WebApi
and models at their institutional origins; unknown paths and
origins are rejected. `branch` and `revision` describe the application, while
`workflow_ref` and `workflow_sha` describe the installer. Older records remain
eligible; a verified same-SHA no-op records the new selection without rebuilding.
-1
View File
@@ -136,7 +136,6 @@ SUBMODULE_ORIGINS = {
'ISSSTELEON/WebApp': 'WebApp',
'ISSSTELEON/WebApi': 'WebApi',
'ISSSTELEON/models': 'models',
'ISSSTELEON/indicadores_kit': 'indicadores_kit',
}
+2 -2
View File
@@ -430,7 +430,7 @@ class SimulatedDeployment:
def pinned_manifest(self, repo, revision):
return {'ISSSTELEON': revision, 'WebApi': 'e' * 40, 'WebApp': 'f' * 40,
'models': '1' * 40, 'indicadores_kit': '2' * 40}
'models': '1' * 40}
def run(self, args, **kwargs):
args = list(map(str, args))
@@ -554,7 +554,7 @@ class UpdateTests(unittest.TestCase):
record = host.read_record(self.root)
self.assertEqual(record['result'], 'updated')
self.assertEqual(record['phase'], 'complete')
self.assertEqual(set(record['gitlinks']), {'ISSSTELEON', 'WebApi', 'WebApp', 'models', 'indicadores_kit'})
self.assertEqual(set(record['gitlinks']), {'ISSSTELEON', 'WebApi', 'WebApp', 'models'})
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), self.runtime.revision)
self.assertEqual((Path(record['archive']) / 'codigo' / 'version.txt').read_text(), 'old')
+3 -9
View File
@@ -59,6 +59,8 @@ jobs:
git submodule update --init --recursive -- ISSSTELEON
- name: Validate selection mechanism
run: python3 -m unittest discover -s .gitea/ci -p 'test_*.py' -v
- name: Require submodule commits on dev
run: python3 .gitea/ci/on_dev.py
- name: Select checks
id: select
run: python3 .gitea/ci/select.py '${{ steps.candidate.outputs.base }}' '${{ steps.candidate.outputs.tree }}'
@@ -130,12 +132,6 @@ jobs:
continue-on-error: true
working-directory: ISSSTELEON/models
run: uv run --python 3.12 pytest -q -rs
- name: indicadores_kit pytest
id: indicadores
if: steps.select.outputs.indicadores_kit == 'true'
continue-on-error: true
working-directory: ISSSTELEON/indicadores_kit
run: uv run --python 3.12 pytest -q -rs
- name: WebApi pytest
id: webapi
if: steps.select.outputs.WebApi == 'true'
@@ -163,7 +159,6 @@ jobs:
EXTRACTION: ${{ steps.extraction.outcome }}
TRANSFORMATION: ${{ steps.transformation.outcome }}
MODELS: ${{ steps.models.outcome }}
INDICADORES: ${{ steps.indicadores.outcome }}
WEBAPI: ${{ steps.webapi.outcome }}
WEBAPP: ${{ steps.webapp.outcome }}
CORE_REQUIRED: ${{ steps.select.outputs.Core }}
@@ -171,12 +166,11 @@ jobs:
EXTRACTION_REQUIRED: ${{ steps.select.outputs.Extraction }}
TRANSFORMATION_REQUIRED: ${{ steps.select.outputs.Transformation }}
MODELS_REQUIRED: ${{ steps.select.outputs.models }}
INDICADORES_REQUIRED: ${{ steps.select.outputs.indicadores_kit }}
WEBAPI_REQUIRED: ${{ steps.select.outputs.WebApi }}
WEBAPP_REQUIRED: ${{ steps.select.outputs.WebApp }}
run: |
failed=0
for name in CORE PERSISTANCE EXTRACTION TRANSFORMATION MODELS INDICADORES WEBAPI WEBAPP; do
for name in CORE PERSISTANCE EXTRACTION TRANSFORMATION MODELS WEBAPI WEBAPP; do
result=${!name:-skipped}
required_var=${name}_REQUIRED
required=${!required_var:-}