autogits/bots-common/config.go
2024-08-27 11:18:46 +02:00

57 lines
1.2 KiB
Go

package common
import (
"encoding/json"
"fmt"
"io"
"os"
"slices"
"strings"
)
type AutogitConfig struct {
Workflows []string
Organization string
GitProjectName string
}
func ReadWorkflowConfigs(reader io.Reader) ([]*AutogitConfig, error) {
data, err := io.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("Error reading config file. err: %w", err)
}
var config []*AutogitConfig
if err = json.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("Error parsing config file. err: %w", err)
}
availableWorkflows := []string{"pr", "push", "test"}
for _, workflow := range config {
for _, w := range workflow.Workflows {
if !slices.Contains(availableWorkflows, w) {
return nil, fmt.Errorf(
"Invalid Workflow '%s'. Only available workflows are: %s",
w, strings.Join(availableWorkflows, " "),
)
}
}
if len(workflow.GitProjectName) == 0 {
workflow.GitProjectName = DefaultGitPrj
}
}
return config, nil
}
func ReadWorkflowConfigsFile(filename string) ([]*AutogitConfig, error) {
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("Cannot open config file for reading. err: %w", err)
}
defer file.Close()
return ReadWorkflowConfigs(file)
}