Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create initial .myks.yaml and print configs #87

Merged
merged 10 commits into from
Sep 13, 2023
26 changes: 25 additions & 1 deletion cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,17 @@ func init() {
log.Fatal().Err(err).Msg("Failed to read flag")
}

if err := myks.New(".").Bootstrap(force); errors.Is(err, myks.ErrNotClean) {
onlyPrint, err := cmd.Flags().GetBool("print")
if err != nil {
log.Fatal().Err(err).Msg("Failed to read flag")
}

components, err := cmd.Flags().GetStringSlice("components")
if err != nil {
log.Fatal().Err(err).Msg("Failed to read flag")
}

if err := myks.New(".").Bootstrap(force, onlyPrint, components); errors.Is(err, myks.ErrNotClean) {
log.Error().Msg("Directory not empty. Use --force to overwrite data.")
} else if err != nil {
log.Fatal().Err(err).Msg("Failed to initialize project")
Expand All @@ -29,5 +39,19 @@ func init() {
}

cmd.Flags().BoolP("force", "f", false, "overwrite existing data")

printHelp := "print configuration instead of creating files\n" +
"applicable only to the following components: gitingore, config, schema"
cmd.Flags().Bool("print", false, printHelp)

componentsDefault := []string{
"config",
"environments",
"gitignore",
"prototypes",
"schema",
}
cmd.Flags().StringSlice("components", componentsDefault, "components to initialize")

rootCmd.AddCommand(cmd)
}
27 changes: 27 additions & 0 deletions cmd/print-config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package cmd

import (
"fmt"

"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
yaml "gopkg.in/yaml.v3"
)

func init() {
cmd := &cobra.Command{
Use: "print-config",
Short: "Print myks configuration",
Long: "Print myks configuration",
Run: func(cmd *cobra.Command, args []string) {
c := viper.AllSettings()
bs, err := yaml.Marshal(c)
if err != nil {
log.Fatal().Err(err).Msg("Failed to marshal config")
}
fmt.Printf("---\n%s\n", bs)
},
}
rootCmd.AddCommand(cmd)
}
23 changes: 16 additions & 7 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import (
const (
ANNOTATION_SMART_MODE = "feat:smart-mode"
ANNOTATION_TRUE = "true"
MYKS_CONFIG_NAME = ".myks"
MYKS_CONFIG_TYPE = "yaml"
)

var (
Expand Down Expand Up @@ -46,8 +48,11 @@ If you do not provide any positional arguments, myks will run in "Smart Mode". I

func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringP("log-level", "l", "info", "Set the logging level")
rootCmd.PersistentFlags().IntVarP(&asyncLevel, "async", "a", 0, "Sets the number of concurrent processed applications. The default is no limit.")

rootCmd.PersistentFlags().StringP("log-level", "l", "info", "set the logging level")

asyncHelp := "sets the number of applications to be processed in parallel\nthe default (0) is no limit"
rootCmd.PersistentFlags().IntVarP(&asyncLevel, "async", "a", 0, asyncHelp)

if err := viper.BindPFlags(rootCmd.PersistentFlags()); err != nil {
log.Fatal().Err(err).Msg("Unable to bind flags")
Expand All @@ -56,7 +61,8 @@ func init() {
log.Fatal().Err(err).Msg("Unable to bind flags")
}

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is the first .myks.yaml up the directory tree)")
configHelp := fmt.Sprintf("config file (default is the first %s.%s up the directory tree)", MYKS_CONFIG_NAME, MYKS_CONFIG_TYPE)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", configHelp)

rootCmd.PersistentPreRunE = detectTargetEnvsAndApps
}
Expand Down Expand Up @@ -101,22 +107,25 @@ func detectTargetEnvsAndApps(cmd *cobra.Command, args []string) (err error) {
return err
}

log.Debug().Strs("environments", targetEnvironments).Strs("applications", targetApplications).Msg("Parsed arguments")
log.Debug().
Strs("environments", targetEnvironments).
Strs("applications", targetApplications).
Msg("Parsed arguments")

return nil
}

func initConfig() {
viper.SetEnvPrefix("MYKS")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
viper.AutomaticEnv()

if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
viper.AddConfigPath(".")
viper.SetConfigName(".myks")
viper.SetConfigType("yaml")
viper.SetConfigName(MYKS_CONFIG_NAME)
viper.SetConfigType(MYKS_CONFIG_TYPE)

// Add all parent directories to the config search path
dir, _ := os.Getwd()
Expand Down
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,21 @@ module github.com/mykso/myks
go 1.20

require (
github.com/alecthomas/chroma v0.10.0
github.com/creasty/defaults v1.7.0
github.com/logrusorgru/aurora/v4 v4.0.0
github.com/pmezard/go-difflib v1.0.0
github.com/rs/zerolog v1.29.1
github.com/spf13/cobra v1.7.0
github.com/spf13/viper v1.16.0
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63
golang.org/x/sync v0.3.0
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/dlclark/regexp2 v1.4.0 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
Expand Down
7 changes: 7 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3f
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek=
github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
Expand All @@ -53,6 +55,8 @@ github.com/creasty/defaults v1.7.0/go.mod h1:iGzKe6pbEHnpMPtfDXZEr0NVxWnPTjb1bbD
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=
github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E=
github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
Expand Down Expand Up @@ -138,6 +142,8 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/logrusorgru/aurora/v4 v4.0.0 h1:sRjfPpun/63iADiSvGGjgA1cAYegEWMPCJdUpJYn9JA=
github.com/logrusorgru/aurora/v4 v4.0.0/go.mod h1:lP0iIa2nrnT/qoFXcOZSrZQpJ1o6n2CUf/hyHi2Q4ZQ=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40=
Expand Down Expand Up @@ -331,6 +337,7 @@ golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
Expand Down
7 changes: 7 additions & 0 deletions internal/myks/assets/myks_config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
# Sets the number of applications to be processed in parallel.
# The default (0) is no limit.
async: 0
# One of the zerolog log levels.
# See: https://github.com/rs/zerolog#leveled-logging
log-level: info
61 changes: 51 additions & 10 deletions internal/myks/globe.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ var dataSchema []byte
//go:embed assets/envs_gitignore
var envsGitignore []byte

//go:embed assets/myks_config.yaml
var myksConfig []byte

//go:embed all:assets/prototypes
var prototypesFs embed.FS

Expand Down Expand Up @@ -215,20 +218,49 @@ func (g *Globe) SyncAndRender(asyncLevel int) error {
}

// Bootstrap creates the initial directory structure and files
func (g *Globe) Bootstrap(force bool) error {
log.Info().Msg("Creating base file structure")
if err := g.createBaseFileStructure(force); err != nil {
return err
func (g *Globe) Bootstrap(force, onlyPrint bool, components []string) error {
compMap := make(map[string]bool, len(components))
for _, comp := range components {
compMap[comp] = true
}

log.Info().Msg("Creating sample prototypes")
if err := g.createSamplePrototypes(); err != nil {
return err
if onlyPrint {
if compMap["gitignore"] {
printFileNicely(".gitignore", string(envsGitignore), "Terminfo")
}
if compMap["config"] {
printFileNicely(".myks.yaml", string(myksConfig), "YAML")
}
if compMap["schema"] {
printFileNicely("data-schema.ytt.yaml", string(dataSchema), "YAML")
}
} else {
log.Info().Msg("Creating base file structure")
if err := g.createBaseFileStructure(force); err != nil {
return err
}
}

log.Info().Msg("Creating sample environment")
if err := g.createSampleEnvironment(); err != nil {
return err
if compMap["prototypes"] {
if onlyPrint {
log.Info().Msg("Skipping printing sample prototypes")
} else {
log.Info().Msg("Creating sample prototypes")
if err := g.createSamplePrototypes(); err != nil {
return err
}
}
}

if compMap["envs"] {
if onlyPrint {
log.Debug().Msg("Skipping printing sample environment")
} else {
log.Info().Msg("Creating sample environment")
if err := g.createSampleEnvironment(); err != nil {
return err
}
}
}

return nil
Expand Down Expand Up @@ -270,11 +302,13 @@ func (g *Globe) createBaseFileStructure(force bool) error {
protoDir := filepath.Join(g.RootDir, g.PrototypesDir)
renderedDir := filepath.Join(g.RootDir, g.RenderedDir)
envsGitignoreFile := filepath.Join(envDir, ".gitignore")
myksConfigFile := filepath.Join(g.RootDir, ".myks.yaml")

log.Debug().Str("environments directory", envDir).Msg("")
log.Debug().Str("prototypes directory", protoDir).Msg("")
log.Debug().Str("rendered directory", renderedDir).Msg("")
log.Debug().Str("environments .gitignore file", envsGitignoreFile).Msg("")
log.Debug().Str("myks config file", myksConfigFile).Msg("")

if !force {
if _, err := os.Stat(envDir); err == nil {
Expand All @@ -289,6 +323,9 @@ func (g *Globe) createBaseFileStructure(force bool) error {
if _, err := os.Stat(envsGitignoreFile); err == nil {
return ErrNotClean
}
if _, err := os.Stat(myksConfigFile); err == nil {
return ErrNotClean
}
}

g.createDataSchemaFile()
Expand All @@ -309,6 +346,10 @@ func (g *Globe) createBaseFileStructure(force bool) error {
return err
}

if err := os.WriteFile(myksConfigFile, myksConfig, 0o600); err != nil {
return err
}

return nil
}

Expand Down
18 changes: 18 additions & 0 deletions internal/myks/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@ import (
"regexp"
"strings"

"github.com/alecthomas/chroma/quick"
aurora "github.com/logrusorgru/aurora/v4"
"github.com/rs/zerolog/log"
"golang.org/x/sync/errgroup"
"golang.org/x/term"
yaml "gopkg.in/yaml.v3"
)

Expand All @@ -36,6 +39,21 @@ func reductSecrets(args []string) []string {
return logArgs
}

func printFileNicely(name, content, syntax string) {
if !term.IsTerminal(int(os.Stdout.Fd())) {
fmt.Println(content)
return
}

fmt.Println(aurora.Bold(fmt.Sprintf("=== %s ===\n", name)))
err := quick.Highlight(os.Stdout, content, syntax, "terminal16m", "doom-one2")
if err != nil {
log.Error().Err(err).Msg("Failed to highlight")
} else {
fmt.Printf("\n\n")
}
}

func process(asyncLevel int, collection interface{}, fn func(interface{}) error) error {
var items []interface{}

Expand Down
Loading