Files
katenary/compose/parser.go

92 lines
1.8 KiB
Go
Raw Permalink Normal View History

2021-11-30 12:04:28 +01:00
package compose
import (
"io/ioutil"
2021-11-30 12:04:28 +01:00
"log"
"os"
"path/filepath"
2021-11-30 12:04:28 +01:00
"github.com/compose-spec/compose-go/cli"
"github.com/compose-spec/compose-go/types"
2021-11-30 12:04:28 +01:00
)
const (
ICON_EXCLAMATION = "❕"
)
2021-11-30 15:45:36 +01:00
// Parser is a docker-compose parser.
2021-11-30 12:04:28 +01:00
type Parser struct {
Data *types.Project
temporary *string
2021-11-30 12:04:28 +01:00
}
var (
Appname = ""
CURRENT_DIR, _ = os.Getwd()
)
2021-11-30 12:04:28 +01:00
// NewParser create a Parser and parse the file given in filename. If filename is empty, we try to parse the content[0] argument that should be a valid YAML content.
func NewParser(filename string, content ...string) *Parser {
2021-11-30 12:04:28 +01:00
p := &Parser{}
if len(content) > 0 { // mainly for the tests...
dir := filepath.Dir(filename)
err := os.MkdirAll(dir, 0755)
if err != nil {
log.Fatal(err)
}
p.temporary = &dir
ioutil.WriteFile(filename, []byte(content[0]), 0644)
cli.DefaultFileNames = []string{filename}
}
// if filename is not in cli Default files, add it
if len(filename) > 0 {
found := false
for _, f := range cli.DefaultFileNames {
if f == filename {
found = true
break
}
}
// add the file at first position
if !found {
cli.DefaultFileNames = append([]string{filename}, cli.DefaultFileNames...)
}
}
2021-11-30 12:04:28 +01:00
return p
}
// Parse using compose-go parser, adapt a bit the Project and set Appname.
func (p *Parser) Parse(appname string) {
// Reminder:
// - set Appname
// - loas services
options, err := cli.NewProjectOptions(nil,
cli.WithDefaultConfigPath,
cli.WithNormalization(true),
cli.WithInterpolation(true),
cli.WithResolvedPaths(true),
)
if err != nil {
log.Fatal(err)
}
proj, err := cli.ProjectFromOptions(options)
if err != nil {
log.Fatal("Failed to create project", err)
}
Appname = proj.Name
p.Data = proj
CURRENT_DIR = p.Data.WorkingDir
}
func GetCurrentDir() string {
return CURRENT_DIR
}