github.com/grafana/pyroscope@v1.18.0/pkg/cfg/dynamic.go (about)

     1  package cfg
     2  
     3  import (
     4  	"flag"
     5  )
     6  
     7  // testMode is used to test flag parsing.
     8  var testMode = false
     9  
    10  // SetTestMode is used to set the testMode flag.
    11  // We don't want to exit the process when running tests.
    12  func SetTestMode(isTestMode bool) {
    13  	testMode = isTestMode
    14  }
    15  
    16  // GetTestMode is used to get the testMode flag when running tests.
    17  func GetTestMode() bool {
    18  	return testMode
    19  }
    20  
    21  // DynamicCloneable must be implemented by config structs that can be dynamically unmarshalled
    22  type DynamicCloneable interface {
    23  	Cloneable
    24  	ApplyDynamicConfig() Source
    25  }
    26  
    27  // DynamicUnmarshal handles populating a config based on the following precedence:
    28  // 1. Defaults provided by the `RegisterFlags` interface
    29  // 2. Sections populated by dynamic logic. Configs passed to this function must implement ApplyDynamicConfig()
    30  // 3. Any config options specified directly in the config file
    31  // 4. Any config options specified on the command line.
    32  func DynamicUnmarshal(dst DynamicCloneable, args []string, fs *flag.FlagSet) error {
    33  	return Unmarshal(dst,
    34  		// First populate the config with defaults including flags from the command line
    35  		Defaults(fs),
    36  		// Next populate the config from the config file, we do this to populate the `common`
    37  		// section of the config file by taking advantage of the code in YAMLFlag which will load
    38  		// and process the config file.
    39  		YAMLFlag(args, "config.file"),
    40  		// Apply any dynamic logic to set other defaults in the config. This function is called after parsing the
    41  		// config files so that values from a common, or shared, section can be used in
    42  		// the dynamic evaluation
    43  		dst.ApplyDynamicConfig(),
    44  		// Load configs from the config file a second time, this will supersede anything set by the common
    45  		// config with values specified in the config file.
    46  		YAMLFlag(args, "config.file"),
    47  		// Load the flags again, this will supersede anything set from config file with flags from the command line.
    48  		Flags(args, fs),
    49  	)
    50  }