diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3bf62c0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +# Generated, byte-compared files stay LF on every platform so +# `make conformance-status-check` behaves the same on Windows and Unix. +conformance/*.json text eol=lf +README.md text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ddbc5b9..40502dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,6 +43,9 @@ jobs: - name: verify conformance corpus run: go run ./cmd/openiac-conformance verify + - name: check conformance summary + run: go run ./cmd/openiac-conformance status -check + - name: build CLI run: go build -o bin/openiac ./cmd/openiac diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml deleted file mode 100644 index a492249..0000000 --- a/.github/workflows/pages.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: Playground - -on: - push: - branches: [main] - workflow_dispatch: - -permissions: - contents: read - pages: write - id-token: write - -concurrency: - group: pages - cancel-in-progress: true - -jobs: - deploy: - name: Deploy playground - runs-on: ubuntu-latest - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-go@v5 - with: - go-version-file: go.mod - cache: true - - - name: build WebAssembly - run: make wasm - - - name: prepare site - run: touch playground/.nojekyll - - - uses: actions/configure-pages@v5 - - - uses: actions/upload-pages-artifact@v3 - with: - path: playground - - - id: deployment - uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index d53672b..bcb1768 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,13 @@ playground/wasm_exec.js conformance/reports/ .cache/ +# ---- Cloudflare deployment (local only) ---- +# The Wrangler project and its state live outside the repository. +/deploy/ +.wrangler/ +.dev.vars +.dev.vars.* + # ---- Node ---- node_modules/ npm-debug.log* diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ffa98c0..5d8a064 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -31,6 +31,51 @@ Serve the playground locally: python3 -m http.server -d playground 8080 ``` +### Running the playground + +The playground is static. `make wasm` writes `main.wasm` and `wasm_exec.js` into +`playground/`, and any static file server can host that folder: + +```bash +make wasm +python3 -m http.server -d playground 8080 # http://localhost:8080 +``` + +### Deploying the playground + +Production is served from a Cloudflare Worker, deployed by a maintainer from a +machine with Wrangler installed. The Wrangler project is intentionally **not** in +this repository: `deploy/` is git-ignored together with Wrangler's `.wrangler/` +state and any `.dev.vars` secrets. A fresh clone therefore has no deploy folder, +and nothing about the deployment is committed. + +To stand up an equivalent Worker yourself, create the project outside this +repository and point it at the built playground: + +1. `npm install --save-dev wrangler` (Wrangler 4 or later). +2. Add a `wrangler.jsonc` that serves `playground/` as static assets and routes + other requests through a script: + + ```jsonc + { + "name": "openiac", + "main": "src/index.js", + "compatibility_date": "2026-10-26", + "assets": { + "directory": "/absolute/path/to/OpenIaC/playground", + "binding": "ASSETS" + }, + "observability": { "enabled": true } + } + ``` + +3. Add a `src/index.js` fetch handler that answers `GET /api/health` with + `Response.json({ status: "ok", service: "openiac" })` and otherwise returns + `env.ASSETS.fetch(request)`. +4. Run `make wasm` in this repository, then `wrangler deploy` in the project. + +Deployment is manual. CI only builds the WebAssembly bundle and never deploys. + ## The fastest contribution: a resource mapping You do **not** need Go to add AWS resource support. diff --git a/Makefile b/Makefile index d375139..87417fc 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ GO ?= go BIN := bin/openiac PLAYGROUND := playground -.PHONY: all build test vet fmt tidy wasm playground clean hooks conformance-inputs conformance-verify conformance-lock +.PHONY: all build test vet fmt tidy wasm playground clean hooks conformance-inputs conformance-verify conformance-lock conformance-status conformance-status-check all: build @@ -38,6 +38,14 @@ conformance-verify: conformance-lock: $(GO) run ./cmd/openiac-conformance lock +# Parse the whole corpus and refresh the summary the README renders. +conformance-status: + $(GO) run ./cmd/openiac-conformance status + +# Fail when the committed summary no longer matches the corpus. +conformance-status-check: + $(GO) run ./cmd/openiac-conformance status -check + # Build the browser playground. Copies wasm_exec.js from the local toolchain, # which lives in a different directory depending on the Go version. wasm: diff --git a/README.md b/README.md index dfb2ae7..14aafb4 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ One parser. One IR. Zero lock-in. [![Terraform](https://img.shields.io/badge/Terraform-1.0_%E2%80%93_1.17-7B42BC?style=flat-square&logo=terraform&logoColor=white)](docs/TERRAFORM-VERSIONS.md) [![AWS CDK](https://img.shields.io/badge/AWS_CDK-TypeScript-FF9900?style=flat-square&logo=amazonaws&logoColor=white)](https://aws.amazon.com/cdk/) [![Pulumi](https://img.shields.io/badge/Pulumi-TypeScript-8A3391?style=flat-square&logo=pulumi&logoColor=white)](https://www.pulumi.com/) +[![Cloudflare Workers](https://img.shields.io/badge/Cloudflare-Workers-F38020?style=flat-square&logo=cloudflare&logoColor=white)](https://openiac.cwz.workers.dev) [![IR](https://img.shields.io/badge/IR-schema_0.2-818cf8?style=flat-square)](docs/IR.md) [![Made with Go](https://img.shields.io/badge/made_with-Go-00ADD8?style=flat-square&logo=go&logoColor=white)](https://go.dev) @@ -27,7 +28,7 @@ One parser. One IR. Zero lock-in.
-[🚀 Playground](playground/) · [📦 Quick Start](#-quick-start) · [🗺️ Roadmap](docs/ROADMAP.md) · [🧠 How It Works](#-how-it-works) · [🧱 Architecture](docs/ARCHITECTURE.md) · [📄 IR Reference](docs/IR.md) · [🧭 Version Support](docs/TERRAFORM-VERSIONS.md) · [🧪 Conformance](docs/CONFORMANCE.md) · [🤝 Contribute](CONTRIBUTING.md) +[🚀 Playground](https://openiac.cwz.workers.dev) · [📦 Quick Start](#-quick-start) · [🗺️ Roadmap](docs/ROADMAP.md) · [🧠 How It Works](#-how-it-works) · [🧱 Architecture](docs/ARCHITECTURE.md) · [📄 IR Reference](docs/IR.md) · [🧭 Version Support](docs/TERRAFORM-VERSIONS.md) · [🧪 Conformance](docs/CONFORMANCE.md) · [🤝 Contribute](CONTRIBUTING.md) @@ -337,10 +338,28 @@ commit, records the input-tree hash, carries the upstream license and is scanned for executables and credentials before it enters the tree. CI re-verifies the tree, its lock and the generated attribution on every pull request. +[![conformance](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbe-thomas%2FOpenIaC%2Fmain%2Fconformance%2Fbadge.json&style=flat-square)](conformance/status.json) + + +```mermaid +xychart-beta + title "Fixtures by minimum Terraform version" + x-axis ["1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8", "1.9", "1.10", "1.11"] + y-axis "Fixtures" 0 --> 500 + bar [477, 34, 4, 168, 1, 117, 15, 3, 6, 9, 6, 13] +``` + + +Every one of the 853 modules parses into schema `0.2` IR. The chart groups each +module by the oldest Terraform release its configuration needs; the exact +distribution is in [`conformance/status.json`](conformance/status.json), which +`make conformance-status` regenerates and CI checks. + ```bash make conformance-inputs # refresh from configured sources make conformance-verify # check the committed tree and lock make conformance-lock # regenerate the lock and attribution +make conformance-status # re-parse the corpus, refresh the summary cat conformance/corpus.lock.json # aggregate counts and tree hash ``` @@ -365,7 +384,7 @@ See [docs/CONFORMANCE.md](docs/CONFORMANCE.md) for the L0–L4 oracle design and | Milestone | Date | Highlights | State | |:--|:--|:--|:--:| | **Foundation** | Oct 2026 | HCL parser · IR · DAG · CDK + Pulumi emitters · WASM playground | ✅ | -| **v0.1 Public Alpha** | Nov 2026 | Docs incl. [IR](docs/IR.md) & [version](docs/TERRAFORM-VERSIONS.md) references · tests · CI · GitHub Pages playground | 🚧 | +| **v0.1 Public Alpha** | Nov 2026 | Docs incl. [IR](docs/IR.md) & [version](docs/TERRAFORM-VERSIONS.md) references · tests · CI · Cloudflare Workers playground | 🚧 | | **v0.2 Depth** | Dec 2026 | Data sources · `locals` · richer L2 mappings | ⏳ | | **v0.3 Scale** | Q1 2027 | Modules · `count` / `for_each` · multi-file imports | ⏳ | | **v1.0 Stable** | Q2 2027 | CloudFormation + Terraform backends · plugin API | 🎯 | diff --git a/cmd/openiac-conformance/main.go b/cmd/openiac-conformance/main.go index 6497308..70dbc18 100644 --- a/cmd/openiac-conformance/main.go +++ b/cmd/openiac-conformance/main.go @@ -3,6 +3,7 @@ package main import ( "context" + "encoding/json" "flag" "fmt" "os" @@ -12,6 +13,7 @@ import ( "syscall" "github.com/be-thomas/openiac/internal/conformance/collect" + "github.com/be-thomas/openiac/internal/conformance/status" ) func main() { @@ -35,6 +37,11 @@ func main() { fmt.Fprintln(os.Stderr, "openiac-conformance:", err) os.Exit(1) } + case "status": + if err := runStatus(os.Args[2:]); err != nil { + fmt.Fprintln(os.Stderr, "openiac-conformance:", err) + os.Exit(1) + } case "-h", "--help", "help": usage() default: @@ -45,7 +52,7 @@ func main() { } func usage() { - fmt.Fprint(os.Stderr, `usage: openiac-conformance [flags] + fmt.Fprint(os.Stderr, `usage: openiac-conformance [flags] collect downloads upstream modules and rewrites the fixture tree. @@ -75,6 +82,16 @@ to the fixture tree and never uses the network. -out string fixture tree (default conformance/fixtures) -lock string lock file (default conformance/corpus.lock.json) -third-party string attribution file (default THIRD_PARTY.md) + +status parses every fixture and rewrites the committed summary the README +renders. It never uses the network. + + -out string fixture tree (default conformance/fixtures) + -lock string lock file (default conformance/corpus.lock.json) + -status string summary file (default conformance/status.json) + -badge string shields.io endpoint file (default conformance/badge.json) + -readme string file holding the generated summary block (default README.md) + -check report a stale summary instead of rewriting it `) } @@ -174,6 +191,99 @@ func runLock(args []string) error { return nil } +func runStatus(args []string) error { + fs := flag.NewFlagSet("status", flag.ExitOnError) + out := fs.String("out", "conformance/fixtures", "fixture tree") + lockPath := fs.String("lock", "conformance/corpus.lock.json", "lock file") + statusPath := fs.String("status", "conformance/status.json", "summary file") + badgePath := fs.String("badge", "conformance/badge.json", "shields.io endpoint file") + readmePath := fs.String("readme", "README.md", "file holding the generated summary block") + check := fs.Bool("check", false, "report a stale summary instead of rewriting it") + if err := fs.Parse(args); err != nil { + return err + } + + report, err := status.Compute(*out, *lockPath) + if err != nil { + return err + } + statusJSON, err := marshalIndent(report) + if err != nil { + return err + } + badgeJSON, err := marshalIndent(report.Badge()) + if err != nil { + return err + } + readme, err := os.ReadFile(*readmePath) + if err != nil { + return err + } + + if *check { + var stale []string + for _, file := range []struct { + path string + want []byte + }{ + {*statusPath, statusJSON}, + {*badgePath, badgeJSON}, + } { + got, err := os.ReadFile(file.path) + if err != nil || normalizeNewlines(string(got)) != normalizeNewlines(string(file.want)) { + stale = append(stale, file.path) + } + } + section, err := status.ExtractSection(string(readme)) + if err != nil { + return fmt.Errorf("%s: %w", *readmePath, err) + } + if normalizeNewlines(section) != normalizeNewlines(report.Section()) { + stale = append(stale, *readmePath) + } + if len(stale) > 0 { + return fmt.Errorf("%s is stale: run `make conformance-status` and commit the result", strings.Join(stale, ", ")) + } + fmt.Printf("status: %d/%d modules parse, summary current\n", report.Parse.Parsed, report.Parse.Modules) + return nil + } + + // Render the README block before touching any file, so a missing marker + // fails the run instead of leaving half the summary rewritten. + updated, err := status.ReplaceSection(string(readme), report.Section()) + if err != nil { + return fmt.Errorf("%s: %w", *readmePath, err) + } + if err := os.WriteFile(*statusPath, statusJSON, 0o644); err != nil { + return err + } + if err := os.WriteFile(*badgePath, badgeJSON, 0o644); err != nil { + return err + } + if err := os.WriteFile(*readmePath, []byte(updated), 0o644); err != nil { + return err + } + fmt.Printf("status: %d/%d modules parse\n", report.Parse.Parsed, report.Parse.Modules) + fmt.Println(report.Markdown()) + return nil +} + +// normalizeNewlines keeps -check independent of the checkout's line endings: +// Git for Windows hands out CRLF files for content stored as LF. +func normalizeNewlines(s string) string { + return strings.ReplaceAll(s, "\r\n", "\n") +} + +// marshalIndent encodes a report the way the rest of the repository encodes +// committed JSON: two-space indent and a trailing newline. +func marshalIndent(v any) ([]byte, error) { + data, err := json.MarshalIndent(v, "", " ") + if err != nil { + return nil, err + } + return append(data, '\n'), nil +} + func githubToken() string { for _, key := range []string{"GITHUB_TOKEN", "GH_TOKEN"} { if v := strings.TrimSpace(os.Getenv(key)); v != "" { diff --git a/conformance/README.md b/conformance/README.md index 0b7f2fc..6f366eb 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -182,8 +182,10 @@ re-derived from the parsed features. `collection/sources.json`. 2. Run the collector. 3. Review `git status` and the new `fixture.json` files. -4. Run `make conformance-verify` and `go test ./...`, then commit the fixtures - with the code that consumes them. +4. Run `make conformance-status`, which rewrites `status.json`, `badge.json` and + the summary block in the README. +5. Run `make conformance-verify` and `go test ./...`, then commit the fixtures, + the refreshed summary and the code that consumes them. Do not edit vendored Terraform files. If an upstream module needs a fix, add a note and wait for a new upstream revision. Hand-curated fixtures under a future diff --git a/conformance/badge.json b/conformance/badge.json new file mode 100644 index 0000000..f4b9748 --- /dev/null +++ b/conformance/badge.json @@ -0,0 +1,6 @@ +{ + "schemaVersion": 1, + "label": "conformance", + "message": "853 / 853 modules", + "color": "brightgreen" +} diff --git a/conformance/status.json b/conformance/status.json new file mode 100644 index 0000000..facf3c1 --- /dev/null +++ b/conformance/status.json @@ -0,0 +1,41 @@ +{ + "schema": 1, + "corpus": { + "fixtures": 853, + "files": 6471, + "bytes": 24314566, + "tree_sha256": "c09b8e91907e03f86c30cc7e77d8e82471b14ade98a66c3e0c2779074b846117" + }, + "parse": { + "modules": 853, + "parsed": 853, + "failed": 0 + }, + "min_versions": { + "1.0.0": 468, + "1.0.11": 3, + "1.0.2": 1, + "1.0.8": 5, + "1.1.0": 20, + "1.1.4": 9, + "1.1.5": 1, + "1.1.9": 4, + "1.10.0": 6, + "1.11.0": 4, + "1.11.1": 9, + "1.2.0": 4, + "1.3.0": 164, + "1.3.2": 2, + "1.3.6": 2, + "1.4.0": 1, + "1.5.0": 15, + "1.5.6": 20, + "1.5.7": 82, + "1.6.0": 1, + "1.6.1": 13, + "1.6.6": 1, + "1.7.0": 3, + "1.8.0": 6, + "1.9.0": 9 + } +} diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 2e64728..812a01a 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -150,6 +150,26 @@ therefore fails verification instead of silently drifting. Provider, CloudFormation and Pulumi schemas are dependencies rather than source: they are pinned by lockfile and cached outside the tree. +### Parse summary + +`openiac-conformance status` parses every fixture and writes three committed +files: [`status.json`](../conformance/status.json) holds the corpus size, the +parse counts and the minimum-version distribution, +[`badge.json`](../conformance/badge.json) is the shields.io endpoint the README +renders as a badge, and the chart between the `conformance:summary` markers in +the [`README`](../README.md) is regenerated in place. CI runs `status -check`, +so the summary cannot drift from the corpus without failing a pull request. + +```bash +make conformance-status # re-parse the corpus and rewrite all three +make conformance-status-check # fail when the committed summary is stale +``` + +The minimum version is the oldest Terraform release a fixture needs, derived +from its `required_version` constraint and the language features it uses (see +[TERRAFORM-VERSIONS.md](TERRAFORM-VERSIONS.md)); it measures parse coverage, not +conversion completeness. + ### Sources | Source | Access | License posture | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a6244f1..66e2559 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -40,7 +40,7 @@ playground produces the same output as the CLI. | Task | Exit criteria | |:--|:--| | CI | Format, vet, test, native build, WASM build on every PR | -| Pages | Playground deployed from `main` on every push | +| Hosting | Playground served from a Cloudflare Worker | | Golden tests | Snapshot output for `examples/aws-web-app` in both targets | | Docs | Architecture, IR reference, Terraform version support, contributing, roadmap, README | | Versioning | `openiac version` reads a single source of truth | diff --git a/internal/conformance/status/status.go b/internal/conformance/status/status.go new file mode 100644 index 0000000..8cfc81c --- /dev/null +++ b/internal/conformance/status/status.go @@ -0,0 +1,314 @@ +// Package status summarises how the parser handles the committed conformance +// corpus. +// +// The report is committed as conformance/status.json and rendered in the +// README, so a reader can see what the corpus actually proves without running +// the corpus test. It stays small so the playground can serve it unchanged. +package status + +import ( + "encoding/json" + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + + hclparser "github.com/be-thomas/openiac/pkg/parsers/hcl" +) + +// Schema is the report format version. +const Schema = 1 + +// Report is the committed snapshot of corpus size and parse results. +type Report struct { + Schema int `json:"schema"` + Corpus Corpus `json:"corpus"` + Parse Parse `json:"parse"` + MinVersions map[string]int `json:"min_versions"` +} + +// Corpus repeats the lock's aggregate sizes so a reader needs one file. +type Corpus struct { + Fixtures int `json:"fixtures"` + Files int `json:"files"` + Bytes int64 `json:"bytes"` + TreeSHA256 string `json:"tree_sha256"` +} + +// Parse counts fixture modules and how many of them parse cleanly. +type Parse struct { + Modules int `json:"modules"` + Parsed int `json:"parsed"` + Failed int `json:"failed"` + Failures []string `json:"failures,omitempty"` +} + +// Badge is the shields.io endpoint document rendered in the README. +type Badge struct { + SchemaVersion int `json:"schemaVersion"` + Label string `json:"label"` + Message string `json:"message"` + Color string `json:"color"` +} + +// maxFailures caps the messages kept in the report so a broad regression still +// produces a committable file. +const maxFailures = 20 + +// lock mirrors the fields of conformance/corpus.lock.json that the report +// repeats. It is read here rather than imported so this package stays free of +// the collector's dependencies. +type lock struct { + FixtureCount int `json:"fixtureCount"` + FileCount int `json:"fileCount"` + TotalBytes int64 `json:"totalBytes"` + TreeSHA256 string `json:"treeSha256"` +} + +// Compute parses every fixture input under fixturesDir. It reads the lock for +// the aggregate sizes but never writes anything. +func Compute(fixturesDir, lockPath string) (Report, error) { + report := Report{Schema: Schema, MinVersions: map[string]int{}} + + var l lock + raw, err := os.ReadFile(lockPath) + if err != nil { + return report, fmt.Errorf("read lock: %w", err) + } + if err := json.Unmarshal(raw, &l); err != nil { + return report, fmt.Errorf("parse lock %s: %w", lockPath, err) + } + report.Corpus = Corpus{ + Fixtures: l.FixtureCount, + Files: l.FileCount, + Bytes: l.TotalBytes, + TreeSHA256: l.TreeSHA256, + } + + inputs, err := fixtureInputs(fixturesDir) + if err != nil { + return report, err + } + report.Parse.Modules = len(inputs) + for _, dir := range inputs { + graph, err := hclparser.ParseDir(dir) + if err != nil { + report.Parse.Failed++ + if len(report.Parse.Failures) < maxFailures { + report.Parse.Failures = append(report.Parse.Failures, fmt.Sprintf("%s: %v", filepath.ToSlash(trim(fixturesDir, dir)), err)) + } + continue + } + report.Parse.Parsed++ + report.MinVersions[graph.MinVersion]++ + } + return report, nil +} + +// fixtureInputs lists every fixture module root in deterministic order. +func fixtureInputs(root string) ([]string, error) { + var inputs []string + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() && entry.Name() == "input" { + inputs = append(inputs, path) + return fs.SkipDir + } + return nil + }) + if err != nil { + return nil, fmt.Errorf("walk %s: %w", root, err) + } + sort.Strings(inputs) + if len(inputs) == 0 { + return nil, fmt.Errorf("no fixture inputs found under %s", root) + } + return inputs, nil +} + +func trim(root, path string) string { + if rel, err := filepath.Rel(root, path); err == nil { + return rel + } + return path +} + +// Badge renders the shields.io endpoint document. +func (r Report) Badge() Badge { + badge := Badge{ + SchemaVersion: 1, + Label: "conformance", + Message: fmt.Sprintf("%d / %d modules", r.Parse.Parsed, r.Parse.Modules), + Color: "brightgreen", + } + if r.Parse.Failed > 0 { + badge.Color = "red" + } + return badge +} + +// VersionRows returns the minimum Terraform versions present, oldest first, +// with the fixture count for each. +func (r Report) VersionRows() []VersionCount { + return sortedRows(r.MinVersions) +} + +// MinorRows aggregates the distribution by MAJOR.MINOR, which is the +// resolution that reads well in a chart: patch releases come from individual +// modules' required_version pins, not from language differences. +func (r Report) MinorRows() []VersionCount { + counts := make(map[string]int, len(r.MinVersions)) + for version, count := range r.MinVersions { + counts[minor(version)] += count + } + return sortedRows(counts) +} + +func sortedRows(counts map[string]int) []VersionCount { + rows := make([]VersionCount, 0, len(counts)) + for version, count := range counts { + rows = append(rows, VersionCount{Version: version, Fixtures: count}) + } + sort.Slice(rows, func(i, j int) bool { return lessVersion(rows[i].Version, rows[j].Version) }) + return rows +} + +// minor reduces "1.10.2" to "1.10". +func minor(version string) string { + parts := strings.Split(version, ".") + if len(parts) < 2 { + return version + } + return parts[0] + "." + parts[1] +} + +// VersionCount is one row of the minimum-version distribution. +type VersionCount struct { + Version string + Fixtures int +} + +// lessVersion orders dotted version strings numerically, then as text so the +// order is total even for unexpected values. +func lessVersion(a, b string) bool { + as := strings.Split(a, ".") + bs := strings.Split(b, ".") + for i := 0; i < len(as) && i < len(bs); i++ { + an, aerr := strconv.Atoi(as[i]) + bn, berr := strconv.Atoi(bs[i]) + if aerr == nil && berr == nil { + if an != bn { + return an < bn + } + continue + } + if as[i] != bs[i] { + return as[i] < bs[i] + } + } + return len(as) < len(bs) +} + +// Markdown renders the distribution as a table with inline bars, for the README +// and for `openiac-conformance status`. +func (r Report) Markdown() string { + var b strings.Builder + b.WriteString("| Minimum Terraform | Fixtures | Share |\n") + b.WriteString("|:--|--:|:--|\n") + total := r.Parse.Parsed + for _, row := range r.MinorRows() { + share := 0 + if total > 0 { + share = row.Fixtures * 100 / total + } + bar := strings.Repeat("█", share/2) + if bar == "" && row.Fixtures > 0 { + bar = "▏" + } + fmt.Fprintf(&b, "| `%s` | %d | %s %d%% |\n", row.Version, row.Fixtures, bar, share) + } + return b.String() +} + +// Mermaid renders the distribution as a GitHub-renderable bar chart. +func (r Report) Mermaid() string { + rows := r.MinorRows() + labels := make([]string, 0, len(rows)) + bars := make([]string, 0, len(rows)) + max := 0 + for _, row := range rows { + labels = append(labels, fmt.Sprintf("%q", row.Version)) + bars = append(bars, fmt.Sprintf("%d", row.Fixtures)) + if row.Fixtures > max { + max = row.Fixtures + } + } + var b strings.Builder + b.WriteString("```mermaid\nxychart-beta\n") + b.WriteString(" title \"Fixtures by minimum Terraform version\"\n") + fmt.Fprintf(&b, " x-axis [%s]\n", strings.Join(labels, ", ")) + fmt.Fprintf(&b, " y-axis \"Fixtures\" 0 --> %d\n", axisMax(max)) + fmt.Fprintf(&b, " bar [%s]\n", strings.Join(bars, ", ")) + b.WriteString("```\n") + return b.String() +} + +// axisMax rounds the chart's y-axis up to a readable bound. +func axisMax(max int) int { + if max <= 0 { + return 10 + } + step := 10 + for step*10 < max { + step *= 10 + } + return (max/step + 1) * step +} + +// Section markers delimit the generated block in README.md. +const ( + SectionStart = "" + SectionEnd = "" +) + +// Section renders the generated README block, markers included and without a +// trailing newline: the document keeps the one after the closing marker. +func (r Report) Section() string { + return SectionStart + "\n" + r.Mermaid() + SectionEnd +} + +// ExtractSection returns the marked block of document. +func ExtractSection(document string) (string, error) { + start, end, err := sectionBounds(document) + if err != nil { + return "", err + } + return document[start:end], nil +} + +// ReplaceSection returns document with its marked block replaced by section. +func ReplaceSection(document, section string) (string, error) { + start, end, err := sectionBounds(document) + if err != nil { + return "", err + } + return document[:start] + section + document[end:], nil +} + +// sectionBounds locates the marked block, markers included. +func sectionBounds(document string) (int, int, error) { + start := strings.Index(document, SectionStart) + if start < 0 { + return 0, 0, fmt.Errorf("missing marker %s", SectionStart) + } + end := strings.Index(document[start:], SectionEnd) + if end < 0 { + return 0, 0, fmt.Errorf("missing marker %s after %s", SectionEnd, SectionStart) + } + return start, start + end + len(SectionEnd), nil +} diff --git a/internal/conformance/status/status_test.go b/internal/conformance/status/status_test.go new file mode 100644 index 0000000..dc68994 --- /dev/null +++ b/internal/conformance/status/status_test.go @@ -0,0 +1,153 @@ +package status_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/be-thomas/openiac/internal/conformance/status" +) + +func TestComputeCountsParsedModules(t *testing.T) { + root := t.TempDir() + fixtures := filepath.Join(root, "fixtures") + writeModule(t, fixtures, "registry/aws/mod/1.0.0/input", `resource "aws_s3_bucket" "b" { + bucket = "example" +} +`) + lock := writeLock(t, root, `{"fixtureCount":1,"fileCount":1,"totalBytes":42,"treeSha256":"abc"}`) + + report, err := status.Compute(fixtures, lock) + if err != nil { + t.Fatalf("Compute: %v", err) + } + if report.Parse.Modules != 1 || report.Parse.Parsed != 1 || report.Parse.Failed != 0 { + t.Fatalf("parse = %+v, want 1/1 with no failures", report.Parse) + } + if got := report.MinVersions["1.0.0"]; got != 1 { + t.Errorf("min_versions[1.0.0] = %d, want 1 (%v)", got, report.MinVersions) + } + if report.Corpus != (status.Corpus{Fixtures: 1, Files: 1, Bytes: 42, TreeSHA256: "abc"}) { + t.Errorf("corpus = %+v, want the lock's aggregates", report.Corpus) + } + if got := report.Badge(); got.Message != "1 / 1 modules" || got.Color != "brightgreen" { + t.Errorf("badge = %+v, want 1 / 1 modules in brightgreen", got) + } +} + +func TestComputeReportsFailures(t *testing.T) { + root := t.TempDir() + fixtures := filepath.Join(root, "fixtures") + writeModule(t, fixtures, "registry/aws/broken/1.0.0/input", "resource \"aws_s3_bucket\" {\n") + lock := writeLock(t, root, `{"fixtureCount":1,"fileCount":1,"totalBytes":1,"treeSha256":"abc"}`) + + report, err := status.Compute(fixtures, lock) + if err != nil { + t.Fatalf("Compute: %v", err) + } + if report.Parse.Failed != 1 || report.Parse.Parsed != 0 { + t.Fatalf("parse = %+v, want one failure", report.Parse) + } + if len(report.Parse.Failures) != 1 || !strings.Contains(report.Parse.Failures[0], "broken/1.0.0/input") { + t.Errorf("failures = %v, want the fixture path", report.Parse.Failures) + } + if got := report.Badge().Color; got != "red" { + t.Errorf("badge color = %q, want red", got) + } +} + +func TestMinorRowsAggregateAndSort(t *testing.T) { + report := status.Report{ + Parse: status.Parse{Modules: 6, Parsed: 6}, + MinVersions: map[string]int{ + "1.10.0": 2, + "1.9.0": 1, + "1.0.0": 3, + }, + } + rows := report.MinorRows() + want := []status.VersionCount{{Version: "1.0", Fixtures: 3}, {Version: "1.9", Fixtures: 1}, {Version: "1.10", Fixtures: 2}} + if len(rows) != len(want) { + t.Fatalf("rows = %v, want %v", rows, want) + } + for i := range want { + if rows[i] != want[i] { + t.Fatalf("rows = %v, want %v", rows, want) + } + } + + chart := report.Mermaid() + for _, token := range []string{`x-axis ["1.0", "1.9", "1.10"]`, "bar [3, 1, 2]", "y-axis \"Fixtures\" 0 --> 10"} { + if !strings.Contains(chart, token) { + t.Errorf("chart missing %q:\n%s", token, chart) + } + } +} + +func TestSectionRoundTrip(t *testing.T) { + report := status.Report{ + Parse: status.Parse{Modules: 2, Parsed: 2}, + MinVersions: map[string]int{"1.0.0": 1, "1.5.0": 1}, + } + header := "# Title\n\nIntro.\n\n" + footer := "\n\nTrailing prose.\n" + document := header + report.Section() + footer + + section, err := status.ExtractSection(document) + if err != nil { + t.Fatalf("ExtractSection: %v", err) + } + if section != report.Section() { + t.Fatalf("ExtractSection = %q, want the generated section", section) + } + + updated := status.Report{ + Parse: status.Parse{Modules: 2, Parsed: 2}, + MinVersions: map[string]int{"1.0.0": 2}, + } + replaced, err := status.ReplaceSection(document, updated.Section()) + if err != nil { + t.Fatalf("ReplaceSection: %v", err) + } + if want := header + updated.Section() + footer; replaced != want { + t.Fatalf("ReplaceSection = %q, want %q", replaced, want) + } + + again, err := status.ReplaceSection(replaced, updated.Section()) + if err != nil { + t.Fatalf("ReplaceSection (second pass): %v", err) + } + if again != replaced { + t.Fatalf("ReplaceSection is not idempotent:\nfirst %q\nsecond %q", replaced, again) + } +} + +func TestSectionRejectsUnmarkedDocument(t *testing.T) { + if _, err := status.ExtractSection("# no markers here\n"); err == nil { + t.Error("ExtractSection accepted a document without markers") + } + if _, err := status.ReplaceSection(status.SectionStart+"\n", "replacement"); err == nil { + t.Error("ReplaceSection accepted a document with an unclosed block") + } +} + +func writeModule(t *testing.T, fixtures, rel, content string) { + t.Helper() + dir := filepath.Join(fixtures, rel) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("mkdir: %v", err) + } + if err := os.WriteFile(filepath.Join(dir, "main.tf"), []byte(content), 0o644); err != nil { + t.Fatalf("write module: %v", err) + } +} + +func writeLock(t *testing.T, root, content string) string { + t.Helper() + path := filepath.Join(root, "corpus.lock.json") + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write lock: %v", err) + } + return path +}