GitRepositoryManager/internal/config/config_file_parse.go

70 lines
1.7 KiB
Go
Raw Normal View History

2021-11-02 18:19:31 +00:00
package config
import (
"errors"
"fmt"
2021-11-03 17:20:28 +00:00
"os"
2021-11-02 18:19:31 +00:00
"strings"
"gopkg.in/yaml.v3"
)
func GetRepositoryConfig(data []byte, fileExtension string) (Configuration, error) {
var config Configuration
var err error
2021-11-03 17:20:28 +00:00
data = []byte(os.ExpandEnv(string(data)))
2021-11-02 18:19:31 +00:00
switch fileExtension {
case "yaml":
err = yaml.Unmarshal(data, &config)
default:
return Configuration{}, errors.New(errNotSupportedType)
}
if err != nil {
return Configuration{}, err
}
if config.Workspace == "" {
return Configuration{}, errors.New(errMissingWorkspaceField)
}
// Get counters to check if name or dest values are not duplicated
nameFieldCounter := make(map[string][]int)
destFieldCounter := make(map[string][]int)
for index, repo := range config.Repositories {
if repo.Src == "" {
errorMessage := fmt.Sprintf(errMissingSrcField, index)
return Configuration{}, errors.New(errorMessage)
}
if repo.Name == "" {
splittedGit := strings.Split(repo.Src, "/")
nameWithExcention := splittedGit[len(splittedGit)-1]
name := strings.Split(nameWithExcention, ".")[0]
config.Repositories[index].Name = name
}
if repo.Dest == "" {
config.Repositories[index].Dest = config.Repositories[index].Name
}
nameFieldCounter[config.Repositories[index].Name] = append(nameFieldCounter[config.Repositories[index].Name], index)
destFieldCounter[config.Repositories[index].Dest] = append(destFieldCounter[config.Repositories[index].Dest], index)
}
for rowId, items := range nameFieldCounter {
if len(items) != 1 {
return Configuration{}, getDuplicateFieldError("name", rowId, items)
}
}
for rowId, items := range destFieldCounter {
if len(items) != 1 {
return Configuration{}, getDuplicateFieldError("dest", rowId, items)
}
}
return config, err
}