generator

package
v1.228.0-rc.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package generator provides sentinel error aliases from the central errors package. These are re-exported for backward compatibility and convenience.

Package generator provides a unified interface for generating Terraform configuration files. This includes varfiles, provider overrides, required_providers blocks, and backend configuration.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrGeneratorNotFound is returned when a requested generator is not in the registry.
	ErrGeneratorNotFound = errUtils.ErrGeneratorNotFound

	// ErrInvalidContext is returned when the generator context is missing required data.
	ErrInvalidContext = errUtils.ErrInvalidGeneratorCtx

	// ErrValidationFailed is returned when generator validation fails.
	ErrValidationFailed = errUtils.ErrGeneratorValidation

	// ErrGenerationFailed is returned when generation fails.
	ErrGenerationFailed = errUtils.ErrGenerationFailed

	// ErrWriteFailed is returned when writing the generated file fails.
	ErrWriteFailed = errUtils.ErrGeneratorWriteFailed

	// ErrMissingWorkingDir is returned when WorkingDir is not set.
	ErrMissingWorkingDir = errUtils.ErrMissingWorkingDir

	// ErrMissingComponent is returned when Component is not set.
	ErrMissingComponent = errUtils.ErrComponentEmpty

	// ErrMissingStack is returned when Stack is not set.
	ErrMissingStack = errUtils.ErrStackEmpty

	// ErrMissingProviderSource is returned when a required_provider is missing the source field.
	ErrMissingProviderSource = errUtils.ErrMissingProviderSource
)

Re-exported errors from the central errors package. These provide the generator-specific errors for use within this package.

View Source
var Templates embed.FS

Templates contains embedded init/scaffold templates shipped with the binary. The `all:` prefix embeds dot- and underscore-prefixed files too (e.g. `.gitignore` and `stacks/_defaults.yaml`), which plain `//go:embed` skips.

Functions

func ApplyOptions

func ApplyOptions(ctx *GeneratorContext, opts ...Option)

ApplyOptions applies functional options to a GeneratorContext.

func ApplyProviderContributors added in v1.222.0

func ApplyProviderContributors(ctx context.Context, genCtx *GeneratorContext) (map[string]any, error)

ApplyProviderContributors runs all registered contributors and deep-merges their fragments UNDER the component's existing ProvidersSection — so an explicit stack `providers:` value always wins over a contribution. It mutates and returns genCtx.ProvidersSection.

func Generate

func Generate(ctx context.Context, name string, genCtx *GeneratorContext, writer Writer) error

Generate runs a specific generator by name.

func GenerateAll

func GenerateAll(ctx context.Context, genCtx *GeneratorContext, writer Writer) error

GenerateAll runs all registered generators that should generate.

func InitGitRepository added in v1.224.0

func InitGitRepository(opts InitGitOptions) (skipped bool, headSHA string, err error)

InitGitRepository initializes targetPath as a git repository and creates an initial commit. If targetPath is already inside a git repository, it is left untouched and skipped=true is returned. HeadSHA is the hash of the initial commit (empty when skipped), so callers can pin it as the project's frozen scaffold base ref -- see PinInitialBaseRef.

func PinInitialBaseRef added in v1.227.0

func PinInitialBaseRef(targetPath, headSHA string, opts ...PinOption) error

PinInitialBaseRef persists headSHA (the initial commit created by InitGitRepository) as targetPath's frozen scaffold base ref, in .atmos/scaffold/metadata.yaml. A later `--update` with no explicit --base-ref reads this pin instead of defaulting to live HEAD, so it always 3-way-merges against the commit that actually contains the pristine generated content -- regardless of what the user has committed since. Without this, a customization the user commits after generation becomes indistinguishable from the unmodified base by the time --update runs, and the merge silently lets the freshly rendered template overwrite it.

TargetPath and headSHA are the operation's actual subject (what to pin, and where) and stay positional; the template's own descriptive metadata (name/version/source) is optional configuration, passed via WithTemplateName/WithTemplateVersion/WithSource.

No-op when headSHA is empty (InitGitRepository returned skipped=true, meaning targetPath was already inside a git repository and no commit -- containing verified pristine content -- was created for atmos to pin).

func Register

func Register(gen Generator)

Register adds a generator to the registry. This is typically called from a generator's init() function.

func RegisterProviderContributor added in v1.222.0

func RegisterProviderContributor(c ProviderContributor)

