jx/cmd/cli/main.go
Matthew Rich 0a6d1a93ee
All checks were successful
Lint / golangci-lint (push) Successful in 10m9s
Declarative Tests / test (push) Successful in 1m21s
add support for multiple document definitions
2024-04-12 09:08:08 -07:00

100 lines
2.3 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package main
import (
"io"
"os"
"flag"
"log"
"log/slog"
"errors"
_ "fmt"
_ "gopkg.in/yaml.v3"
"decl/internal/resource"
)
func main() {
var programLevel = new(slog.LevelVar)
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel}))
slog.SetDefault(logger)
if debugLogging,ok := os.LookupEnv("DECL_DEBUG"); ok && debugLogging != "" {
programLevel.Set(slog.LevelDebug)
} else {
programLevel.Set(slog.LevelError)
}
file := flag.String("resource-file", "", "Resource file path")
resourceUri := flag.String("import-resource", "", "Add an existing resource")
flag.Parse()
var resourceFile *os.File
var inputFileErr error
slog.Info("args", "resource-file", *file, "import-resource", *resourceUri)
if *file == "-" {
if stdinInfo, stdinErr := os.Stdin.Stat(); stdinErr == nil {
if (stdinInfo.Mode() & os.ModeCharDevice) == 0 {
resourceFile = os.Stdin
}
} else {
inputFileErr = stdinErr
}
} else if *file != "" {
resourceFile,inputFileErr = os.Open(*file)
}
if inputFileErr != nil {
log.Fatal(inputFileErr)
}
documents := make([]*resource.Document, 0, 100)
decoder := resource.NewYAMLDecoder(resourceFile)
encoder := resource.NewYAMLEncoder(os.Stdout)
index := 0
slog.Info("loading resource document", "file", resourceFile)
documents = append(documents, resource.NewDocument())
if resourceFile != nil {
for {
d := documents[index]
e := decoder.Decode(d)
if errors.Is(e, io.EOF) {
if len(documents) > 1 {
documents[index] = nil
}
break
}
if e != nil {
log.Fatal(e)
}
if validationErr := d.Validate(); validationErr != nil {
log.Fatal(validationErr)
}
if applyErr := d.Apply(); applyErr != nil {
log.Fatal(applyErr)
}
documents = append(documents, resource.NewDocument())
index++
}
}
for _,document := range documents {
if document != nil {
if *resourceUri != "" {
slog.Info("importing resource", "resource", *resourceUri)
if addResourceErr := document.AddResource(*resourceUri); addResourceErr != nil {
log.Fatal(addResourceErr)
}
}
if documentGenerateErr := encoder.Encode(document); documentGenerateErr != nil {
log.Fatal(documentGenerateErr)
}
}
}
}