2021-11-30 12:04:28 +01:00
package compose
import (
2022-04-05 08:05:33 +02:00
"io/ioutil"
2021-11-30 12:04:28 +01:00
"log"
"os"
2022-04-04 09:53:36 +02:00
"path/filepath"
2021-11-30 12:04:28 +01:00
2022-04-03 16:08:00 +02:00
"github.com/compose-spec/compose-go/cli"
"github.com/compose-spec/compose-go/types"
2021-11-30 12:04:28 +01:00
)
2021-12-05 09:05:48 +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 {
2022-04-04 09:53:36 +02:00
Data * types . Project
temporary * string
2021-11-30 12:04:28 +01:00
}
2022-04-05 08:05:33 +02:00
var (
Appname = ""
CURRENT_DIR , _ = os . Getwd ( )
)
2021-11-30 12:04:28 +01:00
2022-03-31 14:12:20 +02: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
2022-04-04 09:53:36 +02:00
p := & Parser { }
2022-04-05 08:05:33 +02:00
if len ( content ) > 0 { // mainly for the tests...
dir := filepath . Dir ( filename )
err := os . MkdirAll ( dir , 0755 )
2022-03-31 14:12:20 +02:00
if err != nil {
log . Fatal ( err )
}
2022-04-05 08:05:33 +02:00
p . temporary = & dir
ioutil . WriteFile ( filename , [ ] byte ( content [ 0 ] ) , 0644 )
2022-04-04 13:52:28 +02:00
cli . DefaultFileNames = [ ] string { filename }
2022-04-04 09:53:36 +02:00
}
// 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 ... )
2022-03-31 14:12:20 +02:00
}
}
2021-11-30 12:04:28 +01:00
2022-03-31 14:12:20 +02:00
return p
}
2022-04-04 09:53:36 +02:00
// Parse using compose-go parser, adapt a bit the Project and set Appname.
2022-03-31 14:12:20 +02:00
func ( p * Parser ) Parse ( appname string ) {
2022-04-03 16:08:00 +02:00
// Reminder:
// - set Appname
// - loas services
2021-12-03 11:49:32 +01:00
2022-04-03 16:08:00 +02:00
options , err := cli . NewProjectOptions ( nil ,
cli . WithDefaultConfigPath ,
cli . WithNormalization ( true ) ,
cli . WithInterpolation ( true ) ,
2022-05-08 09:11:31 +02:00
cli . WithResolvedPaths ( true ) ,
2022-04-03 16:08:00 +02:00
)
2022-05-08 09:11:31 +02:00
2022-04-03 16:08:00 +02:00
if err != nil {
log . Fatal ( err )
2022-04-01 09:22:00 +02:00
}
2022-04-03 16:08:00 +02:00
proj , err := cli . ProjectFromOptions ( options )
if err != nil {
2022-04-04 09:53:36 +02:00
log . Fatal ( "Failed to create project" , err )
2021-12-03 11:49:32 +01:00
}
2022-04-03 16:08:00 +02:00
Appname = proj . Name
p . Data = proj
2022-04-05 08:05:33 +02:00
CURRENT_DIR = p . Data . WorkingDir
}
func GetCurrentDir ( ) string {
return CURRENT_DIR
2022-04-01 16:58:13 +02:00
}