Skip to content
Snippets Groups Projects
parseTemplateCreateConf.go 1.62 KiB
Newer Older
  • Learn to ignore specific revisions
  • package templateCreate
    
    import (
    	"flag"
    	"os"
    
    	"github.com/sirupsen/logrus"
    	"gopkg.in/yaml.v3"
    )
    
    var configPath_default = "templateCreate/templateCreate.clab_vars.yaml" // config path if no other path is given via -config flag
    var tcConf *TemplateCreateConfig                                        // pointer to parsed config
    // ipPrefix: ipBase without number after last ".".
    // e.g. ipBase = "172.100.20.0" -> ipPrefix = "172.100.20.".
    var ipPrefix string
    
    func ParseTemplateCreateConfig() {
    	// TODO: flag validation
    	configPath := flag.String("config", "", "path to the config file")
    	logLevel := flag.String("log", "", "logrus log level (debug, info, warn, error, fatal, panic)")
    
    	flag.Parse()
    
    	logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})
    	// parse string, this is built-in feature of logrus
    	ll, err := logrus.ParseLevel(*logLevel)
    	if err != nil {
    		ll = logrus.InfoLevel
    		logrus.Info("-log flag not provided, using default: ", ll)
    	}
    	// set global log level
    	logrus.SetLevel(ll)
    	logrus.Info("Setting log level to ", ll)
    
    	// if no argument
    	if *configPath == "" {
    		err = flag.Set("config", configPath_default)
    		if err != nil {
    			ll = logrus.InfoLevel
    			logrus.Info("-log flag not provided, using default: ", ll)
    		}
    		logrus.Info("-config flag not provided, using default: ", *configPath)
    	}
    
    	// unmarshal config
    	config := &TemplateCreateConfig{}
    	file, err := os.ReadFile(*configPath)
    	if err != nil {
    		logrus.Fatal(err)
    	}
    	if err := yaml.Unmarshal(file, config); err != nil {
    		logrus.Fatal(err)
    	}
    	// set TemplateCreateConfig variable
    	tcConf = config
    	//logrus.Info(*tcConf) // print entire parsed config
    }