Allow passing environment variables into config

Signed-off-by: Steven Kriegler <61625851+justusbunsi@users.noreply.github.com>
This commit is contained in:
justusbunsi 2021-06-20 18:24:12 +02:00
parent 86ea377d64
commit 6c2bb413cd
No known key found for this signature in database
GPG key ID: 990B348ECAC9C7DB
2 changed files with 47 additions and 17 deletions

View file

@ -2,6 +2,7 @@ package settings
import (
"fmt"
"strings"
"github.com/spf13/viper"
)
@ -22,27 +23,35 @@ var (
Gitea GiteaConfig
)
func Load(configPath string) {
func init() {
viper.SetConfigName("config.yaml")
viper.SetConfigType("yaml")
viper.SetEnvPrefix("prbot")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AllowEmptyEnv(true)
viper.AutomaticEnv()
}
func Load(configPath string) {
viper.AddConfigPath(configPath)
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error while reading config file: %w \n", err))
}
var giteaConfig GiteaConfig
if viper.Sub("gitea") == nil {
if viper.IsSet("gitea") == false {
panic("Gitea not configured")
}
err = viper.UnmarshalKey("gitea", &giteaConfig)
if err != nil {
panic(fmt.Errorf("Unable to decode into struct, %v", err))
var fullConfig struct {
Gitea GiteaConfig
}
Gitea = giteaConfig
err = viper.Unmarshal(&fullConfig)
if err != nil {
panic(fmt.Errorf("Unable to load config into struct, %v", err))
}
Gitea = fullConfig.Gitea
}

View file

@ -12,13 +12,13 @@ import (
var defaultConfigInlineSecrets []byte = []byte(
`gitea:
url: https://example.com/gitea
token: 1337
webhookSecret: ""
token: d0fcdeb5eaa99c506831f9eb4e63fc7cc484a565
webhookSecret: "haxxor"
repositories: []
sonarqube:
url: https://example.com/sonarqube
token: 42
webhookSecret: ""
token: a09eb5785b25bb2cbacf48808a677a0709f02d8e
webhookSecret: "haxxor"
projects: []
`)
@ -53,12 +53,33 @@ func TestLoadGiteaStructure(t *testing.T) {
WriteConfigFile(t, defaultConfigInlineSecrets)
Load(os.TempDir())
expected := &GiteaConfig{
expected := GiteaConfig{
Url: "https://example.com/gitea",
Token: "1337",
WebhookSecret: "",
Token: "d0fcdeb5eaa99c506831f9eb4e63fc7cc484a565",
WebhookSecret: "haxxor",
Repositories: []GiteaRepository{},
}
assert.True(t, assert.ObjectsAreEqualValues(&Gitea, expected))
assert.EqualValues(t, expected, Gitea)
}
func TestLoadGiteaStructureWithEnvInjectedWebhookSecret(t *testing.T) {
os.Setenv("PRBOT_GITEA_WEBHOOKSECRET", "injected-secret")
os.Setenv("PRBOT_GITEA_TOKEN", "injected-token")
WriteConfigFile(t, defaultConfigInlineSecrets)
Load(os.TempDir())
expected := GiteaConfig{
Url: "https://example.com/gitea",
Token: "injected-token",
WebhookSecret: "injected-secret",
Repositories: []GiteaRepository{},
}
assert.EqualValues(t, expected, Gitea)
t.Cleanup(func() {
os.Unsetenv("PRBOT_GITEA_WEBHOOKSECRET")
os.Unsetenv("PRBOT_GITEA_TOKEN")
})
}