diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ffa98c0..76b1c66 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -113,6 +113,25 @@ make fmt && make vet && make test `gofmt -l .` should print nothing. +## Golden output + +`pkg/engine/golden_test.go` snapshots `examples/aws-web-app` for both targets +into `pkg/engine/testdata/golden/`, and `pkg/engine/testdata/fixtures/warned` +the same way so the warning section is covered too. Any change to generated +TypeScript, or to the warnings a target reports, fails the test. When a change +is intended, refresh the snapshots, review the diff, and commit it with the +code: + +```bash +go test ./pkg/engine -run TestGolden -update +``` + +## Releasing a version + +The version is recorded once, in `internal/buildinfo/VERSION`, and embedded at +build time. `go build`, `go run` and `make build` all report the same value, so +a release only bumps that file. + ## Code style - Standard Go. No frameworks. diff --git a/cmd/openiac/main.go b/cmd/openiac/main.go index 8fc4b2b..90028bc 100644 --- a/cmd/openiac/main.go +++ b/cmd/openiac/main.go @@ -11,12 +11,11 @@ import ( "path/filepath" "strings" + "github.com/be-thomas/openiac/internal/buildinfo" "github.com/be-thomas/openiac/pkg/emitters" "github.com/be-thomas/openiac/pkg/engine" ) -const version = "0.1.0-dev" - func main() { os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) } @@ -32,7 +31,7 @@ func run(args []string, stdout, stderr io.Writer) int { case "ir": return runIR(args[1:], stdout, stderr) case "version", "--version", "-v": - fmt.Fprintf(stdout, "openiac %s\n", version) + fmt.Fprintf(stdout, "openiac %s\n", buildinfo.Version) return 0 case "help", "--help", "-h": usage(stdout) diff --git a/cmd/openiac/main_test.go b/cmd/openiac/main_test.go new file mode 100644 index 0000000..08706b3 --- /dev/null +++ b/cmd/openiac/main_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "bytes" + "testing" + + "github.com/be-thomas/openiac/internal/buildinfo" +) + +func TestVersionCommand(t *testing.T) { + for _, arg := range []string{"version", "--version", "-v"} { + var stdout, stderr bytes.Buffer + if code := run([]string{arg}, &stdout, &stderr); code != 0 { + t.Fatalf("%s: exit code %d, want 0 (stderr %q)", arg, code, stderr.String()) + } + want := "openiac " + buildinfo.Version + "\n" + if stdout.String() != want { + t.Errorf("%s: stdout = %q, want %q", arg, stdout.String(), want) + } + if stderr.Len() != 0 { + t.Errorf("%s: stderr = %q, want empty", arg, stderr.String()) + } + } +} diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a6244f1..74c21bc 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -45,6 +45,10 @@ playground produces the same output as the CLI. | Docs | Architecture, IR reference, Terraform version support, contributing, roadmap, README | | Versioning | `openiac version` reads a single source of truth | +The work is in place; the milestone stays in progress until the release is cut. +`internal/buildinfo/VERSION` keeps a `-dev` suffix and no `v0.1.1` tag exists +yet, so nothing reports this milestone as shipped. + --- ## v0.2 — Depth · Dec 2026 ⏳ diff --git a/internal/buildinfo/VERSION b/internal/buildinfo/VERSION new file mode 100644 index 0000000..0d4d124 --- /dev/null +++ b/internal/buildinfo/VERSION @@ -0,0 +1 @@ +0.1.0-dev diff --git a/internal/buildinfo/buildinfo.go b/internal/buildinfo/buildinfo.go new file mode 100644 index 0000000..1f2f7ef --- /dev/null +++ b/internal/buildinfo/buildinfo.go @@ -0,0 +1,18 @@ +// Package buildinfo reports the OpenIaC release version. +package buildinfo + +import ( + _ "embed" + "strings" +) + +// raw holds the VERSION file that sits next to this package. Keeping the +// version in a file rather than in a constant means the CLI, the Makefile and +// a plain `go build` all read the same value. +// +//go:embed VERSION +var raw string + +// Version is the release version, for example "0.1.0". A development build +// reports a "-dev" suffix. +var Version = strings.TrimSpace(raw) diff --git a/internal/buildinfo/buildinfo_test.go b/internal/buildinfo/buildinfo_test.go new file mode 100644 index 0000000..1cc1a9a --- /dev/null +++ b/internal/buildinfo/buildinfo_test.go @@ -0,0 +1,20 @@ +package buildinfo_test + +import ( + "regexp" + "strings" + "testing" + + "github.com/be-thomas/openiac/internal/buildinfo" +) + +func TestVersion(t *testing.T) { + if buildinfo.Version != strings.TrimSpace(buildinfo.Version) { + t.Fatalf("Version = %q, want no surrounding whitespace", buildinfo.Version) + } + // MAJOR.MINOR.PATCH, optionally followed by a pre-release suffix. + pattern := regexp.MustCompile(`^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$`) + if !pattern.MatchString(buildinfo.Version) { + t.Fatalf("Version = %q, want MAJOR.MINOR.PATCH", buildinfo.Version) + } +} diff --git a/pkg/engine/golden_test.go b/pkg/engine/golden_test.go new file mode 100644 index 0000000..14a9a20 --- /dev/null +++ b/pkg/engine/golden_test.go @@ -0,0 +1,151 @@ +package engine_test + +import ( + "flag" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/be-thomas/openiac/pkg/emitters" + "github.com/be-thomas/openiac/pkg/engine" +) + +// update rewrites the golden files instead of comparing against them: +// +// go test ./pkg/engine -run TestGolden -update +var update = flag.Bool("update", false, "rewrite golden files") + +// goldenTargets is the pair of emitters every snapshot covers. +var goldenTargets = []engine.Target{engine.TargetCDK, engine.TargetPulumi} + +// TestGoldenAwsWebApp snapshots the documented example in both targets. It is +// the regression guard for emitter output: any change to generated TypeScript +// has to be visible here. +func TestGoldenAwsWebApp(t *testing.T) { + snapshot(t, "aws-web-app", filepath.Join("examples", "aws-web-app"), false) +} + +// TestGoldenWarned snapshots a module the targets cannot fully convert, so the +// warning section of the snapshots is exercised. Without it a warning-free +// fixture would leave the section empty in every golden file and changes to +// warning collection would go unnoticed. +func TestGoldenWarned(t *testing.T) { + snapshot(t, "warned", filepath.Join("pkg", "engine", "testdata", "fixtures", "warned"), true) +} + +// snapshot converts a fixture in both targets and compares each result with +// its committed golden file. wantWarnings fails the test unless every target +// reports at least one warning, so a fixture added for that purpose cannot +// decay into a copy of the warning-free case. +func snapshot(t *testing.T, name, dir string, wantWarnings bool) { + t.Helper() + + // The generated "// Source:" comment carries the path the parser was given, + // so the test runs from the repository root to keep the snapshot portable. + t.Chdir(repoRoot(t)) + + graph, err := engine.Parse(dir) + if err != nil { + t.Fatalf("Parse: %v", err) + } + + results, err := engine.Convert(graph, goldenTargets, emitters.Options{ + StackName: "OpenIacStack", + ProjectName: "openiac", + }) + if err != nil { + t.Fatalf("Convert: %v", err) + } + if len(results) != len(goldenTargets) { + t.Fatalf("results = %d, want %d", len(results), len(goldenTargets)) + } + + for _, result := range results { + if wantWarnings && len(result.Warnings) == 0 { + t.Errorf("%s: warnings = 0, want at least one", result.Target) + } + path := filepath.Join("pkg", "engine", "testdata", "golden", name+"."+string(result.Target)+".txt") + checkGolden(t, path, renderResult(result)) + } +} + +// repoRoot finds the module root, so the snapshots do not depend on the +// directory the test binary was started from: `go test` starts in pkg/engine, +// but a prebuilt binary or a debugger can start anywhere. +func repoRoot(t *testing.T) string { + t.Helper() + if _, file, _, ok := runtime.Caller(0); ok { + if root, ok := moduleRoot(filepath.Dir(file)); ok { + return root + } + } + wd, err := os.Getwd() + if err != nil { + t.Fatalf("working directory: %v", err) + } + if root, ok := moduleRoot(wd); ok { + return root + } + t.Fatalf("cannot find go.mod above %s", wd) + return "" +} + +// moduleRoot walks up from dir until it finds a go.mod. +func moduleRoot(dir string) (string, bool) { + for { + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { + return dir, true + } + parent := filepath.Dir(dir) + if parent == dir { + return "", false + } + dir = parent + } +} + +// renderResult turns a target result into the text that is snapshotted: each +// generated file under a header, then every warning in order. +func renderResult(result engine.TargetResult) string { + var b strings.Builder + for i, file := range result.Files { + if i > 0 { + b.WriteString("\n") + } + fmt.Fprintf(&b, "// ==== %s ====\n", file.Path) + b.WriteString(file.Content) + if !strings.HasSuffix(file.Content, "\n") { + b.WriteString("\n") + } + } + b.WriteString("\n// ==== warnings ====\n") + for _, warning := range result.Warnings { + fmt.Fprintf(&b, "// %s\n", warning) + } + return b.String() +} + +func checkGolden(t *testing.T, path, got string) { + t.Helper() + if *update { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("create golden directory: %v", err) + } + if err := os.WriteFile(path, []byte(got), 0o644); err != nil { + t.Fatalf("write %s: %v", path, err) + } + return + } + + want, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v (run with -update to create it)", path, err) + } + if string(want) != got { + t.Errorf("%s is stale; run `go test ./pkg/engine -run TestGolden -update`\n--- want\n%s\n--- got\n%s", + path, want, got) + } +} diff --git a/pkg/engine/testdata/fixtures/warned/main.tf b/pkg/engine/testdata/fixtures/warned/main.tf new file mode 100644 index 0000000..401d3bc --- /dev/null +++ b/pkg/engine/testdata/fixtures/warned/main.tf @@ -0,0 +1,21 @@ +terraform { + required_version = ">= 1.0" + + backend "s3" { + bucket = "openiac-state" + key = "warned.tfstate" + region = "us-east-1" + } +} + +# A moved block is valid Terraform 1.1+ but has no target equivalent, so the +# emitters keep it out of the generated code and report it as a warning. This +# fixture exists so the golden snapshots exercise the warning section. +moved { + from = aws_s3_bucket.old + to = aws_s3_bucket.assets +} + +resource "aws_s3_bucket" "assets" { + bucket = "openiac-warned-assets" +} diff --git a/pkg/engine/testdata/golden/aws-web-app.cdk.txt b/pkg/engine/testdata/golden/aws-web-app.cdk.txt new file mode 100644 index 0000000..052606a --- /dev/null +++ b/pkg/engine/testdata/golden/aws-web-app.cdk.txt @@ -0,0 +1,73 @@ +// ==== index.ts ==== +// Generated by OpenIaC. Review this file before deploying. +// Source: examples/aws-web-app/main.tf +import * as cdk from 'aws-cdk-lib'; +import * as ec2 from 'aws-cdk-lib/aws-ec2'; +import * as s3 from 'aws-cdk-lib/aws-s3'; +import * as sqs from 'aws-cdk-lib/aws-sqs'; +import { Construct } from 'constructs'; + +export interface OpenIacStackProps extends cdk.StackProps {} + +export class OpenIacStack extends cdk.Stack { + constructor(scope: Construct, id: string, props: OpenIacStackProps = {}) { + super(scope, id, props); + + // var.region + const region = this.node.tryGetContext("region") ?? "us-east-1"; + // var.environment + const environment = this.node.tryGetContext("environment") ?? "dev"; + + // aws_s3_bucket.assets + const assetsS3Bucket = new s3.Bucket(this, "aws_s3_bucket.assets", { + bucketName: `openiac-assets-${environment}`, + tags: {"Environment": environment}, + }); + // aws_sqs_queue.jobs + const jobsSqsQueue = new sqs.CfnQueue(this, "aws_sqs_queue.jobs", { + MessageRetentionPeriod: 1209600, + QueueName: "openiac-jobs", + VisibilityTimeout: 300, + }); + // aws_vpc.main + const mainVpc = new ec2.CfnVPC(this, "aws_vpc.main", { + CidrBlock: "10.0.0.0/16", + EnableDnsHostnames: true, + EnableDnsSupport: true, + Tags: [{ Key: "Environment", Value: environment }, { Key: "Name", Value: `openiac-${environment}` }], + }); + // aws_security_group.web + const webSecurityGroup = new ec2.CfnSecurityGroup(this, "aws_security_group.web", { + GroupDescription: "Allow HTTP from anywhere", + GroupName: "openiac-web", + Tags: [{ Key: "Name", Value: "openiac-web" }], + VpcId: mainVpc.ref, + SecurityGroupEgress: [{ CidrIp: "0.0.0.0/0", FromPort: 0, IpProtocol: "-1", ToPort: 0 }], + SecurityGroupIngress: [{ CidrIp: "0.0.0.0/0", FromPort: 80, IpProtocol: "tcp", ToPort: 80 }], + }); + // aws_subnet.public + const publicSubnet = new ec2.CfnSubnet(this, "aws_subnet.public", { + AvailabilityZone: `${region}a`, + CidrBlock: "10.0.1.0/24", + MapPublicIpOnLaunch: true, + Tags: [{ Key: "Name", Value: "openiac-public" }], + VpcId: mainVpc.ref, + }); + // aws_instance.web + const webInstance = new ec2.CfnInstance(this, "aws_instance.web", { + ImageId: "ami-0123456789abcdef0", + InstanceType: "t3.micro", + SubnetId: publicSubnet.ref, + Tags: [{ Key: "Name", Value: "openiac-web" }], + SecurityGroupIds: [webSecurityGroup.attrGroupId], + }); + + // output.bucket_arn + new cdk.CfnOutput(this, "bucket_arn", { value: assetsS3Bucket.bucketArn }); + // output.instance_ip + new cdk.CfnOutput(this, "instance_ip", { value: webInstance.attrPublicIp }); + + } +} + +// ==== warnings ==== diff --git a/pkg/engine/testdata/golden/aws-web-app.pulumi.txt b/pkg/engine/testdata/golden/aws-web-app.pulumi.txt new file mode 100644 index 0000000..e037e7f --- /dev/null +++ b/pkg/engine/testdata/golden/aws-web-app.pulumi.txt @@ -0,0 +1,71 @@ +// ==== index.ts ==== +// Generated by OpenIaC. Review this file before deploying. +// Source: examples/aws-web-app/main.tf +import * as pulumi from '@pulumi/pulumi'; +import * as aws from '@pulumi/aws'; + +const config = new pulumi.Config(); + +// var.region +const region = config.get("region") ?? "us-east-1"; + +// var.environment +const environment = config.get("environment") ?? "dev"; + +// aws_s3_bucket.assets +const assetsS3Bucket = new aws.s3.Bucket("assets", { + bucket: `openiac-assets-${environment}`, + tags: {"Environment": environment}, +}); + +// aws_sqs_queue.jobs +const jobsSqsQueue = new aws.sqs.Queue("jobs", { + messageRetentionSeconds: 1209600, + name: "openiac-jobs", + visibilityTimeoutSeconds: 300, +}); + +// aws_vpc.main +const mainVpc = new aws.ec2.Vpc("main", { + cidrBlock: "10.0.0.0/16", + enableDnsHostnames: true, + enableDnsSupport: true, + tags: {"Environment": environment, "Name": `openiac-${environment}`}, +}); + +// aws_security_group.web +const webSecurityGroup = new aws.ec2.SecurityGroup("web", { + description: "Allow HTTP from anywhere", + name: "openiac-web", + tags: {"Name": "openiac-web"}, + vpcId: mainVpc.id, + egress: [{ cidrBlocks: ["0.0.0.0/0"], fromPort: 0, protocol: "-1", toPort: 0 }], + ingress: [{ cidrBlocks: ["0.0.0.0/0"], fromPort: 80, protocol: "tcp", toPort: 80 }], +}); + +// aws_subnet.public +const publicSubnet = new aws.ec2.Subnet("public", { + availabilityZone: `${region}a`, + cidrBlock: "10.0.1.0/24", + mapPublicIpOnLaunch: true, + tags: {"Name": "openiac-public"}, + vpcId: mainVpc.id, +}); + +// aws_instance.web +const webInstance = new aws.ec2.Instance("web", { + ami: "ami-0123456789abcdef0", + instanceType: "t3.micro", + subnetId: publicSubnet.id, + tags: {"Name": "openiac-web"}, + vpcSecurityGroupIds: [webSecurityGroup.id], +}); + +// output.bucket_arn +export const bucketArn = assetsS3Bucket.arn; + +// output.instance_ip +export const instanceIp = webInstance.publicIp; + + +// ==== warnings ==== diff --git a/pkg/engine/testdata/golden/warned.cdk.txt b/pkg/engine/testdata/golden/warned.cdk.txt new file mode 100644 index 0000000..f6a6b87 --- /dev/null +++ b/pkg/engine/testdata/golden/warned.cdk.txt @@ -0,0 +1,24 @@ +// ==== index.ts ==== +// Generated by OpenIaC. Review this file before deploying. +// Source: pkg/engine/testdata/fixtures/warned/main.tf +import * as cdk from 'aws-cdk-lib'; +import * as s3 from 'aws-cdk-lib/aws-s3'; +import { Construct } from 'constructs'; + +export interface OpenIacStackProps extends cdk.StackProps {} + +export class OpenIacStack extends cdk.Stack { + constructor(scope: Construct, id: string, props: OpenIacStackProps = {}) { + super(scope, id, props); + + // aws_s3_bucket.assets + const assetsS3Bucket = new s3.Bucket(this, "aws_s3_bucket.assets", { + bucketName: "openiac-warned-assets", + }); + + } +} + +// ==== warnings ==== +// W_PRESERVED_BLOCK: a moved block at main.tf:14 is preserved but not converted +// W_TERRAFORM_BACKEND: terraform backend "s3" at main.tf:4 is not converted; configure state in the target stack instead diff --git a/pkg/engine/testdata/golden/warned.pulumi.txt b/pkg/engine/testdata/golden/warned.pulumi.txt new file mode 100644 index 0000000..c28aa8a --- /dev/null +++ b/pkg/engine/testdata/golden/warned.pulumi.txt @@ -0,0 +1,14 @@ +// ==== index.ts ==== +// Generated by OpenIaC. Review this file before deploying. +// Source: pkg/engine/testdata/fixtures/warned/main.tf +import * as aws from '@pulumi/aws'; + +// aws_s3_bucket.assets +const assetsS3Bucket = new aws.s3.Bucket("assets", { + bucket: "openiac-warned-assets", +}); + + +// ==== warnings ==== +// W_PRESERVED_BLOCK: a moved block at main.tf:14 is preserved but not converted +// W_TERRAFORM_BACKEND: terraform backend "s3" at main.tf:4 is not converted; configure state in the target stack instead