summaryrefslogtreecommitdiff
path: root/ext/transform/transformer.go
blob: 511d0a2907e3abea8741edc6a5cd5f580bd4066e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package transform

import (
	"github.com/hashicorp/hcl/v2"
)

// A Transformer takes a given body, applies some (possibly no-op)
// transform to it, and returns the new body.
//
// It must _not_ mutate the given body in-place.
//
// The transform call cannot fail, but it _can_ return a body that immediately
// returns diagnostics when its methods are called. NewErrorBody is a utility
// to help with this.
type Transformer interface {
	TransformBody(hcl.Body) hcl.Body
}

// TransformerFunc is a function type that implements Transformer.
type TransformerFunc func(hcl.Body) hcl.Body

// TransformBody is an implementation of Transformer.TransformBody.
func (f TransformerFunc) TransformBody(in hcl.Body) hcl.Body {
	return f(in)
}

type chain []Transformer

// Chain takes a slice of transformers and returns a single new
// Transformer that applies each of the given transformers in sequence.
func Chain(c []Transformer) Transformer {
	return chain(c)
}

func (c chain) TransformBody(body hcl.Body) hcl.Body {
	for _, t := range c {
		body = t.TransformBody(body)
	}
	return body
}