77 lines
2.5 KiB
Go
77 lines
2.5 KiB
Go
package consumers
|
|
|
|
import (
|
|
"errors"
|
|
"io/fs"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
|
|
configkit "go.maximumdirect.net/configkit"
|
|
)
|
|
|
|
func TestExternalSharedImports(t *testing.T) {
|
|
t.Parallel()
|
|
root := t.TempDir()
|
|
app, shared := filepath.Join(root, "app"), filepath.Join(root, "shared")
|
|
for _, directory := range []string{app, shared} {
|
|
if err := os.Mkdir(directory, 0700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
fixture := func(name string) string {
|
|
t.Helper()
|
|
data, err := bundledFiles.ReadFile("testdata/external-imports/" + name)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return string(data)
|
|
}
|
|
write := func(name, contents string) {
|
|
t.Helper()
|
|
if err := os.WriteFile(name, []byte(contents), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
sharedConfig := filepath.Join(shared, "config.yml")
|
|
main := filepath.Join(app, "main.yml")
|
|
write(main, strings.ReplaceAll(fixture("main.yml"), "/srv/shared/config.yml", strconv.Quote(sharedConfig)))
|
|
write(sharedConfig, fixture("config.yml"))
|
|
write(filepath.Join(shared, "extra.yml"), fixture("extra.yml"))
|
|
write(filepath.Join(shared, "message.txt"), "shared template")
|
|
type configuration struct {
|
|
Name string `yaml:"name"`
|
|
Template string `yaml:"template"`
|
|
Format string `yaml:"format"`
|
|
}
|
|
// One ordinary load handles both the absolute import and its relative import.
|
|
result, err := configkit.Load[configuration](configkit.File(main), configkit.Options[configuration]{Imports: true})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if result.Config.Name != "application" || result.Config.Format != "plain" {
|
|
t.Fatalf("configuration=%#v", result.Config)
|
|
}
|
|
info, ok := result.Metadata().Lookup(configkit.Keys("template"))
|
|
if !ok || len(info.Origin.Locations) != 1 {
|
|
t.Fatalf("template origin=%#v", info)
|
|
}
|
|
context, ok := result.SourceContext(info.Origin.Locations[0].SourceID)
|
|
if !ok {
|
|
t.Fatal("template source context unavailable")
|
|
}
|
|
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, result.Config.Template))
|
|
if err != nil || string(data) != "shared template" {
|
|
t.Fatalf("template=%q, %v", data, err)
|
|
}
|
|
// An application can deliberately retain containment at its main directory.
|
|
_, err = configkit.Load[configuration](configkit.File(main), configkit.Options[configuration]{Imports: true, Filesystem: &configkit.FilesystemContext{Root: app}})
|
|
var failure *configkit.LoadError
|
|
if !errors.As(err, &failure) || failure.Diagnostics()[0].Code != configkit.CodeImportOutsideRoot {
|
|
t.Fatalf("contained load=%v", err)
|
|
}
|
|
}
|