feat(cli): discover ThothII projects and installations

This commit is contained in:
2026-08-15 22:24:15 +02:00
parent 4fc03574e1
commit 66614fe8cf
6 changed files with 583 additions and 6 deletions
+144
View File
@@ -0,0 +1,144 @@
package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/aritmolab/thothii/tools/tht/internal/project"
)
// Resolve selects one installation descriptor without searching arbitrary descendants.
// Explicit paths and THOTHII_INSTALLATION are authoritative; automatic discovery considers
// only the current directory, its parents, and immediate deploy/* descriptors.
func Resolve(explicit string, environment func(string) string, workingDirectory string) (string, error) {
if explicit != "" {
return validateSelectedPath(explicit, "--installation")
}
if environment != nil {
if value := strings.TrimSpace(environment("THOTHII_INSTALLATION")); value != "" {
return validateSelectedPath(value, "THOTHII_INSTALLATION")
}
}
friendlyRoot, err := filepath.Abs(workingDirectory)
if err != nil {
return "", errors.New("installation discovery could not resolve the current directory")
}
info, err := os.Stat(friendlyRoot)
if err != nil || !info.IsDir() {
return "", errors.New("installation discovery could not read the current directory")
}
root, err := project.Discover(friendlyRoot)
if err != nil {
return "", fmt.Errorf("installation descriptor not found from %s; run tht setup or use --installation <absolute-path>/%s", filepath.Clean(friendlyRoot), installationFileName)
}
start, err := filepath.EvalSymlinks(friendlyRoot)
if err != nil {
return "", errors.New("installation discovery could not resolve the current directory")
}
candidates := make(map[string]string)
for directory := filepath.Clean(start); ; directory = filepath.Dir(directory) {
for _, path := range discoveryCandidates(directory) {
if hasArtifactsComponent(path) {
continue
}
info, statErr := os.Stat(path)
if statErr != nil || !info.Mode().IsRegular() {
continue
}
if _, loadErr := Load(path); loadErr != nil {
continue
}
canonical := canonicalPath(path)
candidates[canonical] = path
}
if directory == root.Path {
break
}
parent := filepath.Dir(directory)
if parent == directory {
break
}
}
paths := make([]string, 0, len(candidates))
for _, path := range candidates {
paths = append(paths, path)
}
sort.Strings(paths)
switch len(paths) {
case 1:
return paths[0], nil
case 0:
return "", fmt.Errorf("installation descriptor not found from %s; run tht setup or use --installation <absolute-path>/%s", filepath.Clean(friendlyRoot), installationFileName)
default:
return "", fmt.Errorf("multiple valid installation descriptors found: %s; use --installation <absolute-path>/%s", formatCandidates(paths, root.Path), installationFileName)
}
}
func formatCandidates(paths []string, root string) string {
formatted := make([]string, 0, len(paths))
for _, path := range paths {
id := filepath.Base(filepath.Dir(path))
relative, err := filepath.Rel(filepath.Join(root, "deploy"), path)
if err == nil {
parts := strings.Split(filepath.Clean(relative), string(filepath.Separator))
if len(parts) == 2 && parts[1] == installationFileName {
id = parts[0]
}
}
formatted = append(formatted, fmt.Sprintf("%s: %s", id, path))
}
return strings.Join(formatted, ", ")
}
func validateSelectedPath(path, source string) (string, error) {
if !filepath.IsAbs(path) {
return "", fmt.Errorf("%s must be an absolute path", source)
}
path = filepath.Clean(path)
if filepath.Base(path) != installationFileName {
return "", fmt.Errorf("%s must name %s", source, installationFileName)
}
if _, err := Load(path); err != nil {
return "", fmt.Errorf("%s is unavailable: %w", source, err)
}
return path, nil
}
func discoveryCandidates(directory string) []string {
candidates := []string{filepath.Join(directory, installationFileName)}
deploy := filepath.Join(directory, "deploy")
entries, err := os.ReadDir(deploy)
if err != nil {
return candidates
}
for _, entry := range entries {
if entry.IsDir() {
candidates = append(candidates, filepath.Join(deploy, entry.Name(), installationFileName))
}
}
sort.Strings(candidates)
return candidates
}
func canonicalPath(path string) string {
if resolved, err := filepath.EvalSymlinks(path); err == nil {
return filepath.Clean(resolved)
}
return filepath.Clean(path)
}
func hasArtifactsComponent(path string) bool {
for _, component := range strings.Split(filepath.Clean(path), string(filepath.Separator)) {
if component == ".artifacts" {
return true
}
}
return false
}
+150
View File
@@ -0,0 +1,150 @@
package config
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestResolveExplicitPathWinsOverEnvironmentAndDiscovery(t *testing.T) {
root := t.TempDir()
writeDiscoverableProject(t, root)
first := writeDiscoverableInstallation(t, root, filepath.Join(root, "first"))
second := writeDiscoverableInstallation(t, root, filepath.Join(root, "second"))
got, err := Resolve(first, func(string) string { return second }, root)
if err != nil {
t.Fatal(err)
}
if got != first {
t.Fatalf("Resolve() = %q, want explicit %q", got, first)
}
}
func TestResolveUsesEnvironmentBeforeAutomaticDiscovery(t *testing.T) {
root := t.TempDir()
writeDiscoverableProject(t, root)
writeDiscoverableInstallation(t, root, filepath.Join(root, "deploy", "one"))
environmentPath := writeDiscoverableInstallation(t, root, filepath.Join(root, "deploy", "two"))
got, err := Resolve("", func(name string) string {
if name == "THOTHII_INSTALLATION" {
return environmentPath
}
return ""
}, root)
if err != nil {
t.Fatal(err)
}
if got != environmentPath {
t.Fatalf("Resolve() = %q, want environment %q", got, environmentPath)
}
}
func TestResolveFindsDeployDescriptorFromNestedDirectory(t *testing.T) {
root := t.TempDir()
writeDiscoverableProject(t, root)
want := writeDiscoverableInstallation(t, root, filepath.Join(root, "deploy", "psd"))
nested := filepath.Join(root, "tools", "nested")
if err := os.MkdirAll(nested, 0o755); err != nil {
t.Fatal(err)
}
got, err := Resolve("", func(string) string { return "" }, nested)
if err != nil {
t.Fatal(err)
}
canonicalWant, err := filepath.EvalSymlinks(want)
if err != nil {
t.Fatal(err)
}
if got != canonicalWant {
t.Fatalf("Resolve() = %q, want canonical %q", got, canonicalWant)
}
}
func TestResolveIgnoresArtifactsAndRejectsAmbiguousValidCandidates(t *testing.T) {
root := t.TempDir()
writeDiscoverableProject(t, root)
artifacts := writeDiscoverableInstallation(t, root, filepath.Join(root, ".artifacts", "run"))
_ = artifacts
first := writeDiscoverableInstallation(t, root, filepath.Join(root, "deploy", "one"))
second := writeDiscoverableInstallation(t, root, filepath.Join(root, "deploy", "two"))
_, err := Resolve("", func(string) string { return "" }, root)
if err == nil || !strings.Contains(err.Error(), "multiple") || !strings.Contains(err.Error(), "one") || !strings.Contains(err.Error(), "two") || !strings.Contains(err.Error(), first) || !strings.Contains(err.Error(), second) {
t.Fatalf("Resolve() error = %v, want ambiguity naming valid candidates", err)
}
}
func TestResolveDoesNotSelectAnArtifactsDescriptor(t *testing.T) {
root := t.TempDir()
writeDiscoverableProject(t, root)
writeDiscoverableInstallation(t, root, filepath.Join(root, ".artifacts", "run"))
_, err := Resolve("", func(string) string { return "" }, root)
if err == nil || !strings.Contains(err.Error(), "descriptor not found") {
t.Fatalf("Resolve() error = %v, want artifacts candidate excluded", err)
}
}
func TestResolveReportsNoCandidateWithOverrideGuidance(t *testing.T) {
root := t.TempDir()
writeDiscoverableProject(t, root)
_, err := Resolve("", func(string) string { return "" }, root)
if err == nil || !strings.Contains(err.Error(), "tht setup") || !strings.Contains(err.Error(), "--installation") {
t.Fatalf("Resolve() error = %v, want setup and override guidance", err)
}
}
func TestResolveDoesNotSearchAboveTheDiscoveredProjectRoot(t *testing.T) {
container := t.TempDir()
root := filepath.Join(container, "thothii")
writeDiscoverableProject(t, root)
outside := writeDiscoverableInstallation(t, root, container)
_, err := Resolve("", func(string) string { return "" }, filepath.Join(root, "frontend"))
if err == nil || !strings.Contains(err.Error(), "tht setup") || strings.Contains(err.Error(), outside) {
t.Fatalf("Resolve() error = %v, want project-bounded setup guidance", err)
}
}
func writeDiscoverableProject(t *testing.T, root string) {
t.Helper()
for _, path := range []string{"backend", "frontend", "harness", "tools", "deploy"} {
if err := os.MkdirAll(filepath.Join(root, path), 0o755); err != nil {
t.Fatal(err)
}
}
if err := os.MkdirAll(filepath.Join(root, ".git"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "compose.yaml"), []byte("services: {}\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "deploy", "compose.local.yaml"), []byte("services: {}\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "operator.env"), nil, 0o600); err != nil {
t.Fatal(err)
}
}
func writeDiscoverableInstallation(t *testing.T, projectRoot, directory string) string {
t.Helper()
if err := os.MkdirAll(directory, 0o755); err != nil {
t.Fatal(err)
}
envFile := filepath.Join(directory, "operator.env")
if err := os.WriteFile(envFile, nil, 0o600); err != nil {
t.Fatal(err)
}
installationPath := filepath.Join(directory, "thothii-installation.yaml")
contents := "profile: local\nprojectDirectory: " + projectRoot + "\nenvFile: " + envFile + "\n"
if err := os.WriteFile(installationPath, []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
return installationPath
}