nix-amer/internal/cnf/parser/bash/encoder.go

60 lines
929 B
Go
Raw Normal View History

package bash
import (
"fmt"
"io"
"strings"
)
// Encoder implements parser.Encoder
type Encoder struct {
writer io.Writer
prefix []byte
indent []byte
}
// Encode is the main function of the parser.Encoder interface
func (e *Encoder) Encode(v interface{}) error {
// check 'v'
vcast, ok := v.(*File)
if !ok {
return ErrInvalidReceiver
}
// empty config
if len(vcast.Lines) < 1 {
return nil
}
for _, line := range vcast.Lines {
// line representation
repr := ""
// ASSIGNMENT
if line.Type == ASSIGNMENT {
repr = fmt.Sprintf("%s%s=%s;", line.Components[0], line.Components[1], line.Components[2])
// optional comment
if len(line.Components[3]) > 0 {
repr += fmt.Sprintf(" %s", line.Components[3])
}
// ANY
} else {
repr = strings.Join(line.Components, "")
}
repr += "\n"
_, err := e.writer.Write([]byte(repr))
if err != nil {
return err
}
}
return nil
}