package configuration import ( "encoding/json" "io" "os" "regexp" ) type UserConfig struct { Types *[]string `json:"types"` Contexts *[]string `json:"contexts"` Excludes *[]string `json:"excludes"` MaxLengthLine *int `json:"maxLengthLine"` } type Config struct { Types []string Contexts []string Excludes []*regexp.Regexp MaxLengthLine int } func CreateConfig(pPath *string) (*Config, error) { config := Config{ Types: []string{"fix", "feat"}, Contexts: []string{}, Excludes: []*regexp.Regexp{}, MaxLengthLine: 72, } if pPath != nil && isFileExists(*pPath) { userConfig, err := readUserConfig(*pPath) if err != nil { return nil, err } mergeConfigs(&config, userConfig) } return &config, nil } func isFileExists(path string) bool { info, err := os.Stat(path) if os.IsNotExist(err) { return false } return !info.IsDir() } func readUserConfig(path string) (*UserConfig, error) { file, err := os.Open(path) if err != nil { return nil, err } defer func(fileJson *os.File) { err := fileJson.Close() if err != nil { panic(err) } }(file) bytes, err := io.ReadAll(file) if err != nil { return nil, err } var userConfig UserConfig err = json.Unmarshal(bytes, &userConfig) if err != nil { return nil, err } return &userConfig, nil } func mergeConfigs(config *Config, userConfig *UserConfig) { if userConfig.Types != nil { for _, item := range *(*userConfig).Types { config.Types = append(config.Types, item) } } if userConfig.Contexts != nil { for _, item := range *(userConfig.Contexts) { config.Contexts = append(config.Contexts, item) } } if userConfig.Excludes != nil { for _, item := range *(userConfig.Excludes) { pattern, err := regexp.Compile("(?i)" + item) if err != nil { panic(err) } config.Excludes = append(config.Excludes, pattern) } } if userConfig.MaxLengthLine != nil { config.MaxLengthLine = *(userConfig.MaxLengthLine) } }