2024-11-10 16:08:16 +00:00
|
|
|
// Definition fetcher
|
|
|
|
//
|
|
|
|
// Handles fetching and building ServiceDefinition structs from different
|
|
|
|
// data sources.
|
|
|
|
|
2024-11-10 15:37:46 +00:00
|
|
|
package service_definition
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/goccy/go-yaml"
|
|
|
|
"os"
|
2024-11-10 16:08:16 +00:00
|
|
|
git "spud/git"
|
2024-11-10 15:52:06 +00:00
|
|
|
"strings"
|
2024-11-10 15:37:46 +00:00
|
|
|
)
|
|
|
|
|
2024-11-10 16:08:16 +00:00
|
|
|
type DefinitionFetcher struct {
|
|
|
|
Git git.GitClient
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewDefinitionFetcher() DefinitionFetcher {
|
|
|
|
return DefinitionFetcher{
|
|
|
|
Git: git.Git{},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Gets a ServiceDefinition from the given location.
|
|
|
|
//
|
|
|
|
// Depending on location prefix, different sources are used:
|
|
|
|
// git+: Clones the target git repository and extracts a service definition from it.
|
|
|
|
// <no-prefix>: Uses the location as a filepath to the service definition.
|
|
|
|
func (f DefinitionFetcher) GetDefinition(path string) (ServiceDefinition, error) {
|
|
|
|
if strings.HasPrefix(path, "git+") {
|
|
|
|
return f.getDefinitionFromGit(path)
|
|
|
|
}
|
|
|
|
|
|
|
|
return f.getDefinitionFromFile(path)
|
|
|
|
}
|
|
|
|
|
2024-11-10 15:52:06 +00:00
|
|
|
// Clones the target git repository and uses it as a basis to extract
|
|
|
|
// a service definition.
|
2024-11-10 16:08:16 +00:00
|
|
|
func (f DefinitionFetcher) getDefinitionFromGit(path string) (ServiceDefinition, error) {
|
2024-11-10 15:52:06 +00:00
|
|
|
dir, err := os.MkdirTemp("/tmp", "spud-service-")
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return ServiceDefinition{}, err
|
|
|
|
}
|
|
|
|
|
2024-11-10 16:08:16 +00:00
|
|
|
if _, err := f.Git.Clone(strings.TrimPrefix(path, "git+"), dir); err != nil {
|
2024-11-10 15:52:06 +00:00
|
|
|
return ServiceDefinition{}, err
|
|
|
|
}
|
|
|
|
|
2024-11-10 16:08:16 +00:00
|
|
|
return f.getDefinitionFromFile(dir + "/service.yml")
|
2024-11-10 15:52:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Extracts a service definition from the given filepath.
|
2024-11-10 16:08:16 +00:00
|
|
|
func (f DefinitionFetcher) getDefinitionFromFile(path string) (ServiceDefinition, error) {
|
2024-11-10 15:37:46 +00:00
|
|
|
var definition ServiceDefinition
|
|
|
|
|
|
|
|
defData, err := os.ReadFile(path)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return ServiceDefinition{}, &FileDoesNotExistError{Message: "Could not find service configuration file", ExpectedPath: path}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = yaml.Unmarshal(defData, &definition); err != nil {
|
|
|
|
return ServiceDefinition{}, &InvalidServiceDefinitionError{Path: path}
|
|
|
|
}
|
|
|
|
|
|
|
|
return definition, nil
|
|
|
|
}
|