@@ -3,7 +3,9 @@ package config
33import (
44 "log"
55 "os"
6+ "path/filepath"
67 "regexp"
8+ "strings"
79
810 "gopkg.in/yaml.v3"
911)
@@ -31,6 +33,8 @@ type Config struct {
3133
3234// ReadConfig reads the config file and returns a filled Config struct.
3335func ReadConfig (configPath string ) (Config , error ) {
36+ log .Printf ("Reading config file '%s'...\n " , configPath )
37+
3438 conf , parseErr := parseConfigFromFile (configPath )
3539 if parseErr != nil {
3640 log .Fatalln ("Error while parsing yaml file:" , parseErr )
@@ -47,7 +51,42 @@ func ReadConfig(configPath string) (Config, error) {
4751// parseConfigFromFile reads the config file as bytes and passes it to parseConfigFromBytes.
4852// It returns a filled Config struct.
4953func parseConfigFromFile (configFile string ) (Config , error ) {
50- yamlFileContent , readErr := os .ReadFile (configFile )
54+ if configFile == "" {
55+ configFile = "config.yml"
56+ }
57+
58+ // Check if the file exists
59+ absPath , err := filepath .Abs (configFile )
60+ if err != nil {
61+ log .Printf ("Couldn't convert to absolute path: '%s'\n " , configFile )
62+ return Config {}, err
63+ }
64+
65+ if _ , statErr := os .Stat (absPath ); os .IsNotExist (statErr ) {
66+ log .Printf ("Config file '%s' does not exist\n " , absPath )
67+ ext := filepath .Ext (absPath )
68+ absPath = strings .TrimSuffix (absPath , ext )
69+
70+ switch ext {
71+ case ".yaml" :
72+ absPath += ".yml"
73+ case ".yml" :
74+ absPath += ".yaml"
75+ default :
76+ log .Printf ("Config file '%s' does not have a valid extension\n " , configFile )
77+ return Config {}, statErr
78+ }
79+
80+ log .Printf ("Check if '%s' exists\n " , absPath )
81+
82+ if _ , secondStatErr := os .Stat (absPath ); os .IsNotExist (secondStatErr ) {
83+ log .Printf ("Config file '%s' does not exist\n " , absPath )
84+ return Config {}, secondStatErr
85+ }
86+ }
87+ log .Printf ("File '%s' exists\n " , absPath )
88+
89+ yamlFileContent , readErr := os .ReadFile (absPath )
5190 if readErr != nil {
5291 return Config {}, readErr
5392 }
0 commit comments