53 lines
929 B
Go
53 lines
929 B
Go
package hcl
|
|
|
|
import (
|
|
"io"
|
|
"reflect"
|
|
|
|
"github.com/hashicorp/hcl/v2/hclwrite"
|
|
|
|
"code.icb4dc0.de/buildr/buildr/modules"
|
|
)
|
|
|
|
type writerCfg struct {
|
|
SkipZeroValues bool
|
|
}
|
|
|
|
type WriterOption func(*writerCfg)
|
|
|
|
func WithSkipZeroValues(skip bool) WriterOption {
|
|
return func(cfg *writerCfg) {
|
|
cfg.SkipZeroValues = skip
|
|
}
|
|
}
|
|
|
|
func NewWriter[T modules.ModuleWithMeta](w io.Writer, opts ...WriterOption) *Writer[T] {
|
|
writer := &Writer[T]{writer: w}
|
|
|
|
for _, opt := range opts {
|
|
opt(&writer.writerCfg)
|
|
}
|
|
|
|
return writer
|
|
}
|
|
|
|
type Writer[T modules.ModuleWithMeta] struct {
|
|
writer io.Writer
|
|
writerCfg
|
|
}
|
|
|
|
func (w *Writer[T]) Write(in T) error {
|
|
f := hclwrite.NewEmptyFile()
|
|
|
|
block := hclwrite.NewBlock(modules.CategoryName(in.Category()), []string{in.Type(), in.Name()})
|
|
if err := w.marshalInto(reflect.ValueOf(in), block); err != nil {
|
|
return err
|
|
}
|
|
|
|
f.Body().AppendBlock(block)
|
|
|
|
_, err := f.WriteTo(w.writer)
|
|
|
|
return err
|
|
}
|