address

package module
v0.0.0-...-3e5760e Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2025 License: MPL-2.0 Imports: 13 Imported by: 4

README

tf-address

CircleCI

This package provides utilities for properly parsing Terraform addresses.

The parser is implemented using pigeon, a PEG implementation.

Addresses

Resource addresses are described by the Terraform documentation.

Identifiers are described in the Terraform Configuration Syntax document

Generating

If you change the peg, please regenerate the go code with:

go get -u github.com/mna/pigeon
go generate .

You may need to clean up the go.mod with:

go mod tidy

Examples

package main

import (
	"fmt"

	address "github.com/hashicorp/go-terraform-address"
)

func main() {

	a, err := address.NewAddress(`module.first.module.second["xyz"].resource.name[2]`)
	if err != nil {
		panic(err)
	}

	fmt.Println(len(a.ModulePath))                  // 2
	fmt.Println(a.ModulePath[0].Name)               // "first"
	fmt.Println(a.ModulePath[1].Index.String())     // "xyz"
	fmt.Printf("%T\n", a.ModulePath[1].Index.Value) // string
	fmt.Println(a.ResourceSpec.Type)                // "resource"
	fmt.Println(a.ResourceSpec.Name)                // "name"
	fmt.Printf("%T\n", a.ResourceSpec.Index.Value)  // int
}

Documentation

Overview

Package address contains logic for parsing a Terraform address.

The Terraform address grammar is documented at https://www.terraform.io/docs/internals/resource-addressing.html

Parsing is implemented using Pigeon, a PEG parser generator.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(filename string, b []byte, opts ...Option) (interface{}, error)

Parse parses the data from b using filename as information in the error messages.

func ParseFile

func ParseFile(filename string, opts ...Option) (i interface{}, err error)

ParseFile parses the file identified by filename.

func ParseReader

func ParseReader(filename string, r io.Reader, opts ...Option) (interface{}, error)

ParseReader parses the data from r using filename as information in the error messages.

Types

type Address

type Address struct {
	ModulePath   ModulePath
	ResourceSpec ResourceSpec
}

Address holds the parsed components of a Terraform address.

func NewAddress

func NewAddress(a string) (*Address, error)

NewAddress parses the given address `a` into an Address struct. Returns an error if we find a malformed address. [module path][resource spec]

func (*Address) Clone

func (a *Address) Clone() *Address

Clone copies the memory containing the address structure.

func (*Address) String

func (a *Address) String() string

String representation of the address.

type Cloner

type Cloner interface {
	Clone() interface{}
}

Cloner is implemented by any value that has a Clone method, which returns a copy of the value. This is mainly used for types which are not passed by value (e.g map, slice, chan) or structs that contain such types.

This is used in conjunction with the global state feature to create proper copies of the state to allow the parser to properly restore the state in the case of backtracking.

type Index

type Index struct {
	Value interface{}
}

Index of either a module or a resource. Can either be an int or a string.

func (*Index) String

func (i *Index) String() string

String representation of an index. If the index is a string, it will be quoted and escaped using go's string escaping semantics.

type Module

type Module struct {
	// Name of the module
	Name string
	// Index of the module. May be nil.
	Index Index
}

Module represents a module component of an address. module.module_name[module index]

func (*Module) String

func (m *Module) String() string

String representation of the module. The literal `module.` will be prepended.

type ModulePath

type ModulePath []Module

ModulePath holds a list of modules contained in the address. The furthest module on the left-hand side (outer-most) of the address is at index 0.

func (ModulePath) String

func (m ModulePath) String() string

String representation of the path component of an address.

type Option

type Option func(*parser) Option

Option is a function that can set an option on the parser. It returns the previous setting as an Option.

func AllowInvalidUTF8

func AllowInvalidUTF8(b bool) Option

AllowInvalidUTF8 creates an Option to allow invalid UTF-8 bytes. Every invalid UTF-8 byte is treated as a utf8.RuneError (U+FFFD) by character class matchers and is matched by the any matcher. The returned matched value, c.text and c.offset are NOT affected.

The default is false.

func Debug

func Debug(b bool) Option

Debug creates an Option to set the debug flag to b. When set to true, debugging information is printed to stdout while parsing.

The default is false.

func Entrypoint

func Entrypoint(ruleName string) Option

Entrypoint creates an Option to set the rule name to use as entrypoint. The rule name must have been specified in the -alternate-entrypoints if generating the parser with the -optimize-grammar flag, otherwise it may have been optimized out. Passing an empty string sets the entrypoint to the first rule in the grammar.

The default is to start parsing at the first rule in the grammar.

func GlobalStore

func GlobalStore(key string, value interface{}) Option

GlobalStore creates an Option to set a key to a certain value in the globalStore.

func InitState

func InitState(key string, value interface{}) Option

InitState creates an Option to set a key to a certain value in the global "state" store.

func MaxExpressions

func MaxExpressions(maxExprCnt uint64) Option

MaxExpressions creates an Option to stop parsing after the provided number of expressions have been parsed, if the value is 0 then the parser will parse for as many steps as needed (possibly an infinite number).

The default for maxExprCnt is 0.

func Memoize

func Memoize(b bool) Option

Memoize creates an Option to set the memoize flag to b. When set to true, the parser will cache all results so each expression is evaluated only once. This guarantees linear parsing time even for pathological cases, at the expense of more memory and slower times for typical cases.

The default is false.

func Recover

func Recover(b bool) Option

Recover creates an Option to set the recover flag to b. When set to true, this causes the parser to recover from panics and convert it to an error. Setting it to false can be useful while debugging to access the full stack trace.

The default is true.

func Statistics

func Statistics(stats *Stats, choiceNoMatch string) Option

Statistics adds a user provided Stats struct to the parser to allow the user to process the results after the parsing has finished. Also the key for the "no match" counter is set.

Example usage:

input := "input"
stats := Stats{}
_, err := Parse("input-file", []byte(input), Statistics(&stats, "no match"))
if err != nil {
    log.Panicln(err)
}
b, err := json.MarshalIndent(stats.ChoiceAltCnt, "", "  ")
if err != nil {
    log.Panicln(err)
}
fmt.Println(string(b))

type ResourceSpec

type ResourceSpec struct {
	Type  string
	Name  string
	Index Index
}

ResourceSpec describes the resource of an address. resource_type.resource_name[resource index]

func (*ResourceSpec) String

func (r *ResourceSpec) String() string

String representation of the resource component of an address.

type Stats

type Stats struct {
	// ExprCnt counts the number of expressions processed during parsing
	// This value is compared to the maximum number of expressions allowed
	// (set by the MaxExpressions option).
	ExprCnt uint64

	// ChoiceAltCnt is used to count for each ordered choice expression,
	// which alternative is used how may times.
	// These numbers allow to optimize the order of the ordered choice expression
	// to increase the performance of the parser
	//
	// The outer key of ChoiceAltCnt is composed of the name of the rule as well
	// as the line and the column of the ordered choice.
	// The inner key of ChoiceAltCnt is the number (one-based) of the matching alternative.
	// For each alternative the number of matches are counted. If an ordered choice does not
	// match, a special counter is incremented. The name of this counter is set with
	// the parser option Statistics.
	// For an alternative to be included in ChoiceAltCnt, it has to match at least once.
	ChoiceAltCnt map[string]map[string]int
}

Stats stores some statistics, gathered during parsing

Jump to

Keyboard shortcuts

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