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 08d063c
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 62 deletions.
7 changes: 1 addition & 6 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 {
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
11 changes: 1 addition & 10 deletions cli/support/init_cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,8 @@ 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)
config.InitGdgConfig(configOverride)
appconfig.InitializeAppLogger(os.Stdout, os.Stderr, config.Config().IsDebug())

// Validate current configuration
Expand Down
6 changes: 3 additions & 3 deletions cli/test/backup/alerting_contactpoints_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ func TestUploadContactPoints(t *testing.T) {
{
name: "ErrNoDataTest",
validateFn: func(t *testing.T, output string) {
assert.True(t, strings.Contains(output, "WRN GDG does not manage the 'email receiver' entity."))
assert.True(t, strings.Contains(output, "ERR unable to upload contact points err=\"Unable to download data data\""))
assert.True(t, strings.Contains(output, "GDG does not manage the 'email receiver' entity."))
assert.True(t, strings.Contains(output, "unable to upload contact points err=\"Unable to download data data\""))
},
setupMocks: func(testSvc *mocks.GrafanaService) {
testSvc.EXPECT().InitOrganizations().Return()
Expand All @@ -40,7 +40,7 @@ func TestUploadContactPoints(t *testing.T) {
{
name: "SuccessUpload",
validateFn: func(t *testing.T, output string) {
assert.True(t, strings.Contains(output, "WRN GDG does not manage the 'email receiver' entity."))
assert.True(t, strings.Contains(output, "GDG does not manage the 'email receiver' entity."))
assert.True(t, strings.Contains(output, "NAME"))
assert.True(t, strings.Contains(output, "─────"), "table structure not found")
assert.True(t, strings.Contains(output, "discord"))
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) {
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)
config.InitTemplateConfig(tplCfgFile)
cfg := config.Config()
appconfig.InitializeAppLogger(os.Stdout, os.Stderr, cfg.IsDebug())
Expand Down
37 changes: 13 additions & 24 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
}

func (s *Configuration) ClearContexts() {
newContext := make(map[string]*GrafanaConfig)
newContext["example"] = &GrafanaConfig{
Expand Down Expand Up @@ -230,7 +238,7 @@ func buildConfigSearchPath(configFile string, appName string) ([]string, string,
return configDirs, appName, ext
}

func InitGdgConfig(override, defaultConfig string) {
func InitGdgConfig(override string) {
configData = &Configuration{}
appName := "importer"
configDirs, appName, ext := buildConfigSearchPath(override, appName)
Expand All @@ -239,28 +247,9 @@ func InitGdgConfig(override, defaultConfig string) {
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")
}
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
4 changes: 2 additions & 2 deletions internal/service/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ func fixEnvironment(t *testing.T) {
assert.NoError(t, path.FixTestDir("service", "../.."))
err := os.Setenv("GDG_CONTEXT_NAME", "qa")
assert.Nil(t, err)
config.InitGdgConfig(common.DefaultTestConfig, "'")
config.InitGdgConfig(common.DefaultTestConfig)
}

func TestRelativePathLogin(t *testing.T) {
envKey := "GDG_CONTEXTS__QA__URL"
assert.NoError(t, os.Setenv(envKey, "http://localhost:3000/grafana/"))
fixEnvironment(t)
config.InitGdgConfig(common.DefaultTestConfig, "'")
config.InitGdgConfig(common.DefaultTestConfig)
defer assert.NoError(t, os.Unsetenv(envKey))

svc := NewApiService("dummy")
Expand Down
2 changes: 1 addition & 1 deletion internal/templating/templating_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func TestGenerate(t *testing.T) {
if strings.Contains(dir, "templating") {
os.Chdir("../..")
}
config.InitGdgConfig(common.DefaultTestConfig, "")
config.InitGdgConfig(common.DefaultTestConfig)
config.InitTemplateConfig("templates-example")
template := NewTemplate()
data, err := template.Generate("template_example")
Expand Down
2 changes: 1 addition & 1 deletion pkg/test_tooling/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func CreateSimpleClient(t *testing.T, cfgName *string, container testcontainers.
slog.Info("Grafana Test container running", slog.String("host", grafanaHost+"/login"), slog.String("imageVersion", dockerContainer.Image))
}

config.InitGdgConfig(*cfgName, "'")
config.InitGdgConfig(*cfgName)
conf := config.Config().GetViperConfig(config.ViperGdgConfig)
assert.NotNil(t, conf)
// Hack for Local testing
Expand Down
2 changes: 1 addition & 1 deletion pkg/test_tooling/support.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func InterceptStdout() (*os.File, *os.File, context.CancelFunc) {
panic(e)
}
// Restore streams
config.InitGdgConfig("testing", "")
config.InitGdgConfig("testing")
cleanup := func() {
os.Stdout = backupStd
os.Stderr = backupErr
Expand Down

0 comments on commit 08d063c

Please sign in to comment.