// parseConfig loads a TOML configuration from a provided path and
// returns the AST produced from the TOML parser. When loading the file, it
// will find environment variables and replace them.
355881
func parseConfig(contents []byte) (*ast.Table, error) {
	contents = trimBOM(contents)

	parameters := envVarRe.FindAllSubmatch(contents, -1)
	for _, parameter := range parameters {
		if len(parameter) != 3 {
			continue
		}

		var env_var []byte
		if parameter[1] != nil {
			env_var = parameter[1]
		} else if parameter[2] != nil {
			env_var = parameter[2]
		} else {
			continue
		}

		env_val, ok := os.LookupEnv(strings.TrimPrefix(string(env_var), "$"))
		if ok {
			env_val = escapeEnv(env_val)
			contents = bytes.Replace(contents, parameter[0], []byte(env_val), 1)
		}
	}

	return toml.Parse(contents)
}
206317
func initConfiguration(path string) error {
	log.Println("Parsing JSON config file " + path)

	contents, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	Configuration = new(Config)
	if err = json.Unmarshal(contents, Configuration); err != nil {
		return err
	}

	var dirs []os.FileInfo
	if dirs, err = ioutil.ReadDir(Configuration.NERDZPath + "/data/langs/"); err != nil || len(dirs) == 0 {
		return errors.New("Check your NERDZPath: " + Configuration.NERDZPath)
	}

	for _, language := range dirs {
		if language.Name() != "index.html" {
			Configuration.Languages = append(Configuration.Languages, language.Name())
		}
	}

	Configuration.Scopes = scopes

	if dirs, err = ioutil.ReadDir(Configuration.NERDZPath + "/tpl/"); err != nil {
		return err
	}

	Configuration.Templates = make(map[uint8]string)
	for _, tpl := range dirs {
		if tpl.Name() != "index.html" {
			var tplNumber int
			if tplNumber, err = strconv.Atoi(tpl.Name()); err != nil {
				return err
			}

			var byteName []byte
			if byteName, err = ioutil.ReadFile(Configuration.NERDZPath + "/tpl/" + tpl.Name() + "/NAME"); err != nil {
				return err
			}
			Configuration.Templates[uint8(tplNumber)] = string(byteName)
		}
	}

	if Configuration.Port == 0 {
		Configuration.Port = 7536
	}

	if Configuration.NERDZHost != "" {
		if _, e := url.Parse(Configuration.NERDZHost); e != nil {
			return e
		}
	} else {
		return errors.New("NERDZHost is a required field")
	}

	if Configuration.Host != "" {
		if _, e := url.Parse(Configuration.Host); e != nil {
			return e
		}
	} else {
		return errors.New("Host is a required field")
	}

	if !strings.HasPrefix(Configuration.Scheme, "http") {
		return errors.New("Scheme shoud be http or https only. Https is mandatory in production environment")
	}

	return nil
}
184365
func loadConfig(fname string) (conf jsonConfig, err error) {
  var data []byte
  data, err = ioutil.ReadFile(fname)
  if err == nil {
    err = json.Unmarshal(data, &conf)
  }
  return
}
503104
func LoadConfig(path string) (*Config, error) {
	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			return nil, os.ErrNotExist
		}

		return nil, err
	}

	config := Config{}
	if _, err := toml.DecodeFile(path, &config); err != nil {
		return nil, errors.Wrapf(err, "failed to unmarshal data at '%s'", path)
	}

	if err := config.parse(); err != nil {
		return nil, err
	}

	if err := config.Validate(); err != nil {
		return nil, err
	}

	return &config, nil
}
115539
func ParseConfig(reader io.Reader) (config Config, err error) {
	// TODO: make a better decoder to avoid having a buffer here and decoding
	// twice.
	buf := &bytes.Buffer{}
	var common Common
	err = json.NewDecoder(io.TeeReader(reader, buf)).Decode(&common)
	if err != nil {
		return nil, err
	}
	v, err := parseVersion(common.Version)
	if err != nil {
		return nil, err
	}
	switch v {
	case Version1:
		var v1 V1
		err = json.NewDecoder(buf).Decode(&v1)
		if err != nil {
			return nil, err
		}
		return &v1, (&v1).EnsureInit()
	default:
		return nil, ErrInvalidVersion{}
	}
}
516826
func MustPathConfig(ctx context.Context) *types.PathConfig {
	return ctx.Value(PathConfigKey).(*types.PathConfig)
}
416320
func ParseConfigs(client client.ConfigAPIClient, requestedConfigs []*swarm.ConfigReference) ([]*swarm.ConfigReference, error) {
	if len(requestedConfigs) == 0 {
		return []*swarm.ConfigReference{}, nil
	}

	configRefs := make(map[string]*swarm.ConfigReference)
	ctx := context.Background()

	for _, config := range requestedConfigs {
		if _, exists := configRefs[config.File.Name]; exists {
			return nil, errors.Errorf("duplicate config target for %s not allowed", config.ConfigName)
		}

		configRef := new(swarm.ConfigReference)
		*configRef = *config
		configRefs[config.File.Name] = configRef
	}

	args := filters.NewArgs()
	for _, s := range configRefs {
		args.Add("name", s.ConfigName)
	}

	configs, err := client.ConfigList(ctx, types.ConfigListOptions{
		Filters: args,
	})
	if err != nil {
		return nil, err
	}

	foundConfigs := make(map[string]string)
	for _, config := range configs {
		foundConfigs[config.Spec.Annotations.Name] = config.ID
	}

	addedConfigs := []*swarm.ConfigReference{}

	for _, ref := range configRefs {
		id, ok := foundConfigs[ref.ConfigName]
		if !ok {
			return nil, errors.Errorf("config not found: %s", ref.ConfigName)
		}

		// set the id for the ref to properly assign in swarm
		// since swarm needs the ID instead of the name
		ref.ConfigID = id
		addedConfigs = append(addedConfigs, ref)
	}

	return addedConfigs, nil
}
678014
func Config() (*DefaultConfig, error) {
	conf, err := config.Config()
	return (*DefaultConfig)(conf), err
}
782789
func loadConfig() (*config, error) {
	loadConfigError := func(err error) (*config, error) {
		return nil, err
	}

	// Default config.
	cfg := defaultConfig

	// A config file in the current directory takes precedence.
	if _, err := os.Stat(defaultConfigFilename); !os.IsNotExist(err) {
		cfg.ConfigFile = defaultConfigFile
	}

	// Pre-parse the command line options to see if an alternative config
	// file or the version flag was specified.
	preCfg := cfg
	preParser := flags.NewParser(&preCfg, flags.HelpFlag|flags.PassDoubleDash)
	_, err := preParser.Parse()
	if err != nil {
		e, ok := err.(*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(err)
	}

	// 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, %s-%s)\n", appName,
			ver.String(), runtime.Version(), runtime.GOOS, runtime.GOARCH)
		os.Exit(0)
	}

	// Load additional config from file.
	var configFileError error
	parser := flags.NewParser(&cfg, flags.Default)
	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
	}

	// 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)
	}

	// 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 {
		log.Printf("%v", configFileError)
		//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"
		err := fmt.Errorf(str, "loadConfig")
		fmt.Fprintln(os.Stderr, err)
		parser.WriteHelp(os.Stderr)
		return loadConfigError(err)
	}

	// Set the host names and ports to the default if the
	// user does not specify them.
	if cfg.DcrdServ == "" {
		cfg.DcrdServ = defaultHost + ":" + activeNet.JSONRPCClientPort
	}

	// Append the network type to the log directory so it is "namespaced"
	// per network.
	// cfg.LogDir = cleanAndExpandPath(cfg.LogDir)
	// cfg.LogDir = filepath.Join(cfg.LogDir, activeNet.Name)

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

	// Initialize logging at the default logging level.
	// initSeelogLogger(filepath.Join(cfg.LogDir, defaultLogFilename))
	// setLogLevels(defaultLogLevel)

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

	return &cfg, nil
}
1100487
func ParseFile(path string, unmarshal func([]byte, interface{}) error) (*Config, error) {
	bs, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	conf := &Config{}
	if err := unmarshal(bs, conf); err != nil {
		return nil, err
	}

	if err := conf.Sanitize(); err != nil {
		return nil, err
	}
	return conf, nil
}
1106882
func LoadConfig() (*Config, error) {
	cfg, err := NewConfig(torusRootPath())
	if err != nil {
		return nil, errs.NewErrorExitError("Failed to load config.", err)
	}

	return cfg, nil
}
251333
func ParseConfig(rawConfig map[string]interface{}, out interface{}) error {
	decodeConf := &mapstructure.DecoderConfig{
		Result:           out,
		WeaklyTypedInput: true,
		ErrorUnused:      true,
	}

	decoder, err := mapstructure.NewDecoder(decodeConf)
	if err != nil {
		return err
	}

	if err := decoder.Decode(rawConfig); err != nil {
		return fmt.Errorf("error decoding config: %s", err)
	}

	return nil
}
603857
func (p *ConnectManagedProxy) ParseConfig() (*ConnectManagedProxyConfig, error) {
	var cfg ConnectManagedProxyConfig
	d, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
		ErrorUnused:      false,
		WeaklyTypedInput: true, // allow string port etc.
		Result:           &cfg,
	})
	if err != nil {
		return nil, err
	}
	err = d.Decode(p.Config)
	if err != nil {
		return nil, err
	}
	return &cfg, nil
}
770558
func (m *Meta) loadConfig(rootDir string) (*configs.Config, tfdiags.Diagnostics) {
	var diags tfdiags.Diagnostics
	rootDir = m.normalizePath(rootDir)

	loader, err := m.initConfigLoader()
	if err != nil {
		diags = diags.Append(err)
		return nil, diags
	}

	config, hclDiags := loader.LoadConfig(rootDir)
	diags = diags.Append(hclDiags)
	return config, diags
}
157178
func ParseConfig(raw []byte, id string) (*Config, error) {
	var result Config
	if err := util.Unmarshal(raw, &result); err != nil {
		return nil, err
	}
	return &result, result.validateAndInjectDefaults(id)
}
1003611
func (m *Meta) Config(path string) (*config.Config, error) {
	// If no explicit path was given then it is okay for there to be
	// no backend configuration found.
	emptyOk := path == ""

	// If we had no path set, it is an error. We can't initialize unset
	if path == "" {
		path = "."
	}

	// Expand the path
	if !filepath.IsAbs(path) {
		var err error
		path, err = filepath.Abs(path)
		if err != nil {
			return nil, fmt.Errorf(
				"Error expanding path to backend config %q: %s", path, err)
		}
	}

	log.Printf("[DEBUG] command: loading backend config file: %s", path)

	// We first need to determine if we're loading a file or a directory.
	fi, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) && emptyOk {
			log.Printf(
				"[INFO] command: backend config not found, returning nil: %s",
				path)
			return nil, nil
		}

		return nil, err
	}

	var f func(string) (*config.Config, error) = config.LoadFile
	if fi.IsDir() {
		f = config.LoadDir
	}

	// Load the configuration
	c, err := f(path)
	if err != nil {
		// Check for the error where we have no config files and return nil
		// as the configuration type.
		if errwrap.ContainsType(err, new(config.ErrNoConfigsFound)) {
			log.Printf(
				"[INFO] command: backend config not found, returning nil: %s",
				path)
			return nil, nil
		}

		return nil, err
	}

	return c, nil
}
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
}