Skip to content

Commit

Permalink
some cobra work
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-huganir committed Mar 19, 2024
1 parent 0f49a58 commit a878421
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 48 deletions.
95 changes: 63 additions & 32 deletions cmd/yutc/yutc.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,86 +2,117 @@ package main

import (
"bytes"
"context"
"github.com/adam-huganir/yutc/internal"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"os"
"path/filepath"
)

var YutcLog = &internal.YutcLog
var rootCLI = &cobra.Command{
Use: "yutc [ OPTIONS ... ] templates ...",
Example: "yutc -d data.yaml -c common.tmpl -o output.yaml template.tmpl",
Args: cobra.MinimumNArgs(1),
Run: run,
}

func main() {
var err error
func initCLI(cmd *cobra.Command) *internal.CLISettings {
// Define flags
var overwrite, version bool
var dataFiles, commonTemplateFiles []string
var commonTemplates []*bytes.Buffer
var output string
runSettings := &internal.CLISettings{}

internal.InitLogger()
YutcLog.Trace().Msg("Starting yutc...")

pflag.StringArrayVarP(
&dataFiles,
cmd.Flags().SortFlags = false
cmd.Flags().StringArrayVarP(
&runSettings.DataFiles,
"data",
"d",
nil,
"Data file to parse and merge. Can be a file or a URL. "+
"Can be specified multiple times and the inputs will be merged.",
)
pflag.StringArrayVarP(
&commonTemplateFiles,
cmd.Flags().StringArrayVarP(
&runSettings.CommonTemplateFiles,
"common-templates",
"c",
nil,
"Templates to be shared across all arguments in template list. Can be a file or a URL. Can be specified multiple times.",
)
pflag.StringVarP(&output, "output", "o", "-", "Output file/directory, defaults to stdout")
pflag.BoolVarP(&overwrite, "overwrite", "w", false, "Overwrite existing files")
pflag.BoolVar(&version, "version", false, "Print the version and exit")
pflag.Parse()
templateFiles := pflag.Args()
if version {
cmd.Flags().StringVarP(&runSettings.Output, "output", "o", "-", "Output file/directory, defaults to stdout")
cmd.Flags().BoolVarP(&runSettings.Overwrite, "overwrite", "w", false, "Overwrite existing files")
cmd.Flags().BoolVar(&runSettings.Version, "version", false, "Print the version and exit")
return runSettings
}

func main() {

internal.InitLogger()
YutcLog.Trace().Msg("Starting yutc...")

cmd := rootCLI
//args := os.Args[1:]
ctx := cmd.Context()
if ctx == nil {
ctx = context.Background()
}
settings := initCLI(cmd)
ctx = context.WithValue(ctx, "settings", settings)

err := rootCLI.ExecuteContext(ctx)
if err != nil {
YutcLog.Error().Msg(err.Error())
os.Exit(10101)
}
}

func run(cmd *cobra.Command, args []string) {
var err error
settings := cmd.Context().Value("settings").(*internal.CLISettings)
if err != nil {
YutcLog.Error().Msg(err.Error())
//os.Exit(10)
}
settings.TemplateFiles = cmd.Flags().Args()
if settings.Version {
internal.PrintVersion()
os.Exit(0)
}

YutcLog.Trace().Msg("Settings:")
pflag.VisitAll(func(flag *pflag.Flag) {
cmd.Flags().VisitAll(func(flag *pflag.Flag) {
YutcLog.Trace().Msgf("\t%s: %s", flag.Name, flag.Value.String())
})

valCode := internal.ValidateArguments(
dataFiles, commonTemplateFiles, templateFiles, output, overwrite,
)
valCode := internal.ValidateArguments(settings)
if valCode > 0 {
YutcLog.Error().Msg("Invalid arguments")
os.Exit(int(valCode))
}

data, err := internal.MergeData(dataFiles)
data, err := internal.MergeData(settings.DataFiles)
if err != nil {
panic(err)
}

commonTemplates = internal.LoadSharedTemplates(commonTemplateFiles)
commonTemplates := internal.LoadSharedTemplates(settings.CommonTemplateFiles)

templates, err := internal.LoadTemplates(templateFiles, commonTemplates)
templates, err := internal.LoadTemplates(settings.TemplateFiles, commonTemplates)
for templateIndex, tmpl := range templates {
var outData *bytes.Buffer
outData = new(bytes.Buffer)
err = tmpl.Execute(outData, data)
if err != nil {
panic(err)
}
basename := filepath.Base(templateFiles[templateIndex])
basename := filepath.Base(settings.TemplateFiles[templateIndex])
// stdin not handled here, gotta do that
if output != "-" {
if settings.Output != "-" {
var outputPath string
if len(templates) > 1 {
outputPath = filepath.Join(output, basename)
outputPath = filepath.Join(settings.Output, basename)
} else {
outputPath = output
outputPath = settings.Output
}
if err != nil {
panic(err)
Expand All @@ -90,14 +121,14 @@ func main() {
if err == nil && *isDir && len(templates) == 1 {
// behavior for single template file and output is a directory
// matches normal behavior expected by commands like cp, mv etc.
outputPath = filepath.Join(output, basename)
outputPath = filepath.Join(settings.Output, basename)
}
// check again in case the output path was changed and the file still exists,
// we can probably make this into just one case statement but it's late and i am tired
isDir, err = checkIfDir(outputPath)
// error here is going to be that the file doesnt exist
if err != nil || (!*isDir && overwrite) {
YutcLog.Debug().Msg("Overwrite enabled, writing to file(s): " + output)
if err != nil || (!*isDir && settings.Overwrite) {
YutcLog.Debug().Msg("Overwrite enabled, writing to file(s): " + settings.Output)
err = os.WriteFile(outputPath, outData.Bytes(), 0644)
if err != nil {
panic(err)
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/google/uuid v1.1.1 // indirect
github.com/huandu/xstrings v1.3.3 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/copystructure v1.0.0 // indirect
Expand All @@ -23,6 +24,7 @@ require (
github.com/rs/zerolog v1.32.0 // indirect
github.com/shopspring/decimal v1.2.0 // indirect
github.com/spf13/cast v1.3.1 // indirect
github.com/spf13/cobra v1.8.0 // indirect
github.com/stretchr/testify v1.9.0 // indirect
golang.org/x/crypto v0.3.0 // indirect
golang.org/x/sys v0.18.0 // indirect
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYr
github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA=
github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand All @@ -15,6 +16,8 @@ github.com/huandu/xstrings v1.3.3 h1:/Gcsuc1x8JVbJ9/rlye4xZnVAbEkGauT8lbebqcQws4
github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA=
github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
Expand All @@ -31,10 +34,13 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
Expand Down
39 changes: 23 additions & 16 deletions internal/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,66 +8,64 @@ import (
)

func ValidateArguments(
dataFiles, commonTemplateFiles, templateFiles []string,
output string,
overwrite bool,
settings *CLISettings,
) int64 {
var err error
var errs []error
var code, v int64

if len(templateFiles) == 0 {
if len(settings.TemplateFiles) == 0 {
err = errors.New("must provide at least one template file")
v, _ = strconv.ParseInt("1", 2, 64)
code += v
errs = append(errs, err)
}

outputFiles := output != "-"
if !outputFiles && len(templateFiles) > 1 {
outputFiles := settings.Output != "-"
if !outputFiles && len(settings.TemplateFiles) > 1 {
err = errors.New("cannot use `stdout` with multiple template files")
v, _ = strconv.ParseInt("100", 2, 64)
code += v
errs = append(errs, err)
}
if outputFiles {
_, err = os.Stat(output)
_, err = os.Stat(settings.Output)
if err != nil {
if os.IsNotExist(err) && len(templateFiles) > 1 {
err = errors.New("folder " + output + " does not exist to generate multiple templates")
if os.IsNotExist(err) && len(settings.TemplateFiles) > 1 {
err = errors.New("folder " + settings.Output + " does not exist to generate multiple templates")
v, _ = strconv.ParseInt("1000", 2, 64)
code += v
errs = append(errs, err)
}
} else {
if !overwrite && len(templateFiles) == 1 {
err = errors.New("file " + output + " exists and `overwrite` is not set")
if !settings.Overwrite && len(settings.TemplateFiles) == 1 {
err = errors.New("file " + settings.Output + " exists and `overwrite` is not set")
v, _ = strconv.ParseInt("10000", 2, 64)
code += v
errs = append(errs, err)
}
}
}

if overwrite && !outputFiles {
if settings.Overwrite && !outputFiles {
err = errors.New("cannot use `overwrite` with `stdout`")
v, _ = strconv.ParseInt("100000", 2, 64)
code += v
errs = append(errs, err)
}

stdins := 0
for _, dataFile := range dataFiles {
for _, dataFile := range settings.DataFiles {
if dataFile == "-" {
stdins++
}
}
for _, commonTemplate := range commonTemplateFiles {
for _, commonTemplate := range settings.CommonTemplateFiles {
if commonTemplate == "-" {
stdins++
}
}
for _, templateFile := range templateFiles {
for _, templateFile := range settings.TemplateFiles {
if templateFile == "-" {
stdins++
}
Expand All @@ -79,7 +77,7 @@ func ValidateArguments(
errs = append(errs, err)
}

for _, f := range slices.Concat(dataFiles, commonTemplateFiles, templateFiles) {
for _, f := range slices.Concat(settings.DataFiles, settings.CommonTemplateFiles, settings.TemplateFiles) {
if f == "-" {
continue
}
Expand All @@ -101,3 +99,12 @@ func ValidateArguments(
}
return code
}

type CLISettings struct {
DataFiles []string
CommonTemplateFiles []string
TemplateFiles []string
Output string
Overwrite bool
Version bool
}

0 comments on commit a878421

Please sign in to comment.