1
0
Fork 0
mirror of https://github.com/Luzifer/korvike.git synced 2024-12-20 19:21:17 +00:00
korvike/main.go

105 lines
2.3 KiB
Go
Raw Permalink Normal View History

2016-07-31 19:13:01 +00:00
package main
import (
"fmt"
"io"
"log"
"os"
"text/template"
"github.com/Luzifer/go_helpers/v2/env"
2016-09-14 11:06:04 +00:00
korvike "github.com/Luzifer/korvike/functions"
"github.com/Luzifer/rconfig/v2"
2016-07-31 19:13:01 +00:00
)
var (
cfg = struct {
Input string `flag:"in,i" default:"-" description:"Source to read the template from ('-' = stdin)"`
KeyPairs []string `flag:"key-value,v" default:"" description:"Key-value pairs to use in templating (-v key=value)"`
Output string `flag:"out,o" default:"-" description:"Destination to write the output to ('-' = stdout)"`
VersionAndExit bool `flag:"version" default:"false" description:"Prints current version and exits"`
}{}
version = "dev"
)
func initApp() (err error) {
2016-07-31 19:13:01 +00:00
if err := rconfig.Parse(&cfg); err != nil {
return fmt.Errorf("parsing CLI options: %w", err)
2016-07-31 19:13:01 +00:00
}
return nil
2016-07-31 19:13:01 +00:00
}
func openInput(f string) (io.Reader, error) {
if f == "-" {
return os.Stdin, nil
}
if _, err := os.Stat(f); err != nil {
return nil, fmt.Errorf("finding file %q: %s", f, err)
}
r, err := os.Open(f) //#nosec G304 // Intended to use user-given file
if err != nil {
return nil, fmt.Errorf("opening file: %w", err)
2016-07-31 19:13:01 +00:00
}
return r, nil
2016-07-31 19:13:01 +00:00
}
func openOutput(f string) (io.Writer, error) {
if f == "-" {
return os.Stdout, nil
}
w, err := os.Create(f) //#nosec G304 // Intended to use user-given file
if err != nil {
return nil, fmt.Errorf("creating file: %w", err)
}
return w, nil
2016-07-31 19:13:01 +00:00
}
func main() {
var err error
if err = initApp(); err != nil {
log.Fatalf("initializing app: %s", err)
}
if cfg.VersionAndExit {
fmt.Printf("korvike %s\n", version) //nolint:forbidigo
os.Exit(0)
}
2016-07-31 19:13:01 +00:00
in, err := openInput(cfg.Input)
if err != nil {
log.Fatalf("opening input: %s", err)
2016-07-31 19:13:01 +00:00
}
out, err := openOutput(cfg.Output)
if err != nil {
log.Fatalf("opening output: %s", err)
2016-07-31 19:13:01 +00:00
}
rawTpl, err := io.ReadAll(in)
2016-07-31 19:13:01 +00:00
if err != nil {
log.Fatalf("reading from input: %s", err)
2016-07-31 19:13:01 +00:00
}
2016-09-14 11:06:04 +00:00
tpl, err := template.New("in").Funcs(korvike.GetFunctionMap()).Parse(string(rawTpl))
2016-07-31 19:13:01 +00:00
if err != nil {
log.Fatalf("parsing template: %s", err)
2016-07-31 19:13:01 +00:00
}
vars := map[string]interface{}{}
for k, v := range env.ListToMap(cfg.KeyPairs) {
vars[k] = v
}
korvike.SetSubTemplateVariables(vars)
if err := tpl.Execute(out, vars); err != nil {
log.Fatalf("executing template: %s", err)
2016-07-31 19:13:01 +00:00
}
}