RegisterProviderContributor adds a provider-config contributor to the registry. Typically called from a contributor package's init().

Types

type FileWriter

type FileWriter struct {
	// contains filtered or unexported fields
}

FileWriter is the production implementation that writes to the filesystem.

func NewFileWriter

func NewFileWriter(opts ...WriterOption) *FileWriter

NewFileWriter creates a new file writer with optional configuration.

func (*FileWriter) WriteHCL

func (w *FileWriter) WriteHCL(dir, filename string, data map[string]any) error

WriteHCL writes content as HCL to the specified directory and filename.

func (*FileWriter) WriteJSON

func (w *FileWriter) WriteJSON(dir, filename string, data map[string]any) error

WriteJSON writes content as JSON to the specified directory and filename.

type Format

type Format string

Format represents the output format for generated files.

const (
	// FormatJSON generates JSON output (.tf.json files).
	FormatJSON Format = "json"
	// FormatHCL generates HCL output (.tf files).
	FormatHCL Format = "hcl"
)

type Generator

type Generator interface {
	// Name returns the unique identifier for this generator.
	Name() string

	// Generate produces the Terraform configuration content.
	// Returns a map structure suitable for JSON/HCL serialization.
	Generate(ctx context.Context, genCtx *GeneratorContext) (map[string]any, error)

	// Validate checks if the generator context has sufficient data.
	Validate(genCtx *GeneratorContext) error

	// DefaultFilename returns the default output filename.
	DefaultFilename() string

	// ShouldGenerate returns true if this generator should run.
	// Based on whether relevant config exists.
	ShouldGenerate(genCtx *GeneratorContext) bool
}

Generator is the interface for Terraform file generators.

type GeneratorContext

type GeneratorContext struct {
	// AtmosConfig holds the Atmos configuration.
	AtmosConfig *schema.AtmosConfiguration

	// StackInfo holds the processed stack and component information.
	StackInfo *schema.ConfigAndStacksInfo

	// Component is the component name.
	Component string

	// Stack is the stack name.
	Stack string

	// ComponentPath is the path to the component directory.
	ComponentPath string

	// WorkingDir is the directory where generated files will be written.
	WorkingDir string

	// VarsSection contains the component variables.
	VarsSection map[string]any

	// ProvidersSection contains the provider configuration.
	ProvidersSection map[string]any

	// RequiredVersion is the Terraform version constraint (e.g., ">= 1.10.1").
	RequiredVersion string

	// RequiredProviders maps provider names to their configuration.
	// Example: {"aws": {"source": "hashicorp/aws", "version": "~> 5.0"}}.
	RequiredProviders map[string]map[string]any

	// BackendType is the Terraform backend type (e.g., "s3", "gcs").
	BackendType string

	// BackendConfig contains the backend configuration.
	BackendConfig map[string]any

	// DryRun when true, prevents file writes.
	DryRun bool

	// Format specifies the output format (JSON or HCL).
	Format Format

	// CustomFilename overrides the default filename when set.
	CustomFilename string
}

GeneratorContext provides component and stack context to generators.

func NewGeneratorContext

func NewGeneratorContext(
	atmosConfig *schema.AtmosConfiguration,
	info *schema.ConfigAndStacksInfo,
	workingDir string,
) *GeneratorContext

NewGeneratorContext creates a GeneratorContext from ConfigAndStacksInfo.

func NewGeneratorContextWithOptions

func NewGeneratorContextWithOptions(
	atmosConfig *schema.AtmosConfiguration,
	info *schema.ConfigAndStacksInfo,
	workingDir string,
	opts ...Option,
) *GeneratorContext

NewGeneratorContextWithOptions creates a GeneratorContext with functional options.

type GeneratorRegistry

type GeneratorRegistry struct {
	// contains filtered or unexported fields
}

GeneratorRegistry manages generator registration and execution.

func GetRegistry

func GetRegistry() *GeneratorRegistry

GetRegistry returns the global generator registry singleton.

func (*GeneratorRegistry) Get

func (r *GeneratorRegistry) Get(name string) (Generator, error)

Get retrieves a generator by name.

func (*GeneratorRegistry) List

func (r *GeneratorRegistry) List() []string

List returns all registered generator names in sorted order.

type InitGitOptions added in v1.224.0

type InitGitOptions struct {
	TargetPath      string
	TemplateName    string
	TemplateVersion string
}

