Skip to content

Commit

Permalink
Removing default configuration. GDG will now require a valid config f…
Browse files Browse the repository at this point in the history
…or backup/tools functionality.
  • Loading branch information
safaci2000 committed Nov 8, 2024
1 parent 6fd14bd commit 5524b7d
Show file tree
Hide file tree
Showing 16 changed files with 90 additions and 91 deletions.
9 changes: 2 additions & 7 deletions cli/commandeer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,16 @@ package cli

import (
"context"
"log/slog"

"github.com/bep/simplecobra"
"github.com/esnet/gdg/cli/backup"
"github.com/esnet/gdg/cli/support"
"github.com/esnet/gdg/cli/tools"
assets "github.com/esnet/gdg/config"
)

// Execute executes a command.
func Execute(defaultCfg string, args []string, options ...support.RootOption) error {
func Execute(args []string, options ...support.RootOption) error {
var err error
support.DefaultConfig, err = assets.GetFile(defaultCfg)
if err != nil {
slog.Warn("unable to find load default configuration", "err", err)
}
rootCmd := support.NewRootCmd(getNewRootCmd(), options...)
x, err := simplecobra.New(rootCmd)
if err != nil {
Expand All @@ -41,6 +35,7 @@ func getNewRootCmd() *support.RootCommand {
NameP: "gdg",
CommandEntries: []simplecobra.Commander{
newVersionCmd(),
newDefaultConfig(),
tools.NewToolsCommand(),
backup.NewBackupCommand(),
},
Expand Down
13 changes: 3 additions & 10 deletions cli/support/init_cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,10 @@ import (
// InitConfiguration Loads configuration, and setups fail over case
func InitConfiguration(cmd *cobra.Command) {
configOverride, _ := cmd.Flags().GetString("config")
if DefaultConfig == "" {
raw, err := os.ReadFile("config/importer-example.yml")
if err == nil {
DefaultConfig = string(raw)
} else {
DefaultConfig = ""
}
}

// Registers sub CommandsList
config.InitGdgConfig(configOverride, DefaultConfig)
if config.Config() == nil {
config.InitGdgConfig(configOverride)
}

Check warning on line 17 in cli/support/init_cfg.go

View check run for this annotation

Codecov / codecov/patch

cli/support/init_cfg.go#L16-L17

Added lines #L16 - L17 were not covered by tests
appconfig.InitializeAppLogger(os.Stdout, os.Stderr, config.Config().IsDebug())

// Validate current configuration
Expand Down
9 changes: 4 additions & 5 deletions cli/test/backup/alerting_contactpoints_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/esnet/gdg/cli"
"github.com/esnet/gdg/internal/service/mocks"
"github.com/esnet/gdg/pkg/test_tooling"
"github.com/esnet/gdg/pkg/test_tooling/common"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -66,7 +65,7 @@ func TestUploadContactPoints(t *testing.T) {
r, w, cleanup := test_tooling.InterceptStdout()
defer cleanup()

err := cli.Execute(common.DefaultTestConfig, listCmd, optionMockSvc())
err := cli.Execute(listCmd, optionMockSvc())
if tc.expectErr {
assert.NotNil(t, err)
} else {
Expand Down Expand Up @@ -129,7 +128,7 @@ func TestDownloadContactPoints(t *testing.T) {
r, w, cleanup := test_tooling.InterceptStdout()
defer cleanup()

err := cli.Execute(common.DefaultTestConfig, listCmd, optionMockSvc())
err := cli.Execute(listCmd, optionMockSvc())
if tc.expectErr {
assert.NotNil(t, err)
} else {
Expand Down Expand Up @@ -210,7 +209,7 @@ func TestListContactPoints(t *testing.T) {
r, w, cleanup := test_tooling.InterceptStdout()
defer cleanup()

err := cli.Execute(common.DefaultTestConfig, listCmd, optionMockSvc())
err := cli.Execute(listCmd, optionMockSvc())
if tc.expectErr {
assert.NotNil(t, err)
} else {
Expand Down Expand Up @@ -285,7 +284,7 @@ func TestClearContactPoints(t *testing.T) {
r, w, cleanup := test_tooling.InterceptStdout()
defer cleanup()

err := cli.Execute(common.DefaultTestConfig, clearCmd, optionMockSvc())
err := cli.Execute(clearCmd, optionMockSvc())
assert.Nil(t, err)
defer cleanup()
assert.NoError(t, w.Close())
Expand Down
3 changes: 1 addition & 2 deletions cli/test/backup/conections_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"github.com/esnet/gdg/cli/support"
"github.com/esnet/gdg/internal/service"
"github.com/esnet/gdg/internal/service/mocks"
"github.com/esnet/gdg/pkg/test_tooling/common"
"github.com/grafana/grafana-openapi-client-go/models"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
Expand Down Expand Up @@ -42,7 +41,7 @@ func TestConnectionCommand(t *testing.T) {
}
r, w, cleanup := test_tooling.InterceptStdout()

err := cli.Execute(common.DefaultTestConfig, []string{"backup", "connections", "list"}, optionMockSvc())
err := cli.Execute([]string{"backup", "connections", "list"}, optionMockSvc())
assert.Nil(t, err)
defer cleanup()
assert.NoError(t, w.Close())
Expand Down
10 changes: 5 additions & 5 deletions cli/test/tools/devel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ import (
)

func TestDevelSrvInfo(t *testing.T) {
execMe := func(mock *mocks.GrafanaService, data []byte, optionMockSvc func() support.RootOption) error {
execMe := func(mock *mocks.GrafanaService, optionMockSvc func() support.RootOption) error {
expected := make(map[string]interface{})
expected["Database"] = "db"
expected["Commit"] = "commit"
expected["Version"] = "version"

mock.EXPECT().GetServerInfo().Return(expected)
err := cli.Execute(string(data), []string{"tools", "devel", "srvinfo"}, optionMockSvc())
err := cli.Execute([]string{"tools", "devel", "srvinfo"}, optionMockSvc())
return err
}
outStr, closeReader := test_tooling.SetupAndExecuteMockingServices(t, execMe)
Expand All @@ -32,9 +32,9 @@ func TestDevelSrvInfo(t *testing.T) {
}

func TestDevelSrvCompletion(t *testing.T) {
fn := func(args []string) func(mock *mocks.GrafanaService, data []byte, optionMockSvc func() support.RootOption) error {
return func(mock *mocks.GrafanaService, data []byte, optionMockSvc func() support.RootOption) error {
err := cli.Execute(string(data), args, optionMockSvc())
fn := func(args []string) func(mock *mocks.GrafanaService, optionMockSvc func() support.RootOption) error {
return func(mock *mocks.GrafanaService, optionMockSvc func() support.RootOption) error {
err := cli.Execute(args, optionMockSvc())
return err
}
}
Expand Down
7 changes: 3 additions & 4 deletions cli/test/version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,13 @@ import (
"github.com/esnet/gdg/internal/service"
"github.com/esnet/gdg/internal/service/mocks"
"github.com/esnet/gdg/internal/version"
"github.com/esnet/gdg/pkg/test_tooling/common"
"github.com/stretchr/testify/assert"
)

func TestVersionCommand(t *testing.T) {
assert.NoError(t, path.FixTestDir("test", "../.."))
execMe := func(mock *mocks.GrafanaService, data []byte, optionMockSvc func() support.RootOption) error {
err := cli.Execute(string(data), []string{"version"}, optionMockSvc())
execMe := func(mock *mocks.GrafanaService, optionMockSvc func() support.RootOption) error {
err := cli.Execute([]string{"version"}, optionMockSvc())
return err
}
outStr, closeReader := test_tooling.SetupAndExecuteMockingServices(t, execMe)
Expand Down Expand Up @@ -49,7 +48,7 @@ func TestVersionErrCommand(t *testing.T) {
}
r, w, cleanup := test_tooling.InterceptStdout()
defer cleanup()
err := cli.Execute(common.DefaultTestConfig, []string{"dumb", "dumb"}, optionMockSvc())
err := cli.Execute([]string{"dumb", "dumb"}, optionMockSvc())
assert.NotNil(t, err)
assert.NoError(t, w.Close())

Expand Down
20 changes: 19 additions & 1 deletion cli/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package cli

import (
"context"
"fmt"

"github.com/bep/simplecobra"
"github.com/esnet/gdg/cli/support"
"github.com/esnet/gdg/internal/config"
"github.com/esnet/gdg/internal/version"
"github.com/spf13/cobra"
)
Expand All @@ -20,6 +22,22 @@ func newVersionCmd() simplecobra.Commander {
cmd.Aliases = []string{"v"}
},
Short: "Print the version number of generated code example",
Long: "All software has versions. This is generated code example",
Long: "Print the version number of generated code example",
}
}

func newDefaultConfig() simplecobra.Commander {
return &support.SimpleCommand{
NameP: "default-config",
RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, r *support.RootCommand, args []string) error {
o := config.Configuration{}
fmt.Print(o.DefaultConfig())
return nil
},
WithCFunc: func(cmd *cobra.Command, r *support.RootCommand) {

Check warning on line 37 in cli/version.go

View check run for this annotation

Codecov / codecov/patch

cli/version.go#L33-L37

Added lines #L33 - L37 were not covered by tests
cmd.Aliases = []string{"v"}
},
Short: "Prints an example configuration",
Long: "Prints an example configuration",
}
}
11 changes: 4 additions & 7 deletions cmd/gdg-generate/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import (
"log/slog"
"os"

assets "github.com/esnet/gdg/config"
"github.com/esnet/gdg/internal/version"

"github.com/esnet/gdg/internal/config"
appconfig "github.com/esnet/gdg/internal/log"
"github.com/esnet/gdg/internal/templating"
Expand Down Expand Up @@ -33,6 +34,7 @@ func init() {

func initConfig() {
var err error
slog.Info("Running gdg-generate", slog.Any("version", version.Version))
cfgFile, err = rootCmd.Flags().GetString("config")
if err != nil {
log.Fatal("unable to get config file")
Expand All @@ -42,12 +44,7 @@ func initConfig() {
log.Fatal("unable to get template config file")
}

defaultConfiguration, err := assets.GetFile("importer-example.yml")
if err != nil {
slog.Warn("unable to load default configuration, no fallback")
}

config.InitGdgConfig(cfgFile, defaultConfiguration)
config.InitGdgConfig(cfgFile)

Check warning on line 47 in cmd/gdg-generate/cli/root.go

View check run for this annotation

Codecov / codecov/patch

cmd/gdg-generate/cli/root.go#L47

Added line #L47 was not covered by tests
config.InitTemplateConfig(tplCfgFile)
cfg := config.Config()
appconfig.InitializeAppLogger(os.Stdout, os.Stderr, cfg.IsDebug())
Expand Down
2 changes: 1 addition & 1 deletion cmd/gdg/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func main() {
}
}

err := cli.Execute("importer-example.yml", os.Args[1:], setGrafanaSvc())
err := cli.Execute(os.Args[1:], setGrafanaSvc())

Check warning on line 24 in cmd/gdg/main.go

View check run for this annotation

Codecov / codecov/patch

cmd/gdg/main.go#L24

Added line #L24 was not covered by tests
if err != nil {
log.Fatalf("Error: %s", err)
}
Expand Down
55 changes: 27 additions & 28 deletions internal/config/config_loader.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package config

import (
"errors"
"fmt"
"log"
"log/slog"
"os"
"path/filepath"
"strings"

assets "github.com/esnet/gdg/config"
"github.com/esnet/gdg/internal/tools"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
Expand All @@ -21,6 +21,14 @@ func (s *Configuration) GetViperConfig(name string) *viper.Viper {
return s.viperConfiguration[name]
}

func (s *Configuration) DefaultConfig() string {
cfg, err := assets.GetFile("importer-example.yml")
if err != nil {
slog.Warn("unable to find load default configuration", "err", err)
}
return cfg

Check warning on line 29 in internal/config/config_loader.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config_loader.go#L24-L29

Added lines #L24 - L29 were not covered by tests
}

func (s *Configuration) ClearContexts() {
newContext := make(map[string]*GrafanaConfig)
newContext["example"] = &GrafanaConfig{
Expand Down Expand Up @@ -143,7 +151,7 @@ func (s *Configuration) SaveToDisk(useViper bool) error {
}

var (
configData = new(Configuration)
configData *Configuration
configSearchPaths = []string{"config", ".", "../config", "../../config", "/etc/gdg"}
)

Expand Down Expand Up @@ -208,8 +216,10 @@ func (s *TemplatingConfig) GetTemplate(name string) (*TemplateDashboards, bool)
}

// buildConfigSearchPath common pattern used when loading configuration for both CLI tools.
func buildConfigSearchPath(configFile string, appName string) ([]string, string, string) {
func buildConfigSearchPath(configFile string) ([]string, string, string) {
ext := filepath.Ext(configFile)
appName := filepath.Base(configFile)

var configDirs []string
if configFile != "" {
configFileDir := filepath.Dir(configFile)
Expand All @@ -230,37 +240,26 @@ func buildConfigSearchPath(configFile string, appName string) ([]string, string,
return configDirs, appName, ext
}

func InitGdgConfig(override, defaultConfig string) {
func InitGdgConfig(override string) {
if override == "" && configData != nil {
return
}

Check warning on line 246 in internal/config/config_loader.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config_loader.go#L245-L246

Added lines #L245 - L246 were not covered by tests
configData = &Configuration{}
appName := "importer"
configDirs, appName, ext := buildConfigSearchPath(override, appName)
var configDirs []string
var ext, appName string
if override == "" {
configDirs, appName, ext = buildConfigSearchPath("config/importer.yml")

Check warning on line 251 in internal/config/config_loader.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config_loader.go#L251

Added line #L251 was not covered by tests
} else {
configDirs, appName, ext = buildConfigSearchPath(override)
}
var err error
var v *viper.Viper
configData.gdgConfig = new(GDGAppConfiguration)

v, err = readViperConfig[GDGAppConfiguration](appName, configDirs, configData.gdgConfig, ext)
var configFileNotFoundError viper.ConfigFileNotFoundError
ok := errors.As(err, &configFileNotFoundError)

if err != nil && ok {
slog.Info("No configuration file has been found, creating a default configuration")
err = os.MkdirAll("config", 0o750)
if err != nil {
log.Fatal("unable to create configuration folder: 'config'")
}
err = os.WriteFile("config/importer.yml", []byte(defaultConfig), 0o600)
if err != nil {
log.Panic("Could not persist default config locally")
}
appName = "importer"

v, err = readViperConfig[GDGAppConfiguration](appName, configDirs, configData.gdgConfig, "")
if err != nil {
log.Panic(err)
}

} else if err != nil { // config is found but is invalid
log.Fatal("Invalid configuration detected, please fix your configuration and try again.")
if err != nil {
log.Fatal("No configuration file has been found or config is invalid. Expected a file named 'importer.yml' in one of the following folders: ['.', 'config', '/etc/gdg']. " +
"Try using `gdg default-config > config/importer.yml` go use the default example")

Check warning on line 262 in internal/config/config_loader.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config_loader.go#L261-L262

Added lines #L261 - L262 were not covered by tests
}
if configData.viperConfiguration == nil {
configData.viperConfiguration = make(map[string]*viper.Viper)
Expand Down
12 changes: 6 additions & 6 deletions internal/config/config_loader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func TestSetup(t *testing.T) {
}

os.Setenv("GDG_CONTEXT_NAME", "qa")
config.InitGdgConfig(common.DefaultTestConfig, "")
config.InitGdgConfig(common.DefaultTestConfig)
conf := config.Config().GetViperConfig(config.ViperGdgConfig)
slog.Info(conf.ConfigFileUsed())

Expand All @@ -65,8 +65,8 @@ func TestWatchedFoldersConfig(t *testing.T) {
}
}

os.Setenv("GDG_CONTEXT_NAME", "qa")
config.InitGdgConfig(common.DefaultTestConfig, "")
assert.NoError(t, os.Setenv("GDG_CONTEXT_NAME", "qa"))
config.InitGdgConfig(common.DefaultTestConfig)
conf := config.Config().GetViperConfig(config.ViperGdgConfig)
slog.Info(conf.ConfigFileUsed())

Expand Down Expand Up @@ -97,7 +97,7 @@ func TestWatchedFoldersConfig(t *testing.T) {
// Ensures that if the config is on a completely different path, the searchPath is updated accordingly
func TestSetupDifferentPath(t *testing.T) {
cfgFile := DuplicateConfig(t)
config.InitGdgConfig(cfgFile, "")
config.InitGdgConfig(cfgFile)
conf := config.Config().GetViperConfig(config.ViperGdgConfig)
assert.NotNil(t, conf)
context := conf.GetString("context_name")
Expand All @@ -110,7 +110,7 @@ func TestSetupDifferentPath(t *testing.T) {
func TestConfigEnv(t *testing.T) {
os.Setenv("GDG_CONTEXT_NAME", "testing")
os.Setenv("GDG_CONTEXTS__TESTING__URL", "www.google.com")
config.InitGdgConfig(common.DefaultTestConfig, "")
config.InitGdgConfig(common.DefaultTestConfig)
conf := config.Config().GetViperConfig(config.ViperGdgConfig)
context := conf.GetString("context_name")
assert.Equal(t, context, "testing")
Expand All @@ -120,7 +120,7 @@ func TestConfigEnv(t *testing.T) {
assert.Equal(t, grafanaConfig.URL, url)
os.Setenv("GDG_CONTEXT_NAME", "production")
os.Setenv("GDG_CONTEXTS__PRODUCTION__URL", "grafana.com")
config.InitGdgConfig(common.DefaultTestConfig, "")
config.InitGdgConfig(common.DefaultTestConfig)
conf = config.Config().GetViperConfig(config.ViperGdgConfig)
url = conf.GetString("contexts.production.url")
assert.Equal(t, url, "grafana.com")
Expand Down
Loading

0 comments on commit 5524b7d

Please sign in to comment.