GitRepositoryManager/config/config_file_parse.go

70 lines
1.7 KiB
Go

package config
import (
"errors"
"fmt"
"os"
"strings"
"gopkg.in/yaml.v3"
)
func GetRepositoryConfig(data []byte, fileExtension string) (Configuration, error) {
var config Configuration
var err error
data = []byte(os.ExpandEnv(string(data)))
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
}