Skip to content

Commit

Permalink
feat: ability to specify path to config file (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
luhring authored Sep 23, 2024
1 parent 142514f commit 1e543d8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
40 changes: 35 additions & 5 deletions pkg/cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package cmd

import (
"errors"
"fmt"
"io"
"os"

osAdapter "github.com/chainguard-dev/yam/pkg/rwfs/os"
"github.com/chainguard-dev/yam/pkg/util"
"github.com/chainguard-dev/yam/pkg/yam"
"github.com/chainguard-dev/yam/pkg/yam/formatted"
"github.com/spf13/cobra"
Expand All @@ -17,6 +19,7 @@ const (
flagFinalNewline = "final-newline"
flagTrimLines = "trim-lines"
flagLint = "lint"
flagConfig = "config"
)

func Root() *cobra.Command {
Expand All @@ -33,17 +36,16 @@ func Root() *cobra.Command {
cmd.Flags().Bool(flagFinalNewline, true, "ensure file ends with a final newline character")
cmd.Flags().Bool(flagTrimLines, true, "trim any trailing spaces from each line")
cmd.Flags().Bool(flagLint, false, "don't modify files, but exit 1 if files aren't formatted")
cmd.Flags().StringP(flagConfig, "c", "", "path to a yam configuration YAML file")

cmd.RunE = runRoot

return cmd
}

func runRoot(cmd *cobra.Command, args []string) error {
var err error

encoderConfig, err := formatted.ReadConfig()
if err != nil && !errors.Is(err, os.ErrNotExist) {
encoderConfig, err := getConfig(cmd)
if err != nil {
return err
}

Expand All @@ -70,6 +72,34 @@ func runRoot(cmd *cobra.Command, args []string) error {
return nil
}

func getConfig(cmd *cobra.Command) (*formatted.EncodeOptions, error) {
var r io.Reader
if v, _ := cmd.Flags().GetString(flagConfig); v != "" {
f, err := os.Open(v)
if err != nil {
return nil, fmt.Errorf("opening configuration file: %w", err)
}
r = f
} else {
f, err := os.Open(util.ConfigFileName)
if err != nil {
// This is a default best-effort attempt, no need to bubble up the error.
return nil, nil
}
r = f
}

if r == nil {
return nil, nil
}

cfg, err := formatted.ReadConfigFrom(r)
if err != nil {
return nil, fmt.Errorf("reading configuration: %w", err)
}
return cfg, nil
}

// computeFormatOptions produces a new yam.FormatOptions using an optional
// provided config (unmarshalled from a file) and flags from a Cobra command.
// CLI flag values take priority over config file values, which take priority
Expand Down
2 changes: 1 addition & 1 deletion pkg/yam/formatted/encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func ReadConfigFrom(r io.Reader) (*EncodeOptions, error) {

err := yaml.NewDecoder(r).Decode(&options)
if err != nil {
return nil, fmt.Errorf("unable to read yam config: %w", err)
return nil, fmt.Errorf("parsing yam config: %w", err)
}

return &options, nil
Expand Down

0 comments on commit 1e543d8

Please sign in to comment.