chore: publish IntegraCI build modules 732ec6c83925

This commit is contained in:
dhimaz0445 committed 2026-10-28 08:09:16 +00:00
1 parent 7a84930dea
commit 5f8a24d014
133 files changed
+18990 -2

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
# IntegraCI — Release Dagger Module
Computes the next [SemVer](https://semver.org) from
[Conventional Commits](https://www.conventionalcommits.org) and renders a
changelog using [`git-cliff`](https://git-cliff.org). Designed to drive the
release lifecycle from CI without prescribing how tags or PRs are pushed.
## Functions
| Function | Description |
|----------------|----------------------------------------------------------|
| `next-version` | Inspect commits since `current`, output bump + next SemVer |
| `changelog` | Render the Markdown changelog for a tag (`git-cliff`) |
| `plan` | One-shot `next-version` + `changelog` |
## Usage
```bash
# Compute the next version from current v1.2.3
dagger call -m dagger/release next-version \
--src . \
--current v1.2.3
# Render a changelog
dagger call -m dagger/release changelog \
--src . --tag v1.3.0
# Combined release plan (used by IntegraCI release pipelines)
dagger call -m dagger/release plan \
--src . --current v1.2.3
```
## Bump Rules
| Commit pattern | Bump |
|---------------------------------------------|--------|
| `BREAKING CHANGE:` footer or `<type>!:` | major |
| `feat:` / `feat(<scope>):` | minor |
| `fix:` / `perf:` / `refactor:` (any scope) | patch |
| anything else | none |
The module is intentionally pure: it never tags or pushes. Callers compose
the side-effects (e.g. `git tag`, `gh release create`, opening a PR with the
generated changelog) in their own pipeline so platform policy gates apply.
## License
Apache 2.0.
+11
View File
@@ -0,0 +1,11 @@
{
"name": "release",
"engineVersion": "v0.21.7",
"sdk": {
"source": "go"
},
"source": ".",
"include": [
"./main.go"
]
}
+508
View File
@@ -0,0 +1,508 @@
// Package main implements the IntegraCI release Dagger module.
//
// Provides Conventional-Commits → SemVer bump computation and changelog
// rendering using `git-cliff`. Designed to be called from CI:
//
// dagger call -m dagger/release next-version --src . --current v1.2.3
// dagger call -m dagger/release changelog --src . --tag v1.3.0
//
// Version/changelog computation is pure: it does NOT push tags or open PRs —
// callers wire those side-effects so policy / approval gates remain in the
// platform. The one impure op is `promote`, which re-tags a tested image to an
// environment tag (e.g. :prod) and publishes it.
//
// "Policy stays in the platform" used to mean the platform was never told. Given
// --api-url, --token and --service-id, `promote` now ASKS it first — the gates
// run, a Deployment is recorded, and the retag happens only if the answer was
// yes. Without those flags it degrades to the plain retag, which is what a local
// `dagger call` gets.
package main
import (
"bytes"
"context"
"dagger/release/internal/dagger"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
// Release is the IntegraCI release-management Dagger module.
type Release struct{}
// VersionDecision is the output of a SemVer computation.
type VersionDecision struct {
Current string `json:"current"`
Next string `json:"next"`
Bump string `json:"bump"` // "major" | "minor" | "patch" | "none"
Reason string `json:"reason"` // human-readable explanation
}
// NextVersion inspects commits since `current` and computes the next SemVer.
//
// Rules (Conventional Commits):
//
// - Any `BREAKING CHANGE:` footer or `!:` indicator → MAJOR bump
// - `feat:` commits → MINOR bump
// - `fix:`, `perf:`, `refactor:` commits → PATCH bump
// - Otherwise → no bump
func (m *Release) NextVersion(
ctx context.Context,
// Source repo
src *dagger.Directory,
// Current SemVer (e.g. "v1.2.3"). Empty string = first release.
// +optional
current string,
) (*VersionDecision, error) {
current = strings.TrimSpace(current)
if current == "" {
current = "v0.0.0"
}
rangeSpec := current
if !strings.HasPrefix(rangeSpec, "v") && !strings.Contains(rangeSpec, "..") {
rangeSpec = "v" + rangeSpec
}
// Collect commit subjects + bodies between current..HEAD
out, err := dag.Container().
From("alpine/git:2.45.2").
WithMountedDirectory("/src", src).
WithWorkdir("/src").
WithExec([]string{
"git", "log",
fmt.Sprintf("%s..HEAD", rangeSpec),
"--no-merges",
"--format=%s%n%b%n----",
}).Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("git log failed: %w", err)
}
bump := classifyCommits(out)
next := bumpVersion(current, bump)
return &VersionDecision{
Current: current,
Next: next,
Bump: bump,
Reason: reasonFor(bump),
}, nil
}
// Changelog renders a Markdown changelog for `tag` using git-cliff.
//
// Returns the rendered Markdown as a string so callers can store it in
// release notes, attach to a PR, or upload to a release artefact.
func (m *Release) Changelog(
ctx context.Context,
// Source repo
src *dagger.Directory,
// Tag to render (e.g. "v1.3.0")
tag string,
// Custom git-cliff config; defaults to the bundled "keep-a-changelog" preset.
// +optional
config *dagger.File,
) (string, error) {
args := []string{"--tag", tag, "--unreleased"}
container := dag.Container().
From("orhunp/git-cliff:2.6.1").
WithMountedDirectory("/src", src).
WithWorkdir("/src")
if config != nil {
container = container.WithMountedFile("/cliff.toml", config)
args = append([]string{"--config", "/cliff.toml"}, args...)
}
return container.WithExec(append([]string{"git-cliff"}, args...)).Stdout(ctx)
}
// Plan combines NextVersion + Changelog and returns both as a single object.
type ReleasePlan struct {
Decision *VersionDecision `json:"decision"`
Changelog string `json:"changelog"`
}
// Plan computes the next version AND renders the changelog in one call.
func (m *Release) Plan(
ctx context.Context,
// Source repo
src *dagger.Directory,
// Current SemVer (e.g. "v1.2.3"). Empty string = first release.
// +optional
current string,
) (*ReleasePlan, error) {
dec, err := m.NextVersion(ctx, src, current)
if err != nil {
return nil, err
}
if dec.Bump == "none" {
return &ReleasePlan{Decision: dec, Changelog: "_No releasable changes since " + dec.Current + "._"}, nil
}
cl, err := m.Changelog(ctx, src, dec.Next, nil)
if err != nil {
return &ReleasePlan{Decision: dec, Changelog: ""}, nil
}
return &ReleasePlan{Decision: dec, Changelog: cl}, nil
}
// ─── helpers ────────────────────────────────────────────────────────────────
func classifyCommits(log string) string {
if log == "" {
return "none"
}
bump := "none"
for _, line := range strings.Split(log, "\n") {
line = strings.TrimSpace(line)
if line == "" || line == "----" {
continue
}
lower := strings.ToLower(line)
switch {
case strings.Contains(lower, "breaking change:") ||
breakingType(line):
return "major"
case strings.HasPrefix(lower, "feat:") ||
strings.HasPrefix(lower, "feat("):
if rank(bump) < rank("minor") {
bump = "minor"
}
case strings.HasPrefix(lower, "fix:") ||
strings.HasPrefix(lower, "fix(") ||
strings.HasPrefix(lower, "perf:") ||
strings.HasPrefix(lower, "perf(") ||
strings.HasPrefix(lower, "refactor:") ||
strings.HasPrefix(lower, "refactor("):
if rank(bump) < rank("patch") {
bump = "patch"
}
}
}
return bump
}
func breakingType(line string) bool {
for _, prefix := range []string{"feat", "fix", "refactor", "perf", "build", "ci", "chore"} {
if strings.HasPrefix(strings.ToLower(line), prefix+"!:") ||
strings.HasPrefix(strings.ToLower(line), prefix+"(") &&
strings.Contains(line, ")!:") {
return true
}
}
return false
}
func rank(bump string) int {
switch bump {
case "major":
return 3
case "minor":
return 2
case "patch":
return 1
}
return 0
}
func reasonFor(bump string) string {
switch bump {
case "major":
return "BREAKING CHANGE detected in commits"
case "minor":
return "feat: commits since last release"
case "patch":
return "fix/perf/refactor commits since last release"
}
return "no releasable conventional commits"
}
func bumpVersion(current, bump string) string {
prefix := ""
v := current
if strings.HasPrefix(v, "v") {
prefix = "v"
v = v[1:]
}
parts := strings.SplitN(v, "-", 2) // strip pre-release
core := strings.Split(parts[0], ".")
for len(core) < 3 {
core = append(core, "0")
}
major, _ := strconv.Atoi(core[0])
minor, _ := strconv.Atoi(core[1])
patch, _ := strconv.Atoi(core[2])
switch bump {
case "major":
major++
minor = 0
patch = 0
case "minor":
minor++
patch = 0
case "patch":
patch++
default:
return current
}
return fmt.Sprintf("%s%d.%d.%d", prefix, major, minor, patch)
}
// PromoteResult is the output of an image promotion.
type PromoteResult struct {
Source string `json:"source"` // source image ref (the tested, SHA-tagged build)
// Release-version ref minted from the same manifest (e.g. repo:v1.2.3). This
// is what the platform's release record and the GitOps desired state name.
Release string `json:"release"`
Target string `json:"target"` // promoted env-tag ref (e.g. repo:prod)
Pinned string `json:"pinned"` // immutable env-pinned ref (e.g. repo:prod-1.2.3)
Digest string `json:"digest"` // published manifest digest
To string `json:"to"` // target environment
// Deployment created by the platform's governed promote endpoint. Empty
// when the call was not configured (no --api-url / --token / --service-id),
// i.e. a retag-only run.
DeploymentID string `json:"deployment_id"`
Governed bool `json:"governed"`
}
// Promote re-tags an already-built image to a target-environment tag and
// publishes it — e.g. `repo:1.2.3 --to=prod` publishes `repo:prod` plus an
// immutable `repo:prod-1.2.3`. The manifest is copied BY REFERENCE (no rebuild),
// so the promoted image is bit-identical to the one that was tested.
//
// When --api-url, --token and --service-id are supplied, the platform's
// governed promote endpoint is called FIRST and the retag only happens if it
// succeeds. That ordering is the point: POST /api/v1/environments/promote runs
// the promotion-order gate, the image-digest policy (G1), the freeze window,
// the single-in-flight lock and the compute budget, and it creates the
// Deployment that writes the new ref back into the GitOps desired state. Doing
// the retag first would leave a `:prod` tag pointing at an image the platform
// had just refused, and — because nothing reconciles a registry tag — a release
// job that reported success while production never moved.
//
// Without those flags the call degrades to a pure retag, which is what a local
// `dagger call` or a tenant who has not wired a token gets. That is a real
// capability (convenience tags for an external CD), not a governed promotion,
// so the result says so via Governed.
func (m *Release) Promote(
ctx context.Context,
// Source image ref including tag (e.g. ghcr.io/org/app:1.2.3)
image string,
// Target environment tag (e.g. "prod", "staging")
to string,
// Release version to mint and to pin the env tag with (e.g. "v1.2.3").
// Defaults to the source image's tag.
// +optional
version string,
// Registry username (required to push to a private registry)
// +optional
registryUser string,
// Registry password / token
// +optional
registryPassword *dagger.Secret,
// IntegraCI API base URL. With --token and --service-id this makes the
// promotion GOVERNED: the platform gates it and records the deployment.
// +optional
apiURL string,
// JWT token for API authentication
// +optional
token *dagger.Secret,
// Service UUID the promotion belongs to
// +optional
serviceID string,
// Environment being promoted FROM (the promotion-order gate needs both ends)
// +optional
// +default="staging"
fromEnv string,
// Leave the deployment awaiting an explicit approval instead of dispatching
// it. Defaults true so a tag push cannot silently ship to the target env.
// +optional
// +default=true
requireApproval bool,
) (*PromoteResult, error) {
image = strings.TrimSpace(image)
to = strings.TrimSpace(to)
if image == "" {
return nil, fmt.Errorf("--image is required")
}
if to == "" {
return nil, fmt.Errorf("--to is required (target env tag, e.g. prod)")
}
repo, tag := splitImageRef(image)
if tag == "" {
return nil, fmt.Errorf("--image must include a tag (e.g. repo:1.2.3)")
}
// The SOURCE is whatever the build actually pushed, and every engine in this
// repo pushes ONE tag: the commit SHA (CI_COMMIT_SHA / CIRCLE_SHA1 /
// BUILDKITE_COMMIT / DRONE_COMMIT_SHA / GIT_COMMIT / github.sha). Nothing has
// ever pushed a semver tag. The release workflow nonetheless promoted
// `repo:v1.2.3`, and the platform's own release record asks GitOps for
// `image_tag=rel.version` — so both ends assumed an image that no pipeline
// produces, and the promote would have failed on the pull.
//
// --version closes that: promote the SHA-tagged manifest that was actually
// built and tested, and let this call be what mints `repo:v1.2.3`. Defaults
// to the source tag, so a caller that already passes a semver ref behaves
// exactly as before.
version = strings.TrimSpace(version)
if version == "" {
version = tag
}
release := repo + ":" + version
target := repo + ":" + to
pinned := fmt.Sprintf("%s:%s-%s", repo, to, version)
// An UNSET GitHub secret renders as an empty string, not as a missing input,
// so `--token=env://INTEGRACI_TOKEN` still hands us a Secret — one holding
// "". Treating that as configured would send `Authorization: Bearer ` and
// turn every release into a 401 for tenants who never wired a token, whose
// releases work today. Empty means not configured.
tokenStr := ""
if token != nil {
plain, err := token.Plaintext(ctx)
if err != nil {
return nil, fmt.Errorf("read token secret: %w", err)
}
tokenStr = strings.TrimSpace(plain)
}
// Gate BEFORE pushing. See the doc comment: a refused promotion must not
// leave an env tag behind.
deploymentID := ""
governed := apiURL != "" && serviceID != "" && tokenStr != ""
if governed {
id, err := m.requestGovernedPromotion(
ctx, apiURL, tokenStr, serviceID, fromEnv, to, image, requireApproval,
)
if err != nil {
return nil, err
}
deploymentID = id
}
ctr := dag.Container().From(image)
if registryUser != "" && registryPassword != nil {
ctr = ctr.WithRegistryAuth(registryHost(image), registryUser, registryPassword)
}
// The release artefact first: `repo:v1.2.3` is what the platform's release
// record and the GitOps write-back both name, so it has to exist before
// anything points at it. Skipped when the source already IS that ref —
// re-publishing a manifest onto its own tag is a no-op with a network cost.
if version != tag {
if _, err := ctr.Publish(ctx, release); err != nil {
return nil, fmt.Errorf("release-tag publish %q failed: %w", release, err)
}
}
digest, err := ctr.Publish(ctx, target)
if err != nil {
return nil, fmt.Errorf("promote publish %q failed: %w", target, err)
}
if _, err := ctr.Publish(ctx, pinned); err != nil {
return nil, fmt.Errorf("promote pinned-tag publish %q failed: %w", pinned, err)
}
return &PromoteResult{
Source: image,
Release: release,
Target: target,
Pinned: pinned,
Digest: digest,
To: to,
DeploymentID: deploymentID,
Governed: governed,
}, nil
}
// requestGovernedPromotion asks the platform to promote, and returns the id of
// the Deployment it created. Any non-2xx is returned as an error so the release
// job fails instead of retagging: a refusal here is the platform saying this
// promotion must not happen (stage skipped, env frozen, image not digest-pinned,
// another deploy in flight, budget exhausted), and the whole point of calling it
// is that those answers are binding.
//
// The SOURCE ref is sent as the version, not the `:prod` tag we are about to
// create: the digest policy has to evaluate the immutable ref that was actually
// built and tested, and a floating env tag is exactly what that policy exists
// to reject.
func (m *Release) requestGovernedPromotion(
ctx context.Context,
apiURL string,
token string,
serviceID string,
fromEnv string,
toEnv string,
version string,
requireApproval bool,
) (string, error) {
payload := map[string]any{
"service_id": serviceID,
"from_env": fromEnv,
"to_env": toEnv,
"version": version,
"require_approval": requireApproval,
}
body, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("marshal promote payload: %w", err)
}
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/environments/promote"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return "", fmt.Errorf("build request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("promote request to %s failed: %w", endpoint, err)
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 8192))
if resp.StatusCode >= 300 {
// The API answers with RFC 7807, whose `detail` is written for a human
// ("Promote to 'staging' before 'prod'"). Surfacing it beats a bare
// status code in a CI log.
return "", fmt.Errorf(
"platform refused the promotion (%d): %s", resp.StatusCode, strings.TrimSpace(string(raw)),
)
}
var out struct {
ID string `json:"id"`
}
if err := json.Unmarshal(raw, &out); err != nil {
return "", fmt.Errorf("parse promote response: %w", err)
}
return out.ID, nil
}
// splitImageRef splits an image reference into repo and tag, correctly handling
// a registry host:port (e.g. "ghcr.io:443/org/app:1.2.3" -> repo + "1.2.3").
// Returns an empty tag when the ref has none.
func splitImageRef(ref string) (repo, tag string) {
slash := strings.LastIndexByte(ref, '/')
colon := strings.LastIndexByte(ref, ':')
if colon > slash {
return ref[:colon], ref[colon+1:]
}
return ref, ""
}
// registryHost returns the registry hostname from an image ref (default docker.io).
func registryHost(image string) string {
if i := strings.IndexByte(image, '/'); i > 0 {
return image[:i]
}
return "docker.io"
}