build(gitea): reconstruct tests packaging images and release lanes (Refs #1)
This commit is contained in:
1 parent
21f0530b6c
commit
ad2a582b63
43 files changed
+10898
-646
No files matched your search
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -qq
|
||||
apt-get install -y --no-install-recommends ca-certificates curl git nodejs python3 unzip postgresql-client docker.io docker-compose-v2
|
||||
# Fail explicitly if a runner cannot provide the required Docker build service.
|
||||
docker version --format '{{.Server.Version}}'
|
||||
docker compose version
|
||||
[[ "$(uname -m)" == x86_64 ]] || { echo 'The current image lane requires an amd64 runner' >&2; exit 1; }
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Fail closed when NuGet reports vulnerable direct or transitive packages."""
|
||||
import json
|
||||
import sys
|
||||
|
||||
with open(sys.argv[1], encoding="utf-8") as report:
|
||||
data = json.load(report)
|
||||
if data.get("problems"):
|
||||
raise SystemExit("NuGet advisory lookup failed; see retained report")
|
||||
findings = []
|
||||
for project in data.get("projects", []):
|
||||
for framework in project.get("frameworks", []):
|
||||
for group in ("topLevelPackages", "transitivePackages"):
|
||||
for package in framework.get(group, []):
|
||||
for advisory in package.get("vulnerabilities", []):
|
||||
if advisory.get("severity", "").lower() in ("high", "critical"):
|
||||
findings.append((package["id"], advisory["severity"], advisory["advisoryurl"]))
|
||||
for package, severity, url in sorted(set(findings)):
|
||||
print(f"{severity}: {package}: {url}")
|
||||
if findings:
|
||||
raise SystemExit("HIGH/CRITICAL dependency advisories block publication")
|
||||
@@ -1,43 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rapport markdown des vulnérabilités HIGH/CRITICAL du JSON OWASP Dependency-Check.
|
||||
Usage: dc_report.py <dependency-check-report.json> [count]
|
||||
(2e argument 'count' → affiche uniquement le nombre de vulnérabilités)"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
try:
|
||||
data = json.load(open(sys.argv[1]))
|
||||
except Exception:
|
||||
print("")
|
||||
sys.exit(0)
|
||||
|
||||
mode_count = len(sys.argv) > 2 and sys.argv[2] == "count"
|
||||
|
||||
vulns = []
|
||||
seen = set()
|
||||
for dep in data.get("dependencies", []):
|
||||
for v in dep.get("vulnerabilities", []):
|
||||
sev = (v.get("cvssv3", {}) or {}).get("baseScore", 0)
|
||||
sev_label = v.get("severity", "UNKNOWN")
|
||||
if sev < 7.0 and sev_label not in ("HIGH", "CRITICAL"):
|
||||
continue
|
||||
vid = v.get("name", "CVE-?")
|
||||
if vid in seen:
|
||||
continue
|
||||
seen.add(vid)
|
||||
vulns.append((vid, sev_label, sev, dep.get("fileName", "?"), (v.get("description", "") or "")[:80]))
|
||||
|
||||
if mode_count:
|
||||
print(len(vulns))
|
||||
sys.exit(0)
|
||||
|
||||
if not vulns:
|
||||
print("")
|
||||
sys.exit(0)
|
||||
|
||||
print(f"### 🛡️ OWASP Dependency-Check — Vulnerabilités HIGH/CRITICAL ({len(vulns)})")
|
||||
print("")
|
||||
print("| CVE | Sévérité | Dépendance | Description |")
|
||||
print("|---|---|---|---|")
|
||||
for vid, sev_label, sev, fname, desc in vulns:
|
||||
print(f"| {vid} | {sev_label} (CVSS {sev}) | {fname} | {desc} |")
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
version=$(cat artifacts/version)
|
||||
sha=$(git rev-parse HEAD)
|
||||
for component in server agent; do
|
||||
file=docker/Dockerfile
|
||||
[[ "$component" == agent ]] && file=docker/Dockerfile.agent
|
||||
docker build --pull --platform linux/amd64 -f "$file" --build-arg "VERSION=$version" \
|
||||
--label "org.opencontainers.image.revision=$sha" \
|
||||
--label "org.opencontainers.image.version=$version" \
|
||||
--label "org.opencontainers.image.source=https://sources.tordais.cc/arnaud.dartois/Heimdall" \
|
||||
-t "heimdall-$component:ci-$sha" .
|
||||
done
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Injecte des secrets au format dotenv dans $GITHUB_ENV (steps suivants du job).
|
||||
Usage: inject_env.py <dotenv-content>
|
||||
Sûr pour les valeurs multi-lignes et caractères spéciaux (délimiteur EOF)."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
dotenv = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
out = os.environ.get("GITHUB_ENV")
|
||||
if not out:
|
||||
print("GITHUB_ENV non défini — rien à injecter")
|
||||
sys.exit(0)
|
||||
|
||||
count = 0
|
||||
with open(out, "a") as f:
|
||||
for line in dotenv.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, val = line.partition("=")
|
||||
key = key.strip()
|
||||
val = val.strip().strip("'").strip('"')
|
||||
if not key:
|
||||
continue
|
||||
f.write(f"{key}<<HEIMDALL_EOF\n{val}\nHEIMDALL_EOF\n")
|
||||
count += 1
|
||||
print(f"Secrets Infisical injectés dans l'environnement du job ({count} clés)")
|
||||
@@ -0,0 +1,2 @@
|
||||
#:package Microsoft.Playwright@1.61.0
|
||||
return Microsoft.Playwright.Program.Main(args);
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
sha=$(git rev-parse HEAD)
|
||||
ref=${BUILD_REF:-}
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
tag=${ref#refs/tags/}
|
||||
[[ "$tag" =~ ^v([0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z]+([.-][0-9A-Za-z]+)*)?)$ ]] || { echo 'Expected vMAJOR.MINOR.PATCH[-prerelease]' >&2; exit 1; }
|
||||
version=${BASH_REMATCH[1]}
|
||||
fi
|
||||
mkdir -p artifacts/packages
|
||||
for component in Web Agent; do
|
||||
rid=portable
|
||||
out="artifacts/publish/$component-$rid"
|
||||
dotnet publish "src/Heimdall.$component" -c Release --self-contained false \
|
||||
-p:RestoreLockedMode=true -p:Version="$version" -p:SourceRevisionId="$sha" -p:ContinuousIntegrationBuild=true -o "$out"
|
||||
if [[ "$component" == Agent ]]; then
|
||||
mkdir -p "$out/models"
|
||||
cp models/yolov8n.onnx "$out/models/"
|
||||
fi
|
||||
epoch=$(git show -s --format=%ct HEAD)
|
||||
tar --sort=name --mtime="@$epoch" --owner=0 --group=0 --numeric-owner -cf - -C "$out" . | gzip -n > "artifacts/packages/heimdall-${component,,}-$rid-$version.tar.gz"
|
||||
done
|
||||
python3 - "$sha" "$version" "$ref" <<'PY'
|
||||
import json,os,sys
|
||||
from pathlib import Path
|
||||
Path('artifacts/packages/provenance.json').write_text(json.dumps({
|
||||
'commit':sys.argv[1], 'version':sys.argv[2], 'ref':sys.argv[3],
|
||||
'repository':os.environ.get('BUILD_REPOSITORY'), 'run_id':os.environ.get('BUILD_RUN_ID'),
|
||||
'targets':['Web/PWA','Agent'], 'rids':['portable-framework-dependent'],
|
||||
'runtime':'framework-dependent .NET 10', 'mobile_native':False}, indent=2)+'\n')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum *.tar.gz provenance.json > SHA256SUMS)
|
||||
printf '%s' "$version" > artifacts/version
|
||||
@@ -1,135 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Parse les logs `dotnet test` et produit un résumé markdown (tests + coverage).
|
||||
|
||||
Usage:
|
||||
parse_test_log.py <log1> <log2> ... [--coverage-dir <dir>]
|
||||
|
||||
Lit les fichiers de log (générés par les jobs CI) et les rapports coverage
|
||||
cobertura (optionnel) ; sort le markdown sur stdout.
|
||||
|
||||
Comportement :
|
||||
- Si des tests ont tourné : tableau agrégé (Passed/Failed/Skipped/Total)
|
||||
+ liste des tests échoués nommément (si l'info est dans le log).
|
||||
- Si AUCUN test n'a tourné : message explicite signalant un échec avant
|
||||
l'exécution (et non plus une sortie vide silencieuse qui faisait afficher
|
||||
« Pas de résultats » au récap PR).
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:]
|
||||
cov_dir = None
|
||||
if "--coverage-dir" in args:
|
||||
i = args.index("--coverage-dir")
|
||||
cov_dir = args[i + 1]
|
||||
del args[i:i + 2]
|
||||
logs = [a for a in args if os.path.isfile(a)]
|
||||
|
||||
results = [] # (projet, failed, passed, skipped, total, status)
|
||||
error_lines = [] # erreurs de compilation
|
||||
failed_tests = [] # noms des tests échoués
|
||||
|
||||
for f in sorted(logs):
|
||||
try:
|
||||
with open(f, errors="replace") as fh:
|
||||
content = fh.read()
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
# --- Comptes agrégés (Pattern 1 : avec nom de DLL) ---
|
||||
for m in re.finditer(
|
||||
r"(Passed!|Failed!)\s+-\s+Failed:\s*(\d+),\s+Passed:\s*(\d+),\s+Skipped:\s*(\d+),\s+Total:\s*(\d+)[^:]*-[^:]*\[?\s*([\w.]+)\.dll",
|
||||
content,
|
||||
):
|
||||
results.append((m.group(6), m.group(2), m.group(3), m.group(4), m.group(5), m.group(1)))
|
||||
|
||||
# --- Comptes agrégés (Pattern 2 : sans nom de DLL) ---
|
||||
for m in re.finditer(
|
||||
r"(Passed!|Failed!)\s+-\s+Failed:\s*(\d+),\s+Passed:\s*(\d+),\s+Skipped:\s*(\d+),\s+Total:\s*(\d+)",
|
||||
content,
|
||||
):
|
||||
tot, passed = m.group(5), m.group(3)
|
||||
if any(r[4] == tot and r[2] == passed for r in results):
|
||||
continue
|
||||
line_start = content.rfind("\n", 0, m.start()) + 1
|
||||
line_end = content.find("\n", m.end())
|
||||
line = content[line_start:line_end] if line_end > 0 else content[line_start:]
|
||||
dll_match = re.search(r"-\s*([\w.]+)\.dll", line)
|
||||
proj = dll_match.group(1) if dll_match else "unknown"
|
||||
results.append((proj, m.group(2), m.group(3), m.group(4), m.group(5), m.group(1)))
|
||||
|
||||
# --- Erreurs de compilation ---
|
||||
for m in re.finditer(r"error CS\d+:\s*(.+)", content):
|
||||
error_lines.append(m.group(1).strip()[:120])
|
||||
|
||||
# --- Noms des tests échoués : lignes commençant par "Failed <nom qualifié>" ---
|
||||
# (le compteur « Failed! » porte un '!' collé, donc pas de collision avec ce pattern)
|
||||
for m in re.finditer(r"^\s*Failed\s+([A-Za-z_][\w.]*\.\w[\w.]*)\s", content, re.MULTILINE):
|
||||
name = m.group(1).strip()
|
||||
if name not in failed_tests:
|
||||
failed_tests.append(name)
|
||||
|
||||
if not results and not error_lines and not failed_tests:
|
||||
# Aucune exécution de test détectée : le job a échoué AVANT de lancer dotnet test,
|
||||
# ou il a été skippé. On le dit explicitement plutôt que de sortir vide.
|
||||
if logs:
|
||||
print("_⚠️ Le job n'a produit aucun résultat de test (échec avant l'exécution ou build/DB en amont). Voir le log du job CI._")
|
||||
else:
|
||||
print("_⚠️ Aucun log de test produit par ce job._")
|
||||
sys.exit(0)
|
||||
|
||||
# Dédupliquer par projet
|
||||
seen = set()
|
||||
unique_results = []
|
||||
for r in results:
|
||||
if r[0] not in seen:
|
||||
seen.add(r[0])
|
||||
unique_results.append(r)
|
||||
results = unique_results
|
||||
|
||||
out = []
|
||||
if results:
|
||||
out.append("| Projet | Statut | Passed | Failed | Skipped | Total |")
|
||||
out.append("|---|---|---|---|---|---|")
|
||||
for proj, failed, passed, skipped, total, status in results:
|
||||
icon = "🟢" if status == "Passed!" else "🔴"
|
||||
out.append(f"| `{proj}` | {icon} | {passed} | {failed} | {skipped} | {total} |")
|
||||
failed_total = sum(int(r[1]) for r in results)
|
||||
passed_total = sum(int(r[2]) for r in results)
|
||||
if failed_total:
|
||||
out.append(f"\n**❌ {failed_total} test(s) en échec** — {passed_total} passent.")
|
||||
else:
|
||||
out.append(f"\n**✅ {passed_total} tests passent.**")
|
||||
|
||||
# Liste nominative des tests échoués
|
||||
if failed_tests:
|
||||
out.append("\n**Tests en échec :**")
|
||||
for name in failed_tests[:40]:
|
||||
out.append(f"- ❌ `{name}`")
|
||||
if len(failed_tests) > 40:
|
||||
out.append(f"\n_… et {len(failed_tests) - 40} autre(s) (voir log)_")
|
||||
|
||||
if error_lines:
|
||||
out.append("\n**Erreurs de compilation détectées :**")
|
||||
for e in error_lines[:10]:
|
||||
out.append(f"- `{e}`")
|
||||
|
||||
# Coverage moyen (cobertura)
|
||||
if cov_dir:
|
||||
rates = []
|
||||
for cf in glob.glob(os.path.join(cov_dir, "**", "*.cobertura.xml"), recursive=True):
|
||||
try:
|
||||
with open(cf, errors="replace") as fh:
|
||||
data = fh.read()
|
||||
lm = re.search(r'line-rate="([\d.]+)"', data)
|
||||
if lm:
|
||||
rates.append(float(lm.group(1)))
|
||||
except OSError:
|
||||
continue
|
||||
if rates:
|
||||
avg = sum(rates) / len(rates) * 100
|
||||
out.append(f"\n**Coverage moyen : {avg:.1f}%** ({len(rates)} projet(s))")
|
||||
|
||||
print("\n".join(out))
|
||||
@@ -1,43 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Poste un commentaire markdown sur une PR Forgejo.
|
||||
|
||||
Usage:
|
||||
post_comment.py <texte> [titre]
|
||||
|
||||
Env requis : FORGEJO_TOKEN, REPO (owner/repo), PR_NUMBER.
|
||||
Si REPO/PR_NUMBER/FORGEJO_TOKEN absents → warning, sortie 0 (commentaire ignoré).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
text = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
title = sys.argv[2] if len(sys.argv) > 2 else "CI"
|
||||
|
||||
repo = os.environ.get("REPO", "")
|
||||
pr = os.environ.get("PR_NUMBER", "")
|
||||
token = os.environ.get("FORGEJO_TOKEN", "")
|
||||
|
||||
if not text.strip():
|
||||
print("Rien à commenter — sortie sans commentaire")
|
||||
raise SystemExit(0)
|
||||
|
||||
body = f"## 🤖 {title}\n\n{text}\n\n_Généré automatiquement par la CI._"
|
||||
|
||||
if not repo or not pr or not token:
|
||||
print("::warning::REPO/PR_NUMBER/FORGEJO_TOKEN manquants — commentaire ignoré")
|
||||
raise SystemExit(0)
|
||||
|
||||
url = f"https://forgejo.tordais.cc/api/v1/repos/{repo}/issues/{pr}/comments"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps({"body": body}).encode(),
|
||||
headers={"Authorization": f"token {token}", "Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(req)
|
||||
print(f"Commentaire posté sur la PR #{pr}")
|
||||
except Exception as e:
|
||||
print(f"::warning::Impossible de poster le commentaire: {e}")
|
||||
@@ -1,40 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Poste un commentaire CVE (Trivy + Dependency-Check) sur une PR Forgejo.
|
||||
Usage: post_cve_comment.py
|
||||
Env: FORGEJO_TOKEN, TRIVY_REPORT, DC_REPORT, REPO, PR_NUMBER"""
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
body = ""
|
||||
trivy = os.environ.get("TRIVY_REPORT", "")
|
||||
dc = os.environ.get("DC_REPORT", "")
|
||||
if trivy:
|
||||
body += "\n" + trivy + "\n"
|
||||
if dc:
|
||||
body += "\n" + dc + "\n"
|
||||
if not body.strip():
|
||||
print("Aucune CVE à signaler — pas de commentaire")
|
||||
raise SystemExit(0)
|
||||
|
||||
body = "## 🛡️ Rapport sécurité — CVE détectées\n\n" + body + "\n\n_Généré automatiquement par la CI (Trivy / OWASP Dependency-Check)._"
|
||||
|
||||
repo = os.environ.get("REPO", "")
|
||||
pr = os.environ.get("PR_NUMBER", "")
|
||||
token = os.environ.get("FORGEJO_TOKEN", "")
|
||||
if not repo or not pr or not token:
|
||||
print("::warning::REPO/PR_NUMBER/FORGEJO_TOKEN manquants — commentaire ignoré")
|
||||
raise SystemExit(0)
|
||||
|
||||
url = f"https://forgejo.tordais.cc/api/v1/repos/{repo}/issues/{pr}/comments"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps({"body": body}).encode(),
|
||||
headers={"Authorization": f"token {token}", "Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(req)
|
||||
print(f"Commentaire CVE posté sur la PR #{pr}")
|
||||
except Exception as e:
|
||||
print(f"::warning::Impossible de poster le commentaire CVE: {e}")
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
: "${REGISTRY_USER:?Dedicated registry user is required}"
|
||||
: "${REGISTRY_TOKEN:?Dedicated registry token is required}"
|
||||
: "${RELEASE_TOKEN:?Dedicated Gitea release token is required}"
|
||||
: "${BUILD_SERVER_URL:?Gitea URL is required}"
|
||||
: "${BUILD_REPOSITORY:?Repository is required}"
|
||||
[[ "$BUILD_SERVER_URL" == https://sources.tordais.cc ]] || { echo 'Unexpected publication host' >&2; exit 1; }
|
||||
[[ "$BUILD_REPOSITORY" == arnaud.dartois/Heimdall ]] || { echo 'Unexpected publication repository' >&2; exit 1; }
|
||||
sha=$(git rev-parse HEAD)
|
||||
tag=${BUILD_REF#refs/tags/}
|
||||
[[ "$BUILD_REF" == refs/tags/v* ]] || exit 1
|
||||
python3 - "$sha" "$tag" <<'PY'
|
||||
import json,sys
|
||||
with open('artifacts/packages/provenance.json') as f:p=json.load(f)
|
||||
if p['commit'] != sys.argv[1] or 'v'+p['version'] != sys.argv[2]:
|
||||
raise SystemExit('Artifact provenance does not match checkout/tag')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum --check SHA256SUMS)
|
||||
printf '%s' "${tag#v}" > artifacts/version
|
||||
bash scripts/ci/images.sh
|
||||
# No mutation is attempted until all credentials, provenance and local builds pass.
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
|
||||
printf '%s' "$REGISTRY_TOKEN" | docker login sources.tordais.cc -u "$REGISTRY_USER" --password-stdin
|
||||
: > artifacts/image-digests.txt
|
||||
for component in server agent; do
|
||||
image="sources.tordais.cc/arnaud.dartois/heimdall-$component"
|
||||
for image_tag in "sha-$sha" "${tag#v}"; do
|
||||
if docker manifest inspect "$image:$image_tag" >/dev/null 2>&1; then
|
||||
docker pull "$image:$image_tag"
|
||||
revision=$(docker image inspect "$image:$image_tag" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')
|
||||
[[ "$revision" == "$sha" ]] || { echo 'Refusing to overwrite an image from another commit' >&2; exit 1; }
|
||||
else
|
||||
docker tag "heimdall-$component:ci-$sha" "$image:$image_tag"
|
||||
docker push "$image:$image_tag"
|
||||
fi
|
||||
docker image inspect "$image:$image_tag" --format '{{range .RepoDigests}}{{println .}}{{end}}' >> artifacts/image-digests.txt
|
||||
done
|
||||
done
|
||||
cp artifacts/image-digests.txt artifacts/packages/image-digests.txt
|
||||
(cd artifacts/packages && sha256sum image-digests.txt >> SHA256SUMS)
|
||||
python3 scripts/ci/release-gitea.py
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Create/update only a draft Gitea release; never log auth or response bodies."""
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
base = os.environ['BUILD_SERVER_URL'] + '/api/v1/repos/' + os.environ['BUILD_REPOSITORY']
|
||||
tag = os.environ['BUILD_REF'].removeprefix('refs/tags/')
|
||||
token = os.environ['RELEASE_TOKEN']
|
||||
provenance = json.loads(Path('artifacts/packages/provenance.json').read_text())
|
||||
|
||||
def request(path, method='GET', body=None, content_type='application/json', missing=False):
|
||||
data = json.dumps(body).encode() if content_type == 'application/json' and body is not None else body
|
||||
req = urllib.request.Request(base+path, data=data, method=method, headers={
|
||||
'Authorization': 'token '+token, 'Content-Type': content_type})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=90) as response:
|
||||
payload = response.read()
|
||||
return json.loads(payload) if payload else None
|
||||
except urllib.error.HTTPError as error:
|
||||
if missing and error.code == 404:
|
||||
return None
|
||||
raise SystemExit(f'Gitea release API failed: HTTP {error.code}') from None
|
||||
|
||||
release = request('/releases/tags/'+urllib.parse.quote(tag, safe=''), missing=True)
|
||||
if release is None:
|
||||
release = request('/releases', 'POST', {
|
||||
'tag_name': tag, 'target_commitish': provenance['commit'], 'name': tag,
|
||||
'draft': True, 'prerelease': '-' in tag,
|
||||
'body': f"Commit: `{provenance['commit']}`\nActions run: {provenance['run_id']}\n"
|
||||
'Server/PWA and agent only; checksums and image digests attached.\n'
|
||||
'Draft: promote explicitly after reviewing publication evidence.'})
|
||||
if not release['draft']:
|
||||
raise SystemExit('Refusing to mutate an already public release')
|
||||
# Reruns replace draft assets; published releases remain immutable.
|
||||
for asset in request(f"/releases/{release['id']}/assets"):
|
||||
request(f"/releases/{release['id']}/assets/{asset['id']}", 'DELETE')
|
||||
for path in sorted(Path('artifacts/packages').iterdir()):
|
||||
if path.is_file():
|
||||
boundary = uuid.uuid4().hex
|
||||
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{path.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()
|
||||
+ path.read_bytes() + f'\r\n--{boundary}--\r\n'.encode())
|
||||
request(f"/releases/{release['id']}/assets?name="+urllib.parse.quote(path.name),
|
||||
'POST', payload, 'multipart/form-data; boundary='+boundary)
|
||||
print('Draft release: '+release['html_url'])
|
||||
@@ -1,184 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""release_notes.py — Génère les release notes Forgejo depuis le dernier tag du même préfixe.
|
||||
|
||||
Usage:
|
||||
release_notes.py [TAG] [PREFIX] [REPO_URL]
|
||||
|
||||
TAG : tag de la release courante (défaut : détecté via git describe)
|
||||
PREFIX : préfixe de tag (défaut : 'v') — les notes ne comparent qu'avec
|
||||
les tags du même préfixe (ex. 'agent-v' pour l'agent)
|
||||
REPO_URL : base d'URL du repo pour les liens commits (défaut : forgejo.tordais.cc)
|
||||
|
||||
Sortie : markdown prêt pour le body d'une release Forgejo (stdout).
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import datetime
|
||||
|
||||
|
||||
CATEGORIES = {
|
||||
"feat": ("✨ Features", "feature"),
|
||||
"fix": ("🐛 Fixes", "bug"),
|
||||
"perf": ("⚡ Performance", "perf"),
|
||||
"chore": ("🧹 Maintenance", "chore"),
|
||||
"refactor": ("🧹 Maintenance", "refactor"),
|
||||
"docs": ("🧹 Maintenance", "docs"),
|
||||
"style": ("🧹 Maintenance", "style"),
|
||||
"build": ("🧹 Maintenance", "build"),
|
||||
"ci": ("🧹 Maintenance", "ci"),
|
||||
"test": ("🧹 Maintenance", "test"),
|
||||
"revert": ("↩️ Reverts", "revert"),
|
||||
}
|
||||
|
||||
|
||||
def git(*args):
|
||||
r = subprocess.run(["git", *args], capture_output=True, text=True)
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def git_or_none(*args):
|
||||
r = subprocess.run(["git", *args], capture_output=True, text=True)
|
||||
return r.stdout.strip() if r.returncode == 0 else ""
|
||||
|
||||
|
||||
def tag_date(t):
|
||||
return git_or_none("log", "-1", "--format=%ct", t)
|
||||
|
||||
|
||||
def detect_repo():
|
||||
"""Détecte owner/repo depuis le remote git origin."""
|
||||
url = git_or_none("remote", "get-url", "origin")
|
||||
if not url:
|
||||
return None
|
||||
# https://host/owner/repo.git ou git@host:owner/repo.git
|
||||
m = re.search(r'[:/]([^/]+)/([^/]+?)(?:\.git)?$', url)
|
||||
if m:
|
||||
return f"{m.group(1)}/{m.group(2)}"
|
||||
return None
|
||||
|
||||
|
||||
def parse_commit(line):
|
||||
"""'abc1234|message' -> (sha, subject)"""
|
||||
if "|" in line:
|
||||
sha, subject = line.split("|", 1)
|
||||
else:
|
||||
sha, subject = line, line
|
||||
return sha, subject
|
||||
|
||||
|
||||
def categorize(subject):
|
||||
subject_l = subject.lower()
|
||||
for prefix, (title, _) in CATEGORIES.items():
|
||||
if subject_l.startswith(prefix + ":") or subject_l.startswith(prefix + "("):
|
||||
return title
|
||||
return "📦 Autres"
|
||||
|
||||
|
||||
def link_issues(subject, forgejo_url, repo_slug):
|
||||
"""Convertit les références #N en liens cliquables — scan unique sans double-processing.
|
||||
|
||||
Formats gérés (par priorité) :
|
||||
- Fixes/Closes/Resolves/Refs/See #61 → [Fixes #61](URL)
|
||||
- (#154) → [(#154)](URL)
|
||||
- #42 standalone → [#42](URL)
|
||||
"""
|
||||
if not repo_slug:
|
||||
return subject
|
||||
|
||||
base = f"https://{forgejo_url}/{repo_slug}/issues"
|
||||
|
||||
# Scan unique : tous les patterns dans un seul regex, groupes nommés
|
||||
combined = re.compile(
|
||||
r'(?P<kw>(?:Fixes|Closes|Resolves|Refs|See)\s+#(?P<kw_n>\d+))'
|
||||
r'|\(#(?P<paren_n>\d+)\)'
|
||||
r'|(?<!\w)#(?P<stand_n>\d+)\b'
|
||||
)
|
||||
|
||||
# Collecte de toutes les insertions (offset → replacement)
|
||||
insertions = []
|
||||
for m in combined.finditer(subject):
|
||||
if m.group('kw'):
|
||||
kw_text, num = m.group('kw'), m.group('kw_n')
|
||||
replacement = f"[{kw_text}]({base}/{num})"
|
||||
elif m.group('paren_n'):
|
||||
num = m.group('paren_n')
|
||||
replacement = f"[(#{num})]({base}/{num})"
|
||||
else:
|
||||
num = m.group('stand_n')
|
||||
replacement = f"[#{num}]({base}/{num})"
|
||||
insertions.append((m.start(), m.end(), replacement))
|
||||
|
||||
if not insertions:
|
||||
return subject
|
||||
|
||||
# Reconstruction de la chaîne en une passe
|
||||
parts = []
|
||||
prev_end = 0
|
||||
for start, end, repl in insertions:
|
||||
parts.append(subject[prev_end:start])
|
||||
parts.append(repl)
|
||||
prev_end = end
|
||||
parts.append(subject[prev_end:])
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def main():
|
||||
tag = sys.argv[1] if len(sys.argv) > 1 else git("describe", "--tags", "--abbrev=0") or ""
|
||||
prefix = sys.argv[2] if len(sys.argv) > 2 else "v"
|
||||
forgejo_url = sys.argv[3] if len(sys.argv) > 3 else "forgejo.tordais.cc"
|
||||
|
||||
# Détection automatique owner/repo pour les liens issues
|
||||
repo_slug = detect_repo()
|
||||
|
||||
# Dernier tag du même préfixe, antérieur à celui-ci (par date du commit tagué)
|
||||
all_tags = [t for t in git("tag", "--list").splitlines() if t.startswith(prefix) and t != tag]
|
||||
all_tags.sort(key=lambda t: (tag_date(t) or "0"), reverse=True)
|
||||
prev = all_tags[0] if all_tags else None
|
||||
|
||||
if prev:
|
||||
raw = git("log", f"{prev}..{tag}", "--pretty=format:%h|%s")
|
||||
elif tag:
|
||||
raw = git("log", tag, "--pretty=format:%h|%s")
|
||||
else:
|
||||
raw = git("log", "--pretty=format:%h|%s")
|
||||
|
||||
commits = [parse_commit(l) for l in raw.splitlines() if l]
|
||||
|
||||
if not commits:
|
||||
print(f"## {tag} — {datetime.date.today().isoformat()}\n\n_No commits._")
|
||||
return 0
|
||||
|
||||
grouped = {}
|
||||
for sha, subject in commits:
|
||||
grouped.setdefault(categorize(subject), []).append((sha, subject))
|
||||
|
||||
today = datetime.date.today().isoformat()
|
||||
lines = [f"## {tag} — {today}", ""]
|
||||
|
||||
for title in ["✨ Features", "🐛 Fixes", "⚡ Performance", "↩️ Reverts", "🧹 Maintenance", "📦 Autres"]:
|
||||
items = grouped.get(title)
|
||||
if not items:
|
||||
continue
|
||||
lines.append(f"### {title}")
|
||||
lines.append("")
|
||||
for sha, subject in items:
|
||||
linked = link_issues(subject, forgejo_url, repo_slug)
|
||||
lines.append(f"- {linked} ([`{sha}`](https://{forgejo_url}/commit/{sha}))")
|
||||
lines.append("")
|
||||
|
||||
# Liste complète repliable
|
||||
lines.append(f"<details><summary>🔗 {len(commits)} commits</summary>")
|
||||
lines.append("")
|
||||
for sha, subject in commits:
|
||||
linked = link_issues(subject, forgejo_url, repo_slug)
|
||||
lines.append(f"- [`{sha}`](https://{forgejo_url}/commit/{sha}) {linked}")
|
||||
lines.append("")
|
||||
lines.append("</details>")
|
||||
|
||||
print("\n".join(lines))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts/security
|
||||
dotnet list Heimdall.slnx package --vulnerable --include-transitive --format json > artifacts/security/nuget.json
|
||||
status=0
|
||||
python3 scripts/ci/check-advisories.py artifacts/security/nuget.json || status=1
|
||||
sha=$(git rev-parse HEAD)
|
||||
scanner=aquasec/trivy:0.69.3@sha256:bcc376de8d77cfe086a917230e818dc9f8528e3c852f7b1aff648949b6258d1c
|
||||
for component in server agent; do
|
||||
# Export to a temporary tar: no Docker socket is exposed to the scanner.
|
||||
if ! docker image inspect "heimdall-$component:ci-$sha" >/dev/null 2>&1; then
|
||||
echo "Missing image for security scan: $component" >&2
|
||||
status=1
|
||||
continue
|
||||
fi
|
||||
archive=$(mktemp)
|
||||
docker save "heimdall-$component:ci-$sha" -o "$archive"
|
||||
chmod a+r "$archive"
|
||||
# Docker daemon paths differ from job-container paths; stdin avoids bind mounts.
|
||||
docker run --rm -i "$scanner" image --input /dev/stdin --scanners vuln \
|
||||
--severity HIGH,CRITICAL --exit-code 1 --format json < "$archive" \
|
||||
> "artifacts/security/$component.json" || status=1
|
||||
rm -f "$archive"
|
||||
done
|
||||
exit "$status"
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extrait un rapport markdown des vulnérabilités du JSON Trivy.
|
||||
Usage: trivy_report.py <trivy.json> <severity-label>
|
||||
Sortie: markdown (vide si aucune vulnérabilité)."""
|
||||
import json
|
||||
import sys
|
||||
|
||||
try:
|
||||
data = json.load(open(sys.argv[1]))
|
||||
except Exception:
|
||||
print("")
|
||||
sys.exit(0)
|
||||
|
||||
severity_label = sys.argv[2] if len(sys.argv) > 2 else "HIGH,CRITICAL"
|
||||
seen = set()
|
||||
rows = []
|
||||
for r in data.get("Results", []):
|
||||
target = r.get("Target", "")
|
||||
for v in r.get("Vulnerabilities", []):
|
||||
vid = v.get("VulnerabilityID", "")
|
||||
if vid in seen:
|
||||
continue
|
||||
seen.add(vid)
|
||||
pkg = v.get("PkgName", "?")
|
||||
inst = v.get("InstalledVersion", "?")
|
||||
fixed = v.get("FixedVersion", "") or "—"
|
||||
sev = v.get("Severity", "UNKNOWN")
|
||||
rows.append(f"| {vid} | {sev} | {pkg} {inst} → {fixed} | {target} |")
|
||||
|
||||
if not rows:
|
||||
print("")
|
||||
sys.exit(0)
|
||||
|
||||
print(f"### 🛡️ Trivy — Vulnérabilités {severity_label} ({len(seen)})")
|
||||
print("")
|
||||
print("| CVE | Sévérité | Paquet | Cible |")
|
||||
print("|---|---|---|---|")
|
||||
print("\n".join(rows))
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts/tests artifacts/security
|
||||
: "${DATABASE_URL:?A disposable PostgreSQL database is required}"
|
||||
dotnet --info > artifacts/dotnet-info.txt
|
||||
if [[ -f scripts/ci/validate-compose.sh ]]; then
|
||||
bash scripts/ci/validate-compose.sh
|
||||
else
|
||||
docker compose --env-file .env.example -f docker/docker-compose.yml config --quiet
|
||||
fi
|
||||
dotnet restore Heimdall.slnx --locked-mode
|
||||
dotnet build Heimdall.slnx -c Release --no-restore -m:2
|
||||
# NuGet advisory report is kept separate from compiler warning suppressions.
|
||||
# Each test project gets an independent disposable database. Run sequentially:
|
||||
# several fixtures truncate shared tables and must never race other assemblies.
|
||||
status=0
|
||||
for project in tests/*/*.csproj; do
|
||||
name=$(basename "${project%.csproj}")
|
||||
[[ "$name" == Heimdall.TestCommon || "$name" == Heimdall.E2E.Tests ]] && continue
|
||||
dbname="ci_${name//./_}"
|
||||
psql --no-password -v ON_ERROR_STOP=1 -c "CREATE DATABASE \"$dbname\"" >/dev/null
|
||||
DATABASE_URL="$DATABASE_URL;Database=$dbname" \
|
||||
dotnet test "$project" -c Release --no-build --no-restore \
|
||||
--logger 'trx;LogFileName=results.trx' --results-directory "artifacts/tests/$name" || status=1
|
||||
done
|
||||
dotnet run scripts/ci/install-chromium.cs -- install --with-deps chromium
|
||||
psql --no-password -v ON_ERROR_STOP=1 -c "CREATE DATABASE ci_e2e" >/dev/null
|
||||
DATABASE_URL="$DATABASE_URL;Database=ci_e2e" \
|
||||
dotnet test tests/Heimdall.E2E.Tests -c Release --no-build --no-restore \
|
||||
--logger 'trx;LogFileName=results.trx' --results-directory artifacts/tests/e2e || status=1
|
||||
exit "$status"
|
||||
Reference in new issue
Block a user