InitGitOptions controls repository initialization after project generation.

type MockWriter

type MockWriter struct {
	// Written maps file paths to their written content.
	Written map[string]map[string]any
	// WriteErr if set, will be returned by Write operations.
	WriteErr error
}

MockWriter is a test implementation that captures written content.

func NewMockWriter

func NewMockWriter() *MockWriter

NewMockWriter creates a new mock writer for testing.

func (*MockWriter) Clear

func (w *MockWriter) Clear()

Clear resets the mock writer state.

func (*MockWriter) GetWritten

func (w *MockWriter) GetWritten(dir, filename string) (map[string]any, bool)

GetWritten returns the content written to a specific path.

func (*MockWriter) WriteHCL

func (w *MockWriter) WriteHCL(dir, filename string, data map[string]any) error

WriteHCL captures the content without writing to disk.

func (*MockWriter) WriteJSON

func (w *MockWriter) WriteJSON(dir, filename string, data map[string]any) error

WriteJSON captures the content without writing to disk.

type Option

type Option func(*GeneratorContext)

Option is a functional option for configuring generators.

func WithDryRun

func WithDryRun(dryRun bool) Option

WithDryRun enables dry-run mode (no file writes).

func WithFormat

func WithFormat(format Format) Option

WithFormat sets the output format.

func WithWorkingDir

func WithWorkingDir(dir string) Option

WithWorkingDir sets the working directory for output files.

type PinOption added in v1.227.0

type PinOption func(*pinOptions)

PinOption is a functional option for PinInitialBaseRef.

func WithSource added in v1.227.0

func WithSource(source string) PinOption

WithSource sets the template source recorded in the pinned metadata.

func WithTemplateName added in v1.227.0

func WithTemplateName(name string) PinOption

WithTemplateName sets the template name recorded in the pinned metadata.

func WithTemplateVersion added in v1.227.0

func WithTemplateVersion(version string) PinOption

WithTemplateVersion sets the template version recorded in the pinned metadata.

type ProviderContributor added in v1.222.0

type ProviderContributor interface {
	// Name is the unique contributor identifier.
	Name() string

	// Contribute returns a provider fragment keyed by Terraform provider name
	// (e.g. {"aws": {"skip_requesting_account_id": true, ...}}), or nil/empty when
	// this contributor does not apply to the component in genCtx.
	Contribute(ctx context.Context, genCtx *GeneratorContext) (map[string]any, error)
}

ProviderContributor contributes a Terraform provider-config fragment to a component's ProvidersSection before generation.

Contributors let cross-cutting concerns inject provider behavior flags that environment variables cannot set — mirroring how Terraform RC management assembles `.terraformrc` from contributions. The first consumer is the emulator binding (endpoints + skip-flags + dummy creds); auth and the registry cache can register contributors later without reworking the core.

func ProviderContributors added in v1.222.0

func ProviderContributors() []ProviderContributor

ProviderContributors returns the registered contributors sorted by name (stable order).

type Writer

type Writer interface {
	// WriteJSON writes content as JSON to the specified directory and filename.
	WriteJSON(dir, filename string, data map[string]any) error
	// WriteHCL writes content as HCL to the specified directory and filename.
	WriteHCL(dir, filename string, data map[string]any) error
}

Writer handles file output for generators.

type WriterOption

type WriterOption func(*FileWriter)

WriterOption is a functional option for configuring the file writer.

func WithFileMode

func WithFileMode(mode os.FileMode) WriterOption

WithFileMode sets the file mode for written files.

Directories

Path Synopsis
Package providers provides a generator for Terraform provider override files.
Package providers provides a generator for Terraform provider override files.
Package required_providers provides a generator for Terraform required_providers blocks.
Package required_providers provides a generator for Terraform required_providers blocks.
Package scaffoldhooks runs a scaffold template's declarative hooks: block around atmos scaffold generate / atmos init.
Package scaffoldhooks runs a scaffold template's declarative hooks: block around atmos scaffold generate / atmos init.
Package source resolves scaffold templates from local paths or remote sources (git, https, s3) into a templates.Configuration ready for generation.
Package source resolves scaffold templates from local paths or remote sources (git, https, s3) into a templates.Configuration ready for generation.
Package varfile provides a generator for Terraform variable files (.tfvars.json).
Package varfile provides a generator for Terraform variable files (.tfvars.json).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL