GitRepositoryManager/internal/config/config_file_parse.go
Mikołaj Pęczkowski 68636d5e64 Improve code readability #1
+ Improved tests readability of common_utils_test.go
+ Fixed minor typos
2024-06-16 15:27:55 +02:00

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 == "" {
splitGit := strings.Split(repo.Src, "/")
nameWithExtension := splitGit[len(splitGit)-1]
name := strings.Split(nameWithExtension, ".")[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
}