Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 2 additions & 3 deletions cmd/openiac/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand All @@ -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)
Expand Down
24 changes: 24 additions & 0 deletions cmd/openiac/main_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
}
}
4 changes: 4 additions & 0 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 ⏳
Expand Down
1 change: 1 addition & 0 deletions internal/buildinfo/VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.1.0-dev
18 changes: 18 additions & 0 deletions internal/buildinfo/buildinfo.go
Original file line number Diff line number Diff line change
@@ -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)
20 changes: 20 additions & 0 deletions internal/buildinfo/buildinfo_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
151 changes: 151 additions & 0 deletions pkg/engine/golden_test.go
Original file line number Diff line number Diff line change
@@ -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 {
Comment thread
be-thomas marked this conversation as resolved.
Resolved
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)
}
}
21 changes: 21 additions & 0 deletions pkg/engine/testdata/fixtures/warned/main.tf
Original file line number Diff line number Diff line change
@@ -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"
}
73 changes: 73 additions & 0 deletions pkg/engine/testdata/golden/aws-web-app.cdk.txt
Original file line number Diff line number Diff line change
@@ -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 ====
Loading
Loading