github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/config/loader.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package config
    19  
    20  import (
    21  	"fmt"
    22  	"os"
    23  	"strings"
    24  
    25  	defaults "github.com/mcuadros/go-defaults"
    26  	"github.com/spf13/viper"
    27  	"go.uber.org/zap"
    28  
    29  	"github.com/zntrio/harp/v2/pkg/sdk/flags"
    30  	"github.com/zntrio/harp/v2/pkg/sdk/log"
    31  )
    32  
    33  // Load a config
    34  // Apply defaults first, then environment, then finally config file.
    35  func Load(conf interface{}, envPrefix, cfgFile string) error {
    36  	// Apply defaults first
    37  	defaults.SetDefaults(conf)
    38  
    39  	// Uppercase the prefix
    40  	upPrefix := strings.ToUpper(envPrefix)
    41  
    42  	// Overrides with environment
    43  	for k := range flags.AsEnvVariables(conf, "", false) {
    44  		envName := fmt.Sprintf("%s_%s", upPrefix, k)
    45  		log.CheckErr("unable to bind environment variable", viper.BindEnv(strings.ToLower(strings.ReplaceAll(k, "_", ".")), envName), zap.String("var", envName))
    46  	}
    47  
    48  	// Apply file settings
    49  	if cfgFile != "" {
    50  		// If the config file doesn't exists, let's exit
    51  		if _, err := os.Stat(cfgFile); os.IsNotExist(err) {
    52  			return fmt.Errorf("config: unable to open non-existing file %q: %w", cfgFile, err)
    53  		}
    54  
    55  		log.Bg().Info("Load settings from file", zap.String("path", cfgFile))
    56  
    57  		viper.SetConfigFile(cfgFile)
    58  		if err := viper.ReadInConfig(); err != nil {
    59  			return fmt.Errorf("config: unable to decode config file %q: %w", cfgFile, err)
    60  		}
    61  	}
    62  
    63  	// Update viper values
    64  	if err := viper.Unmarshal(conf); err != nil {
    65  		return fmt.Errorf("config: unable to apply config %q: %w", cfgFile, err)
    66  	}
    67  
    68  	// No error
    69  	return nil
    70  }