// load the config
171257
func (c *config) load() error {
	path, err := c.path()
	if err != nil {
		return nil
	}
	return c.loadFromPath(path)
}
564786
func loadConfig(path string) (config, error) {
	var ret config

	if path == "" {
		return ret, nil
	}

	file, err := os.Open(path)
	switch {
	case err == nil:
		defer file.Close()

		decoder := json.NewDecoder(file)
		if err = decoder.Decode(&ret); err != nil {
			return ret, errors.Annotate(err, "failed to decode file").Err()
		}
		return ret, nil

	case os.IsNotExist(err):
		// The file does not exist. We don't consider this an error, since the file
		// is optional.
		return ret, nil

	default:
		// An unexpected failure occurred.
		return ret, errors.Annotate(err, "failed to open file").Err()
	}
}
1043053
func LoadConf(file string) (*Config, error) {
	config := &Config{}
	if file == "" {
		return config, nil
	}
	f, err := os.Open(file)
	if err != nil {
		return nil, fmt.Errorf("could not open config file %q: %v", file, err)
	}
	defer f.Close()

	dec := json.NewDecoder(f)
	err = dec.Decode(config)
	if err != nil {
		return nil, fmt.Errorf("could not parse config file %q: %v", file, err)
	}
	return config, nil
}
1067635
func LoadConfigDir(dir string) (*Config, error) {
	f, err := os.Open(dir)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	fi, err := f.Stat()
	if err != nil {
		return nil, err
	}
	if !fi.IsDir() {
		return nil, fmt.Errorf(
			"configuration path must be a directory: %s", dir)
	}

	var files []string
	err = nil
	for err != io.EOF {
		var fis []os.FileInfo
		fis, err = f.Readdir(128)
		if err != nil && err != io.EOF {
			return nil, err
		}

		for _, fi := range fis {
			// Ignore directories
			if fi.IsDir() {
				continue
			}

			// Only care about files that are valid to load.
			name := fi.Name()
			skip := true
			if strings.HasSuffix(name, ".hcl") {
				skip = false
			} else if strings.HasSuffix(name, ".json") {
				skip = false
			}
			if skip || isTemporaryFile(name) {
				continue
			}

			path := filepath.Join(dir, name)
			files = append(files, path)
		}
	}

	// Fast-path if we have no files
	if len(files) == 0 {
		return &Config{}, nil
	}

	sort.Strings(files)

	var result *Config
	for _, f := range files {
		config, err := ParseConfigFile(f)
		if err != nil {
			return nil, fmt.Errorf("Error loading %s: %s", f, err)
		}
		config.Files = append(config.Files, f)

		if result == nil {
			result = config
		} else {
			result = result.Merge(config)
		}
	}

	return result, nil
}
274302
func (m multiLoader) Load(s interface{}) error {
	for _, loader := range m {
		if err := loader.Load(s); err != nil {
			return err
		}
	}

	return nil
}
272846
func LoadConfig(path string, v *Config) error {
	if v == nil {
		return errors.Wrapf(errdefs.ErrInvalidArgument, "argument v must not be nil")
	}
	md, err := toml.DecodeFile(path, v)
	if err != nil {
		return err
	}
	v.md = md
	return nil
}
1081993
func loadConfig(data []byte) (*apiserverconfig.EncryptionConfiguration, error) {
	scheme := runtime.NewScheme()
	codecs := serializer.NewCodecFactory(scheme)
	apiserverconfig.AddToScheme(scheme)
	apiserverconfigv1.AddToScheme(scheme)

	configObj, gvk, err := codecs.UniversalDecoder().Decode(data, nil, nil)
	if err != nil {
		return nil, err
	}
	config, ok := configObj.(*apiserverconfig.EncryptionConfiguration)
	if !ok {
		return nil, fmt.Errorf("got unexpected config type: %v", gvk)
	}
	return config, nil
}
38584
func Load() *Config {
	for _, l := range configLocations() {
		if debug {
			fmt.Printf("[DEBUG] Trying to load config from %s\n", l)
		}
		cfg, err := load(l)
		if err == ErrConfigNotFound {
			continue
		}
		if err != nil {
			panic(err)
		}
		_ = cfg.checkDefaults()
		if debug {
			fmt.Printf("[DEBUG] Loaded config from %s: %+v\n", l, cfg)
		}
		return cfg
	}
	cfg := New()
	cfg.Root.Path = backend.FromPath(PwStoreDir(""))
	_ = cfg.checkDefaults()
	if debug {
		fmt.Printf("[DEBUG] config.Load(): %+v\n", cfg)
	}
	return cfg
}
931122
func Load(configFile string, data interface{}) (quick.Config, error) {
	return quick.LoadConfig(configFile, globalEtcdClient, data)
}
1144011
func LoadConfig() (*Config, error) {
	// Load the configuration according to the spec.
	task := "Load Git-related configuration"
	spec := newConfigSpec()
	if err := loader.LoadConfig(spec); err != nil {
		return nil, errs.NewError(task, err)
	}

	// Get the remote name, which may be stored in git config.
	task = "Get the remote name for the main project repository"
	remoteName, err := GetConfigString(GitConfigKeyRemote)
	if err != nil {
		return nil, errs.NewError(task, err)
	}
	if remoteName == "" {
		remoteName = DefaultRemoteName
	}

	// Return the main config struct.
	return &Config{
		LocalConfig: *spec.local,
		RemoteName:  remoteName,
	}, nil
}
99879
func Load(configFile string, logger log.Logger) (*GatewayConfig, error) {
	p, err := loadNoDefault(configFile, logger)
	if err == nil {
		c := pointer.FillDefaultFrom(p, DefaultGatewayConfig()).(*GatewayConfig)
		if err = os.Setenv("gatewayServerName", *c.ServerName); err == nil {
			if c.ClusterName == nil || *c.ClusterName == "" {
				return nil, errors.New("gateway now requires configuring ClusterName at top level of config")
			}
			// fill in environment variable values to override config file
			loadFromEnv(c)
			return c, nil
		}
	}
	return nil, err
}
351153
func loadConfig() (*config, error) {
	loadConfigError := func(err error) (*config, error) {
		return nil, err
	}

	// Default config
	cfg := defaultConfig
	defaultConfigNow := defaultConfig

	// Load settings from environment variables.
	err := env.Parse(&cfg)
	if err != nil {
		return loadConfigError(err)
	}

	// If appdata was specified but not the config file, change the config file
	// path, and record this as the new default config file location.
	if defaultHomeDir != cfg.HomeDir && defaultConfigNow.ConfigFile == cfg.ConfigFile {
		cfg.ConfigFile = filepath.Join(cfg.HomeDir, defaultConfigFilename)
		// Update the defaultConfig to avoid an error if the config file in this
		// "new default" location does not exist.
		defaultConfigNow.ConfigFile = cfg.ConfigFile
	}

	// Pre-parse the command line options to see if an alternative config file
	// or the version flag was specified. Override any environment variables
	// with parsed command line flags.
	preCfg := cfg
	preParser := flags.NewParser(&preCfg, flags.HelpFlag|flags.PassDoubleDash)
	_, flagerr := preParser.Parse()

	if flagerr != nil {
		e, ok := flagerr.(*flags.Error)
		if !ok || e.Type != flags.ErrHelp {
			preParser.WriteHelp(os.Stderr)
		}
		if ok && e.Type == flags.ErrHelp {
			preParser.WriteHelp(os.Stdout)
			os.Exit(0)
		}
		return loadConfigError(flagerr)
	}

	// Show the version and exit if the version flag was specified.
	appName := filepath.Base(os.Args[0])
	appName = strings.TrimSuffix(appName, filepath.Ext(appName))
	if preCfg.ShowVersion {
		fmt.Printf("%s version %s (Go version %s)\n", appName,
			version.Version(), runtime.Version())
		os.Exit(0)
	}

	// If a non-default appdata folder is specified on the command line, it may
	// be necessary adjust the config file location. If the the config file
	// location was not specified on the command line, the default location
	// should be under the non-default appdata directory. However, if the config
	// file was specified on the command line, it should be used regardless of
	// the appdata directory.
	if defaultHomeDir != preCfg.HomeDir && defaultConfigNow.ConfigFile == preCfg.ConfigFile {
		preCfg.ConfigFile = filepath.Join(preCfg.HomeDir, defaultConfigFilename)
		// Update the defaultConfig to avoid an error if the config file in this
		// "new default" location does not exist.
		defaultConfigNow.ConfigFile = preCfg.ConfigFile
	}

	// Load additional config from file.
	var configFileError error
	// Config file name for logging.
	configFile := "NONE (defaults)"
	parser := flags.NewParser(&cfg, flags.Default)

	// Do not error default config file is missing.
	if _, err := os.Stat(preCfg.ConfigFile); os.IsNotExist(err) {
		// Non-default config file must exist
		if defaultConfigNow.ConfigFile != preCfg.ConfigFile {
			fmt.Fprintln(os.Stderr, err)
			return loadConfigError(err)
		}
		// Warn about missing default config file, but continue
		fmt.Printf("Config file (%s) does not exist. Using defaults.\n",
			preCfg.ConfigFile)
	} else {
		// The config file exists, so attempt to parse it.
		err = flags.NewIniParser(parser).ParseFile(preCfg.ConfigFile)
		if err != nil {
			if _, ok := err.(*os.PathError); !ok {
				fmt.Fprintln(os.Stderr, err)
				parser.WriteHelp(os.Stderr)
				return loadConfigError(err)
			}
			configFileError = err
		}
		configFile = preCfg.ConfigFile
	}

	// Parse command line options again to ensure they take precedence.
	_, err = parser.Parse()
	if err != nil {
		if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp {
			parser.WriteHelp(os.Stderr)
		}
		return loadConfigError(err)
	}

	// Create the home directory if it doesn't already exist.
	funcName := "loadConfig"
	err = os.MkdirAll(cfg.HomeDir, 0700)
	if err != nil {
		// Show a nicer error message if it's because a symlink is linked to a
		// directory that does not exist (probably because it's not mounted).
		if e, ok := err.(*os.PathError); ok && os.IsExist(err) {
			if link, lerr := os.Readlink(e.Path); lerr == nil {
				str := "is symlink %s -> %s mounted?"
				err = fmt.Errorf(str, e.Path, link)
			}
		}

		str := "%s: failed to create home directory: %v"
		err := fmt.Errorf(str, funcName, err)
		fmt.Fprintln(os.Stderr, err)
		return nil, err
	}

	// If a non-default appdata folder is specified, it may be necessary to
	// adjust the DataDir and LogDir. If these other paths are their defaults,
	// they should be modifed to look under the non-default appdata directory.
	// If they are not their defaults, the user-specified values should be used.
	if defaultHomeDir != cfg.HomeDir {
		if defaultDataDir == cfg.DataDir {
			cfg.DataDir = filepath.Join(cfg.HomeDir, defaultDataDirname)
		}
		if defaultLogDir == cfg.LogDir {
			cfg.LogDir = filepath.Join(cfg.HomeDir, defaultLogDirname)
		}
	}

	// Warn about missing config file after the final command line parse
	// succeeds.  This prevents the warning on help messages and invalid
	// options.
	if configFileError != nil {
		fmt.Printf("%v\n", configFileError)
		return loadConfigError(configFileError)
	}

	// Choose the active network params based on the selected network. Multiple
	// networks can't be selected simultaneously.
	numNets := 0
	activeNet = &netparams.MainNetParams
	activeChain = &chaincfg.MainNetParams
	if cfg.TestNet {
		activeNet = &netparams.TestNet3Params
		activeChain = &chaincfg.TestNet3Params
		numNets++
	}
	if cfg.SimNet {
		activeNet = &netparams.SimNetParams
		activeChain = &chaincfg.SimNetParams
		numNets++
	}
	if numNets > 1 {
		str := "%s: the testnet and simnet params can't be " +
			"used together -- choose one of the three"
		err := fmt.Errorf(str, funcName)
		fmt.Fprintln(os.Stderr, err)
		parser.WriteHelp(os.Stderr)
		return loadConfigError(err)
	}

	// Append the network type to the data directory so it is "namespaced" per
	// network.  In addition to the block database, there are other pieces of
	// data that are saved to disk such as address manager state. All data is
	// specific to a network, so namespacing the data directory means each
	// individual piece of serialized data does not have to worry about changing
	// names per network and such.
	//
	// Make list of old versions of testnet directories here since the network
	// specific DataDir will be used after this.
	cfg.DataDir = cleanAndExpandPath(cfg.DataDir)
	cfg.DataDir = filepath.Join(cfg.DataDir, activeNet.Name)
	// Create the data folder if it does not exist.
	err = os.MkdirAll(cfg.DataDir, 0700)
	if err != nil {
		return nil, err
	}

	logRotator = nil
	// Append the network type to the log directory so it is "namespaced"
	// per network in the same fashion as the data directory.
	cfg.LogDir = cleanAndExpandPath(cfg.LogDir)
	cfg.LogDir = filepath.Join(cfg.LogDir, activeNet.Name)

	// Initialize log rotation. After log rotation has been initialized, the
	// logger variables may be used. This creates the LogDir if needed.
	initLogRotator(filepath.Join(cfg.LogDir, defaultLogFilename))

	log.Infof("Log folder:  %s", cfg.LogDir)
	log.Infof("Config file: %s", configFile)

	if cfg.FullMode {
		log.Warn("The --pg switch is deprecated since full-mode is now required.")
	}

	// Disable dev balance prefetch if network has invalid script.
	_, err = dbtypes.DevSubsidyAddress(activeChain)
	if !cfg.NoDevPrefetch && err != nil {
		cfg.NoDevPrefetch = true
		log.Warnf("%v. Disabling balance prefetch (--no-dev-prefetch).", err)
	}

	// Validate SyncStatusLimit has been set. Zero means always show sync status
	// page instead of full block explorer pages.
	if cfg.SyncStatusLimit != 0 {
		// The sync-status-limit value should not be set to a value less than 2
		// or greater than maxSyncStatusLimit.
		if cfg.SyncStatusLimit < 2 || cfg.SyncStatusLimit > maxSyncStatusLimit {
			return nil, fmt.Errorf("sync-status-limit should not be set to "+
				"a value less than 2 or more than %d", maxSyncStatusLimit)
		}
	}

	// Validate block purge options.
	if cfg.PurgeNBestBlocks < 0 {
		return nil, fmt.Errorf("purge-n-blocks must be non-negative")
	}

	// Set the host names and ports to the default if the user does not specify
	// them.
	cfg.DcrdServ, err = normalizeNetworkAddress(cfg.DcrdServ, defaultHost, activeNet.JSONRPCClientPort)
	if err != nil {
		return loadConfigError(err)
	}

	// Output folder
	cfg.OutFolder = cleanAndExpandPath(cfg.OutFolder)
	cfg.OutFolder = filepath.Join(cfg.OutFolder, activeNet.Name)

	// Special show command to list supported subsystems and exit.
	if cfg.DebugLevel == "show" {
		fmt.Println("Supported subsystems", supportedSubsystems())
		os.Exit(0)
	}

	// Ensure HTTP profiler is mounted with a valid path prefix.
	if cfg.HTTPProfile && (cfg.HTTPProfPath == "/" || len(defaultHTTPProfPath) == 0) {
		return loadConfigError(fmt.Errorf("httpprofprefix must not be \"\" or \"/\""))
	}

	// Parse, validate, and set debug log level(s).
	if cfg.Quiet {
		cfg.DebugLevel = "error"
	}

	// Validate DB timeout. Zero or negative should be set to the large default
	// timeout to effectively disable timeouts.
	if cfg.PGQueryTimeout <= 0 {
		cfg.PGQueryTimeout = defaultPGQueryTimeout
	}

	// Parse, validate, and set debug log level(s).
	if err := parseAndSetDebugLevels(cfg.DebugLevel); err != nil {
		err = fmt.Errorf("%s: %v", funcName, err.Error())
		fmt.Fprintln(os.Stderr, err)
		parser.WriteHelp(os.Stderr)
		return loadConfigError(err)
	}

	// Checks if the expected format of the API URL was set. It also drops any
	// unnecessary parts of the URL.
	urlPath, err := retrieveRootPath(cfg.PoliteiaAPIURL)
	if err != nil {
		return loadConfigError(err)
	}
	cfg.PoliteiaAPIURL = urlPath

	// Check the supplied APIListen address
	cfg.APIListen, err = normalizeNetworkAddress(cfg.APIListen, defaultHost, defaultAPIPort)
	if err != nil {
		return loadConfigError(err)
	}

	// Expand some additional paths.
	cfg.DcrdCert = cleanAndExpandPath(cfg.DcrdCert)
	cfg.DBFileName = cleanAndExpandPath(cfg.DBFileName)
	cfg.AgendasDBFileName = cleanAndExpandPath(cfg.AgendasDBFileName)
	cfg.ProposalsFileName = cleanAndExpandPath(cfg.ProposalsFileName)
	cfg.RateCertificate = cleanAndExpandPath(cfg.RateCertificate)
	cfg.ChartsCacheDump = cleanAndExpandPath(cfg.ChartsCacheDump)

	// Clean up the provided mainnet and testnet links, ensuring there is a single
	// trailing slash.
	cfg.MainnetLink = strings.TrimSuffix(cfg.MainnetLink, "/") + "/"
	cfg.TestnetLink = strings.TrimSuffix(cfg.TestnetLink, "/") + "/"

	return &cfg, nil
}
404495
func Load(data []byte) (*clientcmdapi.Config, error) {
	config := clientcmdapi.NewConfig()
	// if there's no data in a file, return the default object instead of failing (DecodeInto reject empty input)
	if len(data) == 0 {
		return config, nil
	}
	decoded, _, err := clientcmdlatest.Codec.Decode(data, &schema.GroupVersionKind{Version: clientcmdlatest.Version, Kind: "Config"}, config)
	if err != nil {
		return nil, err
	}
	return decoded.(*clientcmdapi.Config), nil
}
1073785
func LoadConfiguration(Path string) (map[string]string, error) {
	cfgMap := make(map[string]string)
	err := cfg.Load(Path, cfgMap)

	return cfgMap, err
}
1152473
func LoadConfig(path string) (*Config, error) {
	settings := &Config{}

	c, err := config.ReadDefault(path)
	if err != nil {
		return nil, err
	}

	// Cloudinary settings
	var cURI *url.URL
	var uri string

	if uri, err = c.String("cloudinary", "uri"); err != nil {
		return nil, err
	}
	if cURI, err = url.Parse(uri); err != nil {
		return nil, errors.New(fmt.Sprint("cloudinary URI: ", err.Error()))
	}
	settings.CloudinaryURI = cURI

	// An optional remote prepend path
	if prepend, err := c.String("cloudinary", "prepend"); err == nil {
		settings.PrependPath = cloudinary.EnsureTrailingSlash(prepend)
	}
	settings.ProdTag, _ = c.String("global", "prodtag")

	// Keep files regexp? (optional)
	var pattern string
	pattern, _ = c.String("cloudinary", "keepfiles")
	if pattern != "" {
		settings.KeepFilesPattern = pattern
	}

	// mongodb section (optional)
	uri, _ = c.String("database", "uri")
	if uri != "" {
		var mURI *url.URL
		if mURI, err = url.Parse(uri); err != nil {
			return nil, errors.New(fmt.Sprint("mongoDB URI: ", err.Error()))
		}
		settings.MongoURI = mURI
	} else {
		fmt.Fprintf(os.Stderr, "Warning: database not set (upload sync disabled)\n")
	}

	// Looks for env variables, perform substitutions if needed
	if err := settings.handleEnvVars(); err != nil {
		return nil, err
	}
	return settings, nil
}
996040
func LoadConfig() (*AppConfig, error) {
	var (
		conf AppConfig
		err  error
	)
	err = envconfig.Process("digota", &conf)
	if err != nil {
		return nil, err
	}
	return &conf, nil
}
1345584
func (c *Config) LoadDefaultConfig() (err error) {

	c.HTTPSettings = DefaultHTTPClientSettings

	err = yaml.Unmarshal([]byte(DefaultConfigFileContent), c)
	if err != nil {
		logger.Errorf(nil, "Config parse error, %v.", err)
		return
	}

	logger.SetLevel(c.LogLevel)

	c.InitHTTPClient()
	return
}