Example #1
1
func newConfig() *Conf {
	c := new(Conf)
	c.ldapViper = viper.New()
	c.ldapConfig = &LdapConfig{}
	c.notificationConfigs = []NotificationServiceConfig{}

	viper.SetConfigName("indispenso")
	viper.SetEnvPrefix("ind")

	// Defaults
	viper.SetDefault("Token", "")
	viper.SetDefault("Hostname", getDefaultHostName())
	viper.SetDefault("UseAutoTag", true)
	viper.SetDefault("ServerEnabled", false)
	viper.SetDefault("Home", defaultHomePath)
	viper.SetDefault("Debug", false)
	viper.SetDefault("ServerPort", 897)
	viper.SetDefault("EndpointURI", "")
	viper.SetDefault("SslCertFile", "cert.pem")
	viper.SetDefault("SslPrivateKeyFile", "key.pem")
	viper.SetDefault("AutoGenerateCert", true)
	viper.SetDefault("ClientPort", 898)
	viper.SetDefault("EnableLdap", false)
	viper.SetDefault("LdapConfigFile", "")

	//Flags
	c.confFlags = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)

	configFile := c.confFlags.StringP("config", "c", "", "Config file location default is /etc/indispenso/indispenso.{json,toml,yaml,yml,properties,props,prop}")
	c.confFlags.BoolP("serverEnabled", "s", false, "Define if server module should be started or not")
	c.confFlags.BoolP("debug", "d", false, "Enable debug mode")
	c.confFlags.StringP("home", "p", defaultHomePath, "Home directory where all config files are located")
	c.confFlags.StringP("endpointUri", "e", "", "URI of server interface, used by client")
	c.confFlags.StringP("token", "t", "", "Secret token")
	c.confFlags.StringP("hostname", "i", getDefaultHostName(), "Hostname that is use to identify itself")
	c.confFlags.BoolP("enableLdap", "l", false, "Enable LDAP authentication")
	c.confFlags.BoolP("help", "h", false, "Print help message")

	c.confFlags.Parse(os.Args[1:])
	if len(*configFile) > 2 {
		viper.SetConfigFile(*configFile)
	} else {
		legacyConfigFile := "/etc/indispenso/indispenso.conf"
		if _, err := os.Stat(legacyConfigFile); err == nil {
			viper.SetConfigFile(legacyConfigFile)
			viper.SetConfigType("yaml")
		}
	}
	viper.BindPFlags(c.confFlags)
	viper.AutomaticEnv()

	viper.ReadInConfig()

	c.setupHome(nil, viper.GetString("Home"))
	c.setupHome(c.ldapViper, viper.GetString("Home"))

	c.SetupNotificationConfig("slack", &SlackNotifyConfig{})
	c.Update()
	return c
}
Example #2
1
func loadConfig() {
	stormpath.InitLog()

	viper.SetConfigType("yaml")
	viper.AutomaticEnv()

	//Load bundled default config
	defaultConfig, err := Asset("config/web.stormpath.yaml")
	if err != nil {
		stormpath.Logger.Panicf("[ERROR] Couldn't load default bundle configuration: %s", err)
	}

	viper.ReadConfig(bytes.NewBuffer(defaultConfig))

	//Merge users custom configuration
	viper.SetConfigFile("stormpath.yaml")
	viper.AddConfigPath("~/.stormpath/")
	viper.AddConfigPath(".")
	err = viper.MergeInConfig()
	if err != nil {
		stormpath.Logger.Println("[WARN] User didn't provide custom configuration")
	}

	Config.Produces = viper.GetStringSlice("stormpath.web.produces")
	Config.BasePath = viper.GetString("stormpath.web.basePath")

	loadSocialConfig()
	loadCookiesConfig()
	loadEndpointsConfig()
	loadOAuth2Config()
}
Example #3
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if len(cfgFile) != 0 {
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".otp-config")
	viper.AddConfigPath("$HOME")
	viper.AutomaticEnv()

	apiKey, _ := RootCmd.Flags().GetString("api-key")
	if len(apiKey) == 0 && len(os.Getenv("GITHUB_API_KEY")) > 0 {
		RootCmd.Flags().Set("api-key", os.Getenv("GITHUB_API_KEY"))
	}
	if len(apiKey) > 0 {
		if err := os.Setenv("GITHUB_API_KEY", apiKey); err != nil {
			fmt.Fprintf(os.Stderr, "Error: Unable to set GITHUB_API_KEY\n")
			os.Exit(1)
		}
	}

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}

	log.SetFormatter(&log.TextFormatter{})
	log.SetOutput(os.Stderr)
	if api.Verbose {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.WarnLevel)
	}
}
Example #4
0
func NewConfig() (*Config, error) {
	flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)

	c := Config{}
	flags.StringVarP(&c.URL, "url", "u", "", "the url")
	viper.BindPFlag("url", flags.Lookup("url"))

	// This doesn't need to be in the Config struct, because we're just using it to override viper.
	file := flags.StringP("file", "f", "", "name of the config file")

	// Parse the command line args into the flag set, ignoring the command name.
	flags.Parse(os.Args[1:])

	if *file != "" {
		viper.SetConfigFile(*file)
	}

	if err := viper.ReadInConfig(); err != nil {
		return nil, err
	}

	if err := viper.Unmarshal(&c); err != nil {
		return nil, err
	}

	return &c, nil
}
Example #5
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".gogetgithubstats") // name of config file (without extension)
	viper.AddConfigPath("$HOME")             // adding home directory as first search path
	viper.AutomaticEnv()                     // read in environment variables that match

	// This is the defaults
	viper.SetDefault("Verbose", true)

	// If a config file is found, read it in.
	err := viper.ReadInConfig()
	if err != nil {
		if _, ok := err.(viper.ConfigParseError); ok {
			jww.ERROR.Println(err)
		} else {
			jww.ERROR.Println("Unable to locate Config file.", err)
		}
	}

	if rootCmdV.PersistentFlags().Lookup("verbose").Changed {
		viper.Set("Verbose", Verbose)
	}

	if rootCmdV.PersistentFlags().Lookup("access-token").Changed {
		viper.Set("access-token", accessToken)
	}

	if viper.GetBool("verbose") {
		jww.SetStdoutThreshold(jww.LevelDebug)
	}
}
Example #6
0
// Setup sets up defaults for viper configuration options and
// overrides these values with the values from the given configuration file
// if it is not empty. Those values again are overwritten by environment
// variables.
func Setup(configFilePath string) error {
	viper.Reset()

	// Expect environment variables to be prefix with "ALMIGHTY_".
	viper.SetEnvPrefix("ALMIGHTY")

	// Automatically map environment variables to viper values
	viper.AutomaticEnv()

	// To override nested variables through environment variables, we
	// need to make sure that we don't have to use dots (".") inside the
	// environment variable names.
	// To override foo.bar you need to set ALM_FOO_BAR
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

	viper.SetTypeByDefaultValue(true)
	setConfigDefaults()

	// Read the config
	// Explicitly specify which file to load config from
	if configFilePath != "" {
		viper.SetConfigFile(configFilePath)
		viper.SetConfigType("yaml")
		err := viper.ReadInConfig() // Find and read the config file
		if err != nil {             // Handle errors reading the config file
			return fmt.Errorf("Fatal error config file: %s \n", err)
		}
	}

	return nil
}
Example #7
0
func (suite *GitConfigTestSuite) SetupTest() {
	assert := assert.New(suite.T())
	viper.SetConfigFile("../../.ayi.example.yml")
	err := viper.ReadInConfig()
	assert.Nil(err)
	assert.Equal(true, viper.Get("debug"))
}
Example #8
0
// LoadGlobalConfig loads Hugo configuration into the global Viper.
func LoadGlobalConfig(relativeSourcePath, configFilename string) error {

	if relativeSourcePath == "" {
		relativeSourcePath = "."
	}

	viper.AutomaticEnv()
	viper.SetEnvPrefix("hugo")
	viper.SetConfigFile(configFilename)
	// See https://github.com/spf13/viper/issues/73#issuecomment-126970794
	if relativeSourcePath == "" {
		viper.AddConfigPath(".")
	} else {
		viper.AddConfigPath(relativeSourcePath)
	}
	err := viper.ReadInConfig()
	if err != nil {
		if _, ok := err.(viper.ConfigParseError); ok {
			return err
		}
		return fmt.Errorf("Unable to locate Config file. Perhaps you need to create a new site.\n       Run `hugo help new` for details. (%s)\n", err)
	}

	viper.RegisterAlias("indexes", "taxonomies")

	loadDefaultSettings()

	return nil
}
Example #9
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile == "" { // enable ability to specify config file via flag
		cfgFile = filepath.Join(os.Getenv("HOME"), ".alea.toml")
	}

	viper.SetConfigFile(cfgFile)

	viper.SetConfigName(".alea") // name of config file (without extension)
	viper.SetConfigType("toml")  // type of config file (defaults to yaml)
	viper.AddConfigPath("$HOME") // adding home directory as first search path
	viper.AutomaticEnv()         // read in environment variables that match

	// bind flags
	viper.BindPFlag("controller", RootCmd.PersistentFlags().Lookup("controller"))

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		// fmt.Println("Using config file:", viper.ConfigFileUsed())

		// Try to set the controller to the value found in the config
		if cfg.controller == "" {
			cfg.controller = viper.GetString("controller")
		}

		// Try to resolve the controller URL from the deis git remote if it's still blank
		if cfg.controller == "" {
			cfg.controller, err = git.GetControllerFromRemote()
		}
	}
}
Example #10
0
func InitConfig(configFile string) {
	SetDefaults()

	if configFile != "" {
		if _, err := os.Stat(configFile); os.IsNotExist(err) {
			log.WithFields(log.Fields{"file": configFile}).Fatal("Config file does not exist")
		}

		// Load the config file if supplied
		viper.SetConfigFile(configFile)
	} else {
		// Otherwise use the defaults
		viper.SetConfigName("agent")
		viper.AddConfigPath("/etc/reeve")
		viper.AddConfigPath("$HOME/.reeve")
	}

	err := viper.ReadInConfig()
	if err != nil {
		// Check if we got an unsupported config error
		// If so it means that no files were found, and we can just skip it using our defaults
		_, ok := err.(viper.UnsupportedConfigError)
		if !ok {
			log.WithError(err).Fatal("Could not read config")
		}

		log.Debug("No config file available, using all defaults")
	}
}
Example #11
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".ata")  // name of config file (without extension)
	viper.AddConfigPath("$HOME") // adding home directory as first search path
	viper.AutomaticEnv()         // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}

	// deal with verbose and debug mode
	if DebugMode {
		logger.SetLevel(logging.DebugLevel)
	}
	logger.ActivateVerboseOutput(VerboseMode)

	// check that work directory exists
	if !io.DirectoryExists(WorkDirectory) {
		log.Fatalf("Work directory '%s' does not exist or is not readable", WorkDirectory)
	}
}
Example #12
0
File: grnl.go Project: jzorn/grnl
// initConfig reads in config file and ENV variables if set.
func initConfig() {

	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".grnl") // name of config file (without extension)
	viper.AddConfigPath("$HOME") // adding home directory as first search path
	viper.AutomaticEnv()         // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		fmt.Printf("Error using config file %q\n%q", viper.ConfigFileUsed(), err)
	}

	if db != "" {
		viper.Set("db", db)
	}

	if editor != "" {
		viper.Set("editor", editor)
	}

	if dateFormat != "" {
		viper.Set("dateFormat", dateFormat)
	}
}
Example #13
0
func main() {
	mainCmd.AddCommand(versionCmd)
	mainCmd.AddCommand(generateCmd)
	mainCmd.AddCommand(transactCmd)
	mainCmd.AddCommand(logCmd)
	mainCmd.AddCommand(httpCmd)
	mainCmd.AddCommand(domainsCmd)

	viper.SetEnvPrefix("ORIGINS")
	viper.AutomaticEnv()

	// Default locations for the origins config file.
	viper.SetConfigName("origins")

	// Directory the program is being called from
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))

	if err == nil {
		viper.AddConfigPath(dir)
	}

	flags := mainCmd.PersistentFlags()

	flags.String("log", "info", "Level of log messages to emit. Choices are: debug, info, warn, error, fatal, panic.")
	flags.String("config", "", "Path to config file. Defaults to a origins.{json,yml,yaml} in the current working directory.")

	viper.BindPFlag("log", flags.Lookup("log"))
	viper.BindPFlag("config", flags.Lookup("config"))

	// If the target subcommand is generate, remove the generator
	// arguments to prevent flag parsing errors.
	args := parseGenerateArgs(os.Args[1:])

	// Set explicit arguments and parse the flags to setup
	// the config file and logging.
	mainCmd.SetArgs(args)
	mainCmd.ParseFlags(args)

	config := viper.GetString("config")

	if config != "" {
		viper.SetConfigFile(config)
	}

	// Read configuration file if present.
	viper.ReadInConfig()

	// Turn on debugging for all commands.
	level, err := logrus.ParseLevel(viper.GetString("log"))

	if err != nil {
		fmt.Println("Invalid log level choice.")
		mainCmd.Help()
	}

	logrus.SetLevel(level)

	mainCmd.Execute()
}
Example #14
0
func initConfig() {
	viper.SetConfigFile("./config.json")
	viper.SetDefault("listen", ":8000")
	viper.SetDefault("staticFolder", "./static")
	viper.SetDefault("commandsFolder", "./commands")
	viper.SetDefault("log.filename", "go-lazy-remote.log")
	viper.ReadInConfig()
}
Example #15
0
func initConfig() {
	if CfgFile != "" {
		viper.SetConfigFile(CfgFile)
	}
	viper.SetConfigName("config")             // name of config file (without extension)
	viper.AddConfigPath(defaultDataDir + "/") // path to look for the config file in
	viper.ReadInConfig()
}
Example #16
0
func ReadConfigFile(filePath string) error {
	_, err := os.Stat(filePath)
	if err != nil {
		return err
	}
	viper.SetConfigFile(filePath)
	return viper.ReadInConfig()
}
Example #17
0
func initConfig() {
	if CfgFile != "" {
		viper.SetConfigFile(CfgFile)
	}
	viper.SetConfigName("config")
	viper.AddConfigPath("/etc/dagobah/")
	viper.AddConfigPath("$HOME/.dagobah/")
	viper.ReadInConfig()
}
Example #18
0
func Config(file string) (err error) {
	if Exists(file) {
		viper.SetConfigFile(file)
	} else {
		err = errors.New("Config file doesn't exists")
	}

	return err
}
Example #19
0
func initialiseConfig() error {
	viper.SetConfigFile(configPath())
	if err := viper.ReadInConfig(); err != nil {
		if !os.IsNotExist(err) {
			return err
		}
	}
	return nil
}
Example #20
0
File: config.go Project: ovh/tatcli
// ReadConfig reads config in .tatcli/config per default
func ReadConfig() {
	if ConfigFile != "" {
		viper.SetConfigFile(ConfigFile)
		viper.ReadInConfig() // Find and read the config file
		if Debug {
			fmt.Printf("Using config file %s\n", ConfigFile)
		}
	}
}
Example #21
0
func InitConfig() {
	viper.SetConfigFile("config")
	viper.SetConfigType("toml")
	viper.AddConfigPath(".")
	err := viper.ReadInConfig()
	if err != nil {
		log.Println(err)
	}
}
Example #22
0
func initConfig() {
	if CfgFile != "" {
		viper.SetConfigFile(CfgFile)
	}
	viper.SetConfigName("config")          // name of config file (without extension)
	viper.AddConfigPath("/etc/dagobah/")   // path to look for the config file in
	viper.AddConfigPath("$HOME/.dagobah/") // call multiple times to add many search paths
	viper.ReadInConfig()
}
Example #23
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	configPath := constants.ConfigFile
	viper.SetConfigFile(configPath)
	viper.SetConfigType("json")
	err := viper.ReadInConfig()
	if err != nil {
		glog.Warningf("Error reading config file at %s: %s", configPath, err)
	}
	setupViper()
}
Example #24
0
func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	}
	viper.SetConfigName(".sman")
	viper.AddConfigPath("$HOME")
	viper.AutomaticEnv()
	viper.SetEnvPrefix("sman")
	_ = viper.ReadInConfig()
}
Example #25
0
func init() {
	flag.Parse()
	config.SetConfigFile(*configFileName)

	err := config.ReadInConfig()
	if err != nil {
		panic("Config file not found")
	}
	logConfig := config.GetStringMap("log")
	initLog(logConfig)
}
Example #26
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
		// If a config file is found, read it in.
	}

	viper.SetConfigName(".recipe") // name of config file (without extension)
	viper.AddConfigPath("$HOME")   // adding home directory as first search path
	viper.AutomaticEnv()           // read in environment variables that match

	viper.ReadInConfig()
}
Example #27
0
func initConfig() {
	if CfgFile != "" {
		viper.SetConfigFile(CfgFile)
	}
	viper.SetConfigName("config")
	viper.AddConfigPath("$HOME/.cyboard/")
	viper.AddConfigPath(".")
	err := viper.ReadInConfig()
	if err != nil {
		log.Fatal(fmt.Errorf("Fatal error config file: %s \n", err))
	}
}
Example #28
0
func TestViperGetStringOrFail(t *testing.T) {
	assert := assert.New(t)
	viper.SetConfigFile("../.ayi.example.yml")
	err := viper.ReadInConfig()
	assert.Nil(err)
	s, err := ViperGetStringOrFail("scripts.mie")
	assert.Equal("echo mie", s)
	_, err = ViperGetStringOrFail("scripts.qian")
	assert.NotNil(err)
	ss := viper.GetStringSlice("scripts.qian")
	assert.Equal(2, len(ss))
}
Example #29
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	mutex.Lock()
	if cfgFile != "" {
		// enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	path := absPathify("$HOME")
	if _, err := os.Stat(filepath.Join(path, ".hydra.yml")); err != nil {
		_, _ = os.Create(filepath.Join(path, ".hydra.yml"))
	}

	viper.SetConfigType("yaml")
	viper.SetConfigName(".hydra") // name of config file (without extension)
	viper.AddConfigPath("$HOME")  // adding home directory as first search path
	viper.AutomaticEnv()          // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		fmt.Printf(`Config file not found because "%s"`, err)
		fmt.Println("")
	}

	if err := viper.Unmarshal(c); err != nil {
		fatal("Could not read config because %s.", err)
	}

	if consentURL, ok := viper.Get("CONSENT_URL").(string); ok {
		c.ConsentURL = consentURL
	}

	if clientID, ok := viper.Get("CLIENT_ID").(string); ok {
		c.ClientID = clientID
	}

	if systemSecret, ok := viper.Get("SYSTEM_SECRET").(string); ok {
		c.SystemSecret = []byte(systemSecret)
	}

	if clientSecret, ok := viper.Get("CLIENT_SECRET").(string); ok {
		c.ClientSecret = clientSecret
	}

	if databaseURL, ok := viper.Get("DATABASE_URL").(string); ok {
		c.DatabaseURL = databaseURL
	}

	if c.ClusterURL == "" {
		fmt.Printf("Pointing cluster at %s\n", c.GetClusterURL())
	}
	mutex.Unlock()
}
Example #30
0
// LoadConfiguration returns a GlobalConfiguration.
func LoadConfiguration() *GlobalConfiguration {
	configuration := NewGlobalConfiguration()
	viper.SetEnvPrefix("traefik")
	viper.SetConfigType("toml")
	viper.AutomaticEnv()
	if len(viper.GetString("configFile")) > 0 {
		viper.SetConfigFile(viper.GetString("configFile"))
	} else {
		viper.SetConfigName("traefik") // name of config file (without extension)
	}
	viper.AddConfigPath("/etc/traefik/")   // path to look for the config file in
	viper.AddConfigPath("$HOME/.traefik/") // call multiple times to add many search paths
	viper.AddConfigPath(".")               // optionally look for config in the working directory
	if err := viper.ReadInConfig(); err != nil {
		fmtlog.Fatalf("Error reading file: %s", err)
	}
	if len(arguments.Certificates) > 0 {
		viper.Set("certificates", arguments.Certificates)
	}
	if arguments.web {
		viper.Set("web", arguments.Web)
	}
	if arguments.file {
		viper.Set("file", arguments.File)
	}
	if !arguments.dockerTLS {
		arguments.Docker.TLS = nil
	}
	if arguments.docker {
		viper.Set("docker", arguments.Docker)
	}
	if arguments.marathon {
		viper.Set("marathon", arguments.Marathon)
	}
	if arguments.consul {
		viper.Set("consul", arguments.Consul)
	}
	if arguments.zookeeper {
		viper.Set("zookeeper", arguments.Zookeeper)
	}
	if arguments.etcd {
		viper.Set("etcd", arguments.Etcd)
	}
	if arguments.boltdb {
		viper.Set("boltdb", arguments.Boltdb)
	}
	if err := unmarshal(&configuration); err != nil {
		fmtlog.Fatalf("Error reading file: %s", err)
	}

	return configuration
}