Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1c0b8a116 | ||
|
|
c8a219a84b | ||
|
|
4fb9bf9a5a | ||
|
|
2481a0dd27 |
No files matched your search
@@ -0,0 +1,36 @@
|
|||||||
|
# yetano.dev/yetano/core/solutions
|
||||||
|
|
||||||
|
The engine of the **Yetano Solutions Guide** (Yetano Knowledge &
|
||||||
|
Solutions): from what a user wants to achieve, through questions, rules
|
||||||
|
and existing knowledge, to native, checked configuration. Design and
|
||||||
|
requirements: `docs/knowledge-solutions/` in the meta-repo; the catalog
|
||||||
|
it reads: `assets/solutions/`.
|
||||||
|
|
||||||
|
```text
|
||||||
|
module yetano.dev/yetano/core/solutions tags: solutions/v0.1.0, ... go 1.25
|
||||||
|
```
|
||||||
|
|
||||||
|
A nested module of the core repository (like `core/gui`, `core/tui`):
|
||||||
|
standard library, `gopkg.in/yaml.v3` and `yetano.dev/yetano/core`
|
||||||
|
(`secretref`, `paths`). No cgo; builds for js/wasm.
|
||||||
|
|
||||||
|
| Package | What |
|
||||||
|
|---|---|
|
||||||
|
| `catalog` | manifest model, strict loader, Big Picture view, validation, condition language, JSON Schemas |
|
||||||
|
| `ref` | `yetano:<kind>/<path>[#section][@version]` references, heading slugs |
|
||||||
|
| `engine` | `Evaluate` (questions, rules, packages, capabilities, providers, modules, configuration with origins, graph, steps, checks), `Generate`/`Write` (lock, plan, handbook, hand-edit protection), presets |
|
||||||
|
| `knowledge` | index over catalog, Big Picture and manuals; `Resolve`, `Read`, `Search`, backlinks, `Lint`, coverage |
|
||||||
|
| `store` | instances, sessions, presets, favorites, recent as files |
|
||||||
|
| `cli` | `solution`, `task`, `knowledge`, `open` with yet's conventions (`cli.Run`) |
|
||||||
|
| `cmd/yetano-solutions` | the same commands standalone (catalog CI, development) |
|
||||||
|
|
||||||
|
The engine is pure: it never runs a command and never opens a network
|
||||||
|
connection (tested); only the CLI's `doctor` resolves DNS and probes
|
||||||
|
local ports.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go test ./...
|
||||||
|
go run ./cmd/yetano-solutions --catalog ../../assets/solutions solution setup mail-server
|
||||||
|
```
|
||||||
|
|
||||||
|
Tags carry the `solutions/` prefix; never move a tag.
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// BigPicture is the read-only view of assets/bigpicture/verse that the
|
||||||
|
// guide builds on (ADR-0002). Validation of these files belongs to bpgen;
|
||||||
|
// here they are decoded leniently and only the fields the guide uses are
|
||||||
|
// kept.
|
||||||
|
type BigPicture struct {
|
||||||
|
Dir string `json:"-"`
|
||||||
|
fsys fs.FS
|
||||||
|
Title string `json:"title"`
|
||||||
|
WebPath string `json:"webPath"` // "map/"
|
||||||
|
Topics map[string]*BPTopic `json:"topics"`
|
||||||
|
Stories map[string]*BPStory `json:"stories"`
|
||||||
|
Products map[string]*BPProduct `json:"products"`
|
||||||
|
Connections []BPConnection `json:"connections"`
|
||||||
|
Interfaces map[string]BPInterface `json:"interfaces"`
|
||||||
|
Files []FileHash `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BPTopic is a Big Picture topic.
|
||||||
|
type BPTopic struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
Summary string `yaml:"summary" json:"summary"`
|
||||||
|
EntryStory string `yaml:"entryStory" json:"entryStory,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BPStory is a Big Picture goal (user story).
|
||||||
|
type BPStory struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
Intent string `yaml:"intent" json:"intent"`
|
||||||
|
Outcome string `yaml:"outcome" json:"outcome"`
|
||||||
|
Explanation string `yaml:"explanation" json:"explanation,omitempty"`
|
||||||
|
PrimaryTopic string `yaml:"primaryTopic" json:"primaryTopic"`
|
||||||
|
RelatedTopics []string `yaml:"relatedTopics" json:"relatedTopics,omitempty"`
|
||||||
|
Roles []struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Product string `yaml:"product" json:"product"`
|
||||||
|
Contribution string `yaml:"contribution" json:"contribution"`
|
||||||
|
Participation string `yaml:"participation" json:"participation"`
|
||||||
|
} `yaml:"roles" json:"roles"`
|
||||||
|
Next []struct {
|
||||||
|
Story string `yaml:"story" json:"story"`
|
||||||
|
Reason string `yaml:"reason" json:"reason"`
|
||||||
|
} `yaml:"next" json:"next,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BPProduct is a Big Picture program.
|
||||||
|
type BPProduct struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Name string `yaml:"name" json:"name"`
|
||||||
|
Summary string `yaml:"summary" json:"summary"`
|
||||||
|
PrimaryTopic string `yaml:"primaryTopic" json:"primaryTopic"`
|
||||||
|
Tasks []string `yaml:"tasks" json:"tasks,omitempty"`
|
||||||
|
Links []struct {
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
Href string `yaml:"href" json:"href"`
|
||||||
|
} `yaml:"links" json:"links,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BPConnection is a technical relation between programs/interfaces.
|
||||||
|
type BPConnection struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
From string `yaml:"from" json:"from"`
|
||||||
|
To string `yaml:"to" json:"to"`
|
||||||
|
Type string `yaml:"type" json:"type"`
|
||||||
|
Label string `yaml:"label" json:"label"`
|
||||||
|
Scope string `yaml:"scope" json:"scope"`
|
||||||
|
Review string `yaml:"review" json:"review"`
|
||||||
|
Stories []string `yaml:"stories" json:"stories,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BPInterface is a shared interface (OCI registry, ...).
|
||||||
|
type BPInterface struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Name string `yaml:"name" json:"name"`
|
||||||
|
Summary string `yaml:"summary" json:"summary"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadBigPicture reads dir/manifest.yaml and the files it names.
|
||||||
|
func LoadBigPicture(dir string) (*BigPicture, error) {
|
||||||
|
return LoadBigPictureFS(os.DirFS(dir), dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadBigPictureFS reads manifest.yaml and the files it names from fsys
|
||||||
|
// (an embedded copy, e.g. in the browser); dir only names it in messages.
|
||||||
|
func LoadBigPictureFS(fsys fs.FS, dir string) (*BigPicture, error) {
|
||||||
|
bp := &BigPicture{
|
||||||
|
Dir: dir, fsys: fsys, WebPath: "map/",
|
||||||
|
Topics: map[string]*BPTopic{}, Stories: map[string]*BPStory{},
|
||||||
|
Products: map[string]*BPProduct{}, Interfaces: map[string]BPInterface{},
|
||||||
|
}
|
||||||
|
var manifest struct {
|
||||||
|
Title string `yaml:"title"`
|
||||||
|
Content struct {
|
||||||
|
Topics string `yaml:"topics"`
|
||||||
|
Products string `yaml:"products"`
|
||||||
|
Stories string `yaml:"stories"`
|
||||||
|
Connections string `yaml:"connections"`
|
||||||
|
} `yaml:"content"`
|
||||||
|
}
|
||||||
|
if err := bp.read("manifest.yaml", &manifest); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bp.Title = manifest.Title
|
||||||
|
var topics struct {
|
||||||
|
Topics []*BPTopic `yaml:"topics"`
|
||||||
|
}
|
||||||
|
if err := bp.read(manifest.Content.Topics, &topics); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, t := range topics.Topics {
|
||||||
|
bp.Topics[t.ID] = t
|
||||||
|
}
|
||||||
|
if err := bp.readDir(manifest.Content.Products, func(name string) error {
|
||||||
|
var p BPProduct
|
||||||
|
if err := bp.read(name, &p); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
bp.Products[p.ID] = &p
|
||||||
|
return nil
|
||||||
|
}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := bp.readDir(manifest.Content.Stories, func(name string) error {
|
||||||
|
var s BPStory
|
||||||
|
if err := bp.read(name, &s); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
bp.Stories[s.ID] = &s
|
||||||
|
return nil
|
||||||
|
}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var conns struct {
|
||||||
|
Interfaces []BPInterface `yaml:"interfaces"`
|
||||||
|
Connections []BPConnection `yaml:"connections"`
|
||||||
|
}
|
||||||
|
if manifest.Content.Connections != "" {
|
||||||
|
if err := bp.read(manifest.Content.Connections, &conns); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, i := range conns.Interfaces {
|
||||||
|
bp.Interfaces[i.ID] = i
|
||||||
|
}
|
||||||
|
bp.Connections = conns.Connections
|
||||||
|
sort.Slice(bp.Files, func(i, j int) bool { return bp.Files[i].Path < bp.Files[j].Path })
|
||||||
|
return bp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *BigPicture) read(name string, v any) error {
|
||||||
|
if name == "" {
|
||||||
|
return fmt.Errorf("big picture: manifest names no file")
|
||||||
|
}
|
||||||
|
b, err := fs.ReadFile(bp.fsys, path.Clean(filepath.ToSlash(name)))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("big picture: %w", err)
|
||||||
|
}
|
||||||
|
if len(b) > MaxFileSize {
|
||||||
|
return fmt.Errorf("big picture: %s too large", name)
|
||||||
|
}
|
||||||
|
bp.Files = append(bp.Files, FileHash{Path: "bigpicture:" + filepath.ToSlash(name), Hash: sha(b)})
|
||||||
|
if err := yaml.Unmarshal(b, v); err != nil {
|
||||||
|
return fmt.Errorf("big picture: %s: %w", name, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *BigPicture) readDir(sub string, fn func(string) error) error {
|
||||||
|
ents, err := fs.ReadDir(bp.fsys, path.Clean(filepath.ToSlash(sub)))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("big picture: %w", err)
|
||||||
|
}
|
||||||
|
for _, e := range ents {
|
||||||
|
if e.IsDir() || !strings.HasSuffix(e.Name(), ".yaml") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := fn(filepath.Join(sub, e.Name())); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Has reports whether a Big Picture element ID exists.
|
||||||
|
func (bp *BigPicture) Has(id string) bool {
|
||||||
|
if bp == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if _, ok := bp.Topics[id]; ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if _, ok := bp.Stories[id]; ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if _, ok := bp.Products[id]; ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
_, ok := bp.Interfaces[id]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fragment is the map URL fragment for an element (story.x -> story=x).
|
||||||
|
func (bp *BigPicture) Fragment(id string) string {
|
||||||
|
kind, slug, ok := strings.Cut(id, ".")
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
switch kind {
|
||||||
|
case "topic", "story", "product", "interface":
|
||||||
|
return kind + "=" + slug
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestCond(t *testing.T) {
|
||||||
|
env := Env{Answers: map[string]any{"a": "x", "n": 3, "l": []any{"p", "q"}, "b": true, "e": ""}, Mode: LevelGuided}
|
||||||
|
cases := []struct {
|
||||||
|
c Cond
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{Cond{}, true},
|
||||||
|
{Cond{"a": "x"}, true},
|
||||||
|
{Cond{"a": "y"}, false},
|
||||||
|
{Cond{"a": []any{"y", "x"}}, true},
|
||||||
|
{Cond{"l": "q"}, true},
|
||||||
|
{Cond{"l": "z"}, false},
|
||||||
|
{Cond{"a": map[string]any{"not": "x"}}, false},
|
||||||
|
{Cond{"n": map[string]any{"gte": 3, "lt": 4}}, true},
|
||||||
|
{Cond{"l": map[string]any{"count_gte": 2}}, true},
|
||||||
|
{Cond{"e": map[string]any{"set": false}}, true},
|
||||||
|
{Cond{"missing": map[string]any{"set": true}}, false},
|
||||||
|
{Cond{"b": true}, true},
|
||||||
|
{Cond{"b": "true"}, true},
|
||||||
|
{Cond{"any": []any{map[string]any{"a": "y"}, map[string]any{"n": 3}}}, true},
|
||||||
|
{Cond{"all": []any{map[string]any{"a": "x"}, map[string]any{"n": 4}}}, false},
|
||||||
|
{Cond{"not": map[string]any{"a": "x"}}, false},
|
||||||
|
{Cond{"$mode": "guided"}, true},
|
||||||
|
}
|
||||||
|
for i, c := range cases {
|
||||||
|
got, err := c.c.Eval(env)
|
||||||
|
if err != nil || got != c.want {
|
||||||
|
t.Errorf("%d %v: got %v %v", i, c.c, got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := (Cond{"a": map[string]any{"regex": "x"}}).Eval(env); err == nil {
|
||||||
|
t.Error("unknown operator accepted")
|
||||||
|
}
|
||||||
|
deep := Cond{"a": "x"}
|
||||||
|
for i := 0; i < MaxCondDepth+2; i++ {
|
||||||
|
deep = Cond{"not": map[string]any(deep)}
|
||||||
|
}
|
||||||
|
if _, err := deep.Eval(env); err == nil {
|
||||||
|
t.Error("unbounded nesting accepted")
|
||||||
|
}
|
||||||
|
if r := (Cond{"any": []any{map[string]any{"x": 1}}, "y": 2, "$mode": "q"}).Refs(); len(r) != 2 || r[0] != "x" || r[1] != "y" {
|
||||||
|
t.Errorf("refs %v", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSafeRelPath(t *testing.T) {
|
||||||
|
for _, ok := range []string{"a/b.yaml", "yamase/yamase.yaml"} {
|
||||||
|
if !SafeRelPath(ok) {
|
||||||
|
t.Errorf("%s rejected", ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"", "/etc/passwd", "../x", "a/../../x", "a/./b", "a//b", ".hidden/x", `a\b`, "c:/x"} {
|
||||||
|
if SafeRelPath(bad) {
|
||||||
|
t.Errorf("%q accepted", bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,323 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cond is a condition over wizard answers (ADR-0003). It is plain data:
|
||||||
|
//
|
||||||
|
// {q: v} answer equals v (a multiselect answer: contains v)
|
||||||
|
// {q: [a, b]} answer is one of a, b (multiselect: contains one)
|
||||||
|
// {q: {in: [..]}} same as a list
|
||||||
|
// {q: {not: v}} answer is not v (not one of a list)
|
||||||
|
// {q: {set: true|false}} answer is (not) given and non-empty
|
||||||
|
// {q: {gt|gte|lt|lte: n}} numeric comparison
|
||||||
|
// {q: {count_gte|count_lte: n}} number of list items
|
||||||
|
// {all: [c, ..]} {any: [c, ..]} {not: c}
|
||||||
|
// {$mode: guided} wizard mode; {$platform: linux}
|
||||||
|
//
|
||||||
|
// Several keys in one map must all hold. An empty condition is true.
|
||||||
|
type Cond map[string]any
|
||||||
|
|
||||||
|
// Env is what a condition is evaluated against.
|
||||||
|
type Env struct {
|
||||||
|
Answers map[string]any
|
||||||
|
Mode Level
|
||||||
|
Platform string
|
||||||
|
}
|
||||||
|
|
||||||
|
// MaxCondDepth bounds nesting (RULE-08).
|
||||||
|
const MaxCondDepth = 16
|
||||||
|
|
||||||
|
// Eval evaluates c. Errors are malformed conditions (the linter reports
|
||||||
|
// them before a catalog is used).
|
||||||
|
func (c Cond) Eval(env Env) (bool, error) { return evalMap(map[string]any(c), env, 0) }
|
||||||
|
|
||||||
|
// Holds is Eval for callers that validated the catalog: a malformed
|
||||||
|
// condition counts as false.
|
||||||
|
func (c Cond) Holds(env Env) bool {
|
||||||
|
ok, err := c.Eval(env)
|
||||||
|
return err == nil && ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func evalMap(m map[string]any, env Env, depth int) (bool, error) {
|
||||||
|
if depth > MaxCondDepth {
|
||||||
|
return false, fmt.Errorf("condition nested deeper than %d", MaxCondDepth)
|
||||||
|
}
|
||||||
|
keys := sortedKeys(m)
|
||||||
|
for _, k := range keys {
|
||||||
|
v := m[k]
|
||||||
|
var ok bool
|
||||||
|
var err error
|
||||||
|
switch k {
|
||||||
|
case "all", "any":
|
||||||
|
list, isList := v.([]any)
|
||||||
|
if !isList {
|
||||||
|
return false, fmt.Errorf("%s: want a list of conditions", k)
|
||||||
|
}
|
||||||
|
ok = k == "all"
|
||||||
|
for _, item := range list {
|
||||||
|
sub, isMap := asMap(item)
|
||||||
|
if !isMap {
|
||||||
|
return false, fmt.Errorf("%s: want a list of conditions", k)
|
||||||
|
}
|
||||||
|
r, err := evalMap(sub, env, depth+1)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if k == "all" && !r {
|
||||||
|
ok = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if k == "any" && r {
|
||||||
|
ok = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "not":
|
||||||
|
sub, isMap := asMap(v)
|
||||||
|
if !isMap {
|
||||||
|
return false, fmt.Errorf("not: want a condition")
|
||||||
|
}
|
||||||
|
r, err := evalMap(sub, env, depth+1)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
ok = !r
|
||||||
|
case "$mode":
|
||||||
|
ok, err = match(string(env.Mode), v)
|
||||||
|
case "$platform":
|
||||||
|
ok, err = match(env.Platform, v)
|
||||||
|
default:
|
||||||
|
ok, err = match(env.Answers[k], v)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("%s: %w", k, err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// match compares one answer with a condition value.
|
||||||
|
func match(answer any, want any) (bool, error) {
|
||||||
|
if ops, ok := asMap(want); ok {
|
||||||
|
for _, op := range sortedKeys(ops) {
|
||||||
|
arg := ops[op]
|
||||||
|
var r bool
|
||||||
|
switch op {
|
||||||
|
case "in":
|
||||||
|
r = matchAny(answer, arg)
|
||||||
|
case "not":
|
||||||
|
r = !matchAny(answer, arg)
|
||||||
|
case "set":
|
||||||
|
b, isBool := arg.(bool)
|
||||||
|
if !isBool {
|
||||||
|
return false, fmt.Errorf("set: want true or false")
|
||||||
|
}
|
||||||
|
r = IsSet(answer) == b
|
||||||
|
case "gt", "gte", "lt", "lte":
|
||||||
|
a, aok := toFloat(answer)
|
||||||
|
n, nok := toFloat(arg)
|
||||||
|
if !nok {
|
||||||
|
return false, fmt.Errorf("%s: want a number", op)
|
||||||
|
}
|
||||||
|
if !aok {
|
||||||
|
r = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
switch op {
|
||||||
|
case "gt":
|
||||||
|
r = a > n
|
||||||
|
case "gte":
|
||||||
|
r = a >= n
|
||||||
|
case "lt":
|
||||||
|
r = a < n
|
||||||
|
case "lte":
|
||||||
|
r = a <= n
|
||||||
|
}
|
||||||
|
case "count_gte", "count_lte":
|
||||||
|
n, nok := toFloat(arg)
|
||||||
|
if !nok {
|
||||||
|
return false, fmt.Errorf("%s: want a number", op)
|
||||||
|
}
|
||||||
|
cnt := float64(len(asList(answer)))
|
||||||
|
if op == "count_gte" {
|
||||||
|
r = cnt >= n
|
||||||
|
} else {
|
||||||
|
r = cnt <= n
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return false, fmt.Errorf("unknown operator %q", op)
|
||||||
|
}
|
||||||
|
if !r {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
return matchAny(answer, want), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// matchAny: want is a scalar or a list of scalars; answer a scalar or list.
|
||||||
|
func matchAny(answer any, want any) bool {
|
||||||
|
wants := asList(want)
|
||||||
|
if want != nil && len(wants) == 0 {
|
||||||
|
if _, isList := want.([]any); !isList {
|
||||||
|
wants = []any{want}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
answers := asList(answer)
|
||||||
|
if _, isList := answer.([]any); !isList {
|
||||||
|
if _, isStrList := answer.([]string); !isStrList {
|
||||||
|
answers = []any{answer}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, a := range answers {
|
||||||
|
for _, w := range wants {
|
||||||
|
if Equal(a, w) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Equal compares two scalar answer values loosely: numbers by value,
|
||||||
|
// everything else by its string form ("true" == true).
|
||||||
|
func Equal(a, b any) bool {
|
||||||
|
if a == nil || b == nil {
|
||||||
|
return a == nil && b == nil
|
||||||
|
}
|
||||||
|
if fa, ok := toFloat(a); ok {
|
||||||
|
if fb, ok := toFloat(b); ok {
|
||||||
|
return fa == fb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Scalar(a) == Scalar(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scalar renders a scalar answer as text.
|
||||||
|
func Scalar(v any) string {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case nil:
|
||||||
|
return ""
|
||||||
|
case string:
|
||||||
|
return x
|
||||||
|
case bool:
|
||||||
|
return strconv.FormatBool(x)
|
||||||
|
case int:
|
||||||
|
return strconv.Itoa(x)
|
||||||
|
case int64:
|
||||||
|
return strconv.FormatInt(x, 10)
|
||||||
|
case float64:
|
||||||
|
return strconv.FormatFloat(x, 'f', -1, 64)
|
||||||
|
}
|
||||||
|
return fmt.Sprint(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsSet reports whether an answer is present and not empty.
|
||||||
|
func IsSet(v any) bool {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case nil:
|
||||||
|
return false
|
||||||
|
case string:
|
||||||
|
return strings.TrimSpace(x) != ""
|
||||||
|
case []any:
|
||||||
|
return len(x) > 0
|
||||||
|
case []string:
|
||||||
|
return len(x) > 0
|
||||||
|
case map[string]any:
|
||||||
|
return len(x) > 0
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func toFloat(v any) (float64, bool) {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case int:
|
||||||
|
return float64(x), true
|
||||||
|
case int64:
|
||||||
|
return float64(x), true
|
||||||
|
case float64:
|
||||||
|
return x, true
|
||||||
|
case uint64:
|
||||||
|
return float64(x), true
|
||||||
|
}
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func asList(v any) []any {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case []any:
|
||||||
|
return x
|
||||||
|
case []string:
|
||||||
|
out := make([]any, len(x))
|
||||||
|
for i, s := range x {
|
||||||
|
out[i] = s
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func asMap(v any) (map[string]any, bool) {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case map[string]any:
|
||||||
|
return x, true
|
||||||
|
case Cond:
|
||||||
|
return map[string]any(x), true
|
||||||
|
}
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func sortedKeys(m map[string]any) []string {
|
||||||
|
keys := make([]string, 0, len(m))
|
||||||
|
for k := range m {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refs returns the question IDs a condition reads (for the linter).
|
||||||
|
func (c Cond) Refs() []string {
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var walk func(m map[string]any, depth int)
|
||||||
|
walk = func(m map[string]any, depth int) {
|
||||||
|
if depth > MaxCondDepth {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for k, v := range m {
|
||||||
|
switch k {
|
||||||
|
case "all", "any":
|
||||||
|
if list, ok := v.([]any); ok {
|
||||||
|
for _, item := range list {
|
||||||
|
if sub, ok := asMap(item); ok {
|
||||||
|
walk(sub, depth+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "not":
|
||||||
|
if sub, ok := asMap(v); ok {
|
||||||
|
walk(sub, depth+1)
|
||||||
|
}
|
||||||
|
case "$mode", "$platform":
|
||||||
|
default:
|
||||||
|
seen[k] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(map[string]any(c), 0)
|
||||||
|
out := make([]string, 0, len(seen))
|
||||||
|
for k := range seen {
|
||||||
|
out = append(out, k)
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,519 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Limits protect against hostile catalogs (SEC-03).
|
||||||
|
const (
|
||||||
|
MaxFileSize = 4 << 20
|
||||||
|
MaxFiles = 10000
|
||||||
|
MaxQuestions = 500
|
||||||
|
MaxRules = 1000
|
||||||
|
)
|
||||||
|
|
||||||
|
// Entity fields shared by all loaded manifests.
|
||||||
|
type Entity struct {
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Meta Meta `json:"metadata"`
|
||||||
|
File string `json:"file"` // relative to the catalog root (or "bigpicture:...")
|
||||||
|
Line int `json:"line"`
|
||||||
|
Hash string `json:"hash"` // sha256 of the document's source
|
||||||
|
}
|
||||||
|
|
||||||
|
// Package is a loaded Package manifest.
|
||||||
|
type Package struct {
|
||||||
|
Entity
|
||||||
|
Spec PackageSpec `json:"spec"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Module returns the module with that ID.
|
||||||
|
func (p *Package) Module(id string) *Module {
|
||||||
|
for i := range p.Spec.Modules {
|
||||||
|
if p.Spec.Modules[i].ID == id {
|
||||||
|
return &p.Spec.Modules[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Profile is a loaded Profile manifest.
|
||||||
|
type Profile struct {
|
||||||
|
Entity
|
||||||
|
Spec ProfileSpec `json:"spec"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Key is "<package>/<id>".
|
||||||
|
func (p *Profile) Key() string { return p.Meta.Package + "/" + p.Meta.ID }
|
||||||
|
|
||||||
|
// Solution is a loaded Solution or Task manifest.
|
||||||
|
type Solution struct {
|
||||||
|
Entity
|
||||||
|
Spec SolutionSpec `json:"spec"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsTask reports whether this is a Task.
|
||||||
|
func (s *Solution) IsTask() bool { return s.Kind == KindTask }
|
||||||
|
|
||||||
|
// Question returns the question with that ID and its index.
|
||||||
|
func (s *Solution) Question(id string) (*Question, int) {
|
||||||
|
for i := range s.Spec.Questions {
|
||||||
|
if s.Spec.Questions[i].ID == id {
|
||||||
|
return &s.Spec.Questions[i], i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, -1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Example is a loaded Example manifest.
|
||||||
|
type Example struct {
|
||||||
|
Entity
|
||||||
|
Spec ExampleSpec `json:"spec"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Key is "<solution>/<id>".
|
||||||
|
func (e *Example) Key() string { return e.Spec.Solution + "/" + e.Meta.ID }
|
||||||
|
|
||||||
|
// KnowledgeSource is a loaded KnowledgeSource manifest.
|
||||||
|
type KnowledgeSource struct {
|
||||||
|
Entity
|
||||||
|
Spec KnowledgeSourceSpec `json:"spec"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Catalog is everything loaded from one catalog root.
|
||||||
|
type Catalog struct {
|
||||||
|
Root string `json:"-"`
|
||||||
|
Meta Meta `json:"metadata"`
|
||||||
|
Spec CatalogSpec `json:"spec"`
|
||||||
|
Capabilities map[string]*Capability `json:"capabilities"`
|
||||||
|
Packages map[string]*Package `json:"packages"`
|
||||||
|
Profiles map[string]*Profile `json:"profiles"`
|
||||||
|
Solutions map[string]*Solution `json:"solutions"`
|
||||||
|
Tasks map[string]*Solution `json:"tasks"`
|
||||||
|
Examples map[string]*Example `json:"examples"`
|
||||||
|
Sources map[string]*KnowledgeSource `json:"sources"`
|
||||||
|
BigPicture *BigPicture `json:"bigpicture"`
|
||||||
|
// Files are all source files with their hashes, sorted (for locks).
|
||||||
|
Files []FileHash `json:"files"`
|
||||||
|
// Issues found while loading (fatal ones make Load fail).
|
||||||
|
Issues []Issue `json:"-"`
|
||||||
|
|
||||||
|
capFile map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileHash is one source file and its sha256.
|
||||||
|
type FileHash struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
Hash string `json:"sha256"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Issue is a problem in a catalog (load, validation or lint).
|
||||||
|
type Issue struct {
|
||||||
|
Severity string `json:"severity"` // error | warning
|
||||||
|
File string `json:"file,omitempty"`
|
||||||
|
Line int `json:"line,omitempty"`
|
||||||
|
ID string `json:"id,omitempty"`
|
||||||
|
Code string `json:"code"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i Issue) String() string {
|
||||||
|
loc := i.File
|
||||||
|
if i.Line > 0 {
|
||||||
|
loc = fmt.Sprintf("%s:%d", i.File, i.Line)
|
||||||
|
}
|
||||||
|
if loc != "" {
|
||||||
|
loc += ": "
|
||||||
|
}
|
||||||
|
id := ""
|
||||||
|
if i.ID != "" {
|
||||||
|
id = i.ID + ": "
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s%s%s (%s)", loc, id, i.Message, i.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrInvalid wraps load errors.
|
||||||
|
var ErrInvalid = errors.New("invalid catalog")
|
||||||
|
|
||||||
|
// Load reads a catalog root directory (the one with catalog.yaml).
|
||||||
|
func Load(root string) (*Catalog, error) {
|
||||||
|
return LoadFS(os.DirFS(root), root)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadFS reads a catalog from fsys (root is only used for messages and
|
||||||
|
// to find the Big Picture relative to it, when fsys is a directory).
|
||||||
|
func LoadFS(fsys fs.FS, root string) (*Catalog, error) {
|
||||||
|
return LoadFSWith(fsys, root, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadFSWith is LoadFS with the Big Picture read from bigPicture instead
|
||||||
|
// of the directory catalog.yaml names -- for a catalog without a disk
|
||||||
|
// (embedded in a program, or in the browser as WebAssembly). nil: as
|
||||||
|
// LoadFS.
|
||||||
|
func LoadFSWith(fsys fs.FS, root string, bigPicture fs.FS) (*Catalog, error) {
|
||||||
|
c := &Catalog{
|
||||||
|
Root: root,
|
||||||
|
Capabilities: map[string]*Capability{},
|
||||||
|
Packages: map[string]*Package{},
|
||||||
|
Profiles: map[string]*Profile{},
|
||||||
|
Solutions: map[string]*Solution{},
|
||||||
|
Tasks: map[string]*Solution{},
|
||||||
|
Examples: map[string]*Example{},
|
||||||
|
Sources: map[string]*KnowledgeSource{},
|
||||||
|
capFile: map[string]string{},
|
||||||
|
}
|
||||||
|
var files []string
|
||||||
|
err := fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
name := d.Name()
|
||||||
|
if d.IsDir() {
|
||||||
|
if p != "." && (strings.HasPrefix(name, ".") || name == "schema" || name == "testdata" || name == "golden") {
|
||||||
|
return fs.SkipDir
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(name, ".yaml") || strings.HasSuffix(name, ".yml") {
|
||||||
|
files = append(files, p)
|
||||||
|
if len(files) > MaxFiles {
|
||||||
|
return fmt.Errorf("more than %d files", MaxFiles)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%w: %v", ErrInvalid, err)
|
||||||
|
}
|
||||||
|
sort.Strings(files)
|
||||||
|
sawRoot := false
|
||||||
|
for _, f := range files {
|
||||||
|
b, err := readLimited(fsys, f)
|
||||||
|
if err != nil {
|
||||||
|
c.add("error", f, 0, "", "read", err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
c.Files = append(c.Files, FileHash{Path: f, Hash: sha(b)})
|
||||||
|
if c.loadFile(f, b) {
|
||||||
|
sawRoot = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !sawRoot {
|
||||||
|
c.add("error", "catalog.yaml", 0, "", "no-root", "no Catalog manifest (catalog.yaml) found")
|
||||||
|
}
|
||||||
|
if c.Spec.BigPicture != "" && bigPicture != nil {
|
||||||
|
bp, err := LoadBigPictureFS(bigPicture, c.Spec.BigPicture)
|
||||||
|
if err != nil {
|
||||||
|
c.add("error", "catalog.yaml", 0, "", "bigpicture", err.Error())
|
||||||
|
} else {
|
||||||
|
c.BigPicture = bp
|
||||||
|
c.Files = append(c.Files, bp.Files...)
|
||||||
|
}
|
||||||
|
} else if c.Spec.BigPicture != "" {
|
||||||
|
bpDir := c.Spec.BigPicture
|
||||||
|
if !filepath.IsAbs(bpDir) {
|
||||||
|
bpDir = filepath.Join(root, bpDir)
|
||||||
|
}
|
||||||
|
bp, err := LoadBigPicture(bpDir)
|
||||||
|
if err != nil {
|
||||||
|
c.add("error", "catalog.yaml", 0, "", "bigpicture", err.Error())
|
||||||
|
} else {
|
||||||
|
c.BigPicture = bp
|
||||||
|
c.Files = append(c.Files, bp.Files...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(c.Files, func(i, j int) bool { return c.Files[i].Path < c.Files[j].Path })
|
||||||
|
if errs := c.Errors(); len(errs) > 0 {
|
||||||
|
return c, fmt.Errorf("%w: %d error(s), first: %s", ErrInvalid, len(errs), errs[0])
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readLimited(fsys fs.FS, p string) ([]byte, error) {
|
||||||
|
f, err := fsys.Open(p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
b, err := io.ReadAll(io.LimitReader(f, MaxFileSize+1))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(b) > MaxFileSize {
|
||||||
|
return nil, fmt.Errorf("larger than %d bytes", MaxFileSize)
|
||||||
|
}
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func sha(b []byte) string {
|
||||||
|
h := sha256.Sum256(b)
|
||||||
|
return hex.EncodeToString(h[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Catalog) add(sev, file string, line int, id, code, msg string) {
|
||||||
|
c.Issues = append(c.Issues, Issue{Severity: sev, File: file, Line: line, ID: id, Code: code, Message: msg})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Errors returns the issues with severity error.
|
||||||
|
func (c *Catalog) Errors() []Issue {
|
||||||
|
var out []Issue
|
||||||
|
for _, i := range c.Issues {
|
||||||
|
if i.Severity == "error" {
|
||||||
|
out = append(out, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadFile decodes all documents of one file; reports whether it held the root.
|
||||||
|
func (c *Catalog) loadFile(file string, b []byte) bool {
|
||||||
|
dec := yaml.NewDecoder(bytes.NewReader(b))
|
||||||
|
root := false
|
||||||
|
for {
|
||||||
|
var doc yaml.Node
|
||||||
|
err := dec.Decode(&doc)
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
c.add("error", file, 0, "", "yaml", err.Error())
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
if len(doc.Content) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
raw, _ := yaml.Marshal(&doc)
|
||||||
|
var h Header
|
||||||
|
if err := strictDecode(raw, &h); err != nil {
|
||||||
|
c.add("error", file, doc.Line, "", "header", err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
line := doc.Content[0].Line
|
||||||
|
if h.APIVersion != APIVersion {
|
||||||
|
c.add("error", file, line, h.Metadata.ID, "api-version", fmt.Sprintf("apiVersion %q, want %q", h.APIVersion, APIVersion))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ent := Entity{Kind: h.Kind, Meta: h.Metadata, File: file, Line: line, Hash: sha(raw)}
|
||||||
|
specRaw, _ := yaml.Marshal(&h.Spec)
|
||||||
|
if h.Spec.Kind == 0 {
|
||||||
|
specRaw = []byte("{}")
|
||||||
|
}
|
||||||
|
if err := c.addEntity(ent, specRaw); err != nil {
|
||||||
|
c.add("error", file, line, h.Metadata.ID, "spec", err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if h.Kind == KindCatalog {
|
||||||
|
root = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
func strictDecode(b []byte, v any) error {
|
||||||
|
d := yaml.NewDecoder(bytes.NewReader(b))
|
||||||
|
d.KnownFields(true)
|
||||||
|
if err := d.Decode(v); err != nil && !errors.Is(err, io.EOF) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Catalog) addEntity(e Entity, spec []byte) error {
|
||||||
|
dup := func(kind, id, other string) error {
|
||||||
|
return fmt.Errorf("duplicate %s %q (also in %s)", kind, id, other)
|
||||||
|
}
|
||||||
|
switch e.Kind {
|
||||||
|
case KindCatalog:
|
||||||
|
if c.Meta.ID != "" {
|
||||||
|
return fmt.Errorf("more than one Catalog manifest")
|
||||||
|
}
|
||||||
|
if err := strictDecode(spec, &c.Spec); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.Meta = e.Meta
|
||||||
|
case KindCapabilities:
|
||||||
|
var s CapabilitiesSpec
|
||||||
|
if err := strictDecode(spec, &s); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for i := range s.Capabilities {
|
||||||
|
cp := s.Capabilities[i]
|
||||||
|
if other, ok := c.capFile[cp.ID]; ok {
|
||||||
|
return dup("capability", cp.ID, other)
|
||||||
|
}
|
||||||
|
c.Capabilities[cp.ID] = &cp
|
||||||
|
c.capFile[cp.ID] = e.File
|
||||||
|
}
|
||||||
|
case KindPackage:
|
||||||
|
p := &Package{Entity: e}
|
||||||
|
if err := strictDecode(spec, &p.Spec); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if o, ok := c.Packages[e.Meta.ID]; ok {
|
||||||
|
return dup("package", e.Meta.ID, o.File)
|
||||||
|
}
|
||||||
|
c.Packages[e.Meta.ID] = p
|
||||||
|
case KindProfile:
|
||||||
|
p := &Profile{Entity: e}
|
||||||
|
if err := strictDecode(spec, &p.Spec); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if e.Meta.Package == "" {
|
||||||
|
return fmt.Errorf("profile %q: metadata.package is required", e.Meta.ID)
|
||||||
|
}
|
||||||
|
if o, ok := c.Profiles[p.Key()]; ok {
|
||||||
|
return dup("profile", p.Key(), o.File)
|
||||||
|
}
|
||||||
|
c.Profiles[p.Key()] = p
|
||||||
|
case KindSolution, KindTask:
|
||||||
|
s := &Solution{Entity: e}
|
||||||
|
if err := strictDecode(spec, &s.Spec); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(s.Spec.Questions) > MaxQuestions || len(s.Spec.Rules) > MaxRules {
|
||||||
|
return fmt.Errorf("more than %d questions or %d rules", MaxQuestions, MaxRules)
|
||||||
|
}
|
||||||
|
m := c.Solutions
|
||||||
|
if e.Kind == KindTask {
|
||||||
|
m = c.Tasks
|
||||||
|
}
|
||||||
|
if o, ok := m[e.Meta.ID]; ok {
|
||||||
|
return dup(strings.ToLower(e.Kind), e.Meta.ID, o.File)
|
||||||
|
}
|
||||||
|
m[e.Meta.ID] = s
|
||||||
|
case KindExample:
|
||||||
|
x := &Example{Entity: e}
|
||||||
|
if err := strictDecode(spec, &x.Spec); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if x.Spec.Solution == "" {
|
||||||
|
// default: the solution directory the example lives in
|
||||||
|
x.Spec.Solution = solutionDirOf(e.File)
|
||||||
|
}
|
||||||
|
if o, ok := c.Examples[x.Key()]; ok {
|
||||||
|
return dup("example", x.Key(), o.File)
|
||||||
|
}
|
||||||
|
c.Examples[x.Key()] = x
|
||||||
|
case KindKnowledgeSource:
|
||||||
|
k := &KnowledgeSource{Entity: e}
|
||||||
|
if err := strictDecode(spec, &k.Spec); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if o, ok := c.Sources[e.Meta.ID]; ok {
|
||||||
|
return dup("knowledge source", e.Meta.ID, o.File)
|
||||||
|
}
|
||||||
|
c.Sources[e.Meta.ID] = k
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unknown kind %q", e.Kind)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// solutionDirOf: solutions/<category>/<id>/examples/x.yaml -> <id>.
|
||||||
|
func solutionDirOf(file string) string {
|
||||||
|
dir := path.Dir(path.Dir(file))
|
||||||
|
return path.Base(dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SortedIDs returns the keys of a map in order.
|
||||||
|
func SortedIDs[V any](m map[string]V) []string {
|
||||||
|
out := make([]string, 0, len(m))
|
||||||
|
for k := range m {
|
||||||
|
out = append(out, k)
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup finds a solution or task by ID (solutions first).
|
||||||
|
func (c *Catalog) Lookup(id string) *Solution {
|
||||||
|
if s, ok := c.Solutions[id]; ok {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
if s, ok := c.Tasks[id]; ok {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
for _, m := range []map[string]*Solution{c.Solutions, c.Tasks} {
|
||||||
|
for _, s := range m {
|
||||||
|
for _, a := range s.Meta.Aliases {
|
||||||
|
if a == id {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProvidersOf lists package modules providing a capability, best first.
|
||||||
|
func (c *Catalog) ProvidersOf(capID string) []ModuleRef {
|
||||||
|
var out []ModuleRef
|
||||||
|
for _, pid := range SortedIDs(c.Packages) {
|
||||||
|
p := c.Packages[pid]
|
||||||
|
for _, m := range p.Spec.Modules {
|
||||||
|
for _, pr := range m.Provides {
|
||||||
|
if pr == capID {
|
||||||
|
out = append(out, ModuleRef{Package: pid, Module: m.ID, Priority: m.Priority, Support: m.Support})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.SliceStable(out, func(i, j int) bool { return out[i].Priority > out[j].Priority })
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ModuleRef points at one module of one package.
|
||||||
|
type ModuleRef struct {
|
||||||
|
Package string `json:"package"`
|
||||||
|
Module string `json:"module"`
|
||||||
|
Priority int `json:"priority,omitempty"`
|
||||||
|
Support Support `json:"support,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m ModuleRef) String() string { return m.Package + "/" + m.Module }
|
||||||
|
|
||||||
|
// ProfileChain returns the profile and its ancestors, base first; it
|
||||||
|
// fails on unknown profiles and cycles (PROF-03).
|
||||||
|
func (c *Catalog) ProfileChain(pkg, id string) ([]*Profile, error) {
|
||||||
|
var chain []*Profile
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for cur := id; cur != ""; {
|
||||||
|
key := pkg + "/" + cur
|
||||||
|
if seen[key] {
|
||||||
|
return nil, fmt.Errorf("profile %s: inheritance cycle", key)
|
||||||
|
}
|
||||||
|
seen[key] = true
|
||||||
|
p, ok := c.Profiles[key]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("unknown profile %s", key)
|
||||||
|
}
|
||||||
|
chain = append(chain, p)
|
||||||
|
cur = p.Spec.Extends
|
||||||
|
}
|
||||||
|
for i, j := 0, len(chain)-1; i < j; i, j = i+1, j-1 {
|
||||||
|
chain[i], chain[j] = chain[j], chain[i]
|
||||||
|
}
|
||||||
|
return chain, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash is a digest over all catalog files (catalog version for locks).
|
||||||
|
func (c *Catalog) Hash() string {
|
||||||
|
h := sha256.New()
|
||||||
|
for _, f := range c.Files {
|
||||||
|
fmt.Fprintf(h, "%s %s\n", f.Path, f.Hash)
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(h.Sum(nil))
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A catalog without a disk (embedded, or in the browser) loads the Big
|
||||||
|
// Picture from its own fs.FS and gives the same catalog as from disk.
|
||||||
|
func TestLoadFSWith(t *testing.T) {
|
||||||
|
disk, err := Load("../engine/testdata/cat")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// "/nonexistent" as root: nothing may be read from disk
|
||||||
|
emb, err := LoadFSWith(os.DirFS("../engine/testdata/cat"), "/nonexistent", os.DirFS("../engine/testdata/bp"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if emb.BigPicture == nil || len(emb.BigPicture.Products) == 0 {
|
||||||
|
t.Fatal("no Big Picture")
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(SortedIDs(disk.BigPicture.Products), SortedIDs(emb.BigPicture.Products)) || disk.Hash() != emb.Hash() {
|
||||||
|
t.Fatalf("embedded catalog differs: %v / %v", disk.Hash(), emb.Hash())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,509 @@
|
|||||||
|
// Package catalog is the data model of Yetano Knowledge & Solutions: the
|
||||||
|
// manifests under assets/solutions (Capability, Package, Profile,
|
||||||
|
// Solution, Task, Example, KnowledgeSource) and the read-only view of the
|
||||||
|
// Big Picture sources (topics, goals, programs) they build on.
|
||||||
|
//
|
||||||
|
// Everything here is data. Nothing in a catalog is ever executed: there
|
||||||
|
// are no template functions, no commands run by the engine and no network
|
||||||
|
// access (see docs/knowledge-solutions/SECURITY.md in the meta-repo).
|
||||||
|
package catalog
|
||||||
|
|
||||||
|
import "gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
// APIVersion is the only manifest version this package reads.
|
||||||
|
const APIVersion = "yetano.dev/v1"
|
||||||
|
|
||||||
|
// Manifest kinds.
|
||||||
|
const (
|
||||||
|
KindCatalog = "Catalog"
|
||||||
|
KindCapabilities = "Capabilities"
|
||||||
|
KindPackage = "Package"
|
||||||
|
KindProfile = "Profile"
|
||||||
|
KindSolution = "Solution"
|
||||||
|
KindTask = "Task"
|
||||||
|
KindExample = "Example"
|
||||||
|
KindPreset = "Preset"
|
||||||
|
KindInstance = "SolutionInstance"
|
||||||
|
KindSession = "WizardSession"
|
||||||
|
KindKnowledgeSource = "KnowledgeSource"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Support says how far an option, module or solution is backed by the
|
||||||
|
// real programs (RULE-03). Only Supported, Experimental, Untested and
|
||||||
|
// Discouraged can be selected; the others are shown with their reason.
|
||||||
|
type Support string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Supported Support = "supported"
|
||||||
|
Experimental Support = "experimental"
|
||||||
|
Untested Support = "untested"
|
||||||
|
Discouraged Support = "discouraged"
|
||||||
|
NeedsPrereq Support = "needs-prerequisites"
|
||||||
|
NotImplemented Support = "not-implemented"
|
||||||
|
NotSupported Support = "not-supported"
|
||||||
|
Impossible Support = "impossible"
|
||||||
|
Insecure Support = "insecure"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Selectable reports whether an option with this support level may be chosen.
|
||||||
|
func (s Support) Selectable() bool {
|
||||||
|
switch s {
|
||||||
|
case "", Supported, Experimental, Untested, Discouraged, NeedsPrereq:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Valid reports whether s is a known support level ("" means supported).
|
||||||
|
func (s Support) Valid() bool {
|
||||||
|
switch s {
|
||||||
|
case "", Supported, Experimental, Untested, Discouraged, NeedsPrereq,
|
||||||
|
NotImplemented, NotSupported, Impossible, Insecure:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text is a translatable string set: the English base plus translations.
|
||||||
|
type Translations map[string]map[string]string // lang -> field -> text
|
||||||
|
|
||||||
|
// Meta is the common metadata block.
|
||||||
|
type Meta struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Name string `yaml:"name,omitempty" json:"name,omitempty"` // presets/instances
|
||||||
|
Package string `yaml:"package,omitempty" json:"package,omitempty"`
|
||||||
|
Version string `yaml:"version,omitempty" json:"version,omitempty"`
|
||||||
|
Title string `yaml:"title,omitempty" json:"title,omitempty"`
|
||||||
|
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"`
|
||||||
|
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||||
|
Category string `yaml:"category,omitempty" json:"category,omitempty"`
|
||||||
|
Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"`
|
||||||
|
Synonyms []string `yaml:"synonyms,omitempty" json:"synonyms,omitempty"`
|
||||||
|
Difficulty string `yaml:"difficulty,omitempty" json:"difficulty,omitempty"`
|
||||||
|
Status Support `yaml:"status,omitempty" json:"status,omitempty"`
|
||||||
|
Audience []string `yaml:"audience,omitempty" json:"audience,omitempty"`
|
||||||
|
Featured bool `yaml:"featured,omitempty" json:"featured,omitempty"`
|
||||||
|
Origin string `yaml:"origin,omitempty" json:"origin,omitempty"` // official | local | org | community | ai
|
||||||
|
Aliases []string `yaml:"aliases,omitempty" json:"aliases,omitempty"`
|
||||||
|
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Header is the envelope every manifest file has.
|
||||||
|
type Header struct {
|
||||||
|
APIVersion string `yaml:"apiVersion"`
|
||||||
|
Kind string `yaml:"kind"`
|
||||||
|
Metadata Meta `yaml:"metadata"`
|
||||||
|
Spec yaml.Node `yaml:"spec"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Catalog root -------------------------------------------------------
|
||||||
|
|
||||||
|
// CatalogSpec is catalog.yaml: where the other sources are.
|
||||||
|
type CatalogSpec struct {
|
||||||
|
// BigPicture is the directory with the Big Picture manifest.yaml,
|
||||||
|
// relative to catalog.yaml.
|
||||||
|
BigPicture string `yaml:"bigpicture"`
|
||||||
|
// SourcesRoot is where repositories named in knowledge sources are
|
||||||
|
// checked out, relative to catalog.yaml (optional; manuals are then
|
||||||
|
// only referenced, not indexed).
|
||||||
|
SourcesRoot string `yaml:"sourcesRoot,omitempty"`
|
||||||
|
// WebBase resolves web references (https://yetano.app/).
|
||||||
|
WebBase string `yaml:"webBase"`
|
||||||
|
// Categories maps Big Picture topics to guide categories (order = display order).
|
||||||
|
Categories []Category `yaml:"categories"`
|
||||||
|
// Locales the catalog is (partly) translated into; English is the base.
|
||||||
|
Locales []string `yaml:"locales,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Category is a guide category, normally one Big Picture topic.
|
||||||
|
type Category struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Topic string `yaml:"topic,omitempty" json:"topic,omitempty"`
|
||||||
|
Title string `yaml:"title,omitempty" json:"title,omitempty"`
|
||||||
|
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"`
|
||||||
|
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Capabilities ---------------------------------------------------------
|
||||||
|
|
||||||
|
// Capability is an abstract ability (mail.smtp.server); see CAPABILITIES.md.
|
||||||
|
type Capability struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||||
|
Requires []string `yaml:"requires,omitempty" json:"requires,omitempty"`
|
||||||
|
Conflicts []string `yaml:"conflicts,omitempty" json:"conflicts,omitempty"`
|
||||||
|
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||||
|
// Providers outside Yetano (an existing LDAP, PostgreSQL, ...).
|
||||||
|
External []ExternalProvider `yaml:"external,omitempty" json:"external,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExternalProvider is a provider that is not a Yetano package.
|
||||||
|
type ExternalProvider struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||||
|
Support Support `yaml:"support,omitempty" json:"support,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CapabilitiesSpec is a capabilities file.
|
||||||
|
type CapabilitiesSpec struct {
|
||||||
|
Capabilities []Capability `yaml:"capabilities"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Packages -------------------------------------------------------------
|
||||||
|
|
||||||
|
// PackageSpec describes a Yetano package for the guide. Its human summary
|
||||||
|
// comes from the Big Picture program (BigPicture), never copied here.
|
||||||
|
type PackageSpec struct {
|
||||||
|
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"` // product.<name>
|
||||||
|
Registry string `yaml:"registry,omitempty" json:"registry,omitempty"` // yetano.app/yetano/<pkg>
|
||||||
|
Microsite string `yaml:"microsite,omitempty" json:"microsite,omitempty"` // path below webBase
|
||||||
|
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
|
||||||
|
Modules []Module `yaml:"modules" json:"modules"`
|
||||||
|
// Sources back every claim about what the package can do (ANA-02).
|
||||||
|
Sources []string `yaml:"sources" json:"sources"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Module is one functional part of a package (a yamase-* program, ...).
|
||||||
|
type Module struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||||
|
Program string `yaml:"program,omitempty" json:"program,omitempty"` // binary name
|
||||||
|
Kind string `yaml:"kind,omitempty" json:"kind,omitempty"` // daemon | cli | plugin | library
|
||||||
|
Provides []string `yaml:"provides,omitempty" json:"provides,omitempty"`
|
||||||
|
Requires []string `yaml:"requires,omitempty" json:"requires,omitempty"` // capabilities
|
||||||
|
Support Support `yaml:"support,omitempty" json:"support,omitempty"`
|
||||||
|
// Priority orders providers of the same capability (higher first).
|
||||||
|
Priority int `yaml:"priority,omitempty" json:"priority,omitempty"`
|
||||||
|
// Manual is the knowledge source with this module's manual, if any.
|
||||||
|
Manual string `yaml:"manual,omitempty" json:"manual,omitempty"`
|
||||||
|
Doctor []string `yaml:"doctor,omitempty" json:"doctor,omitempty"` // commands that check it
|
||||||
|
Sources []string `yaml:"sources,omitempty" json:"sources,omitempty"`
|
||||||
|
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Profiles -------------------------------------------------------------
|
||||||
|
|
||||||
|
// ProfileSpec is a recommended way to run one package.
|
||||||
|
type ProfileSpec struct {
|
||||||
|
Extends string `yaml:"extends,omitempty" json:"extends,omitempty"`
|
||||||
|
Modules map[string]string `yaml:"modules,omitempty" json:"modules,omitempty"` // module -> enabled|disabled
|
||||||
|
Parameters []string `yaml:"parameters,omitempty" json:"parameters,omitempty"`
|
||||||
|
Config []Fragment `yaml:"config,omitempty" json:"config,omitempty"`
|
||||||
|
Recommendations []Recommendation `yaml:"recommendations,omitempty" json:"recommendations,omitempty"`
|
||||||
|
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
|
||||||
|
References []string `yaml:"references,omitempty" json:"references,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recommendation names something worth adding, with the reason.
|
||||||
|
type Recommendation struct {
|
||||||
|
Package string `yaml:"package,omitempty" json:"package,omitempty"`
|
||||||
|
Capability string `yaml:"capability,omitempty" json:"capability,omitempty"`
|
||||||
|
Reason string `yaml:"reason" json:"reason"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fragment is a typed YAML piece for one generated file (ADR-0005).
|
||||||
|
type Fragment struct {
|
||||||
|
ID string `yaml:"id,omitempty" json:"id,omitempty"`
|
||||||
|
File string `yaml:"file" json:"file"`
|
||||||
|
// Module: the fragment only applies while this module of the file's
|
||||||
|
// package is enabled (a disabled program gets no configuration).
|
||||||
|
Module string `yaml:"module,omitempty" json:"module,omitempty"`
|
||||||
|
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||||
|
Set yaml.Node `yaml:"set" json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Solutions and tasks ----------------------------------------------------
|
||||||
|
|
||||||
|
// SolutionSpec is a complete use case. Tasks use the same structure.
|
||||||
|
type SolutionSpec struct {
|
||||||
|
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
|
||||||
|
Kind string `yaml:"kind,omitempty" json:"kind,omitempty"` // tasks: read-only|generate|diagnostic|planning|mutating|deployment|maintenance
|
||||||
|
Goals []string `yaml:"goals,omitempty" json:"goals,omitempty"`
|
||||||
|
Scenarios []string `yaml:"scenarios,omitempty" json:"scenarios,omitempty"`
|
||||||
|
NotFor []string `yaml:"notFor,omitempty" json:"notFor,omitempty"`
|
||||||
|
AppliesTo *AppliesTo `yaml:"appliesTo,omitempty" json:"appliesTo,omitempty"`
|
||||||
|
Capabilities CapSets `yaml:"capabilities,omitempty" json:"capabilities"`
|
||||||
|
Packages []PackageUse `yaml:"packages,omitempty" json:"packages"`
|
||||||
|
Questions []Question `yaml:"questions,omitempty" json:"questions"`
|
||||||
|
Rules []Rule `yaml:"rules,omitempty" json:"rules,omitempty"`
|
||||||
|
Config []Fragment `yaml:"configuration,omitempty" json:"-"`
|
||||||
|
Steps []Step `yaml:"steps,omitempty" json:"steps,omitempty"`
|
||||||
|
Requirements []Check `yaml:"requirements,omitempty" json:"requirements,omitempty"`
|
||||||
|
Architecture Architecture `yaml:"architecture,omitempty" json:"architecture"`
|
||||||
|
References References `yaml:"references,omitempty" json:"references"`
|
||||||
|
Related []string `yaml:"related,omitempty" json:"related,omitempty"`
|
||||||
|
Operations []string `yaml:"operations,omitempty" json:"operations,omitempty"`
|
||||||
|
Lifecycle Lifecycle `yaml:"lifecycle,omitempty" json:"lifecycle"`
|
||||||
|
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
|
||||||
|
Sources []string `yaml:"sources,omitempty" json:"sources,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppliesTo limits a task to solutions/capabilities (applicableWhen).
|
||||||
|
type AppliesTo struct {
|
||||||
|
Solutions []string `yaml:"solutions,omitempty" json:"solutions,omitempty"`
|
||||||
|
Capabilities []string `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CapSets are the capabilities a solution needs.
|
||||||
|
type CapSets struct {
|
||||||
|
Required []string `yaml:"required,omitempty" json:"required,omitempty"`
|
||||||
|
Recommended []string `yaml:"recommended,omitempty" json:"recommended,omitempty"`
|
||||||
|
Optional []string `yaml:"optional,omitempty" json:"optional,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PackageUse puts a package into a solution, optionally under a condition.
|
||||||
|
type PackageUse struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Profile string `yaml:"profile,omitempty" json:"profile,omitempty"`
|
||||||
|
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||||
|
Role string `yaml:"role,omitempty" json:"role,omitempty"` // core | optional
|
||||||
|
Recommended bool `yaml:"recommended,omitempty" json:"recommended,omitempty"`
|
||||||
|
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Level orders the wizard modes.
|
||||||
|
type Level string
|
||||||
|
|
||||||
|
const (
|
||||||
|
LevelQuick Level = "quick"
|
||||||
|
LevelGuided Level = "guided"
|
||||||
|
LevelAdvanced Level = "advanced"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Rank is the order of the modes (quick < guided < advanced).
|
||||||
|
func (l Level) Rank() int {
|
||||||
|
switch l {
|
||||||
|
case LevelGuided:
|
||||||
|
return 1
|
||||||
|
case LevelAdvanced:
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Question is one wizard question.
|
||||||
|
type Question struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Type string `yaml:"type" json:"type"`
|
||||||
|
Item string `yaml:"item,omitempty" json:"item,omitempty"` // list element type
|
||||||
|
Group string `yaml:"group,omitempty" json:"group,omitempty"`
|
||||||
|
Level Level `yaml:"level,omitempty" json:"level,omitempty"`
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
Help string `yaml:"help,omitempty" json:"help,omitempty"`
|
||||||
|
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||||
|
Decide string `yaml:"decide,omitempty" json:"decide,omitempty"` // "Help me decide" text
|
||||||
|
Placeholder string `yaml:"placeholder,omitempty" json:"placeholder,omitempty"`
|
||||||
|
Examples []string `yaml:"examples,omitempty" json:"examples,omitempty"`
|
||||||
|
Default any `yaml:"default,omitempty" json:"default,omitempty"`
|
||||||
|
DefaultWhen []CondValue `yaml:"defaultWhen,omitempty" json:"defaultWhen,omitempty"`
|
||||||
|
Recommended any `yaml:"recommended,omitempty" json:"recommended,omitempty"`
|
||||||
|
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
|
||||||
|
Required bool `yaml:"required,omitempty" json:"required,omitempty"`
|
||||||
|
RequiredWhen Cond `yaml:"requiredWhen,omitempty" json:"requiredWhen,omitempty"`
|
||||||
|
VisibleWhen Cond `yaml:"visibleWhen,omitempty" json:"visibleWhen,omitempty"`
|
||||||
|
InstanceSpecific bool `yaml:"instanceSpecific,omitempty" json:"instanceSpecific,omitempty"`
|
||||||
|
Options []Option `yaml:"options,omitempty" json:"options,omitempty"`
|
||||||
|
Validation Validation `yaml:"validation,omitempty" json:"validation"`
|
||||||
|
ValidateWhen []CondCheck `yaml:"validateWhen,omitempty" json:"validateWhen,omitempty"`
|
||||||
|
References []string `yaml:"references,omitempty" json:"references,omitempty"`
|
||||||
|
Warnings []CondText `yaml:"warnings,omitempty" json:"warnings,omitempty"`
|
||||||
|
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
|
||||||
|
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Option is one choice of a select/multiselect question.
|
||||||
|
type Option struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||||
|
Recommended bool `yaml:"recommended,omitempty" json:"recommended,omitempty"`
|
||||||
|
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
|
||||||
|
Support Support `yaml:"support,omitempty" json:"support,omitempty"`
|
||||||
|
SupportNote string `yaml:"supportNote,omitempty" json:"supportNote,omitempty"`
|
||||||
|
EnabledWhen Cond `yaml:"enabledWhen,omitempty" json:"enabledWhen,omitempty"`
|
||||||
|
Effects Effects `yaml:",inline" json:"effects"`
|
||||||
|
References []string `yaml:"references,omitempty" json:"references,omitempty"`
|
||||||
|
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Effects are what a rule or a chosen option does (RULE-01).
|
||||||
|
type Effects struct {
|
||||||
|
Requires *Targets `yaml:"requires,omitempty" json:"requires,omitempty"`
|
||||||
|
Excludes *Targets `yaml:"excludes,omitempty" json:"excludes,omitempty"`
|
||||||
|
Conflicts *Targets `yaml:"conflicts,omitempty" json:"conflicts,omitempty"`
|
||||||
|
Implies *Targets `yaml:"implies,omitempty" json:"implies,omitempty"`
|
||||||
|
Recommends *Targets `yaml:"recommends,omitempty" json:"recommends,omitempty"`
|
||||||
|
Discourages *Targets `yaml:"discourages,omitempty" json:"discourages,omitempty"`
|
||||||
|
Provides []string `yaml:"provides,omitempty" json:"provides,omitempty"` // capabilities provided outside Yetano
|
||||||
|
}
|
||||||
|
|
||||||
|
// Targets lists packages, capabilities, modules and option answers.
|
||||||
|
type Targets struct {
|
||||||
|
Packages []string `yaml:"packages,omitempty" json:"packages,omitempty"`
|
||||||
|
Capabilities []string `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
|
||||||
|
Modules []string `yaml:"modules,omitempty" json:"modules,omitempty"` // pkg/module
|
||||||
|
Answers map[string]any `yaml:"answers,omitempty" json:"answers,omitempty"` // question -> option
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rule is a declarative rule of a solution or task.
|
||||||
|
type Rule struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||||
|
Effects Effects `yaml:",inline" json:"effects"`
|
||||||
|
Severity string `yaml:"severity,omitempty" json:"severity,omitempty"` // for warnings: info|warning|error
|
||||||
|
Message string `yaml:"message,omitempty" json:"message,omitempty"`
|
||||||
|
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
|
||||||
|
Source string `yaml:"source,omitempty" json:"source,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validation constrains an answer.
|
||||||
|
type Validation struct {
|
||||||
|
Min *float64 `yaml:"min,omitempty" json:"min,omitempty"`
|
||||||
|
Max *float64 `yaml:"max,omitempty" json:"max,omitempty"`
|
||||||
|
MinItems int `yaml:"minItems,omitempty" json:"minItems,omitempty"`
|
||||||
|
MaxItems int `yaml:"maxItems,omitempty" json:"maxItems,omitempty"`
|
||||||
|
MinLength int `yaml:"minLength,omitempty" json:"minLength,omitempty"`
|
||||||
|
MaxLength int `yaml:"maxLength,omitempty" json:"maxLength,omitempty"`
|
||||||
|
Pattern string `yaml:"pattern,omitempty" json:"pattern,omitempty"`
|
||||||
|
Message string `yaml:"message,omitempty" json:"message,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CondValue is a conditional default.
|
||||||
|
type CondValue struct {
|
||||||
|
When Cond `yaml:"when" json:"when"`
|
||||||
|
Value any `yaml:"value" json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CondText is a conditional message.
|
||||||
|
type CondText struct {
|
||||||
|
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||||
|
Severity string `yaml:"severity,omitempty" json:"severity,omitempty"`
|
||||||
|
Text string `yaml:"text" json:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CondCheck is a conditional validation (validateWhen).
|
||||||
|
type CondCheck struct {
|
||||||
|
When Cond `yaml:"when" json:"when"`
|
||||||
|
Validation Validation `yaml:"validation" json:"validation"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step is a setup step that is not configuration (yamase-ctl directory
|
||||||
|
// domain add ...). The engine only lists steps; it never runs them.
|
||||||
|
type Step struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||||
|
Package string `yaml:"package,omitempty" json:"package,omitempty"`
|
||||||
|
Module string `yaml:"module,omitempty" json:"module,omitempty"`
|
||||||
|
ForEach string `yaml:"forEach,omitempty" json:"forEach,omitempty"` // list parameter; ${item}
|
||||||
|
Run string `yaml:"run,omitempty" json:"run,omitempty"`
|
||||||
|
Note string `yaml:"note,omitempty" json:"note,omitempty"`
|
||||||
|
Phase string `yaml:"phase,omitempty" json:"phase,omitempty"` // install | configure | data | dns | start | verify
|
||||||
|
Mutating bool `yaml:"mutating,omitempty" json:"mutating,omitempty"`
|
||||||
|
Reversible *bool `yaml:"reversible,omitempty" json:"reversible,omitempty"`
|
||||||
|
References []string `yaml:"references,omitempty" json:"references,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check is a requirement or doctor check (DR-01).
|
||||||
|
type Check struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
Kind string `yaml:"kind" json:"kind"` // os | arch | port | dns | tls | program | command | manual
|
||||||
|
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||||
|
Severity string `yaml:"severity,omitempty" json:"severity,omitempty"` // error | warning | info
|
||||||
|
Local bool `yaml:"local,omitempty" json:"local,omitempty"` // needs the target system
|
||||||
|
Params map[string]string `yaml:"params,omitempty" json:"params,omitempty"`
|
||||||
|
Run string `yaml:"run,omitempty" json:"run,omitempty"` // command the operator can run
|
||||||
|
Hint string `yaml:"hint,omitempty" json:"hint,omitempty"`
|
||||||
|
References []string `yaml:"references,omitempty" json:"references,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Architecture adds solution-specific nodes and edges to the resolved graph.
|
||||||
|
type Architecture struct {
|
||||||
|
Nodes []ArchNode `yaml:"nodes,omitempty" json:"nodes,omitempty"`
|
||||||
|
Edges []ArchEdge `yaml:"edges,omitempty" json:"edges,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ArchNode is an extra node (clients, external services, storage, ...).
|
||||||
|
type ArchNode struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Type string `yaml:"type" json:"type"` // client | external | storage | network | identity | target
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ArchEdge connects two nodes; IDs are node IDs, "pkg:<id>", "mod:<pkg>/<id>" or "cap:<id>".
|
||||||
|
type ArchEdge struct {
|
||||||
|
From string `yaml:"from" json:"from"`
|
||||||
|
To string `yaml:"to" json:"to"`
|
||||||
|
Type string `yaml:"type" json:"type"`
|
||||||
|
Label string `yaml:"label,omitempty" json:"label,omitempty"`
|
||||||
|
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// References are typed yetano: references.
|
||||||
|
type References struct {
|
||||||
|
Manuals []string `yaml:"manuals,omitempty" json:"manuals,omitempty"`
|
||||||
|
Microsites []string `yaml:"microsites,omitempty" json:"microsites,omitempty"`
|
||||||
|
BigPicture []string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
|
||||||
|
Other []string `yaml:"other,omitempty" json:"other,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// All returns every reference in a stable order.
|
||||||
|
func (r References) All() []string {
|
||||||
|
var out []string
|
||||||
|
out = append(out, r.Manuals...)
|
||||||
|
out = append(out, r.Microsites...)
|
||||||
|
out = append(out, r.BigPicture...)
|
||||||
|
out = append(out, r.Other...)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lifecycle says which lifecycle operations a solution supports.
|
||||||
|
type Lifecycle struct {
|
||||||
|
Configure bool `yaml:"configure,omitempty" json:"configure"`
|
||||||
|
Validate bool `yaml:"validate,omitempty" json:"validate"`
|
||||||
|
Plan bool `yaml:"plan,omitempty" json:"plan"`
|
||||||
|
Deploy string `yaml:"deploy,omitempty" json:"deploy,omitempty"` // no | optional | yes
|
||||||
|
Doctor bool `yaml:"doctor,omitempty" json:"doctor"`
|
||||||
|
Update string `yaml:"update,omitempty" json:"update,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Examples, presets, instances ------------------------------------------
|
||||||
|
|
||||||
|
// ExampleSpec is a curated answer set for a solution (EX-01). Examples
|
||||||
|
// are generated by the engine like any session, so they cannot drift.
|
||||||
|
type ExampleSpec struct {
|
||||||
|
Solution string `yaml:"solution" json:"solution"`
|
||||||
|
Mode Level `yaml:"mode,omitempty" json:"mode,omitempty"`
|
||||||
|
Scenario string `yaml:"scenario,omitempty" json:"scenario,omitempty"`
|
||||||
|
Parameters map[string]any `yaml:"parameters" json:"parameters"`
|
||||||
|
Tested bool `yaml:"tested,omitempty" json:"tested"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Knowledge sources --------------------------------------------------------
|
||||||
|
|
||||||
|
// KnowledgeSourceSpec points at existing documentation (KNOW-04/06): the
|
||||||
|
// documents stay where they are; sections are extracted from headings.
|
||||||
|
type KnowledgeSourceSpec struct {
|
||||||
|
Package string `yaml:"package" json:"package"`
|
||||||
|
Type string `yaml:"type" json:"type"` // manual
|
||||||
|
Format string `yaml:"format" json:"format"` // markdown
|
||||||
|
Repository string `yaml:"repository" json:"repository"`
|
||||||
|
Root string `yaml:"root,omitempty" json:"root,omitempty"` // dir with README.md and docs/
|
||||||
|
Program string `yaml:"program,omitempty" json:"program,omitempty"`
|
||||||
|
Layout string `yaml:"layout,omitempty" json:"layout,omitempty"` // core-manual (README + docs/**) | docs-tree
|
||||||
|
Web string `yaml:"web,omitempty" json:"web,omitempty"` // URL base for topics, {slug} placeholder
|
||||||
|
Exclude []string `yaml:"exclude,omitempty" json:"exclude,omitempty"`
|
||||||
|
Topics []SourceTopic `yaml:"topics,omitempty" json:"topics,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SourceTopic attaches capabilities/modules to one manual topic.
|
||||||
|
type SourceTopic struct {
|
||||||
|
Slug string `yaml:"slug" json:"slug"`
|
||||||
|
Capabilities []string `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
|
||||||
|
Modules []string `yaml:"modules,omitempty" json:"modules,omitempty"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SchemaKinds maps a schema file name to the manifest it describes.
|
||||||
|
var SchemaKinds = map[string]struct {
|
||||||
|
Kind string
|
||||||
|
Spec any
|
||||||
|
}{
|
||||||
|
"catalog": {KindCatalog, CatalogSpec{}},
|
||||||
|
"capabilities": {KindCapabilities, CapabilitiesSpec{}},
|
||||||
|
"package": {KindPackage, PackageSpec{}},
|
||||||
|
"profile": {KindProfile, ProfileSpec{}},
|
||||||
|
"solution": {KindSolution, SolutionSpec{}},
|
||||||
|
"example": {KindExample, ExampleSpec{}},
|
||||||
|
"knowledge-source": {KindKnowledgeSource, KnowledgeSourceSpec{}},
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSONSchema returns the JSON Schema (draft 2020-12) of a manifest kind,
|
||||||
|
// derived from the Go types the loader decodes with KnownFields -- so the
|
||||||
|
// editor's check and the loader cannot disagree (CAT-05). Several
|
||||||
|
// documents per file ("---") are not expressible in JSON Schema; the
|
||||||
|
// schema describes one document. Solution and Task share a schema.
|
||||||
|
func JSONSchema(name string) map[string]any {
|
||||||
|
k := SchemaKinds[name]
|
||||||
|
kinds := []any{k.Kind}
|
||||||
|
if k.Kind == KindSolution {
|
||||||
|
kinds = append(kinds, KindTask)
|
||||||
|
}
|
||||||
|
return map[string]any{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://yetano.app/schema/solutions/" + name + ".schema.json",
|
||||||
|
"title": "Yetano " + k.Kind + " manifest",
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"required": []any{"apiVersion", "kind", "metadata"},
|
||||||
|
"properties": map[string]any{
|
||||||
|
"apiVersion": map[string]any{"const": APIVersion},
|
||||||
|
"kind": map[string]any{"enum": kinds},
|
||||||
|
"metadata": schemaOf(reflect.TypeOf(Meta{}), 0),
|
||||||
|
"spec": schemaOf(reflect.TypeOf(k.Spec), 0),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
nodeType = reflect.TypeOf(yaml.Node{})
|
||||||
|
condType = reflect.TypeOf(Cond{})
|
||||||
|
)
|
||||||
|
|
||||||
|
func schemaOf(t reflect.Type, depth int) map[string]any {
|
||||||
|
if depth > 12 {
|
||||||
|
return map[string]any{}
|
||||||
|
}
|
||||||
|
if t.Kind() == reflect.Pointer {
|
||||||
|
t = t.Elem()
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case t == nodeType:
|
||||||
|
return map[string]any{"description": "native configuration (any YAML)"}
|
||||||
|
case t == condType:
|
||||||
|
return map[string]any{"type": "object", "description": "condition over earlier answers (ADR-0003)"}
|
||||||
|
case t == reflect.TypeOf(Support("")):
|
||||||
|
return map[string]any{"enum": []any{"supported", "experimental", "untested", "discouraged", "needs-prerequisites", "not-implemented", "not-supported", "impossible", "insecure"}}
|
||||||
|
case t == reflect.TypeOf(Level("")):
|
||||||
|
return map[string]any{"enum": []any{"quick", "guided", "advanced"}}
|
||||||
|
}
|
||||||
|
switch t.Kind() {
|
||||||
|
case reflect.String:
|
||||||
|
return map[string]any{"type": "string"}
|
||||||
|
case reflect.Bool:
|
||||||
|
return map[string]any{"type": "boolean"}
|
||||||
|
case reflect.Int, reflect.Int64:
|
||||||
|
return map[string]any{"type": "integer"}
|
||||||
|
case reflect.Float64:
|
||||||
|
return map[string]any{"type": "number"}
|
||||||
|
case reflect.Slice:
|
||||||
|
return map[string]any{"type": "array", "items": schemaOf(t.Elem(), depth+1)}
|
||||||
|
case reflect.Map:
|
||||||
|
return map[string]any{"type": "object", "additionalProperties": schemaOf(t.Elem(), depth+1)}
|
||||||
|
case reflect.Interface:
|
||||||
|
return map[string]any{}
|
||||||
|
case reflect.Struct:
|
||||||
|
props := map[string]any{}
|
||||||
|
addFields(t, props, depth)
|
||||||
|
return map[string]any{"type": "object", "additionalProperties": false, "properties": props}
|
||||||
|
}
|
||||||
|
return map[string]any{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func addFields(t reflect.Type, props map[string]any, depth int) {
|
||||||
|
for i := 0; i < t.NumField(); i++ {
|
||||||
|
f := t.Field(i)
|
||||||
|
if !f.IsExported() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
tag := f.Tag.Get("yaml")
|
||||||
|
name, opts, _ := strings.Cut(tag, ",")
|
||||||
|
if name == "-" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.Contains(opts, "inline") {
|
||||||
|
addFields(f.Type, props, depth)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if name == "" {
|
||||||
|
name = strings.ToLower(f.Name)
|
||||||
|
}
|
||||||
|
props[name] = schemaOf(f.Type, depth+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,548 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"path"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QuestionTypes are the built-in question types (WIZ-03).
|
||||||
|
var QuestionTypes = map[string]bool{
|
||||||
|
"boolean": true, "select": true, "multiselect": true,
|
||||||
|
"string": true, "text": true, "integer": true, "decimal": true,
|
||||||
|
"date": true, "duration": true, "hostname": true, "domain": true,
|
||||||
|
"email": true, "ip": true, "cidr": true, "port": true, "url": true,
|
||||||
|
"path": true, "dir": true, "list": true, "keyvalue": true,
|
||||||
|
"package": true, "profile": true, "capability": true, "provider": true,
|
||||||
|
"target": true, "secret": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListItemTypes may be used as list items.
|
||||||
|
var ListItemTypes = map[string]bool{
|
||||||
|
"string": true, "hostname": true, "domain": true, "email": true, "ip": true,
|
||||||
|
"cidr": true, "port": true, "url": true, "path": true, "integer": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
var idRE = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]*[a-z0-9]$|^[a-z0-9]$`)
|
||||||
|
var questionIDRE = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]*$`)
|
||||||
|
|
||||||
|
// SafeRelPath reports whether p is a clean relative slash path without
|
||||||
|
// "..", usable as an output file name (SEC-03).
|
||||||
|
func SafeRelPath(p string) bool {
|
||||||
|
if p == "" || strings.HasPrefix(p, "/") || strings.Contains(p, "\\") || strings.Contains(p, ":") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if path.Clean(p) != p {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, part := range strings.Split(p, "/") {
|
||||||
|
if part == ".." || part == "." || part == "" || strings.HasPrefix(part, ".") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate checks the catalog's internal consistency and returns all
|
||||||
|
// issues (load issues included). Reference targets outside the catalog
|
||||||
|
// (manual sections, microsites) are checked by knowledge.Lint.
|
||||||
|
func (c *Catalog) Validate() []Issue {
|
||||||
|
v := &validator{c: c, issues: append([]Issue(nil), c.Issues...)}
|
||||||
|
v.root()
|
||||||
|
for _, id := range SortedIDs(c.Capabilities) {
|
||||||
|
v.capability(c.Capabilities[id])
|
||||||
|
}
|
||||||
|
for _, id := range SortedIDs(c.Packages) {
|
||||||
|
v.pkg(c.Packages[id])
|
||||||
|
}
|
||||||
|
for _, id := range SortedIDs(c.Profiles) {
|
||||||
|
v.profile(c.Profiles[id])
|
||||||
|
}
|
||||||
|
for _, id := range SortedIDs(c.Solutions) {
|
||||||
|
v.solution(c.Solutions[id])
|
||||||
|
}
|
||||||
|
for _, id := range SortedIDs(c.Tasks) {
|
||||||
|
v.solution(c.Tasks[id])
|
||||||
|
}
|
||||||
|
for _, id := range SortedIDs(c.Examples) {
|
||||||
|
v.example(c.Examples[id])
|
||||||
|
}
|
||||||
|
for _, id := range SortedIDs(c.Sources) {
|
||||||
|
v.source(c.Sources[id])
|
||||||
|
}
|
||||||
|
return v.issues
|
||||||
|
}
|
||||||
|
|
||||||
|
type validator struct {
|
||||||
|
c *Catalog
|
||||||
|
issues []Issue
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) errf(e *Entity, id, code, f string, a ...any) {
|
||||||
|
i := Issue{Severity: "error", ID: id, Code: code, Message: fmt.Sprintf(f, a...)}
|
||||||
|
if e != nil {
|
||||||
|
i.File, i.Line = e.File, e.Line
|
||||||
|
}
|
||||||
|
v.issues = append(v.issues, i)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) warnf(e *Entity, id, code, f string, a ...any) {
|
||||||
|
i := Issue{Severity: "warning", ID: id, Code: code, Message: fmt.Sprintf(f, a...)}
|
||||||
|
if e != nil {
|
||||||
|
i.File, i.Line = e.File, e.Line
|
||||||
|
}
|
||||||
|
v.issues = append(v.issues, i)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) root() {
|
||||||
|
c := v.c
|
||||||
|
if c.Spec.WebBase == "" {
|
||||||
|
v.errf(nil, "catalog", "web-base", "catalog.yaml: spec.webBase is required")
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, cat := range c.Spec.Categories {
|
||||||
|
if seen[cat.ID] {
|
||||||
|
v.errf(nil, cat.ID, "duplicate", "duplicate category %q", cat.ID)
|
||||||
|
}
|
||||||
|
seen[cat.ID] = true
|
||||||
|
if cat.Topic != "" && c.BigPicture != nil {
|
||||||
|
if _, ok := c.BigPicture.Topics[cat.Topic]; !ok {
|
||||||
|
v.errf(nil, cat.ID, "bigpicture-ref", "category %q: unknown Big Picture topic %q", cat.ID, cat.Topic)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cat.Topic == "" && cat.Title == "" {
|
||||||
|
v.errf(nil, cat.ID, "category", "category %q needs a topic or a title", cat.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) capability(cp *Capability) {
|
||||||
|
e := &Entity{File: v.c.capFile[cp.ID]}
|
||||||
|
if !idRE.MatchString(cp.ID) || strings.Contains(cp.ID, "@") {
|
||||||
|
v.errf(e, cp.ID, "id", "capability ID %q: lower case, dot separated, no '@' (ADR-0003)", cp.ID)
|
||||||
|
}
|
||||||
|
if cp.Title == "" {
|
||||||
|
v.errf(e, cp.ID, "required", "capability %q: title is required", cp.ID)
|
||||||
|
}
|
||||||
|
for _, r := range append(append([]string{}, cp.Requires...), cp.Conflicts...) {
|
||||||
|
if _, ok := v.c.Capabilities[r]; !ok {
|
||||||
|
v.errf(e, cp.ID, "capability-ref", "capability %q names unknown capability %q", cp.ID, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, x := range cp.External {
|
||||||
|
if !x.Support.Valid() {
|
||||||
|
v.errf(e, cp.ID, "support", "external provider %q: unknown support %q", x.ID, x.Support)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) caps(e *Entity, id string, list []string) {
|
||||||
|
for _, cp := range list {
|
||||||
|
if _, ok := v.c.Capabilities[cp]; !ok {
|
||||||
|
v.errf(e, id, "capability-ref", "unknown capability %q", cp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) pkg(p *Package) {
|
||||||
|
e := &p.Entity
|
||||||
|
if !idRE.MatchString(p.Meta.ID) {
|
||||||
|
v.errf(e, p.Meta.ID, "id", "package ID %q is not valid", p.Meta.ID)
|
||||||
|
}
|
||||||
|
if p.Spec.BigPicture != "" && v.c.BigPicture != nil {
|
||||||
|
if _, ok := v.c.BigPicture.Products[p.Spec.BigPicture]; !ok {
|
||||||
|
v.errf(e, p.Meta.ID, "bigpicture-ref", "unknown Big Picture program %q", p.Spec.BigPicture)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.Spec.BigPicture == "" && p.Meta.Summary == "" {
|
||||||
|
v.errf(e, p.Meta.ID, "required", "package needs spec.bigpicture or metadata.summary")
|
||||||
|
}
|
||||||
|
if len(p.Spec.Sources) == 0 {
|
||||||
|
v.errf(e, p.Meta.ID, "sources", "package claims need sources (ANA-02)")
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, m := range p.Spec.Modules {
|
||||||
|
if seen[m.ID] {
|
||||||
|
v.errf(e, p.Meta.ID, "duplicate", "duplicate module %q", m.ID)
|
||||||
|
}
|
||||||
|
seen[m.ID] = true
|
||||||
|
if !m.Support.Valid() {
|
||||||
|
v.errf(e, p.Meta.ID, "support", "module %q: unknown support %q", m.ID, m.Support)
|
||||||
|
}
|
||||||
|
v.caps(e, p.Meta.ID+"/"+m.ID, m.Provides)
|
||||||
|
v.caps(e, p.Meta.ID+"/"+m.ID, m.Requires)
|
||||||
|
if m.Manual != "" {
|
||||||
|
if _, ok := v.c.Sources[m.Manual]; !ok {
|
||||||
|
v.errf(e, p.Meta.ID+"/"+m.ID, "source-ref", "unknown knowledge source %q", m.Manual)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) profile(p *Profile) {
|
||||||
|
e := &p.Entity
|
||||||
|
pkg, ok := v.c.Packages[p.Meta.Package]
|
||||||
|
if !ok {
|
||||||
|
v.errf(e, p.Key(), "package-ref", "profile of unknown package %q", p.Meta.Package)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := v.c.ProfileChain(p.Meta.Package, p.Meta.ID); err != nil {
|
||||||
|
v.errf(e, p.Key(), "extends", "%v", err)
|
||||||
|
}
|
||||||
|
for m, state := range p.Spec.Modules {
|
||||||
|
if pkg.Module(m) == nil {
|
||||||
|
v.errf(e, p.Key(), "module-ref", "unknown module %q", m)
|
||||||
|
}
|
||||||
|
if state != "enabled" && state != "disabled" {
|
||||||
|
v.errf(e, p.Key(), "module-state", "module %q: want enabled or disabled, got %q", m, state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, f := range p.Spec.Config {
|
||||||
|
v.fragment(e, p.Key(), f, nil, 0)
|
||||||
|
}
|
||||||
|
for _, r := range p.Spec.Recommendations {
|
||||||
|
if r.Package != "" {
|
||||||
|
if _, ok := v.c.Packages[r.Package]; !ok {
|
||||||
|
v.errf(e, p.Key(), "package-ref", "recommendation names unknown package %q", r.Package)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if r.Capability != "" {
|
||||||
|
v.caps(e, p.Key(), []string{r.Capability})
|
||||||
|
}
|
||||||
|
if r.Reason == "" {
|
||||||
|
v.errf(e, p.Key(), "reason", "a recommendation needs a reason (EX-03)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) fragment(e *Entity, id string, f Fragment, s *Solution, upto int) {
|
||||||
|
if !SafeRelPath(f.File) {
|
||||||
|
v.errf(e, id, "path", "fragment file %q: want a clean relative path", f.File)
|
||||||
|
}
|
||||||
|
if f.Set.Kind == 0 {
|
||||||
|
v.errf(e, id, "fragment", "fragment for %q has no set", f.File)
|
||||||
|
}
|
||||||
|
if s != nil {
|
||||||
|
v.cond(e, id, "fragment "+f.File, f.When, s, upto)
|
||||||
|
} else if len(f.When) > 0 {
|
||||||
|
v.errf(e, id, "fragment", "profile fragments cannot have conditions")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// cond checks a condition: well-formed and only naming questions before
|
||||||
|
// index upto (ADR-0003).
|
||||||
|
func (v *validator) cond(e *Entity, id, where string, c Cond, s *Solution, upto int) {
|
||||||
|
if len(c) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := c.Eval(Env{Answers: map[string]any{}}); err != nil {
|
||||||
|
v.errf(e, id, "condition", "%s: %v", where, err)
|
||||||
|
}
|
||||||
|
for _, ref := range c.Refs() {
|
||||||
|
_, idx := s.Question(ref)
|
||||||
|
if idx < 0 {
|
||||||
|
v.errf(e, id, "condition", "%s: unknown question %q", where, ref)
|
||||||
|
} else if idx >= upto {
|
||||||
|
v.errf(e, id, "condition-order", "%s: names question %q, which is not asked before it", where, ref)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) targets(e *Entity, id string, t *Targets, s *Solution) {
|
||||||
|
if t == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, p := range t.Packages {
|
||||||
|
if _, ok := v.c.Packages[p]; !ok {
|
||||||
|
v.errf(e, id, "package-ref", "unknown package %q", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v.caps(e, id, t.Capabilities)
|
||||||
|
for _, m := range t.Modules {
|
||||||
|
pkg, mod, _ := strings.Cut(m, "/")
|
||||||
|
p, ok := v.c.Packages[pkg]
|
||||||
|
if !ok || p.Module(mod) == nil {
|
||||||
|
v.errf(e, id, "module-ref", "unknown module %q (want package/module)", m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for q, val := range t.Answers {
|
||||||
|
qq, _ := s.Question(q)
|
||||||
|
if qq == nil {
|
||||||
|
v.errf(e, id, "question-ref", "unknown question %q", q)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
v.optionValue(e, id, qq, val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) optionValue(e *Entity, id string, q *Question, val any) {
|
||||||
|
if q.Type != "select" && q.Type != "multiselect" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
vals := asList(val)
|
||||||
|
if _, isList := val.([]any); !isList {
|
||||||
|
vals = []any{val}
|
||||||
|
}
|
||||||
|
for _, x := range vals {
|
||||||
|
found := false
|
||||||
|
for _, o := range q.Options {
|
||||||
|
if Equal(o.ID, x) {
|
||||||
|
found = true
|
||||||
|
if !o.Support.Selectable() {
|
||||||
|
v.errf(e, id, "default-unselectable", "question %q: value %q is %s and cannot be selected", q.ID, Scalar(x), o.Support)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
v.errf(e, id, "option-ref", "question %q has no option %q", q.ID, Scalar(x))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) solution(s *Solution) {
|
||||||
|
e := &s.Entity
|
||||||
|
id := s.Meta.ID
|
||||||
|
if !idRE.MatchString(id) {
|
||||||
|
v.errf(e, id, "id", "ID %q is not valid", id)
|
||||||
|
}
|
||||||
|
if s.Meta.Version == "" {
|
||||||
|
v.errf(e, id, "version", "metadata.version is required (LOCK)")
|
||||||
|
}
|
||||||
|
if !s.Meta.Status.Valid() {
|
||||||
|
v.errf(e, id, "support", "unknown status %q", s.Meta.Status)
|
||||||
|
}
|
||||||
|
if s.Spec.BigPicture != "" && v.c.BigPicture != nil {
|
||||||
|
if _, ok := v.c.BigPicture.Stories[s.Spec.BigPicture]; !ok {
|
||||||
|
v.errf(e, id, "bigpicture-ref", "unknown Big Picture goal %q", s.Spec.BigPicture)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.Meta.Title == "" && s.Spec.BigPicture == "" {
|
||||||
|
v.errf(e, id, "required", "title or spec.bigpicture is required")
|
||||||
|
}
|
||||||
|
if s.Kind == KindSolution && s.Meta.Category != "" {
|
||||||
|
found := false
|
||||||
|
for _, cat := range v.c.Spec.Categories {
|
||||||
|
found = found || cat.ID == s.Meta.Category
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
v.errf(e, id, "category", "unknown category %q", s.Meta.Category)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.Kind == KindTask {
|
||||||
|
switch s.Spec.Kind {
|
||||||
|
case "read-only", "generate", "diagnostic", "planning", "mutating", "deployment", "maintenance":
|
||||||
|
default:
|
||||||
|
v.errf(e, id, "task-kind", "spec.kind %q: want read-only, generate, diagnostic, planning, mutating, deployment or maintenance", s.Spec.Kind)
|
||||||
|
}
|
||||||
|
if s.Spec.AppliesTo != nil {
|
||||||
|
for _, sid := range s.Spec.AppliesTo.Solutions {
|
||||||
|
if _, ok := v.c.Solutions[sid]; !ok {
|
||||||
|
v.errf(e, id, "solution-ref", "appliesTo: unknown solution %q", sid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v.caps(e, id, s.Spec.AppliesTo.Capabilities)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v.caps(e, id, s.Spec.Capabilities.Required)
|
||||||
|
v.caps(e, id, s.Spec.Capabilities.Recommended)
|
||||||
|
v.caps(e, id, s.Spec.Capabilities.Optional)
|
||||||
|
nq := len(s.Spec.Questions)
|
||||||
|
for _, pu := range s.Spec.Packages {
|
||||||
|
if _, ok := v.c.Packages[pu.ID]; !ok {
|
||||||
|
v.errf(e, id, "package-ref", "unknown package %q", pu.ID)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if pu.Profile != "" {
|
||||||
|
if _, ok := v.c.Profiles[pu.ID+"/"+pu.Profile]; !ok {
|
||||||
|
v.errf(e, id, "profile-ref", "unknown profile %s/%s", pu.ID, pu.Profile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v.cond(e, id, "package "+pu.ID, pu.When, s, nq)
|
||||||
|
}
|
||||||
|
seenQ := map[string]bool{}
|
||||||
|
for i := range s.Spec.Questions {
|
||||||
|
q := &s.Spec.Questions[i]
|
||||||
|
qid := id + "." + q.ID
|
||||||
|
if !questionIDRE.MatchString(q.ID) {
|
||||||
|
v.errf(e, qid, "id", "question ID %q: letters, digits and _ only", q.ID)
|
||||||
|
}
|
||||||
|
if seenQ[q.ID] {
|
||||||
|
v.errf(e, qid, "duplicate", "duplicate question %q", q.ID)
|
||||||
|
}
|
||||||
|
seenQ[q.ID] = true
|
||||||
|
if !QuestionTypes[q.Type] {
|
||||||
|
v.errf(e, qid, "type", "unknown question type %q", q.Type)
|
||||||
|
}
|
||||||
|
if q.Type == "list" && !ListItemTypes[q.Item] {
|
||||||
|
v.errf(e, qid, "type", "list needs item: one of the scalar types, got %q", q.Item)
|
||||||
|
}
|
||||||
|
if q.Title == "" {
|
||||||
|
v.errf(e, qid, "required", "question needs a title")
|
||||||
|
}
|
||||||
|
switch q.Level {
|
||||||
|
case "", LevelQuick, LevelGuided, LevelAdvanced:
|
||||||
|
default:
|
||||||
|
v.errf(e, qid, "level", "unknown level %q", q.Level)
|
||||||
|
}
|
||||||
|
if (q.Type == "select" || q.Type == "multiselect") && len(q.Options) == 0 {
|
||||||
|
v.errf(e, qid, "options", "%s question without options", q.Type)
|
||||||
|
}
|
||||||
|
if q.Type == "secret" && q.Default != nil {
|
||||||
|
v.errf(e, qid, "secret-default", "a secret question cannot have a default (SEC-01)")
|
||||||
|
}
|
||||||
|
seenO := map[string]bool{}
|
||||||
|
anySelectable := false
|
||||||
|
for _, o := range q.Options {
|
||||||
|
if seenO[o.ID] {
|
||||||
|
v.errf(e, qid, "duplicate", "duplicate option %q", o.ID)
|
||||||
|
}
|
||||||
|
seenO[o.ID] = true
|
||||||
|
if !o.Support.Valid() {
|
||||||
|
v.errf(e, qid, "support", "option %q: unknown support %q", o.ID, o.Support)
|
||||||
|
}
|
||||||
|
if o.Support.Selectable() {
|
||||||
|
anySelectable = true
|
||||||
|
} else if o.SupportNote == "" {
|
||||||
|
v.errf(e, qid, "support-note", "option %q is %s: supportNote must say why", o.ID, o.Support)
|
||||||
|
}
|
||||||
|
if o.Recommended && o.Reason == "" {
|
||||||
|
v.errf(e, qid, "reason", "recommended option %q needs a reason (EX-03)", o.ID)
|
||||||
|
}
|
||||||
|
v.cond(e, qid, "option "+o.ID+" enabledWhen", o.EnabledWhen, s, i)
|
||||||
|
v.effects(e, qid+"/"+o.ID, o.Effects, s)
|
||||||
|
}
|
||||||
|
if len(q.Options) > 0 && !anySelectable {
|
||||||
|
v.errf(e, qid, "unsatisfiable", "no option of %q can be selected", q.ID)
|
||||||
|
}
|
||||||
|
if q.Default != nil {
|
||||||
|
v.optionValue(e, qid, q, q.Default)
|
||||||
|
}
|
||||||
|
for _, d := range q.DefaultWhen {
|
||||||
|
v.cond(e, qid, "defaultWhen", d.When, s, i)
|
||||||
|
v.optionValue(e, qid, q, d.Value)
|
||||||
|
}
|
||||||
|
v.cond(e, qid, "visibleWhen", q.VisibleWhen, s, i)
|
||||||
|
v.cond(e, qid, "requiredWhen", q.RequiredWhen, s, i)
|
||||||
|
for _, w := range q.ValidateWhen {
|
||||||
|
v.cond(e, qid, "validateWhen", w.When, s, i)
|
||||||
|
}
|
||||||
|
for _, w := range q.Warnings {
|
||||||
|
v.cond(e, qid, "warning", w.When, s, i+1)
|
||||||
|
}
|
||||||
|
if q.Validation.Pattern != "" {
|
||||||
|
if _, err := regexp.Compile(q.Validation.Pattern); err != nil {
|
||||||
|
v.errf(e, qid, "pattern", "validation pattern: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
seenR := map[string]bool{}
|
||||||
|
for _, r := range s.Spec.Rules {
|
||||||
|
rid := id + "#" + r.ID
|
||||||
|
if r.ID == "" || seenR[r.ID] {
|
||||||
|
v.errf(e, rid, "rule-id", "every rule needs a unique id")
|
||||||
|
}
|
||||||
|
seenR[r.ID] = true
|
||||||
|
v.cond(e, rid, "rule when", r.When, s, nq)
|
||||||
|
v.effects(e, rid, r.Effects, s)
|
||||||
|
switch r.Severity {
|
||||||
|
case "", "info", "warning", "error":
|
||||||
|
default:
|
||||||
|
v.errf(e, rid, "severity", "unknown severity %q", r.Severity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i, f := range s.Spec.Config {
|
||||||
|
fid := f.ID
|
||||||
|
if fid == "" {
|
||||||
|
fid = fmt.Sprint(i)
|
||||||
|
}
|
||||||
|
v.fragment(e, id+"#config:"+fid, f, s, nq)
|
||||||
|
if pkg, _, ok := strings.Cut(f.File, "/"); !ok || v.c.Packages[pkg] == nil {
|
||||||
|
v.errf(e, id, "fragment-file", "fragment file %q must start with a package directory", f.File)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, st := range s.Spec.Steps {
|
||||||
|
v.cond(e, id+"#step:"+st.ID, "step", st.When, s, nq)
|
||||||
|
if st.ForEach == "$modules" && st.Package == "" {
|
||||||
|
v.errf(e, id+"#step:"+st.ID, "step", "forEach: $modules needs a package")
|
||||||
|
} else if st.ForEach != "" && st.ForEach != "$modules" {
|
||||||
|
if q, _ := s.Question(st.ForEach); q == nil {
|
||||||
|
v.errf(e, id+"#step:"+st.ID, "question-ref", "forEach names unknown question %q", st.ForEach)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if st.Package != "" && v.c.Packages[st.Package] == nil {
|
||||||
|
v.errf(e, id+"#step:"+st.ID, "package-ref", "unknown package %q", st.Package)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, ck := range s.Spec.Requirements {
|
||||||
|
v.cond(e, id+"#check:"+ck.ID, "requirement", ck.When, s, nq)
|
||||||
|
}
|
||||||
|
for _, n := range s.Spec.Architecture.Nodes {
|
||||||
|
v.cond(e, id+"#node:"+n.ID, "node", n.When, s, nq)
|
||||||
|
}
|
||||||
|
for _, ed := range s.Spec.Architecture.Edges {
|
||||||
|
v.cond(e, id+"#edge", "edge", ed.When, s, nq)
|
||||||
|
}
|
||||||
|
for _, r := range s.Spec.Related {
|
||||||
|
if v.c.Lookup(r) == nil {
|
||||||
|
v.errf(e, id, "related", "related: unknown solution or task %q", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) effects(e *Entity, id string, fx Effects, s *Solution) {
|
||||||
|
for _, t := range []*Targets{fx.Requires, fx.Excludes, fx.Conflicts, fx.Implies, fx.Recommends, fx.Discourages} {
|
||||||
|
v.targets(e, id, t, s)
|
||||||
|
}
|
||||||
|
v.caps(e, id, fx.Provides)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) example(x *Example) {
|
||||||
|
e := &x.Entity
|
||||||
|
s, ok := v.c.Solutions[x.Spec.Solution]
|
||||||
|
if !ok {
|
||||||
|
s, ok = v.c.Tasks[x.Spec.Solution]
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
v.errf(e, x.Key(), "solution-ref", "example of unknown solution %q", x.Spec.Solution)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for k, val := range x.Spec.Parameters {
|
||||||
|
q, _ := s.Question(k)
|
||||||
|
if q == nil {
|
||||||
|
v.errf(e, x.Key(), "question-ref", "unknown parameter %q", k)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
v.optionValue(e, x.Key(), q, val)
|
||||||
|
}
|
||||||
|
if x.Meta.Title == "" {
|
||||||
|
v.errf(e, x.Key(), "required", "an example needs a title")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) source(k *KnowledgeSource) {
|
||||||
|
e := &k.Entity
|
||||||
|
if _, ok := v.c.Packages[k.Spec.Package]; !ok {
|
||||||
|
v.errf(e, k.Meta.ID, "package-ref", "unknown package %q", k.Spec.Package)
|
||||||
|
}
|
||||||
|
if k.Spec.Type != "manual" {
|
||||||
|
v.errf(e, k.Meta.ID, "type", "type %q: only manual is supported", k.Spec.Type)
|
||||||
|
}
|
||||||
|
if k.Spec.Format != "markdown" {
|
||||||
|
v.errf(e, k.Meta.ID, "format", "format %q: only markdown is supported", k.Spec.Format)
|
||||||
|
}
|
||||||
|
switch k.Spec.Layout {
|
||||||
|
case "", "core-manual", "docs-tree":
|
||||||
|
default:
|
||||||
|
v.errf(e, k.Meta.ID, "layout", "layout %q: want core-manual or docs-tree", k.Spec.Layout)
|
||||||
|
}
|
||||||
|
if k.Spec.Root != "" && !SafeRelPath(k.Spec.Root) {
|
||||||
|
v.errf(e, k.Meta.ID, "path", "root %q: want a clean relative path", k.Spec.Root)
|
||||||
|
}
|
||||||
|
if !SafeRelPath(k.Spec.Repository) {
|
||||||
|
v.errf(e, k.Meta.ID, "path", "repository %q: want a plain name", k.Spec.Repository)
|
||||||
|
}
|
||||||
|
for _, t := range k.Spec.Topics {
|
||||||
|
v.caps(e, k.Meta.ID+"/"+t.Slug, t.Capabilities)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,327 @@
|
|||||||
|
// Package cli implements the guide's commands -- solution, task,
|
||||||
|
// knowledge and open -- with yet's conventions (stdlib flag, --json on
|
||||||
|
// every command, data on stdout, messages on stderr, stable exit codes).
|
||||||
|
// The guide's own program calls Run from main; yet does not embed it.
|
||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
"yetano.dev/yetano/core/solutions/engine"
|
||||||
|
"yetano.dev/yetano/core/solutions/knowledge"
|
||||||
|
"yetano.dev/yetano/core/solutions/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exit codes, the same as yet's (yet/internal/cliutil). 0-3 are the
|
||||||
|
// family-wide ones (docs/program-conventions.md in the meta-repo); 3 is
|
||||||
|
// "interrupted" there, so "not found" is 7 (owner decision 2026-12-01,
|
||||||
|
// it was 3 up to solutions/v0.1.0).
|
||||||
|
const (
|
||||||
|
ExitOK = 0
|
||||||
|
ExitError = 1
|
||||||
|
ExitUsage = 2
|
||||||
|
ExitInterrupted = 3 // stopped by SIGINT/SIGTERM (the context was cancelled)
|
||||||
|
ExitConflict = 4
|
||||||
|
ExitNotFound = 7
|
||||||
|
)
|
||||||
|
|
||||||
|
// Env is what the embedding program provides.
|
||||||
|
type Env struct {
|
||||||
|
Stdin io.Reader
|
||||||
|
Stdout io.Writer
|
||||||
|
Stderr io.Writer
|
||||||
|
// Interactive: stdin and stdout are a terminal. Without it no command
|
||||||
|
// ever waits for input (CLI-03).
|
||||||
|
Interactive bool
|
||||||
|
// Program is the command name in messages.
|
||||||
|
Program string
|
||||||
|
// Catalogs are default catalog directories (an installed knowledge
|
||||||
|
// bundle); --catalog and $YETANO_SOLUTIONS_CATALOG come first.
|
||||||
|
Catalogs []string
|
||||||
|
// StoreDir keeps instances, sessions, presets (from core/paths).
|
||||||
|
StoreDir string
|
||||||
|
// Version is stamped into lock files.
|
||||||
|
Version string
|
||||||
|
// Getenv defaults to os.Getenv.
|
||||||
|
Getenv func(string) string
|
||||||
|
}
|
||||||
|
|
||||||
|
type app struct {
|
||||||
|
env Env
|
||||||
|
ctx context.Context
|
||||||
|
catDir string
|
||||||
|
locale string
|
||||||
|
cat *catalog.Catalog
|
||||||
|
ix *knowledge.Index
|
||||||
|
eng *engine.Engine
|
||||||
|
store store.Store
|
||||||
|
jsonOut bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// exitErr carries an exit code.
|
||||||
|
type exitErr struct {
|
||||||
|
code int
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e exitErr) Error() string { return e.err.Error() }
|
||||||
|
|
||||||
|
func fail(code int, f string, a ...any) error { return exitErr{code, fmt.Errorf(f, a...)} }
|
||||||
|
|
||||||
|
// Run runs one command; args start with the command name.
|
||||||
|
func Run(ctx context.Context, args []string, env Env) int {
|
||||||
|
if env.Getenv == nil {
|
||||||
|
env.Getenv = os.Getenv
|
||||||
|
}
|
||||||
|
if env.Program == "" {
|
||||||
|
env.Program = "yetano-solutions"
|
||||||
|
}
|
||||||
|
if env.Stdin == nil {
|
||||||
|
env.Stdin = os.Stdin
|
||||||
|
}
|
||||||
|
a := &app{env: env, ctx: ctx, store: store.Store{Dir: env.StoreDir}}
|
||||||
|
if env.Version != "" {
|
||||||
|
engine.GeneratorVersion = env.Version
|
||||||
|
}
|
||||||
|
err := a.dispatch(args)
|
||||||
|
if err == nil {
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
if errors.Is(err, flag.ErrHelp) {
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
code := ExitError
|
||||||
|
var ee exitErr
|
||||||
|
if errors.As(err, &ee) {
|
||||||
|
code = ee.code
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case ctx.Err() != nil:
|
||||||
|
// whatever failed, it failed because we were told to stop
|
||||||
|
code = ExitInterrupted
|
||||||
|
case errors.Is(err, engine.ErrNotFound), errors.Is(err, store.ErrNotFound):
|
||||||
|
code = ExitNotFound
|
||||||
|
case errors.Is(err, engine.ErrModified):
|
||||||
|
code = ExitConflict
|
||||||
|
case errors.Is(err, engine.ErrIncomplete):
|
||||||
|
code = ExitUsage
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
enc := json.NewEncoder(env.Stdout)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
_ = enc.Encode(map[string]any{"error": err.Error(), "code": code})
|
||||||
|
} else if err.Error() != "" {
|
||||||
|
fmt.Fprintf(env.Stderr, "error: %v\n", err)
|
||||||
|
}
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) dispatch(args []string) error {
|
||||||
|
// global flags before the command (--catalog dir solution list) move
|
||||||
|
// behind it, where every subcommand's flag set parses them
|
||||||
|
var lead []string
|
||||||
|
for len(args) > 0 && strings.HasPrefix(args[0], "-") && args[0] != "-h" && args[0] != "--help" {
|
||||||
|
lead = append(lead, args[0])
|
||||||
|
name := strings.TrimLeft(args[0], "-")
|
||||||
|
args = args[1:]
|
||||||
|
if (name == "catalog" || name == "locale") && len(args) > 0 {
|
||||||
|
lead = append(lead, args[0])
|
||||||
|
args = args[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(lead) > 0 && len(args) > 0 {
|
||||||
|
args = append(append([]string{}, args...), lead...)
|
||||||
|
}
|
||||||
|
if len(args) == 0 {
|
||||||
|
return a.usage("")
|
||||||
|
}
|
||||||
|
cmd, rest := args[0], args[1:]
|
||||||
|
switch cmd {
|
||||||
|
case "solution", "solutions":
|
||||||
|
return a.solution(rest)
|
||||||
|
case "task", "tasks":
|
||||||
|
return a.task(rest)
|
||||||
|
case "knowledge":
|
||||||
|
return a.knowledge(rest)
|
||||||
|
case "open":
|
||||||
|
return a.open(rest)
|
||||||
|
case "help", "-h", "--help":
|
||||||
|
return a.usage("")
|
||||||
|
}
|
||||||
|
return a.usage(cmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usage is the help text.
|
||||||
|
const Usage = `Solutions Guide -- describe what you want to achieve, get native configuration:
|
||||||
|
|
||||||
|
solution list|search|show|setup|generate|validate|plan|doctor
|
||||||
|
solution config show|explain, architecture, handbook, package
|
||||||
|
solution instance list|show|export|import|delete
|
||||||
|
solution preset list|save|show|export|import|delete
|
||||||
|
solution catalog validate|test|coverage
|
||||||
|
task list|search|show|run
|
||||||
|
knowledge search|show|status|backlinks|coverage
|
||||||
|
open <yetano:reference>
|
||||||
|
|
||||||
|
Common flags: --catalog DIR, --locale de, --json.
|
||||||
|
`
|
||||||
|
|
||||||
|
func (a *app) usage(unknown string) error {
|
||||||
|
if unknown != "" {
|
||||||
|
fmt.Fprintf(a.env.Stderr, "unknown command %q\n\n", unknown)
|
||||||
|
}
|
||||||
|
fmt.Fprint(a.env.Stderr, Usage)
|
||||||
|
if unknown != "" {
|
||||||
|
return exitErr{ExitUsage, errors.New("")}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// flags makes a flag set with the common flags.
|
||||||
|
func (a *app) flags(name string) *flag.FlagSet {
|
||||||
|
fs := flag.NewFlagSet(a.env.Program+" "+name, flag.ContinueOnError)
|
||||||
|
fs.SetOutput(a.env.Stderr)
|
||||||
|
fs.StringVar(&a.catDir, "catalog", "", "catalog directory (default: $YETANO_SOLUTIONS_CATALOG, then the installed bundle)")
|
||||||
|
fs.StringVar(&a.locale, "locale", "", "language of texts (en, de); default from $LANG")
|
||||||
|
fs.BoolVar(&a.jsonOut, "json", false, "machine-readable output")
|
||||||
|
return fs
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) parse(fs *flag.FlagSet, args []string) error {
|
||||||
|
// allow flags after positional arguments (yet does the same)
|
||||||
|
var flags, pos []string
|
||||||
|
for i := 0; i < len(args); i++ {
|
||||||
|
s := args[i]
|
||||||
|
if s == "--" {
|
||||||
|
pos = append(pos, args[i+1:]...)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(s, "-") && len(s) > 1 {
|
||||||
|
flags = append(flags, s)
|
||||||
|
name := strings.TrimLeft(s, "-")
|
||||||
|
if !strings.Contains(name, "=") {
|
||||||
|
if f := fs.Lookup(name); f != nil {
|
||||||
|
if bf, ok := f.Value.(interface{ IsBoolFlag() bool }); !ok || !bf.IsBoolFlag() {
|
||||||
|
if i+1 < len(args) {
|
||||||
|
flags = append(flags, args[i+1])
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pos = append(pos, s)
|
||||||
|
}
|
||||||
|
if err := fs.Parse(flags); err != nil {
|
||||||
|
if errors.Is(err, flag.ErrHelp) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return exitErr{ExitUsage, err}
|
||||||
|
}
|
||||||
|
return fs.Parse(append([]string{"--"}, pos...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// load finds and loads the catalog and the index.
|
||||||
|
func (a *app) load() error {
|
||||||
|
if a.cat != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if a.locale == "" {
|
||||||
|
lang := a.env.Getenv("LANG")
|
||||||
|
if strings.HasPrefix(lang, "de") {
|
||||||
|
a.locale = "de"
|
||||||
|
} else {
|
||||||
|
a.locale = "en"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidates := []string{a.catDir, a.env.Getenv("YETANO_SOLUTIONS_CATALOG")}
|
||||||
|
candidates = append(candidates, a.env.Catalogs...)
|
||||||
|
dir := ""
|
||||||
|
for _, c := range candidates {
|
||||||
|
if c == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(c, "catalog.yaml")); err == nil {
|
||||||
|
dir = c
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if c == a.catDir {
|
||||||
|
return fail(ExitUsage, "--catalog %s: no catalog.yaml there", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dir == "" {
|
||||||
|
return fail(ExitNotFound, "no solutions catalog found: pass --catalog <dir> or set YETANO_SOLUTIONS_CATALOG (the meta-repo's assets/solutions)")
|
||||||
|
}
|
||||||
|
c, err := catalog.Load(dir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.cat = c
|
||||||
|
a.ix = knowledge.Build(c)
|
||||||
|
a.eng = engine.New(c)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) out() io.Writer { return a.env.Stdout }
|
||||||
|
|
||||||
|
func (a *app) printJSON(v any) error {
|
||||||
|
enc := json.NewEncoder(a.env.Stdout)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
return enc.Encode(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) say(f string, args ...any) { fmt.Fprintf(a.env.Stdout, f, args...) }
|
||||||
|
|
||||||
|
func (a *app) note(f string, args ...any) { fmt.Fprintf(a.env.Stderr, f, args...) }
|
||||||
|
|
||||||
|
// tr localizes a meta field.
|
||||||
|
func (a *app) tr(t catalog.Translations, field, base string) string {
|
||||||
|
return engine.Tr(t, a.locale, field, base)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) readLine(r *bufio.Reader) (string, error) {
|
||||||
|
s, err := r.ReadString('\n')
|
||||||
|
if err != nil && (s == "" || !errors.Is(err, io.EOF)) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func sortedKeys[V any](m map[string]V) []string {
|
||||||
|
out := make([]string, 0, len(m))
|
||||||
|
for k := range m {
|
||||||
|
out = append(out, k)
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func wrap(s string, width int, indent string) string {
|
||||||
|
words := strings.Fields(s)
|
||||||
|
var b strings.Builder
|
||||||
|
line := 0
|
||||||
|
for _, w := range words {
|
||||||
|
if line > 0 && line+len(w)+1 > width {
|
||||||
|
b.WriteString("\n" + indent)
|
||||||
|
line = 0
|
||||||
|
} else if line > 0 {
|
||||||
|
b.WriteByte(' ')
|
||||||
|
line++
|
||||||
|
}
|
||||||
|
b.WriteString(w)
|
||||||
|
line += len(w)
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type result struct {
|
||||||
|
code int
|
||||||
|
stdout, stderr string
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(t *testing.T, store string, args ...string) result {
|
||||||
|
t.Helper()
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
code := Run(context.Background(), args, Env{
|
||||||
|
Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errb,
|
||||||
|
Program: "yetano-solutions", StoreDir: store, Catalogs: []string{"../engine/testdata/cat"},
|
||||||
|
Getenv: func(string) string { return "" },
|
||||||
|
})
|
||||||
|
return result{code, out.String(), errb.String()}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scenario D: CI use without a terminal (ACC-D, CLI-03).
|
||||||
|
func TestNonInteractive(t *testing.T) {
|
||||||
|
store := t.TempDir()
|
||||||
|
out := filepath.Join(t.TempDir(), "gen")
|
||||||
|
// missing answers: exit 2, never a prompt
|
||||||
|
r := run(t, store, "solution", "setup", "app-run", "--json")
|
||||||
|
if r.code != ExitUsage || !strings.Contains(r.stdout, `"missing"`) || !strings.Contains(r.stdout, "hosts") {
|
||||||
|
t.Fatalf("missing: %d %s %s", r.code, r.stdout, r.stderr)
|
||||||
|
}
|
||||||
|
// invalid value: exit 2
|
||||||
|
if r := run(t, store, "solution", "setup", "app-run", "--set", "hosts=bad_host!"); r.code != ExitUsage {
|
||||||
|
t.Errorf("invalid value: %d %s", r.code, r.stderr)
|
||||||
|
}
|
||||||
|
// unknown question: exit 2
|
||||||
|
if r := run(t, store, "solution", "setup", "app-run", "--set", "nope=1"); r.code != ExitUsage {
|
||||||
|
t.Errorf("unknown question: %d", r.code)
|
||||||
|
}
|
||||||
|
// unknown solution: exit 3
|
||||||
|
if r := run(t, store, "solution", "show", "nope"); r.code != ExitNotFound {
|
||||||
|
t.Errorf("unknown solution: %d", r.code)
|
||||||
|
}
|
||||||
|
// complete: files written, instance saved
|
||||||
|
r = run(t, store, "solution", "setup", "app-run", "--set", "hosts=a.example.org", "--name", "prod", "--save", "--output", out)
|
||||||
|
if r.code != 0 {
|
||||||
|
t.Fatalf("setup: %d %s", r.code, r.stderr)
|
||||||
|
}
|
||||||
|
for _, f := range []string{"solution.yaml", "solution.lock.yaml", "config/app/app.yaml", "deployment-plan.yaml", "handbook/index.md", "architecture/graph.json"} {
|
||||||
|
if _, err := os.Stat(filepath.Join(out, f)); err != nil {
|
||||||
|
t.Errorf("missing %s", f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// regenerate from the manifest: same files, exit 0
|
||||||
|
if r := run(t, store, "solution", "generate", "--file", filepath.Join(out, "solution.yaml"), "--output", out, "--locked"); r.code != 0 {
|
||||||
|
t.Fatalf("regenerate: %d %s", r.code, r.stderr)
|
||||||
|
}
|
||||||
|
// a hand edit: exit 4 (conflict)
|
||||||
|
os.WriteFile(filepath.Join(out, "config/app/app.yaml"), []byte("# mine\n"), 0o644)
|
||||||
|
if r := run(t, store, "solution", "generate", "--file", filepath.Join(out, "solution.yaml"), "--output", out); r.code != ExitConflict {
|
||||||
|
t.Errorf("hand edit: %d %s", r.code, r.stderr)
|
||||||
|
}
|
||||||
|
// stored instance works by name
|
||||||
|
if r := run(t, store, "solution", "validate", "prod"); r.code != 0 {
|
||||||
|
t.Errorf("validate prod: %d %s %s", r.code, r.stdout, r.stderr)
|
||||||
|
}
|
||||||
|
r = run(t, store, "solution", "instance", "list", "--json")
|
||||||
|
var rows []map[string]string
|
||||||
|
if err := json.Unmarshal([]byte(r.stdout), &rows); err != nil || len(rows) != 1 || rows[0]["status"] != "Configured" {
|
||||||
|
t.Errorf("instance list: %s %v", r.stdout, err)
|
||||||
|
}
|
||||||
|
// preset from it; a new instance needs only the instance-specific answer
|
||||||
|
if r := run(t, store, "solution", "preset", "save", "mine", "--from", "prod"); r.code != 0 {
|
||||||
|
t.Fatalf("preset: %d %s", r.code, r.stderr)
|
||||||
|
}
|
||||||
|
if r := run(t, store, "solution", "setup", "app-run", "--preset", "mine", "--set", "hosts=b.example.org", "--json"); r.code != 0 {
|
||||||
|
t.Errorf("setup with preset: %d %s", r.code, r.stderr)
|
||||||
|
}
|
||||||
|
// explain
|
||||||
|
r = run(t, store, "solution", "config", "explain", "prod", "app/app.yaml", "limits.max")
|
||||||
|
if r.code != 0 || !strings.Contains(r.stdout, "profile:app/base") {
|
||||||
|
t.Errorf("explain: %d %s %s", r.code, r.stdout, r.stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStateJSONIsTheAPI(t *testing.T) {
|
||||||
|
store := t.TempDir()
|
||||||
|
f := filepath.Join(t.TempDir(), "s.yaml")
|
||||||
|
os.WriteFile(f, []byte("apiVersion: yetano.dev/v1\nkind: WizardSession\nmetadata: {name: x}\nspec:\n solution: {id: app-run}\n mode: guided\n parameters: {hosts: [a.example.org], identity: central}\n"), 0o644)
|
||||||
|
r := run(t, store, "solution", "state", "--file", f)
|
||||||
|
var st map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(r.stdout), &st); err != nil {
|
||||||
|
t.Fatalf("%v: %s %s", err, r.stdout, r.stderr)
|
||||||
|
}
|
||||||
|
if st["complete"] != false || st["next"] != "realm" {
|
||||||
|
t.Errorf("state: complete=%v next=%v", st["complete"], st["next"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSearchOpenKnowledge(t *testing.T) {
|
||||||
|
store := t.TempDir()
|
||||||
|
if r := run(t, store, "solution", "search", "run", "app"); r.code != 0 || !strings.Contains(r.stdout, "yetano:solution/app-run") {
|
||||||
|
t.Errorf("search: %d %s", r.code, r.stdout)
|
||||||
|
}
|
||||||
|
if r := run(t, store, "open", "yetano:solution/app-run"); r.code != 0 {
|
||||||
|
t.Errorf("open: %d %s", r.code, r.stderr)
|
||||||
|
}
|
||||||
|
if r := run(t, store, "open", "yetano:solution/missing"); r.code != ExitNotFound {
|
||||||
|
t.Errorf("open missing: %d", r.code)
|
||||||
|
}
|
||||||
|
if r := run(t, store, "open", "not a ref"); r.code != ExitUsage {
|
||||||
|
t.Errorf("open bad: %d", r.code)
|
||||||
|
}
|
||||||
|
if r := run(t, store, "solution", "catalog", "validate"); r.code != 0 {
|
||||||
|
t.Errorf("catalog validate: %d %s %s", r.code, r.stdout, r.stderr)
|
||||||
|
}
|
||||||
|
if r := run(t, store, "nonsense"); r.code != ExitUsage {
|
||||||
|
t.Errorf("unknown command: %d", r.code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInteractiveWizard(t *testing.T) {
|
||||||
|
store := t.TempDir()
|
||||||
|
out := filepath.Join(t.TempDir(), "gen")
|
||||||
|
var o, e bytes.Buffer
|
||||||
|
// size: Enter (default small), hosts: a.example.org, then actions: 6 export, 8 quit
|
||||||
|
in := strings.NewReader("\na.example.org\n6\n8\n")
|
||||||
|
code := Run(context.Background(), []string{"solution", "setup", "app-run", "--output", out}, Env{
|
||||||
|
Stdin: in, Stdout: &o, Stderr: &e, Interactive: true, Program: "yetano-solutions", StoreDir: store,
|
||||||
|
Catalogs: []string{"../engine/testdata/cat"}, Getenv: func(string) string { return "" },
|
||||||
|
})
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("%d\n%s\n%s", code, o.String(), e.String())
|
||||||
|
}
|
||||||
|
for _, want := range []string{"[1/2] How big?", "(recommended)", "YOUR SOLUTION", "Actions:"} {
|
||||||
|
if !strings.Contains(o.String(), want) {
|
||||||
|
t.Errorf("output lacks %q:\n%s", want, o.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(out, "config/app/app.yaml")); err != nil {
|
||||||
|
t.Error("export did not write the configuration")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ctrl-C: a cancelled context is exit 3, the family-wide "interrupted"
|
||||||
|
// (docs/program-conventions.md); "not found" moved to 7 for it.
|
||||||
|
func TestInterrupted(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
code := Run(ctx, []string{"solution", "show", "nope"}, Env{
|
||||||
|
Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errb,
|
||||||
|
Program: "yetano-solutions", StoreDir: t.TempDir(), Catalogs: []string{"../engine/testdata/cat"},
|
||||||
|
Getenv: func(string) string { return "" },
|
||||||
|
})
|
||||||
|
if code != ExitInterrupted || ExitInterrupted != 3 || ExitNotFound != 7 {
|
||||||
|
t.Fatalf("cancelled: exit %d (%s)", code, errb.String())
|
||||||
|
}
|
||||||
|
if r := run(t, t.TempDir(), "solution", "show", "nope"); r.code != 7 {
|
||||||
|
t.Fatalf("not found: exit %d", r.code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/engine"
|
||||||
|
)
|
||||||
|
|
||||||
|
// doctor runs a state's requirement checks on this machine (DR-01/03).
|
||||||
|
// Only kinds it can really check get PASS/WARNING/ERROR; everything else
|
||||||
|
// stays NOT_CHECKED with the command to run -- never a fake PASS.
|
||||||
|
func (a *app) doctor(args []string) error {
|
||||||
|
fs := a.flags("solution doctor")
|
||||||
|
f := a.instFlags(fs)
|
||||||
|
offline := fs.Bool("offline", false, "skip checks that need the network (DNS)")
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, st, err := a.stateOf(fs, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(a.ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
worst := 0
|
||||||
|
for i := range st.Checks {
|
||||||
|
c := &st.Checks[i]
|
||||||
|
if c.Status == engine.CheckNotApplicable {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
runCheck(ctx, c, *offline)
|
||||||
|
if c.Status == engine.CheckError || c.Status == engine.CheckBlocked {
|
||||||
|
worst = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
if err := a.printJSON(map[string]any{"solution": st.Solution.ID, "instance": st.Instance, "checks": st.Checks}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for _, c := range st.Checks {
|
||||||
|
a.say("%-14s %s\n", c.Status, c.Title)
|
||||||
|
if c.Note != "" {
|
||||||
|
a.say("%-14s %s\n", "", wrap(c.Note, 62, strings.Repeat(" ", 15)))
|
||||||
|
}
|
||||||
|
if c.Status == engine.CheckNotChecked && c.Run != "" {
|
||||||
|
a.say("%-14s run: %s\n", "", c.Run)
|
||||||
|
}
|
||||||
|
if (c.Status == engine.CheckWarning || c.Status == engine.CheckError) && c.Hint != "" {
|
||||||
|
a.say("%-14s hint: %s\n", "", wrap(c.Hint, 60, strings.Repeat(" ", 21)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if worst > 0 {
|
||||||
|
return exitErr{ExitError, errors.New("")}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func sevStatus(sev string) string {
|
||||||
|
switch sev {
|
||||||
|
case "warning":
|
||||||
|
return engine.CheckWarning
|
||||||
|
case "info":
|
||||||
|
return engine.CheckInfo
|
||||||
|
}
|
||||||
|
return engine.CheckError
|
||||||
|
}
|
||||||
|
|
||||||
|
func runCheck(ctx context.Context, c *engine.CheckResult, offline bool) {
|
||||||
|
p := c.Params
|
||||||
|
switch c.Kind {
|
||||||
|
case "os":
|
||||||
|
want := strings.Split(p["want"], ",")
|
||||||
|
for _, w := range want {
|
||||||
|
if w == runtime.GOOS {
|
||||||
|
c.Status, c.Note = engine.CheckPass, runtime.GOOS
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.Status, c.Note = sevStatus(c.Severity), runtime.GOOS+" is not supported"
|
||||||
|
case "port":
|
||||||
|
var busy, denied []string
|
||||||
|
for _, port := range strings.Split(p["port"], ",") {
|
||||||
|
l, err := net.Listen("tcp", ":"+strings.TrimSpace(port))
|
||||||
|
if err == nil {
|
||||||
|
l.Close()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if errors.Is(err, syscall.EACCES) || errors.Is(err, os.ErrPermission) {
|
||||||
|
denied = append(denied, port)
|
||||||
|
} else {
|
||||||
|
busy = append(busy, port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case len(busy) > 0:
|
||||||
|
c.Status, c.Note = sevStatus(c.Severity), "in use: "+strings.Join(busy, ", ")
|
||||||
|
case len(denied) > 0:
|
||||||
|
c.Status, c.Note = engine.CheckNotChecked, "no permission to test port(s) "+strings.Join(denied, ", ")+" as this user"
|
||||||
|
default:
|
||||||
|
c.Status = engine.CheckPass
|
||||||
|
}
|
||||||
|
case "file":
|
||||||
|
var missing []string
|
||||||
|
for _, f := range strings.Split(p["paths"], ",") {
|
||||||
|
if _, err := os.Stat(strings.TrimSpace(f)); err != nil {
|
||||||
|
missing = append(missing, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(missing) > 0 {
|
||||||
|
c.Status, c.Note = sevStatus(c.Severity), "missing: "+strings.Join(missing, ", ")
|
||||||
|
} else {
|
||||||
|
c.Status = engine.CheckPass
|
||||||
|
}
|
||||||
|
case "dns":
|
||||||
|
if offline {
|
||||||
|
c.Status, c.Note = engine.CheckNotChecked, "offline"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
dnsCheck(ctx, c)
|
||||||
|
case "manual":
|
||||||
|
c.Status = engine.CheckInfo
|
||||||
|
c.Note = "check this yourself"
|
||||||
|
default:
|
||||||
|
c.Status = engine.CheckNotChecked
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func dnsCheck(ctx context.Context, c *engine.CheckResult) {
|
||||||
|
p := c.Params
|
||||||
|
r := net.DefaultResolver
|
||||||
|
var problems []string
|
||||||
|
names := strings.Split(p["names"], ",")
|
||||||
|
for _, name := range names {
|
||||||
|
name = p["prefix"] + strings.TrimSpace(name)
|
||||||
|
if name == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
qctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||||
|
switch strings.ToUpper(p["type"]) {
|
||||||
|
case "MX":
|
||||||
|
mx, err := r.LookupMX(qctx, name)
|
||||||
|
if err != nil || len(mx) == 0 {
|
||||||
|
problems = append(problems, name+": no MX record")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if want := strings.TrimSuffix(p["want"], "."); want != "" {
|
||||||
|
ok := false
|
||||||
|
for _, m := range mx {
|
||||||
|
ok = ok || strings.EqualFold(strings.TrimSuffix(m.Host, "."), want)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
problems = append(problems, fmt.Sprintf("%s: MX does not point to %s", name, want))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "A":
|
||||||
|
if ips, err := r.LookupIPAddr(qctx, name); err != nil || len(ips) == 0 {
|
||||||
|
problems = append(problems, name+": does not resolve")
|
||||||
|
}
|
||||||
|
case "TXT":
|
||||||
|
txt, err := r.LookupTXT(qctx, name)
|
||||||
|
found := false
|
||||||
|
for _, t := range txt {
|
||||||
|
found = found || strings.Contains(t, p["contains"])
|
||||||
|
}
|
||||||
|
if err != nil || !found {
|
||||||
|
problems = append(problems, fmt.Sprintf("%s: no TXT record with %q", name, p["contains"]))
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
c.Status = engine.CheckNotChecked
|
||||||
|
cancel()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
c.Status, c.Note = engine.CheckNotChecked, "timed out"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(problems) > 0 {
|
||||||
|
c.Status, c.Note = sevStatus(c.Severity), strings.Join(problems, "; ")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Status = engine.CheckPass
|
||||||
|
}
|
||||||
@@ -0,0 +1,623 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
"yetano.dev/yetano/core/solutions/engine"
|
||||||
|
"yetano.dev/yetano/core/solutions/knowledge"
|
||||||
|
"yetano.dev/yetano/core/solutions/ref"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---- search --------------------------------------------------------------------
|
||||||
|
|
||||||
|
func (a *app) searchCmd(args []string, kinds []string) error {
|
||||||
|
fs := a.flags("search")
|
||||||
|
all := fs.Bool("all", false, "search everything (manuals, packages, Big Picture, ...)")
|
||||||
|
limit := fs.Int("limit", 8, "hits per group")
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() == 0 {
|
||||||
|
return fail(ExitUsage, "usage: search <words>")
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if *all {
|
||||||
|
kinds = nil
|
||||||
|
}
|
||||||
|
groups := a.ix.Search(strings.Join(fs.Args(), " "), knowledge.SearchOptions{Kinds: kinds, Limit: *limit, Locale: a.locale})
|
||||||
|
if a.jsonOut {
|
||||||
|
if groups == nil {
|
||||||
|
groups = []knowledge.Group{}
|
||||||
|
}
|
||||||
|
return a.printJSON(groups)
|
||||||
|
}
|
||||||
|
if len(groups) == 0 {
|
||||||
|
a.note("nothing found\n")
|
||||||
|
return exitErr{ExitNotFound, errors.New("")}
|
||||||
|
}
|
||||||
|
for _, g := range groups {
|
||||||
|
a.say("%s\n", g.Title)
|
||||||
|
for _, h := range g.Hits {
|
||||||
|
a.say(" %-44s %s\n", trunc(h.Title, 44), h.Ref)
|
||||||
|
}
|
||||||
|
a.say("\n")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func trunc(s string, n int) string {
|
||||||
|
r := []rune(s)
|
||||||
|
if len(r) <= n {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return string(r[:n-1]) + "…"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- instances --------------------------------------------------------------------
|
||||||
|
|
||||||
|
func (a *app) instance(args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
args = []string{"list"}
|
||||||
|
}
|
||||||
|
fs := a.flags("solution instance " + args[0])
|
||||||
|
if err := a.parse(fs, args[1:]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "list", "ls":
|
||||||
|
inst, err := a.store.Instances()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sess, err := a.store.Sessions()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
type row struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Solution string `json:"solution"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Updated string `json:"updated"`
|
||||||
|
}
|
||||||
|
var rows []row
|
||||||
|
for _, list := range [][]string{inst, sess} {
|
||||||
|
for _, n := range list {
|
||||||
|
in, err := a.store.LoadInstance(n)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
status := "Draft"
|
||||||
|
if in.Kind == catalog.KindInstance {
|
||||||
|
status = "Configured"
|
||||||
|
if a.load() == nil {
|
||||||
|
if st, err := a.evaluate(in, nil); err == nil && !st.Complete {
|
||||||
|
status = "Invalid"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows = append(rows, row{n, in.Kind, in.Spec.Solution.ID, status, in.Metadata.Updated})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
if rows == nil {
|
||||||
|
rows = []row{}
|
||||||
|
}
|
||||||
|
return a.printJSON(rows)
|
||||||
|
}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
a.note("no saved solutions (save one with: %s solution setup <id> --save)\n", a.env.Program)
|
||||||
|
}
|
||||||
|
for _, r := range rows {
|
||||||
|
a.say("%-24s %-14s %-11s %s\n", r.Name, r.Solution, r.Status, r.Updated)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case "show", "export":
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution instance %s <name>", a.env.Program, args[0])
|
||||||
|
}
|
||||||
|
in, err := a.store.LoadInstance(fs.Arg(0))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(in)
|
||||||
|
}
|
||||||
|
b, err := engine.Marshal(in)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.say("%s", b)
|
||||||
|
return nil
|
||||||
|
case "import":
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution instance import <file>", a.env.Program)
|
||||||
|
}
|
||||||
|
f, err := os.Open(fs.Arg(0))
|
||||||
|
if err != nil {
|
||||||
|
return fail(ExitNotFound, "%v", err)
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
in, err := engine.ReadInstance(f)
|
||||||
|
if err != nil {
|
||||||
|
return fail(ExitUsage, "%v", err)
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := a.evaluate(in, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := a.store.SaveInstance(in); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.note("imported %s\n", in.Metadata.Name)
|
||||||
|
return nil
|
||||||
|
case "delete", "rm":
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution instance delete <name>", a.env.Program)
|
||||||
|
}
|
||||||
|
return a.store.DeleteInstance(fs.Arg(0))
|
||||||
|
case "duplicate", "cp":
|
||||||
|
if fs.NArg() != 2 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution instance duplicate <name> <new-name>", a.env.Program)
|
||||||
|
}
|
||||||
|
in, err := a.store.LoadInstance(fs.Arg(0))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
in.Metadata.Name, in.Metadata.Created = fs.Arg(1), ""
|
||||||
|
return a.store.SaveInstance(in)
|
||||||
|
case "favorite":
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution instance favorite <name>", a.env.Program)
|
||||||
|
}
|
||||||
|
in, err := a.store.LoadInstance(fs.Arg(0))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
in.Metadata.Favorite = !in.Metadata.Favorite
|
||||||
|
return a.store.SaveInstance(in)
|
||||||
|
}
|
||||||
|
return a.usage("solution instance " + args[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- presets ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func (a *app) preset(args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
args = []string{"list"}
|
||||||
|
}
|
||||||
|
fs := a.flags("solution preset " + args[0])
|
||||||
|
from := fs.String("from", "", "save: the instance to take the answers from")
|
||||||
|
file := fs.String("file", "", "save: a solution.yaml to take the answers from")
|
||||||
|
if err := a.parse(fs, args[1:]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "list", "ls":
|
||||||
|
names, err := a.store.Presets()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
if names == nil {
|
||||||
|
names = []string{}
|
||||||
|
}
|
||||||
|
return a.printJSON(names)
|
||||||
|
}
|
||||||
|
for _, n := range names {
|
||||||
|
p, err := a.store.LoadPreset(n)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
a.say("%-24s %-14s %d answer(s)\n", n, p.Spec.Solution, len(p.Spec.Parameters))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case "save":
|
||||||
|
if fs.NArg() != 1 || (*from == "" && *file == "") {
|
||||||
|
return fail(ExitUsage, "usage: %s solution preset save <name> --from <instance> | --file <solution.yaml>", a.env.Program)
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var in *engine.Instance
|
||||||
|
var err error
|
||||||
|
if *file != "" {
|
||||||
|
in, err = a.instanceFrom(*file, fs)
|
||||||
|
} else {
|
||||||
|
in, err = a.store.LoadInstance(*from)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s := a.cat.Lookup(in.Spec.Solution.ID)
|
||||||
|
if s == nil {
|
||||||
|
return fmt.Errorf("%w: solution %s", engine.ErrNotFound, in.Spec.Solution.ID)
|
||||||
|
}
|
||||||
|
p := engine.PresetFrom(fs.Arg(0), in, s)
|
||||||
|
if err := a.store.SavePreset(p); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.note("saved preset %s (%d answers; instance-specific and secret answers are left out)\n", p.Metadata.Name, len(p.Spec.Parameters))
|
||||||
|
return nil
|
||||||
|
case "show", "export":
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution preset show <name>", a.env.Program)
|
||||||
|
}
|
||||||
|
p, err := a.store.LoadPreset(fs.Arg(0))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(p)
|
||||||
|
}
|
||||||
|
b, _ := engine.Marshal(p)
|
||||||
|
a.say("%s", b)
|
||||||
|
return nil
|
||||||
|
case "import":
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution preset import <file>", a.env.Program)
|
||||||
|
}
|
||||||
|
f, err := os.Open(fs.Arg(0))
|
||||||
|
if err != nil {
|
||||||
|
return fail(ExitNotFound, "%v", err)
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
p, err := engine.ReadPreset(f)
|
||||||
|
if err != nil {
|
||||||
|
return fail(ExitUsage, "%v", err)
|
||||||
|
}
|
||||||
|
return a.store.SavePreset(p)
|
||||||
|
case "delete", "rm":
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution preset delete <name>", a.env.Program)
|
||||||
|
}
|
||||||
|
return a.store.DeletePreset(fs.Arg(0))
|
||||||
|
}
|
||||||
|
return a.usage("solution preset " + args[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- catalog --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func (a *app) catalogCmd(args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution catalog validate|test|coverage", a.env.Program)
|
||||||
|
}
|
||||||
|
fs := a.flags("solution catalog " + args[0])
|
||||||
|
update := fs.Bool("update", false, "test: rewrite the golden files")
|
||||||
|
if err := a.parse(fs, args[1:]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
var ee exitErr
|
||||||
|
if a.cat != nil && !errors.As(err, &ee) {
|
||||||
|
// print every load issue, not just the first
|
||||||
|
for _, i := range a.cat.Issues {
|
||||||
|
a.note("%s\n", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "validate", "lint":
|
||||||
|
issues := knowledge.Lint(a.ix)
|
||||||
|
errs := 0
|
||||||
|
for _, i := range issues {
|
||||||
|
if i.Severity == "error" {
|
||||||
|
errs++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
if issues == nil {
|
||||||
|
issues = []catalog.Issue{}
|
||||||
|
}
|
||||||
|
_ = a.printJSON(issues)
|
||||||
|
} else {
|
||||||
|
for _, i := range issues {
|
||||||
|
a.say("%-7s %s\n", strings.ToUpper(i.Severity), i)
|
||||||
|
}
|
||||||
|
a.note("%d solution(s), %d task(s), %d package(s), %d capabilities, %d manual topics: %d error(s), %d warning(s)\n",
|
||||||
|
len(a.cat.Solutions), len(a.cat.Tasks), len(a.cat.Packages), len(a.cat.Capabilities), len(a.ix.Topics), errs, len(issues)-errs)
|
||||||
|
}
|
||||||
|
if errs > 0 {
|
||||||
|
return exitErr{ExitError, errors.New("")}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case "test":
|
||||||
|
return a.catalogTest(*update)
|
||||||
|
case "schema":
|
||||||
|
dir := filepath.Join(a.cat.Root, "schema")
|
||||||
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, name := range sortedKeys(catalog.SchemaKinds) {
|
||||||
|
b, err := json.MarshalIndent(catalog.JSONSchema(name), "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name+".schema.json"), append(b, '\n'), 0o644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a.note("wrote %d schemas to %s\n", len(catalog.SchemaKinds), dir)
|
||||||
|
return nil
|
||||||
|
case "coverage":
|
||||||
|
cov := knowledge.ComputeCoverage(a.ix)
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(cov)
|
||||||
|
}
|
||||||
|
a.say("Yetano Knowledge Coverage (%d packages in the catalog)\n\n", cov.Packages)
|
||||||
|
for _, m := range cov.Metrics {
|
||||||
|
a.say(" %-38s %5.1f%% (%d/%d)\n", m.Name, m.Pct, m.Have, m.Total)
|
||||||
|
}
|
||||||
|
if len(cov.ProgramsWithout) > 0 {
|
||||||
|
a.say("\nBig Picture programs not in the catalog yet: %s\n", strings.Join(cov.ProgramsWithout, ", "))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return a.usage("solution catalog " + args[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
// catalogTest evaluates every example, generates its output and compares
|
||||||
|
// it with the golden files next to the solution (EX-02, QS-08). An example
|
||||||
|
// that stops being complete or changes output fails (ACC-J).
|
||||||
|
func (a *app) catalogTest(update bool) error {
|
||||||
|
failed := 0
|
||||||
|
for _, key := range catalog.SortedIDs(a.cat.Examples) {
|
||||||
|
x := a.cat.Examples[key]
|
||||||
|
s := a.cat.Lookup(x.Spec.Solution)
|
||||||
|
in := engine.NewInstance(x.Meta.ID, s, x.Spec.Mode)
|
||||||
|
in.Kind = catalog.KindInstance
|
||||||
|
for k, v := range x.Spec.Parameters {
|
||||||
|
in.Spec.Parameters[k] = v
|
||||||
|
}
|
||||||
|
in.Spec.Locale = "en"
|
||||||
|
st, err := a.eng.Evaluate(in, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out, err := a.eng.Generate(st, in, nil, false)
|
||||||
|
if err != nil {
|
||||||
|
a.say("FAIL %s: %v\n", key, err)
|
||||||
|
failed++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
dir := filepath.Join(a.cat.Root, filepath.FromSlash(path.Dir(path.Dir(x.File))), "testdata", x.Meta.ID)
|
||||||
|
if update {
|
||||||
|
if err := os.RemoveAll(dir); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, f := range out.Files {
|
||||||
|
if f.Kind == "lock" {
|
||||||
|
continue // hashes of the whole catalog: not stable across unrelated edits
|
||||||
|
}
|
||||||
|
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, f.Content, 0o644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a.say("UPDATED %s (%d files)\n", key, len(out.Files)-1)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var diffs []string
|
||||||
|
want := map[string]bool{}
|
||||||
|
for _, f := range out.Files {
|
||||||
|
if f.Kind == "lock" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
want[f.Path] = true
|
||||||
|
b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(f.Path)))
|
||||||
|
if err != nil {
|
||||||
|
diffs = append(diffs, f.Path+" (no golden file)")
|
||||||
|
} else if !bytes.Equal(b, f.Content) {
|
||||||
|
diffs = append(diffs, f.Path+" ("+firstDiff(b, f.Content)+")")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
|
||||||
|
if err == nil && !d.IsDir() {
|
||||||
|
rel, _ := filepath.Rel(dir, p)
|
||||||
|
if !want[filepath.ToSlash(rel)] {
|
||||||
|
diffs = append(diffs, filepath.ToSlash(rel)+" (no longer generated)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
sort.Strings(diffs)
|
||||||
|
if len(diffs) > 0 {
|
||||||
|
a.say("FAIL %s\n", key)
|
||||||
|
for _, d := range diffs {
|
||||||
|
a.say(" %s\n", d)
|
||||||
|
}
|
||||||
|
failed++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
a.say("ok %s\n", key)
|
||||||
|
}
|
||||||
|
if failed > 0 {
|
||||||
|
a.note("%d example(s) failed; after an intended change: make golden (catalog test --update) and review the diff\n", failed)
|
||||||
|
return exitErr{ExitError, errors.New("")}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstDiff(a, b []byte) string {
|
||||||
|
la, lb := strings.Split(string(a), "\n"), strings.Split(string(b), "\n")
|
||||||
|
for i := 0; i < len(la) || i < len(lb); i++ {
|
||||||
|
var x, y string
|
||||||
|
if i < len(la) {
|
||||||
|
x = la[i]
|
||||||
|
}
|
||||||
|
if i < len(lb) {
|
||||||
|
y = lb[i]
|
||||||
|
}
|
||||||
|
if x != y {
|
||||||
|
return fmt.Sprintf("line %d: golden %q, now %q", i+1, trunc(x, 50), trunc(y, 50))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "differs"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- knowledge, open ------------------------------------------------------------------
|
||||||
|
|
||||||
|
func (a *app) knowledge(args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fail(ExitUsage, "usage: %s knowledge search|show|status|backlinks|coverage|validate", a.env.Program)
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "search":
|
||||||
|
return a.searchCmd(args[1:], nil)
|
||||||
|
case "show":
|
||||||
|
return a.open(args[1:])
|
||||||
|
case "validate", "lint":
|
||||||
|
return a.catalogCmd(append([]string{"validate"}, args[1:]...))
|
||||||
|
case "coverage":
|
||||||
|
return a.catalogCmd(append([]string{"coverage"}, args[1:]...))
|
||||||
|
case "status", "index":
|
||||||
|
fs := a.flags("knowledge " + args[0])
|
||||||
|
if err := a.parse(fs, args[1:]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
kinds := map[string]int{}
|
||||||
|
for _, e := range a.ix.Entries {
|
||||||
|
kinds[e.Kind]++
|
||||||
|
}
|
||||||
|
st := map[string]any{"catalog": a.cat.Root, "id": a.cat.Meta.ID, "version": a.cat.Meta.Version, "hash": a.cat.Hash(),
|
||||||
|
"entries": len(a.ix.Entries), "byKind": kinds, "manualTopics": len(a.ix.Topics), "sourcesNotAvailable": a.ix.Missing}
|
||||||
|
if args[0] == "index" {
|
||||||
|
st["index"] = a.ix.Entries
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(st)
|
||||||
|
}
|
||||||
|
a.say("catalog %s %s (%s)\nentries %d\n", a.cat.Meta.ID, a.cat.Meta.Version, a.cat.Root, len(a.ix.Entries))
|
||||||
|
for _, k := range sortedKeys(kinds) {
|
||||||
|
a.say(" %-12s %d\n", k, kinds[k])
|
||||||
|
}
|
||||||
|
if len(a.ix.Missing) > 0 {
|
||||||
|
a.say("not available locally: %s\n", strings.Join(a.ix.Missing, ", "))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case "backlinks":
|
||||||
|
fs := a.flags("knowledge backlinks")
|
||||||
|
if err := a.parse(fs, args[1:]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s knowledge backlinks <yetano:ref>", a.env.Program)
|
||||||
|
}
|
||||||
|
bl := a.ix.BacklinksOf(fs.Arg(0))
|
||||||
|
if a.jsonOut {
|
||||||
|
if bl == nil {
|
||||||
|
bl = []string{}
|
||||||
|
}
|
||||||
|
return a.printJSON(bl)
|
||||||
|
}
|
||||||
|
for _, b := range bl {
|
||||||
|
a.say("%s\n", b)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return a.usage("knowledge " + args[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
// open shows a reference in the terminal (REF-04): manual text, a
|
||||||
|
// solution's details, or where it lives.
|
||||||
|
func (a *app) open(args []string) error {
|
||||||
|
fs := a.flags("open")
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s open <yetano:reference>", a.env.Program)
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
r := fs.Arg(0)
|
||||||
|
if !strings.HasPrefix(r, "yetano:") {
|
||||||
|
r = "yetano:" + r
|
||||||
|
}
|
||||||
|
res, err := a.ix.Resolve(r)
|
||||||
|
if err != nil {
|
||||||
|
return fail(ExitUsage, "%v", err)
|
||||||
|
}
|
||||||
|
if !res.Exists {
|
||||||
|
return fmt.Errorf("%w: %s", engine.ErrNotFound, r)
|
||||||
|
}
|
||||||
|
if !res.SectionExists {
|
||||||
|
return fmt.Errorf("%w: %s has no such section", engine.ErrNotFound, r)
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(res)
|
||||||
|
}
|
||||||
|
p, _ := ref.Parse(r)
|
||||||
|
switch p.Kind {
|
||||||
|
case ref.Solution:
|
||||||
|
return a.show([]string{p.Path[0]}, false)
|
||||||
|
case ref.Task:
|
||||||
|
return a.show([]string{p.Path[0]}, true)
|
||||||
|
case ref.Package:
|
||||||
|
return a.packageCmd([]string{p.Path[0]})
|
||||||
|
case ref.Manual:
|
||||||
|
if _, md, err := a.ix.Read(r); err == nil {
|
||||||
|
a.say("%s", md)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
case ref.Example:
|
||||||
|
if x := a.cat.Examples[p.Path[0]+"/"+p.Path[1]]; x != nil {
|
||||||
|
b, _ := engine.Marshal(x.Spec)
|
||||||
|
a.say("# %s\n%s", x.Meta.Title, b)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
case ref.Profile:
|
||||||
|
if pr := a.cat.Profiles[p.Path[0]+"/"+p.Path[1]]; pr != nil {
|
||||||
|
b, _ := engine.Marshal(pr.Spec)
|
||||||
|
a.say("# %s\n%s", firstNonEmpty(pr.Meta.Title, pr.Meta.ID), b)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
case ref.Capability:
|
||||||
|
a.say("%s -- %s\n", res.Title, res.Summary)
|
||||||
|
for _, pr := range a.cat.ProvidersOf(p.Path[0]) {
|
||||||
|
a.say(" provided by %s\n", pr)
|
||||||
|
}
|
||||||
|
for _, b := range a.ix.BacklinksOf(r) {
|
||||||
|
a.say(" used by %s\n", b)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
a.say("%s\n", res.Title)
|
||||||
|
if res.Summary != "" {
|
||||||
|
a.say("%s\n", wrap(res.Summary, 76, ""))
|
||||||
|
}
|
||||||
|
if res.Web != "" {
|
||||||
|
a.say("web: %s\n", res.Web)
|
||||||
|
}
|
||||||
|
if res.CLI != "" {
|
||||||
|
a.say("cli: %s\n", res.CLI)
|
||||||
|
}
|
||||||
|
if res.Note != "" {
|
||||||
|
a.say("note: %s\n", res.Note)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,494 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
"yetano.dev/yetano/core/solutions/engine"
|
||||||
|
"yetano.dev/yetano/core/solutions/ref"
|
||||||
|
"yetano.dev/yetano/core/solutions/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *app) setup(args []string, task bool) error {
|
||||||
|
cmd := "solution setup"
|
||||||
|
if task {
|
||||||
|
cmd = "task run"
|
||||||
|
}
|
||||||
|
fs := a.flags(cmd)
|
||||||
|
quick := fs.Bool("quick", false, "quick setup: only what is needed, recommended defaults")
|
||||||
|
guided := fs.Bool("guided", false, "guided setup: the relevant choices, with explanations")
|
||||||
|
advanced := fs.Bool("advanced", false, "advanced setup: every option")
|
||||||
|
presetName := fs.String("preset", "", "take answers from a saved preset")
|
||||||
|
example := fs.String("example", "", "start from an example of the solution")
|
||||||
|
answers := fs.String("answers", "", "start from the answers in a solution.yaml")
|
||||||
|
name := fs.String("name", "", "name of the instance (default: the solution ID)")
|
||||||
|
output := fs.String("output", "", "generate the files into this directory when complete")
|
||||||
|
save := fs.Bool("save", false, "save the instance (incomplete: as a draft session)")
|
||||||
|
nonInteractive := fs.Bool("non-interactive", false, "never ask; fail listing what is missing (the default without a terminal)")
|
||||||
|
platform := fs.String("platform", "", "target platform (linux, freebsd, darwin, windows)")
|
||||||
|
force := fs.Bool("force", false, "with --output: overwrite files changed by hand")
|
||||||
|
var sets multi
|
||||||
|
fs.Var(&sets, "set", "answer as question=value (repeatable; lists comma-separated)")
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s %s <id> [--quick|--guided|--advanced] [--set q=v]...", a.env.Program, cmd)
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s, err := a.lookup(fs.Arg(0), task)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
mode := catalog.LevelQuick
|
||||||
|
switch {
|
||||||
|
case *advanced:
|
||||||
|
mode = catalog.LevelAdvanced
|
||||||
|
case *guided:
|
||||||
|
mode = catalog.LevelGuided
|
||||||
|
}
|
||||||
|
nm := firstNonEmpty(*name, s.Meta.ID)
|
||||||
|
if err := store.ValidName(nm); err != nil {
|
||||||
|
return fail(ExitUsage, "%v", err)
|
||||||
|
}
|
||||||
|
in := engine.NewInstance(nm, s, mode)
|
||||||
|
in.Spec.Locale = a.locale
|
||||||
|
in.Spec.Platform = *platform
|
||||||
|
if *example != "" {
|
||||||
|
x := a.cat.Examples[s.Meta.ID+"/"+*example]
|
||||||
|
if x == nil {
|
||||||
|
return fmt.Errorf("%w: example %s of %s", engine.ErrNotFound, *example, s.Meta.ID)
|
||||||
|
}
|
||||||
|
for k, v := range x.Spec.Parameters {
|
||||||
|
in.Spec.Parameters[k] = v
|
||||||
|
}
|
||||||
|
if !*quick && !*guided && !*advanced && x.Spec.Mode != "" {
|
||||||
|
in.Spec.Mode = x.Spec.Mode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if *answers != "" {
|
||||||
|
f, err := os.Open(*answers)
|
||||||
|
if err != nil {
|
||||||
|
return fail(ExitNotFound, "%v", err)
|
||||||
|
}
|
||||||
|
from, err := engine.ReadInstance(f)
|
||||||
|
f.Close()
|
||||||
|
if err != nil {
|
||||||
|
return fail(ExitUsage, "%s: %v", *answers, err)
|
||||||
|
}
|
||||||
|
for k, v := range from.Spec.Parameters {
|
||||||
|
in.Spec.Parameters[k] = v
|
||||||
|
}
|
||||||
|
in.Spec.Overrides = from.Spec.Overrides
|
||||||
|
}
|
||||||
|
for _, kv := range sets {
|
||||||
|
k, v, ok := strings.Cut(kv, "=")
|
||||||
|
if !ok {
|
||||||
|
return fail(ExitUsage, "--set %q: want question=value", kv)
|
||||||
|
}
|
||||||
|
if q, _ := s.Question(k); q == nil {
|
||||||
|
return fail(ExitUsage, "--set %s: %s has no question %q", kv, s.Meta.ID, k)
|
||||||
|
}
|
||||||
|
in.Spec.Parameters[k] = v
|
||||||
|
}
|
||||||
|
var preset *engine.Preset
|
||||||
|
if *presetName != "" {
|
||||||
|
preset, err = a.presetFor(in, *presetName)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
in.Spec.Preset = preset.Metadata.Name
|
||||||
|
if preset.Spec.Mode != "" && !*quick && !*guided && !*advanced {
|
||||||
|
in.Spec.Mode = preset.Spec.Mode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
kind := ref.Solution
|
||||||
|
if task {
|
||||||
|
kind = ref.Task
|
||||||
|
}
|
||||||
|
_ = a.store.Touch(ref.For(kind, s.Meta.ID), nm)
|
||||||
|
|
||||||
|
if a.env.Interactive && !*nonInteractive && !a.jsonOut {
|
||||||
|
return a.wizard(in, preset, *output, *force)
|
||||||
|
}
|
||||||
|
st, err := a.evaluate(in, preset)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !st.Complete {
|
||||||
|
if *save {
|
||||||
|
in.Kind = catalog.KindSession
|
||||||
|
if err := a.store.SaveInstance(in); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.note("saved draft %s\n", nm)
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
_ = a.printJSON(map[string]any{"complete": false, "missing": st.Progress.Missing, "messages": st.Messages, "state": st})
|
||||||
|
return exitErr{ExitUsage, errors.New("")}
|
||||||
|
}
|
||||||
|
for _, m := range st.Progress.Missing {
|
||||||
|
q := findQ(st, m)
|
||||||
|
a.note("missing: %s (%s) -- --set %s=...\n", m, q.Title, m)
|
||||||
|
}
|
||||||
|
for _, q := range st.Questions {
|
||||||
|
for _, e := range q.Errors {
|
||||||
|
a.note("invalid: %s: %s\n", q.ID, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a.printMessages(st)
|
||||||
|
return fmt.Errorf("%w (%s)", engine.ErrIncomplete, strings.Join(st.Progress.Missing, ", "))
|
||||||
|
}
|
||||||
|
if *save {
|
||||||
|
in.Kind = catalog.KindInstance
|
||||||
|
if err := a.store.SaveInstance(in); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.note("saved instance %s\n", nm)
|
||||||
|
}
|
||||||
|
if *output != "" {
|
||||||
|
return a.writeOut(in, st, *output, *force, false, false)
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(st)
|
||||||
|
}
|
||||||
|
a.summary(st)
|
||||||
|
b, _ := engine.Marshal(in)
|
||||||
|
a.note("\nAnswers (save with --save, or as solution.yaml for '%s solution generate --file'):\n", a.env.Program)
|
||||||
|
a.say("%s", b)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func findQ(st *engine.State, id string) engine.QuestionState {
|
||||||
|
for _, q := range st.Questions {
|
||||||
|
if q.ID == id {
|
||||||
|
return q
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return engine.QuestionState{ID: id}
|
||||||
|
}
|
||||||
|
|
||||||
|
// summary prints "YOUR SOLUTION" (CLI-02).
|
||||||
|
func (a *app) summary(st *engine.State) {
|
||||||
|
w := a.env.Stdout
|
||||||
|
line := strings.Repeat("-", 60)
|
||||||
|
fmt.Fprintf(w, "%s\nYOUR SOLUTION: %s\n\n", line, st.Solution.Title)
|
||||||
|
fmt.Fprintf(w, "Packages:\n")
|
||||||
|
for _, p := range st.Packages {
|
||||||
|
if p.Selected {
|
||||||
|
var mods []string
|
||||||
|
for _, m := range p.Modules {
|
||||||
|
if m.Enabled && m.Program != "" {
|
||||||
|
mods = append(mods, m.Program)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " + %-10s %s\n", p.ID, strings.Join(mods, " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, p := range st.Packages {
|
||||||
|
if !p.Selected {
|
||||||
|
fmt.Fprintf(w, " ? %-10s recommended: %s\n", p.ID, strings.Join(p.Reasons, "; "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "\nCapabilities:\n")
|
||||||
|
for _, c := range st.Capabilities {
|
||||||
|
switch c.Status {
|
||||||
|
case engine.StRequired, engine.StSelected, engine.StExternal:
|
||||||
|
fmt.Fprintf(w, " + %s\n", c.Title)
|
||||||
|
case engine.StRecommended:
|
||||||
|
fmt.Fprintf(w, " ? %s (recommended)\n", c.Title)
|
||||||
|
case engine.StMissing, engine.StConflicting:
|
||||||
|
fmt.Fprintf(w, " ! %s (%s)\n", c.Title, c.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "\nConfiguration: %d file(s)", len(st.Files))
|
||||||
|
if st.Complete {
|
||||||
|
fmt.Fprintf(w, ", complete\n")
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(w, ", INCOMPLETE: %s\n", strings.Join(st.Progress.Missing, ", "))
|
||||||
|
}
|
||||||
|
if len(st.Messages) > 0 {
|
||||||
|
fmt.Fprintf(w, "\nNotes:\n")
|
||||||
|
for _, m := range st.Messages {
|
||||||
|
fmt.Fprintf(w, " %-7s %s\n", strings.ToUpper(m.Severity), wrap(m.Text, 66, " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nc := 0
|
||||||
|
for _, c := range st.Checks {
|
||||||
|
if c.Status == engine.CheckNotChecked {
|
||||||
|
nc++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if nc > 0 {
|
||||||
|
fmt.Fprintf(w, "\nEnvironment: %d check(s) not run yet -- '%s solution doctor' runs them on the target.\n", nc, a.env.Program)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "%s\n", line)
|
||||||
|
}
|
||||||
|
|
||||||
|
// wizard is the interactive CLI wizard (CLI-02). All decisions come from
|
||||||
|
// the engine: this only asks what the state says, in its order.
|
||||||
|
func (a *app) wizard(in *engine.Instance, preset *engine.Preset, output string, force bool) error {
|
||||||
|
r := bufio.NewReader(a.env.Stdin)
|
||||||
|
w := a.env.Stdout
|
||||||
|
done := map[string]bool{}
|
||||||
|
var history []string
|
||||||
|
st, err := a.evaluate(in, preset)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "Yetano Solutions Guide\n%s\n%s (%s setup)\n\n", strings.Repeat("-", 40), st.Solution.Title, st.Mode)
|
||||||
|
fmt.Fprintf(w, "Enter keeps the value in [brackets]. ? explains, m manual, a architecture, b back, q save and quit.\n\n")
|
||||||
|
for {
|
||||||
|
st, err = a.evaluate(in, preset)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var q *engine.QuestionState
|
||||||
|
for i := range st.Questions {
|
||||||
|
x := &st.Questions[i]
|
||||||
|
if x.Visible && x.Asked && !done[x.ID] {
|
||||||
|
q = x
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if q == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
step, total := 0, 0
|
||||||
|
for _, x := range st.Questions {
|
||||||
|
if x.Visible && x.Asked {
|
||||||
|
total++
|
||||||
|
if done[x.ID] || x.ID == q.ID {
|
||||||
|
step++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "[%d/%d] %s\n", step, total, q.Title)
|
||||||
|
if q.Help != "" {
|
||||||
|
fmt.Fprintf(w, " %s\n", wrap(q.Help, 70, " "))
|
||||||
|
}
|
||||||
|
for i, o := range q.Options {
|
||||||
|
mark := " "
|
||||||
|
if !o.Enabled {
|
||||||
|
mark = "x"
|
||||||
|
}
|
||||||
|
rec := ""
|
||||||
|
if o.Recommended {
|
||||||
|
rec = " (recommended)"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " %s %d. %s%s\n", mark, i+1, o.Title, rec)
|
||||||
|
if !o.Enabled && o.Disabled != "" {
|
||||||
|
fmt.Fprintf(w, " not available: %s\n", wrap(o.Disabled, 62, " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def := ""
|
||||||
|
if q.Value != nil {
|
||||||
|
def = displayValue(q, q.Value)
|
||||||
|
}
|
||||||
|
prompt := "> "
|
||||||
|
if def != "" {
|
||||||
|
prompt = fmt.Sprintf("[%s] > ", def)
|
||||||
|
}
|
||||||
|
fmt.Fprint(w, prompt)
|
||||||
|
line, err := a.readLine(r)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(w)
|
||||||
|
return a.saveDraft(in, "input ended")
|
||||||
|
}
|
||||||
|
switch line {
|
||||||
|
case "?":
|
||||||
|
a.explain(q)
|
||||||
|
continue
|
||||||
|
case "m":
|
||||||
|
a.showManual(q, st)
|
||||||
|
continue
|
||||||
|
case "a":
|
||||||
|
fmt.Fprintf(w, "\n%s\n", engine.GraphText(st.Graph))
|
||||||
|
continue
|
||||||
|
case "b":
|
||||||
|
if len(history) > 0 {
|
||||||
|
last := history[len(history)-1]
|
||||||
|
history = history[:len(history)-1]
|
||||||
|
delete(done, last)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
case "q":
|
||||||
|
return a.saveDraft(in, "")
|
||||||
|
case "":
|
||||||
|
if q.Value == nil && q.Required {
|
||||||
|
fmt.Fprintf(w, " an answer is needed\n")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if q.Value != nil {
|
||||||
|
in.Spec.Parameters[q.ID] = q.Value
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
in.Spec.Parameters[q.ID] = line
|
||||||
|
}
|
||||||
|
st2, err := a.evaluate(in, preset)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if q2 := findQ(st2, q.ID); len(q2.Errors) > 0 {
|
||||||
|
fmt.Fprintf(w, " %s\n", strings.Join(q2.Errors, "; "))
|
||||||
|
delete(in.Spec.Parameters, q.ID)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, s := range st2.Stale {
|
||||||
|
if s.Question == q.ID {
|
||||||
|
fmt.Fprintf(w, " %s\n", s.Reason)
|
||||||
|
delete(in.Spec.Parameters, q.ID)
|
||||||
|
goto next
|
||||||
|
}
|
||||||
|
}
|
||||||
|
done[q.ID] = true
|
||||||
|
history = append(history, q.ID)
|
||||||
|
fmt.Fprintln(w)
|
||||||
|
next:
|
||||||
|
}
|
||||||
|
a.summary(st)
|
||||||
|
for {
|
||||||
|
fmt.Fprintf(w, "\nActions:\n 1. Show configuration\n 2. Show architecture\n 3. Show plan\n 4. Read related manual\n 5. Save solution\n 6. Export configuration (generate files)\n 7. Change an answer\n 8. Quit\n> ")
|
||||||
|
line, err := a.readLine(r)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
switch line {
|
||||||
|
case "1":
|
||||||
|
for _, f := range st.Files {
|
||||||
|
fmt.Fprintf(w, "--- %s\n%s\n", f.Path, f.Content)
|
||||||
|
}
|
||||||
|
case "2":
|
||||||
|
fmt.Fprintf(w, "%s", engine.GraphText(st.Graph))
|
||||||
|
case "3":
|
||||||
|
for i, s := range st.Steps {
|
||||||
|
fmt.Fprintf(w, "%3d. [%s] %s\n", i+1, s.Phase, s.Title)
|
||||||
|
if s.Run != "" {
|
||||||
|
fmt.Fprintf(w, " $ %s\n", s.Run)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "4":
|
||||||
|
for _, rf := range st.References {
|
||||||
|
if res, err := a.ix.Resolve(rf); err == nil {
|
||||||
|
fmt.Fprintf(w, " %s\n", refLine(res))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "5":
|
||||||
|
in.Kind = catalog.KindInstance
|
||||||
|
if !st.Complete {
|
||||||
|
in.Kind = catalog.KindSession
|
||||||
|
}
|
||||||
|
if err := a.store.SaveInstance(in); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "saved %s (%s)\n", in.Metadata.Name, in.Kind)
|
||||||
|
case "6":
|
||||||
|
dir := output
|
||||||
|
if dir == "" {
|
||||||
|
fmt.Fprintf(w, "directory [./%s] > ", in.Metadata.Name)
|
||||||
|
d, _ := a.readLine(r)
|
||||||
|
dir = firstNonEmpty(d, "./"+in.Metadata.Name)
|
||||||
|
}
|
||||||
|
if err := a.writeOut(in, st, dir, force, false, false); err != nil {
|
||||||
|
fmt.Fprintf(w, "error: %v\n", err)
|
||||||
|
}
|
||||||
|
case "7":
|
||||||
|
fmt.Fprintf(w, "question id > ")
|
||||||
|
id, _ := a.readLine(r)
|
||||||
|
if _, ok := in.Spec.Parameters[id]; ok || findQ(st, id).Title != "" {
|
||||||
|
delete(in.Spec.Parameters, id)
|
||||||
|
return a.wizard(in, preset, output, force)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "no such question\n")
|
||||||
|
case "8", "q", "":
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) saveDraft(in *engine.Instance, why string) error {
|
||||||
|
in.Kind = catalog.KindSession
|
||||||
|
if err := a.store.SaveInstance(in); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.note("saved the draft as %s; continue with '%s solution setup %s --answers <(%s solution instance export %s)'\n",
|
||||||
|
in.Metadata.Name, a.env.Program, in.Spec.Solution.ID, a.env.Program, in.Metadata.Name)
|
||||||
|
if why != "" {
|
||||||
|
return fail(ExitUsage, "%s", why)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func displayValue(q *engine.QuestionState, v any) string {
|
||||||
|
if l, ok := v.([]any); ok {
|
||||||
|
var parts []string
|
||||||
|
for _, x := range l {
|
||||||
|
parts = append(parts, catalog.Scalar(x))
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ", ")
|
||||||
|
}
|
||||||
|
s := catalog.Scalar(v)
|
||||||
|
for i, o := range q.Options {
|
||||||
|
if o.ID == s {
|
||||||
|
return fmt.Sprintf("%d", i+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// explain is "Help me decide" (HELP-01/02).
|
||||||
|
func (a *app) explain(q *engine.QuestionState) {
|
||||||
|
w := a.env.Stdout
|
||||||
|
if q.Decide != "" {
|
||||||
|
fmt.Fprintf(w, "\n %s\n", wrap(q.Decide, 72, " "))
|
||||||
|
}
|
||||||
|
if q.Description != "" {
|
||||||
|
fmt.Fprintf(w, "\n %s\n", wrap(q.Description, 72, " "))
|
||||||
|
}
|
||||||
|
for _, o := range q.Options {
|
||||||
|
line := o.Title
|
||||||
|
if o.Description != "" {
|
||||||
|
line += ": " + o.Description
|
||||||
|
}
|
||||||
|
if o.Recommended && o.Reason != "" {
|
||||||
|
line += " Recommended: " + o.Reason
|
||||||
|
}
|
||||||
|
if !o.Enabled {
|
||||||
|
line += " Not available: " + o.Disabled
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " - %s\n", wrap(line, 70, " "))
|
||||||
|
}
|
||||||
|
if q.Recommended != nil && q.Reason != "" {
|
||||||
|
fmt.Fprintf(w, " Recommended: %v -- %s\n", q.Recommended, q.Reason)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) showManual(q *engine.QuestionState, st *engine.State) {
|
||||||
|
w := a.env.Stdout
|
||||||
|
refs := append([]string{}, q.References...)
|
||||||
|
for _, o := range q.Options {
|
||||||
|
refs = append(refs, o.References...)
|
||||||
|
}
|
||||||
|
refs = append(refs, st.References...)
|
||||||
|
for _, r := range refs {
|
||||||
|
if !strings.HasPrefix(r, "yetano:manual/") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
title, md, ok := a.ix.Excerpt(r, 30)
|
||||||
|
res, _ := a.ix.Resolve(r)
|
||||||
|
if !ok {
|
||||||
|
fmt.Fprintf(w, "\n %s\n\n", refLine(res))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "\n=== %s\n%s\n=== full text: %s\n\n", title, md, firstNonEmpty(res.CLI, res.File))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " no manual reference for this question\n")
|
||||||
|
}
|
||||||
@@ -0,0 +1,727 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
"yetano.dev/yetano/core/solutions/engine"
|
||||||
|
"yetano.dev/yetano/core/solutions/knowledge"
|
||||||
|
"yetano.dev/yetano/core/solutions/ref"
|
||||||
|
"yetano.dev/yetano/core/solutions/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
// multi is a repeatable flag.
|
||||||
|
type multi []string
|
||||||
|
|
||||||
|
func (m *multi) String() string { return strings.Join(*m, ",") }
|
||||||
|
func (m *multi) Set(s string) error { *m = append(*m, s); return nil }
|
||||||
|
|
||||||
|
func (a *app) solution(args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return a.usage("")
|
||||||
|
}
|
||||||
|
sub, rest := args[0], args[1:]
|
||||||
|
switch sub {
|
||||||
|
case "list", "ls":
|
||||||
|
return a.list(rest, false)
|
||||||
|
case "search":
|
||||||
|
return a.searchCmd(rest, []string{ref.Solution, ref.Task, ref.Example})
|
||||||
|
case "show":
|
||||||
|
return a.show(rest, false)
|
||||||
|
case "setup", "new":
|
||||||
|
return a.setup(rest, false)
|
||||||
|
case "state", "evaluate":
|
||||||
|
return a.stateCmd(rest)
|
||||||
|
case "generate":
|
||||||
|
return a.generate(rest)
|
||||||
|
case "validate":
|
||||||
|
return a.validate(rest)
|
||||||
|
case "plan":
|
||||||
|
return a.plan(rest)
|
||||||
|
case "doctor":
|
||||||
|
return a.doctor(rest)
|
||||||
|
case "config":
|
||||||
|
return a.config(rest)
|
||||||
|
case "architecture", "arch":
|
||||||
|
return a.architecture(rest)
|
||||||
|
case "handbook":
|
||||||
|
return a.handbook(rest)
|
||||||
|
case "package":
|
||||||
|
return a.packageCmd(rest)
|
||||||
|
case "instance", "instances":
|
||||||
|
return a.instance(rest)
|
||||||
|
case "preset", "presets":
|
||||||
|
return a.preset(rest)
|
||||||
|
case "catalog":
|
||||||
|
return a.catalogCmd(rest)
|
||||||
|
}
|
||||||
|
return a.usage("solution " + sub)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) task(args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return a.usage("")
|
||||||
|
}
|
||||||
|
sub, rest := args[0], args[1:]
|
||||||
|
switch sub {
|
||||||
|
case "list", "ls":
|
||||||
|
return a.list(rest, true)
|
||||||
|
case "search":
|
||||||
|
return a.searchCmd(rest, []string{ref.Task})
|
||||||
|
case "show":
|
||||||
|
return a.show(rest, true)
|
||||||
|
case "run", "setup":
|
||||||
|
return a.setup(rest, true)
|
||||||
|
}
|
||||||
|
return a.usage("task " + sub)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- list, show ------------------------------------------------------------
|
||||||
|
|
||||||
|
type listItem struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Summary string `json:"summary"`
|
||||||
|
Category string `json:"category,omitempty"`
|
||||||
|
Status catalog.Support `json:"status"`
|
||||||
|
Featured bool `json:"featured,omitempty"`
|
||||||
|
TaskKind string `json:"taskKind,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) items(tasks bool) []listItem {
|
||||||
|
m := a.cat.Solutions
|
||||||
|
if tasks {
|
||||||
|
m = a.cat.Tasks
|
||||||
|
}
|
||||||
|
var out []listItem
|
||||||
|
for _, id := range catalog.SortedIDs(m) {
|
||||||
|
s := m[id]
|
||||||
|
e := a.ix.Entry(ref.For(map[bool]string{false: ref.Solution, true: ref.Task}[tasks], id))
|
||||||
|
title, summary := s.Meta.Title, s.Meta.Summary
|
||||||
|
if e != nil {
|
||||||
|
title, summary = e.Title, e.Summary
|
||||||
|
}
|
||||||
|
st := s.Meta.Status
|
||||||
|
if st == "" {
|
||||||
|
st = catalog.Supported
|
||||||
|
}
|
||||||
|
out = append(out, listItem{ID: id, Kind: strings.ToLower(s.Kind), Title: a.tr(s.Meta.Translations, "title", title),
|
||||||
|
Summary: a.tr(s.Meta.Translations, "summary", summary), Category: s.Meta.Category, Status: st, Featured: s.Meta.Featured, TaskKind: s.Spec.Kind})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) list(args []string, tasks bool) error {
|
||||||
|
fs := a.flags("list")
|
||||||
|
category := fs.String("category", "", "only this category")
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
items := a.items(tasks)
|
||||||
|
if *category != "" {
|
||||||
|
var f []listItem
|
||||||
|
for _, it := range items {
|
||||||
|
if it.Category == *category {
|
||||||
|
f = append(f, it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items = f
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
if items == nil {
|
||||||
|
items = []listItem{}
|
||||||
|
}
|
||||||
|
return a.printJSON(items)
|
||||||
|
}
|
||||||
|
for _, it := range items {
|
||||||
|
mark := ""
|
||||||
|
if it.Status != catalog.Supported {
|
||||||
|
mark = " [" + string(it.Status) + "]"
|
||||||
|
}
|
||||||
|
a.say("%-22s %s%s\n%-22s %s\n", it.ID, it.Title, mark, "", wrap(it.Summary, 70, strings.Repeat(" ", 23)))
|
||||||
|
}
|
||||||
|
if len(items) == 0 {
|
||||||
|
a.note("nothing found\n")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) lookup(id string, tasks bool) (*catalog.Solution, error) {
|
||||||
|
s := a.cat.Lookup(id)
|
||||||
|
if s == nil {
|
||||||
|
var hint string
|
||||||
|
if groups := a.ix.Search(id, knowledge.SearchOptions{Kinds: []string{ref.Solution, ref.Task}, Limit: 3}); len(groups) > 0 {
|
||||||
|
hint = " -- did you mean " + strings.TrimPrefix(strings.TrimPrefix(groups[0].Hits[0].Ref, "yetano:solution/"), "yetano:task/") + "?"
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("%w: %s%s", engine.ErrNotFound, id, hint)
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type showOut struct {
|
||||||
|
listItem
|
||||||
|
Goals []string `json:"goals,omitempty"`
|
||||||
|
Scenarios []string `json:"scenarios,omitempty"`
|
||||||
|
NotFor []string `json:"notFor,omitempty"`
|
||||||
|
Outcome string `json:"outcome,omitempty"`
|
||||||
|
Packages []string `json:"packages"`
|
||||||
|
Capabilities catalog.CapSets `json:"capabilities"`
|
||||||
|
Platforms []string `json:"platforms,omitempty"`
|
||||||
|
Questions int `json:"questions"`
|
||||||
|
Quick []string `json:"quickQuestions"`
|
||||||
|
Examples []map[string]string `json:"examples"`
|
||||||
|
References []knowledge.Resolution `json:"references"`
|
||||||
|
Related []string `json:"related,omitempty"`
|
||||||
|
Backlinks []string `json:"backlinks,omitempty"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) show(args []string, tasks bool) error {
|
||||||
|
fs := a.flags("show")
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s %s show <id>", a.env.Program, map[bool]string{false: "solution", true: "task"}[tasks])
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s, err := a.lookup(fs.Arg(0), tasks)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var item listItem
|
||||||
|
for _, it := range a.items(s.IsTask()) {
|
||||||
|
if it.ID == s.Meta.ID {
|
||||||
|
item = it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o := showOut{listItem: item, Goals: s.Spec.Goals, Scenarios: s.Spec.Scenarios, NotFor: s.Spec.NotFor,
|
||||||
|
Capabilities: s.Spec.Capabilities, Platforms: s.Spec.Platforms, Questions: len(s.Spec.Questions), Related: s.Spec.Related,
|
||||||
|
Version: s.Meta.Version, Examples: []map[string]string{}}
|
||||||
|
if bp := a.cat.BigPicture; bp != nil {
|
||||||
|
if g, ok := bp.Stories[s.Spec.BigPicture]; ok {
|
||||||
|
o.Outcome = g.Outcome
|
||||||
|
}
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, p := range s.Spec.Packages {
|
||||||
|
if !seen[p.ID] {
|
||||||
|
seen[p.ID] = true
|
||||||
|
o.Packages = append(o.Packages, p.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, q := range s.Spec.Questions {
|
||||||
|
if q.Level == "" || q.Level == catalog.LevelQuick {
|
||||||
|
o.Quick = append(o.Quick, q.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, k := range catalog.SortedIDs(a.cat.Examples) {
|
||||||
|
x := a.cat.Examples[k]
|
||||||
|
if x.Spec.Solution == s.Meta.ID {
|
||||||
|
o.Examples = append(o.Examples, map[string]string{"id": x.Meta.ID, "title": a.tr(x.Meta.Translations, "title", x.Meta.Title), "summary": x.Meta.Summary})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, r := range s.Spec.References.All() {
|
||||||
|
if res, err := a.ix.Resolve(r); err == nil {
|
||||||
|
o.References = append(o.References, res)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
kind := ref.Solution
|
||||||
|
if s.IsTask() {
|
||||||
|
kind = ref.Task
|
||||||
|
}
|
||||||
|
o.Backlinks = a.ix.BacklinksOf(ref.For(kind, s.Meta.ID))
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(o)
|
||||||
|
}
|
||||||
|
a.say("%s (%s %s, %s)\n\n", o.Title, o.ID, o.Version, o.Status)
|
||||||
|
a.say("%s\n", wrap(o.Summary, 76, ""))
|
||||||
|
if o.Outcome != "" {
|
||||||
|
a.say("\nResult: %s\n", wrap(o.Outcome, 76, " "))
|
||||||
|
}
|
||||||
|
section := func(title string, list []string) {
|
||||||
|
if len(list) > 0 {
|
||||||
|
a.say("\n%s\n", title)
|
||||||
|
for _, l := range list {
|
||||||
|
a.say(" - %s\n", wrap(l, 72, " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
section("Goals", o.Goals)
|
||||||
|
section("Good for", o.Scenarios)
|
||||||
|
section("Not for", o.NotFor)
|
||||||
|
a.say("\nPackages: %s\n", strings.Join(o.Packages, ", "))
|
||||||
|
a.say("Needs: %s\n", strings.Join(o.Capabilities.Required, ", "))
|
||||||
|
if len(o.Platforms) > 0 {
|
||||||
|
a.say("Platforms: %s\n", strings.Join(o.Platforms, ", "))
|
||||||
|
}
|
||||||
|
a.say("Questions: %d (quick setup asks %d)\n", o.Questions, len(o.Quick))
|
||||||
|
if len(o.Examples) > 0 {
|
||||||
|
a.say("\nExamples\n")
|
||||||
|
for _, x := range o.Examples {
|
||||||
|
a.say(" %-16s %s\n", x["id"], x["title"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(o.References) > 0 {
|
||||||
|
a.say("\nRead more\n")
|
||||||
|
for _, r := range o.References {
|
||||||
|
a.say(" %s\n", refLine(r))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cmd := "solution setup"
|
||||||
|
if s.IsTask() {
|
||||||
|
cmd = "task run"
|
||||||
|
}
|
||||||
|
a.say("\nStart: %s %s %s [--quick|--guided|--advanced] [--example <id>]\n", a.env.Program, cmd, o.ID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func refLine(r knowledge.Resolution) string {
|
||||||
|
where := r.Web
|
||||||
|
if r.CLI != "" && (where == "" || r.Kind == ref.Manual) {
|
||||||
|
where = r.CLI
|
||||||
|
}
|
||||||
|
title := r.Title
|
||||||
|
if title == "" {
|
||||||
|
title = r.Ref
|
||||||
|
}
|
||||||
|
if !r.Exists {
|
||||||
|
title += " (missing)"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%-40s %s", title, where)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- instances from files or the store ----------------------------------------
|
||||||
|
|
||||||
|
// instanceFrom reads --file, or a stored instance named by the first argument.
|
||||||
|
func (a *app) instanceFrom(file string, fs *flag.FlagSet) (*engine.Instance, error) {
|
||||||
|
if file != "" {
|
||||||
|
var f *os.File
|
||||||
|
var err error
|
||||||
|
if file == "-" {
|
||||||
|
b := bufio.NewReader(a.env.Stdin)
|
||||||
|
in, err := engine.ReadInstance(b)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fail(ExitUsage, "stdin: %v", err)
|
||||||
|
}
|
||||||
|
return in, nil
|
||||||
|
}
|
||||||
|
f, err = os.Open(file)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fail(ExitNotFound, "%v", err)
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
in, err := engine.ReadInstance(f)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fail(ExitUsage, "%s: %v", file, err)
|
||||||
|
}
|
||||||
|
return in, nil
|
||||||
|
}
|
||||||
|
if fs.NArg() < 1 {
|
||||||
|
return nil, fail(ExitUsage, "name a saved instance or pass --file <solution.yaml>")
|
||||||
|
}
|
||||||
|
return a.store.LoadInstance(fs.Arg(0))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) presetFor(in *engine.Instance, name string) (*engine.Preset, error) {
|
||||||
|
if name == "" {
|
||||||
|
name = in.Spec.Preset
|
||||||
|
}
|
||||||
|
if name == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(name, ".yaml") || strings.Contains(name, string(filepath.Separator)) {
|
||||||
|
f, err := os.Open(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
return engine.ReadPreset(f)
|
||||||
|
}
|
||||||
|
return a.store.LoadPreset(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) evaluate(in *engine.Instance, preset *engine.Preset) (*engine.State, error) {
|
||||||
|
if in.Spec.Locale == "" {
|
||||||
|
in.Spec.Locale = a.locale
|
||||||
|
}
|
||||||
|
return a.eng.Evaluate(in, preset)
|
||||||
|
}
|
||||||
|
|
||||||
|
// common flags of the commands that take an instance
|
||||||
|
type instFlags struct {
|
||||||
|
file *string
|
||||||
|
preset *string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) instFlags(fs *flag.FlagSet) instFlags {
|
||||||
|
return instFlags{
|
||||||
|
file: fs.String("file", "", "solution.yaml (SolutionInstance or WizardSession); - for stdin"),
|
||||||
|
preset: fs.String("preset", "", "preset name or file (default: the instance's)"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) stateOf(fs *flag.FlagSet, f instFlags) (*engine.Instance, *engine.State, error) {
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
in, err := a.instanceFrom(*f.file, fs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
p, err := a.presetFor(in, *f.preset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
st, err := a.evaluate(in, p)
|
||||||
|
return in, st, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// stateCmd prints the full engine state: the shared client API as JSON
|
||||||
|
// (API-01); GUI and web clients render exactly this.
|
||||||
|
func (a *app) stateCmd(args []string) error {
|
||||||
|
fs := a.flags("solution state")
|
||||||
|
f := a.instFlags(fs)
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.jsonOut = true
|
||||||
|
_, st, err := a.stateOf(fs, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return a.printJSON(st)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- generate, validate, plan -------------------------------------------------
|
||||||
|
|
||||||
|
func (a *app) generate(args []string) error {
|
||||||
|
fs := a.flags("solution generate")
|
||||||
|
f := a.instFlags(fs)
|
||||||
|
output := fs.String("output", "", "output directory (required)")
|
||||||
|
force := fs.Bool("force", false, "overwrite files changed by hand")
|
||||||
|
locked := fs.Bool("locked", false, "fail if the catalog changed the meaning since the last generation (solution.lock.yaml)")
|
||||||
|
dry := fs.Bool("dry-run", false, "list the files, write nothing")
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if *output == "" && !*dry {
|
||||||
|
return fail(ExitUsage, "--output <dir> is required")
|
||||||
|
}
|
||||||
|
in, st, err := a.stateOf(fs, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return a.writeOut(in, st, *output, *force, *locked, *dry)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) writeOut(in *engine.Instance, st *engine.State, dir string, force, locked, dry bool) error {
|
||||||
|
out, err := a.eng.Generate(st, in, a.ix, false)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if dir != "" && !dry {
|
||||||
|
if prev, err := engine.ReadLock(dir); err == nil && prev != nil {
|
||||||
|
if drift := engine.LockDrift(prev, out.Lock); len(drift) > 0 {
|
||||||
|
if locked {
|
||||||
|
return fail(ExitConflict, "the catalog changed since the last generation: %s (run without --locked to accept)", strings.Join(drift, "; "))
|
||||||
|
}
|
||||||
|
a.note("note: since the last generation: %s\n", strings.Join(drift, "; "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := engine.Write(dir, out, force); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(map[string]any{"output": dir, "dryRun": dry, "files": out.Files, "complete": st.Complete, "messages": st.Messages})
|
||||||
|
}
|
||||||
|
verb := "wrote"
|
||||||
|
if dry {
|
||||||
|
verb = "would write"
|
||||||
|
}
|
||||||
|
a.note("%s %d files to %s\n", verb, len(out.Files), dir)
|
||||||
|
for _, f := range out.Files {
|
||||||
|
a.say(" %s\n", f.Path)
|
||||||
|
}
|
||||||
|
a.printMessages(st)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) printMessages(st *engine.State) {
|
||||||
|
for _, m := range st.Messages {
|
||||||
|
a.note("%-7s %s\n", strings.ToUpper(m.Severity), wrap(m.Text, 70, " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate: is the instance complete and valid; with --native also run
|
||||||
|
// the programs' own validators on a generated directory.
|
||||||
|
func (a *app) validate(args []string) error {
|
||||||
|
fs := a.flags("solution validate")
|
||||||
|
f := a.instFlags(fs)
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, st, err := a.stateOf(fs, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
type qerr struct {
|
||||||
|
Question string `json:"question"`
|
||||||
|
Errors []string `json:"errors"`
|
||||||
|
}
|
||||||
|
var qerrs []qerr
|
||||||
|
for _, q := range st.Questions {
|
||||||
|
if len(q.Errors) > 0 {
|
||||||
|
qerrs = append(qerrs, qerr{q.ID, q.Errors})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
if err := a.printJSON(map[string]any{"complete": st.Complete, "missing": st.Progress.Missing, "errors": qerrs, "stale": st.Stale, "messages": st.Messages}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for _, q := range qerrs {
|
||||||
|
a.say("ERROR %s: %s\n", q.Question, strings.Join(q.Errors, "; "))
|
||||||
|
}
|
||||||
|
for _, m := range st.Progress.Missing {
|
||||||
|
a.say("MISSING %s\n", m)
|
||||||
|
}
|
||||||
|
for _, s := range st.Stale {
|
||||||
|
a.say("STALE %s=%v: %s\n", s.Question, s.Value, s.Reason)
|
||||||
|
}
|
||||||
|
a.printMessages(st)
|
||||||
|
if st.Complete {
|
||||||
|
a.say("valid: %s is complete\n", st.Solution.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !st.Complete {
|
||||||
|
return exitErr{ExitError, errors.New("")}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) plan(args []string) error {
|
||||||
|
fs := a.flags("solution plan")
|
||||||
|
f := a.instFlags(fs)
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, st, err := a.stateOf(fs, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p := engine.PlanOf(st)
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(p)
|
||||||
|
}
|
||||||
|
a.say("Plan for %s (%s) -- nothing is executed by the guide.\n", firstNonEmpty(st.Instance, st.Solution.ID), p.Spec.Solution)
|
||||||
|
phase := ""
|
||||||
|
for i, s := range p.Spec.Steps {
|
||||||
|
if s.Phase != phase {
|
||||||
|
phase = s.Phase
|
||||||
|
a.say("\n%s\n", strings.ToUpper(phase))
|
||||||
|
}
|
||||||
|
mark := " "
|
||||||
|
if s.Mutating {
|
||||||
|
mark = "*"
|
||||||
|
}
|
||||||
|
a.say("%3d.%s %s\n", i+1, mark, s.Title)
|
||||||
|
if s.Run != "" {
|
||||||
|
a.say(" $ %s\n", s.Run)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a.say("\n* changes the system\n")
|
||||||
|
if !st.Complete {
|
||||||
|
a.printMessages(st)
|
||||||
|
return fail(ExitUsage, "the solution is incomplete: %s", strings.Join(st.Progress.Missing, ", "))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstNonEmpty(a ...string) string {
|
||||||
|
for _, s := range a {
|
||||||
|
if s != "" {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- config, architecture, handbook ------------------------------------------
|
||||||
|
|
||||||
|
func (a *app) config(args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution config show|explain ...", a.env.Program)
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "show":
|
||||||
|
fs := a.flags("solution config show")
|
||||||
|
f := a.instFlags(fs)
|
||||||
|
fs.Bool("effective", true, "show the effective, merged configuration (the default)")
|
||||||
|
origins := fs.Bool("origins", false, "show where each value comes from")
|
||||||
|
if err := a.parse(fs, args[1:]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, st, err := a.stateOf(fs, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(st.Files)
|
||||||
|
}
|
||||||
|
for _, file := range st.Files {
|
||||||
|
a.say("--- %s\n%s\n", file.Path, file.Content)
|
||||||
|
if *origins {
|
||||||
|
for _, k := range sortedKeys(file.Origins) {
|
||||||
|
o := file.Origins[k]
|
||||||
|
a.say(" %-40s %s %s\n", k, o.Source, strings.Join(o.Params, ","))
|
||||||
|
}
|
||||||
|
a.say("\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case "explain":
|
||||||
|
fs := a.flags("solution config explain")
|
||||||
|
f := a.instFlags(fs)
|
||||||
|
if err := a.parse(fs, args[1:]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// [instance] <file> <path>
|
||||||
|
pos := fs.Args()
|
||||||
|
var file, path string
|
||||||
|
switch {
|
||||||
|
case *f.file != "" && len(pos) == 2:
|
||||||
|
file, path = pos[0], pos[1]
|
||||||
|
case *f.file == "" && len(pos) == 3:
|
||||||
|
file, path = pos[1], pos[2]
|
||||||
|
default:
|
||||||
|
return fail(ExitUsage, "usage: %s solution config explain <instance>|--file f <file> <path> (e.g. yamase/yamase.yaml tls.cert-file)", a.env.Program)
|
||||||
|
}
|
||||||
|
_, st, err := a.stateOf(fs, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ex := engine.Explain(st, file, path)
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(ex)
|
||||||
|
}
|
||||||
|
if !ex.Found {
|
||||||
|
return fail(ExitNotFound, "%s: %s is not set by the guide (the program's built-in default applies)", ex.File, path)
|
||||||
|
}
|
||||||
|
a.say("%s %s\n set by %s (%s layer)\n", ex.File, path, ex.Origin.Source, ex.Origin.Layer)
|
||||||
|
for _, p := range sortedKeys(ex.Answers) {
|
||||||
|
a.say(" uses answer %s = %v (%s)\n", p, ex.Answers[p], ex.Origins[p])
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return a.usage("solution config " + args[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) architecture(args []string) error {
|
||||||
|
fs := a.flags("solution architecture")
|
||||||
|
f := a.instFlags(fs)
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, st, err := a.stateOf(fs, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(st.Graph)
|
||||||
|
}
|
||||||
|
a.say("%s", engine.GraphText(st.Graph))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) handbook(args []string) error {
|
||||||
|
fs := a.flags("solution handbook")
|
||||||
|
f := a.instFlags(fs)
|
||||||
|
output := fs.String("output", "", "directory to write the handbook to (default: print index)")
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, st, err := a.stateOf(fs, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pages := a.eng.Handbook(st, a.ix)
|
||||||
|
if *output == "" {
|
||||||
|
for _, p := range pages {
|
||||||
|
a.say("%s\n", p.Content)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, p := range pages {
|
||||||
|
path := filepath.Join(*output, filepath.FromSlash(strings.TrimPrefix(p.Path, "handbook/")))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, p.Content, 0o644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a.note("wrote %d pages to %s\n", len(pages), *output)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *app) packageCmd(args []string) error {
|
||||||
|
fs := a.flags("solution package")
|
||||||
|
if err := a.parse(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := a.load(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return fail(ExitUsage, "usage: %s solution package <id>", a.env.Program)
|
||||||
|
}
|
||||||
|
p := a.cat.Packages[fs.Arg(0)]
|
||||||
|
if p == nil {
|
||||||
|
return fmt.Errorf("%w: package %s", engine.ErrNotFound, fs.Arg(0))
|
||||||
|
}
|
||||||
|
r := ref.For(ref.Package, p.Meta.ID)
|
||||||
|
back := a.ix.BacklinksOf(r)
|
||||||
|
if a.jsonOut {
|
||||||
|
return a.printJSON(map[string]any{"package": p, "summary": a.eng.PackageSummary(p.Meta.ID), "usedBy": back})
|
||||||
|
}
|
||||||
|
a.say("%s -- %s\n\n", p.Meta.ID, wrap(a.eng.PackageSummary(p.Meta.ID), 70, " "))
|
||||||
|
for _, m := range p.Spec.Modules {
|
||||||
|
sup := ""
|
||||||
|
if m.Support != "" && m.Support != catalog.Supported {
|
||||||
|
sup = " [" + string(m.Support) + "]"
|
||||||
|
}
|
||||||
|
a.say(" %-14s %s%s\n", m.ID, m.Title, sup)
|
||||||
|
if len(m.Provides) > 0 {
|
||||||
|
a.say(" %-14s provides %s\n", "", strings.Join(m.Provides, ", "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(back) > 0 {
|
||||||
|
a.say("\nWhat would you like to do with %s?\n", p.Meta.ID)
|
||||||
|
for _, b := range back {
|
||||||
|
if strings.HasPrefix(b, "yetano:solution/") || strings.HasPrefix(b, "yetano:task/") {
|
||||||
|
res, _ := a.ix.Resolve(b)
|
||||||
|
a.say(" %-30s %s\n", res.Title, res.CLI)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if res, err := a.ix.Resolve(ref.For(ref.Microsite, p.Meta.ID)); err == nil && res.Web != "" {
|
||||||
|
a.say("\nMicrosite: %s\n", res.Web)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ = store.ErrNotFound
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// Command yetano-solutions runs the Solutions Guide commands (CI of the
|
||||||
|
// catalog, development). The guide is deliberately not part of yet, which
|
||||||
|
// stays a general tool; the full program with TUI and GUI moves to its
|
||||||
|
// own repository (docs/knowledge-solutions ADR-0006).
|
||||||
|
//
|
||||||
|
// yetano-solutions solution list --catalog assets/solutions
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core"
|
||||||
|
"yetano.dev/yetano/core/paths"
|
||||||
|
"yetano.dev/yetano/core/solutions/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
var version = "dev"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
// instances, sessions and presets are user data: core/paths' data
|
||||||
|
// directory (nothing is created until something is saved)
|
||||||
|
storeDir := os.Getenv("YETANO_SOLUTIONS_HOME")
|
||||||
|
if storeDir == "" {
|
||||||
|
if r, err := paths.For(core.Application{Name: "yetano-solutions", Kind: core.CLI}); err == nil {
|
||||||
|
if d, err := r.DataDir(); err == nil {
|
||||||
|
storeDir = d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
os.Exit(cli.Run(ctx, os.Args[1:], cli.Env{
|
||||||
|
Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr,
|
||||||
|
Interactive: isTerminal(os.Stdin) && isTerminal(os.Stdout),
|
||||||
|
Program: "yetano-solutions",
|
||||||
|
StoreDir: storeDir,
|
||||||
|
Version: version,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// isTerminal: a character device that is not the null device (/dev/null
|
||||||
|
// is a character device too, and must never start an interactive wizard).
|
||||||
|
func isTerminal(f *os.File) bool {
|
||||||
|
st, err := f.Stat()
|
||||||
|
if err != nil || st.Mode()&os.ModeCharDevice == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if null, err := os.Stat(os.DevNull); err == nil && os.SameFile(st, null) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The meta-repo's catalog, when this module is checked out inside it.
|
||||||
|
func assetsCatalog(t *testing.T) *catalog.Catalog {
|
||||||
|
t.Helper()
|
||||||
|
dir, _ := filepath.Abs("../../../assets/solutions")
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, "catalog.yaml")); err != nil {
|
||||||
|
t.Skip("assets/solutions not present (module outside the meta-repo)")
|
||||||
|
}
|
||||||
|
c, err := catalog.Load(dir)
|
||||||
|
if err != nil {
|
||||||
|
for _, i := range c.Issues {
|
||||||
|
t.Log(i)
|
||||||
|
}
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAssetsCatalog(t *testing.T) {
|
||||||
|
c := assetsCatalog(t)
|
||||||
|
for _, i := range c.Validate() {
|
||||||
|
if i.Severity == "error" {
|
||||||
|
t.Error(i)
|
||||||
|
} else {
|
||||||
|
t.Log(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e := New(c)
|
||||||
|
for _, key := range catalog.SortedIDs(c.Examples) {
|
||||||
|
x := c.Examples[key]
|
||||||
|
in := NewInstance(x.Meta.ID, c.Lookup(x.Spec.Solution), x.Spec.Mode)
|
||||||
|
in.Spec.Parameters = x.Spec.Parameters
|
||||||
|
st, err := e.Evaluate(in, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: %v", key, err)
|
||||||
|
}
|
||||||
|
if !st.Complete {
|
||||||
|
t.Errorf("%s: not complete: %s", key, incompleteText(st))
|
||||||
|
}
|
||||||
|
for _, m := range st.Messages {
|
||||||
|
t.Logf("%s: %s %s", key, m.Severity, m.Text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,398 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// placeholder: ${name}, ${name[0]}, ${name.count}, ${name.join}; $${ is a literal "${".
|
||||||
|
var placeholderRE = regexp.MustCompile(`\$\$\{|\$\{((?:instance|solution)\.[a-z]+|[A-Za-z_][A-Za-z0-9_]*)(?:\[(\d+)\]|\.(count|join))?\}`)
|
||||||
|
|
||||||
|
type genFile struct {
|
||||||
|
path string
|
||||||
|
pkg string
|
||||||
|
root *yaml.Node // mapping
|
||||||
|
origins map[string]Origin
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) vars() map[string]any {
|
||||||
|
v := map[string]any{}
|
||||||
|
for k, a := range ev.answers {
|
||||||
|
v[k] = a
|
||||||
|
}
|
||||||
|
v["instance.name"] = ev.in.Metadata.Name
|
||||||
|
v["solution.id"] = ev.s.Meta.ID
|
||||||
|
v["solution.version"] = ev.s.Meta.Version
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) config() {
|
||||||
|
files := map[string]*genFile{}
|
||||||
|
var order []string
|
||||||
|
get := func(path string) *genFile {
|
||||||
|
f, ok := files[path]
|
||||||
|
if !ok {
|
||||||
|
pkg, _, _ := strings.Cut(path, "/")
|
||||||
|
f = &genFile{path: path, pkg: pkg, root: &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}, origins: map[string]Origin{}}
|
||||||
|
files[path] = f
|
||||||
|
order = append(order, path)
|
||||||
|
}
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
vars := ev.vars()
|
||||||
|
applyFrag := func(fr catalog.Fragment, origin Origin) {
|
||||||
|
pkg, _, _ := strings.Cut(fr.File, "/")
|
||||||
|
if !ev.pkgSelected(pkg) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if fr.Module != "" {
|
||||||
|
mp, mm := pkg, fr.Module
|
||||||
|
if a, b, ok := strings.Cut(fr.Module, "/"); ok {
|
||||||
|
mp, mm = a, b
|
||||||
|
}
|
||||||
|
if !ev.moduleEnabled(mp, mm) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
node := deepCopy(&fr.Set)
|
||||||
|
params := map[string]bool{}
|
||||||
|
if err := interpolate(node, vars, params); err != nil {
|
||||||
|
ev.msg("error", "config", fmt.Sprintf("%s: %v", origin.Source, err), origin.Source)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for p := range params {
|
||||||
|
origin.Params = append(origin.Params, p)
|
||||||
|
}
|
||||||
|
sort.Strings(origin.Params)
|
||||||
|
if node.Kind != yaml.MappingNode {
|
||||||
|
ev.msg("error", "config", fmt.Sprintf("%s: fragment for %s is not a map", origin.Source, fr.File), origin.Source)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
f := get(fr.File)
|
||||||
|
mergeMap(f.root, node, "", origin, f.origins)
|
||||||
|
}
|
||||||
|
// layer 2: profiles (base first), in package order
|
||||||
|
ids := append([]string{}, ev.pkgSeen...)
|
||||||
|
sort.Strings(ids)
|
||||||
|
for _, id := range ids {
|
||||||
|
p := ev.pkgs[id]
|
||||||
|
if !p.Selected || p.Profile == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
chain, err := ev.e.Cat.ProfileChain(id, p.Profile)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, prof := range chain {
|
||||||
|
for _, fr := range prof.Spec.Config {
|
||||||
|
applyFrag(fr, Origin{Layer: "profile", Source: "profile:" + prof.Key()})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// layer 3: the solution's fragments
|
||||||
|
for i, fr := range ev.s.Spec.Config {
|
||||||
|
if len(fr.When) > 0 && !fr.When.Holds(ev.env) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
id := fr.ID
|
||||||
|
if id == "" {
|
||||||
|
id = strconv.Itoa(i)
|
||||||
|
}
|
||||||
|
applyFrag(fr, Origin{Layer: "solution", Source: "solution:" + ev.s.Meta.ID + "#" + id})
|
||||||
|
}
|
||||||
|
// layer 6: explicit overrides
|
||||||
|
for _, o := range ev.in.Spec.Overrides {
|
||||||
|
if !catalog.SafeRelPath(o.File) || o.Path == "" {
|
||||||
|
ev.msg("error", "override", fmt.Sprintf("override %s %s: bad file or path", o.File, o.Path), "override")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
f, ok := files[o.File]
|
||||||
|
if !ok {
|
||||||
|
ev.msg("warning", "override", fmt.Sprintf("override for %s: the solution generates no such file", o.File), "override")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var val yaml.Node
|
||||||
|
if err := val.Encode(o.Value); err != nil {
|
||||||
|
ev.msg("error", "override", err.Error(), "override")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
setPath(f.root, strings.Split(o.Path, "."), &val)
|
||||||
|
f.origins[o.Path] = Origin{Layer: "override", Source: "override"}
|
||||||
|
ev.msg("info", "override", fmt.Sprintf("%s: %s is set directly, not through a question", o.File, o.Path), "override")
|
||||||
|
}
|
||||||
|
sort.Strings(order)
|
||||||
|
for _, path := range order {
|
||||||
|
f := files[path]
|
||||||
|
body, err := render(f.root, ev.s, path)
|
||||||
|
if err != nil {
|
||||||
|
ev.msg("error", "config", err.Error(), path)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ev.st.Files = append(ev.st.Files, FilePreview{Path: "config/" + path, Package: f.pkg, Content: body, Origins: f.origins})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func render(root *yaml.Node, s *catalog.Solution, path string) (string, error) {
|
||||||
|
doc := &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{root}}
|
||||||
|
doc.HeadComment = fmt.Sprintf("Generated by the Yetano Solutions Guide from %s %s.\n"+
|
||||||
|
"This is a native configuration file: edit it like any other. See\n"+
|
||||||
|
"solution.lock.yaml before regenerating over hand edits.", s.Meta.ID, s.Meta.Version)
|
||||||
|
var buf bytes.Buffer
|
||||||
|
enc := yaml.NewEncoder(&buf)
|
||||||
|
enc.SetIndent(2)
|
||||||
|
if err := enc.Encode(doc); err != nil {
|
||||||
|
return "", fmt.Errorf("%s: %v", path, err)
|
||||||
|
}
|
||||||
|
enc.Close()
|
||||||
|
return buf.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func deepCopy(n *yaml.Node) *yaml.Node {
|
||||||
|
if n == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
c := *n
|
||||||
|
if c.Kind == yaml.MappingNode || c.Kind == yaml.SequenceNode {
|
||||||
|
c.Style = 0 // generated files use block style, whatever the catalog wrote
|
||||||
|
}
|
||||||
|
c.Line, c.Column = 0, 0
|
||||||
|
c.Content = make([]*yaml.Node, len(n.Content))
|
||||||
|
for i, ch := range n.Content {
|
||||||
|
c.Content[i] = deepCopy(ch)
|
||||||
|
}
|
||||||
|
if n.Kind == yaml.DocumentNode && len(c.Content) == 1 {
|
||||||
|
return c.Content[0]
|
||||||
|
}
|
||||||
|
return &c
|
||||||
|
}
|
||||||
|
|
||||||
|
// interpolate replaces placeholders in scalars (ADR-0005).
|
||||||
|
func interpolate(n *yaml.Node, vars map[string]any, used map[string]bool) error {
|
||||||
|
switch n.Kind {
|
||||||
|
case yaml.MappingNode:
|
||||||
|
for i := 1; i < len(n.Content); i += 2 {
|
||||||
|
if err := interpolate(n.Content[i], vars, used); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case yaml.SequenceNode:
|
||||||
|
for _, ch := range n.Content {
|
||||||
|
if err := interpolate(ch, vars, used); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case yaml.ScalarNode:
|
||||||
|
if !strings.Contains(n.Value, "${") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
whole := placeholderRE.FindStringSubmatchIndex(n.Value)
|
||||||
|
if whole != nil && whole[0] == 0 && whole[1] == len(n.Value) && n.Value != "$${" {
|
||||||
|
v, err := lookup(n.Value, vars, used)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var repl yaml.Node
|
||||||
|
if err := repl.Encode(v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
repl.Style = 0
|
||||||
|
*n = repl
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var firstErr error
|
||||||
|
out := placeholderRE.ReplaceAllStringFunc(n.Value, func(m string) string {
|
||||||
|
if m == "$${" {
|
||||||
|
return "${"
|
||||||
|
}
|
||||||
|
v, err := lookup(m, vars, used)
|
||||||
|
if err != nil && firstErr == nil {
|
||||||
|
firstErr = err
|
||||||
|
}
|
||||||
|
return text(v)
|
||||||
|
})
|
||||||
|
if firstErr != nil {
|
||||||
|
return firstErr
|
||||||
|
}
|
||||||
|
n.Value = out
|
||||||
|
n.Tag = "!!str"
|
||||||
|
n.Style = 0
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookup(ph string, vars map[string]any, used map[string]bool) (any, error) {
|
||||||
|
m := placeholderRE.FindStringSubmatch(ph)
|
||||||
|
name := m[1]
|
||||||
|
v, ok := vars[name]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("placeholder ${%s}: no answer for %q", name, name)
|
||||||
|
}
|
||||||
|
used[name] = true
|
||||||
|
switch {
|
||||||
|
case m[2] != "":
|
||||||
|
i, _ := strconv.Atoi(m[2])
|
||||||
|
l := listOf(v)
|
||||||
|
if i >= len(l) {
|
||||||
|
return nil, fmt.Errorf("placeholder %s: %q has only %d item(s)", ph, name, len(l))
|
||||||
|
}
|
||||||
|
return l[i], nil
|
||||||
|
case m[3] == "count":
|
||||||
|
return len(listOf(v)), nil
|
||||||
|
case m[3] == "join":
|
||||||
|
var parts []string
|
||||||
|
for _, x := range listOf(v) {
|
||||||
|
parts = append(parts, catalog.Scalar(x))
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ","), nil
|
||||||
|
}
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func text(v any) string {
|
||||||
|
if l, ok := v.([]any); ok {
|
||||||
|
var parts []string
|
||||||
|
for _, x := range l {
|
||||||
|
parts = append(parts, catalog.Scalar(x))
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ",")
|
||||||
|
}
|
||||||
|
return catalog.Scalar(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// mergeMap merges src into dst like core/config: maps key by key, lists
|
||||||
|
// and scalars replace, null removes. Origins are recorded per path.
|
||||||
|
func mergeMap(dst, src *yaml.Node, prefix string, origin Origin, origins map[string]Origin) {
|
||||||
|
for i := 0; i+1 < len(src.Content); i += 2 {
|
||||||
|
k, v := src.Content[i], src.Content[i+1]
|
||||||
|
path := k.Value
|
||||||
|
if prefix != "" {
|
||||||
|
path = prefix + "." + k.Value
|
||||||
|
}
|
||||||
|
idx := -1
|
||||||
|
for j := 0; j+1 < len(dst.Content); j += 2 {
|
||||||
|
if dst.Content[j].Value == k.Value {
|
||||||
|
idx = j
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if v.Kind == yaml.ScalarNode && v.Tag == "!!null" {
|
||||||
|
if idx >= 0 {
|
||||||
|
dst.Content = append(dst.Content[:idx], dst.Content[idx+2:]...)
|
||||||
|
}
|
||||||
|
for p := range origins {
|
||||||
|
if p == path || strings.HasPrefix(p, path+".") {
|
||||||
|
delete(origins, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if idx >= 0 && v.Kind == yaml.MappingNode && dst.Content[idx+1].Kind == yaml.MappingNode {
|
||||||
|
mergeMap(dst.Content[idx+1], v, path, origin, origins)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for p := range origins {
|
||||||
|
if strings.HasPrefix(p, path+".") {
|
||||||
|
delete(origins, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if idx >= 0 {
|
||||||
|
dst.Content[idx+1] = v
|
||||||
|
} else {
|
||||||
|
dst.Content = append(dst.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k.Value}, v)
|
||||||
|
}
|
||||||
|
recordLeaves(v, path, origin, origins)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func recordLeaves(v *yaml.Node, path string, origin Origin, origins map[string]Origin) {
|
||||||
|
if v.Kind == yaml.MappingNode {
|
||||||
|
for i := 0; i+1 < len(v.Content); i += 2 {
|
||||||
|
recordLeaves(v.Content[i+1], path+"."+v.Content[i].Value, origin, origins)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
origins[path] = origin
|
||||||
|
}
|
||||||
|
|
||||||
|
func setPath(root *yaml.Node, keys []string, val *yaml.Node) {
|
||||||
|
cur := root
|
||||||
|
for i, k := range keys {
|
||||||
|
idx := -1
|
||||||
|
for j := 0; j+1 < len(cur.Content); j += 2 {
|
||||||
|
if cur.Content[j].Value == k {
|
||||||
|
idx = j
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if i == len(keys)-1 {
|
||||||
|
if idx >= 0 {
|
||||||
|
cur.Content[idx+1] = val
|
||||||
|
} else {
|
||||||
|
cur.Content = append(cur.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k}, val)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if idx < 0 || cur.Content[idx+1].Kind != yaml.MappingNode {
|
||||||
|
m := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||||
|
if idx >= 0 {
|
||||||
|
cur.Content[idx+1] = m
|
||||||
|
} else {
|
||||||
|
cur.Content = append(cur.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k}, m)
|
||||||
|
}
|
||||||
|
cur = m
|
||||||
|
} else {
|
||||||
|
cur = cur.Content[idx+1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Explanation answers "where does this value come from?" (PROF-05).
|
||||||
|
type Explanation struct {
|
||||||
|
File string `json:"file"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
Found bool `json:"found"`
|
||||||
|
Origin Origin `json:"origin"`
|
||||||
|
Answers map[string]any `json:"answers,omitempty"` // the answers it used, with their origin
|
||||||
|
Origins map[string]string `json:"answerOrigins,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Explain finds the origin of a value in a generated file. file may omit
|
||||||
|
// the "config/" prefix; path is dot separated.
|
||||||
|
func Explain(st *State, file, path string) Explanation {
|
||||||
|
file = strings.TrimPrefix(file, "config/")
|
||||||
|
ex := Explanation{File: "config/" + file, Path: path}
|
||||||
|
for _, f := range st.Files {
|
||||||
|
if f.Path != "config/"+file {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p := path
|
||||||
|
for p != "" {
|
||||||
|
if o, ok := f.Origins[p]; ok {
|
||||||
|
ex.Found, ex.Origin = true, o
|
||||||
|
break
|
||||||
|
}
|
||||||
|
i := strings.LastIndex(p, ".")
|
||||||
|
if i < 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
p = p[:i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ex.Found && len(ex.Origin.Params) > 0 {
|
||||||
|
ex.Answers, ex.Origins = map[string]any{}, map[string]string{}
|
||||||
|
for _, p := range ex.Origin.Params {
|
||||||
|
if a, ok := st.Answers[p]; ok {
|
||||||
|
ex.Answers[p] = a.Value
|
||||||
|
ex.Origins[p] = a.Origin
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ex
|
||||||
|
}
|
||||||
@@ -0,0 +1,408 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testCat(t *testing.T) *catalog.Catalog {
|
||||||
|
t.Helper()
|
||||||
|
c, err := catalog.Load("testdata/cat")
|
||||||
|
if err != nil {
|
||||||
|
for _, i := range c.Issues {
|
||||||
|
t.Log(i)
|
||||||
|
}
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, i := range c.Validate() {
|
||||||
|
if i.Severity == "error" {
|
||||||
|
t.Fatal(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func eval(t *testing.T, e *Engine, mode catalog.Level, params map[string]any, p *Preset) *State {
|
||||||
|
t.Helper()
|
||||||
|
in := NewInstance("t1", e.Cat.Solutions["app-run"], mode)
|
||||||
|
for k, v := range params {
|
||||||
|
in.Spec.Parameters[k] = v
|
||||||
|
}
|
||||||
|
st, err := e.Evaluate(in, p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return st
|
||||||
|
}
|
||||||
|
|
||||||
|
func pkg(st *State, id string) *PackageState {
|
||||||
|
for i := range st.Packages {
|
||||||
|
if st.Packages[i].ID == id {
|
||||||
|
return &st.Packages[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func capOf(st *State, id string) *CapState {
|
||||||
|
for i := range st.Capabilities {
|
||||||
|
if st.Capabilities[i].ID == id {
|
||||||
|
return &st.Capabilities[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func file(st *State, path string) string {
|
||||||
|
for _, f := range st.Files {
|
||||||
|
if f.Path == path {
|
||||||
|
return f.Content
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func question(st *State, id string) QuestionState { return findQuestion(st, id) }
|
||||||
|
|
||||||
|
func findQuestion(st *State, id string) QuestionState {
|
||||||
|
for _, q := range st.Questions {
|
||||||
|
if q.ID == id {
|
||||||
|
return q
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return QuestionState{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasMsg(st *State, sub string) bool {
|
||||||
|
for _, m := range st.Messages {
|
||||||
|
if strings.Contains(m.Text, sub) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQuickDefaultPath(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
st := eval(t, e, catalog.LevelQuick, nil, nil)
|
||||||
|
if st.Complete || len(st.Progress.Missing) != 1 || st.Progress.Missing[0] != "hosts" {
|
||||||
|
t.Fatalf("want only hosts missing, got %v", st.Progress.Missing)
|
||||||
|
}
|
||||||
|
if st.Next != "hosts" {
|
||||||
|
t.Errorf("next = %q", st.Next)
|
||||||
|
}
|
||||||
|
// quick asks size and hosts only; guided questions take their defaults
|
||||||
|
var asked []string
|
||||||
|
for _, q := range st.Questions {
|
||||||
|
if q.Asked {
|
||||||
|
asked = append(asked, q.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Join(asked, ",") != "size,hosts" {
|
||||||
|
t.Errorf("asked %v", asked)
|
||||||
|
}
|
||||||
|
st = eval(t, e, catalog.LevelQuick, map[string]any{"hosts": "a.example.org, b.example.org"}, nil)
|
||||||
|
if !st.Complete {
|
||||||
|
t.Fatalf("incomplete: %v %v", st.Progress.Missing, st.Messages)
|
||||||
|
}
|
||||||
|
if p := pkg(st, "app"); p == nil || !p.Selected || p.Profile != "base" {
|
||||||
|
t.Fatalf("app: %+v", p)
|
||||||
|
}
|
||||||
|
if c := capOf(st, "auth.users"); c == nil || c.Provider != "app/users" {
|
||||||
|
t.Errorf("auth.users provider: %+v", c)
|
||||||
|
}
|
||||||
|
if c := capOf(st, "backup.files"); c == nil || c.Status != StRecommended {
|
||||||
|
t.Errorf("backup.files should be recommended: %+v", c)
|
||||||
|
}
|
||||||
|
if c := capOf(st, "feature.x"); c != nil && c.Status != StExcluded {
|
||||||
|
t.Errorf("feature.x should be excluded or absent: %+v", c)
|
||||||
|
}
|
||||||
|
cfg := file(st, "config/app/app.yaml")
|
||||||
|
for _, want := range []string{"hosts:\n - a.example.org\n - b.example.org", "owner: admin@a.example.org", "listen: :8080", "first: a.example.org", "n: 2", "max: 10"} {
|
||||||
|
if !strings.Contains(cfg, want) {
|
||||||
|
t.Errorf("config lacks %q:\n%s", want, cfg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if file(st, "config/bak/bak.yaml") != "" || file(st, "config/idp/idp.yaml") != "" {
|
||||||
|
t.Error("files for packages that are not selected")
|
||||||
|
}
|
||||||
|
if len(st.Steps) != 3 { // 2 hosts + 1 program (server; extra is disabled)
|
||||||
|
t.Errorf("steps: %+v", st.Steps)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scenario B: local -> central identity and back (ACC-B, RULE-06).
|
||||||
|
func TestIdentitySwitch(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
base := map[string]any{"hosts": []any{"a.example.org"}}
|
||||||
|
st := eval(t, e, catalog.LevelGuided, base, nil)
|
||||||
|
if pkg(st, "idp") != nil {
|
||||||
|
t.Fatal("idp without central identity")
|
||||||
|
}
|
||||||
|
central := map[string]any{"hosts": []any{"a.example.org"}, "identity": "central"}
|
||||||
|
st = eval(t, e, catalog.LevelGuided, central, nil)
|
||||||
|
if !question(st, "realm").Visible || st.Complete {
|
||||||
|
t.Fatal("realm must appear and be required")
|
||||||
|
}
|
||||||
|
central["realm"] = "corp"
|
||||||
|
st = eval(t, e, catalog.LevelGuided, central, nil)
|
||||||
|
if !st.Complete {
|
||||||
|
t.Fatalf("incomplete: %v %v", st.Progress.Missing, st.Messages)
|
||||||
|
}
|
||||||
|
if p := pkg(st, "idp"); p == nil || !p.Selected {
|
||||||
|
t.Fatal("idp must be selected")
|
||||||
|
}
|
||||||
|
if c := capOf(st, "auth.sso"); c == nil || c.Provider != "idp/sso" {
|
||||||
|
t.Fatalf("auth.sso must come from idp, not the unimplemented module: %+v", c)
|
||||||
|
}
|
||||||
|
if !strings.Contains(file(st, "config/app/app.yaml"), "realm: corp") || file(st, "config/idp/idp.yaml") == "" {
|
||||||
|
t.Error("central identity config missing")
|
||||||
|
}
|
||||||
|
edge := false
|
||||||
|
for _, ed := range st.Graph.Edges {
|
||||||
|
edge = edge || (ed.From == "pkg:app" && ed.To == "pkg:idp" && ed.Type == "authenticatesVia")
|
||||||
|
}
|
||||||
|
if !edge {
|
||||||
|
t.Error("confirmed Big Picture connection app -> idp missing from the graph")
|
||||||
|
}
|
||||||
|
// back to local: realm is stale, not in the config, idp gone
|
||||||
|
central["identity"] = "local"
|
||||||
|
st = eval(t, e, catalog.LevelGuided, central, nil)
|
||||||
|
if pkg(st, "idp") != nil || strings.Contains(file(st, "config/app/app.yaml"), "realm") {
|
||||||
|
t.Error("central leftovers after switching back")
|
||||||
|
}
|
||||||
|
if len(st.Stale) != 1 || st.Stale[0].Question != "realm" {
|
||||||
|
t.Errorf("stale: %+v", st.Stale)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNotImplementedOptionIsVisibleButNotSelectable(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
st := eval(t, e, catalog.LevelGuided, map[string]any{"hosts": []any{"a.example.org"}, "identity": "ghost"}, nil)
|
||||||
|
q := question(st, "identity")
|
||||||
|
var ghost OptionState
|
||||||
|
for _, o := range q.Options {
|
||||||
|
if o.ID == "ghost" {
|
||||||
|
ghost = o
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ghost.Enabled || ghost.Disabled != "not built" {
|
||||||
|
t.Errorf("ghost option: %+v", ghost)
|
||||||
|
}
|
||||||
|
if len(st.Stale) != 1 || q.Value != "local" {
|
||||||
|
t.Errorf("the unselectable answer must be stale and the default used: %+v %v", st.Stale, q.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestModeSwitchKeepsAnswers(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
params := map[string]any{"hosts": []any{"a.example.org"}, "port": 9090}
|
||||||
|
adv := eval(t, e, catalog.LevelAdvanced, params, nil)
|
||||||
|
quick := eval(t, e, catalog.LevelQuick, params, nil)
|
||||||
|
if file(adv, "config/app/app.yaml") != file(quick, "config/app/app.yaml") {
|
||||||
|
t.Error("the mode must not change the result")
|
||||||
|
}
|
||||||
|
if !strings.Contains(file(quick, "config/app/app.yaml"), ":9090") {
|
||||||
|
t.Error("an advanced answer is lost in quick mode")
|
||||||
|
}
|
||||||
|
if question(quick, "port").Asked {
|
||||||
|
t.Error("quick mode asks an advanced question")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidationAndSecrets(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
st := eval(t, e, catalog.LevelAdvanced, map[string]any{"hosts": []any{"not a host"}, "token": "hunter2"}, nil)
|
||||||
|
if len(question(st, "hosts").Errors) == 0 {
|
||||||
|
t.Error("an invalid host name is accepted")
|
||||||
|
}
|
||||||
|
if len(question(st, "token").Errors) == 0 {
|
||||||
|
t.Error("a plain secret is accepted")
|
||||||
|
}
|
||||||
|
st = eval(t, e, catalog.LevelAdvanced, map[string]any{"hosts": []any{"a.example.org"}, "token": "secret://app/token"}, nil)
|
||||||
|
if !st.Complete || !strings.Contains(file(st, "config/app/app.yaml"), "token: secret://app/token") {
|
||||||
|
t.Errorf("secret reference not taken: %v", st.Messages)
|
||||||
|
}
|
||||||
|
for _, p := range e.Handbook(st, nil) {
|
||||||
|
if strings.Contains(string(p.Content), "secret://app/token") && strings.HasSuffix(p.Path, "index.md") {
|
||||||
|
t.Error("the handbook's decision table shows a secret reference")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scenario G: a preset answers everything but the instance-specific questions.
|
||||||
|
func TestPreset(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelGuided)
|
||||||
|
in.Spec.Parameters = map[string]any{"hosts": []any{"a.example.org"}, "size": "big", "backup": "mine", "token": "secret://x"}
|
||||||
|
p := PresetFrom("mine", in, e.Cat.Solutions["app-run"])
|
||||||
|
if _, ok := p.Spec.Parameters["hosts"]; ok {
|
||||||
|
t.Error("an instance-specific answer in the preset")
|
||||||
|
}
|
||||||
|
if _, ok := p.Spec.Parameters["token"]; ok {
|
||||||
|
t.Error("a secret in the preset")
|
||||||
|
}
|
||||||
|
st := eval(t, e, catalog.LevelQuick, map[string]any{"hosts": []any{"new.example.org"}}, p)
|
||||||
|
if !st.Complete || pkg(st, "app").Profile != "big" || st.Answers["size"].Origin != "preset:mine" {
|
||||||
|
t.Fatalf("preset not applied: %+v %v", st.Answers["size"], st.Messages)
|
||||||
|
}
|
||||||
|
if question(st, "size").Asked {
|
||||||
|
t.Error("a question the preset answered is asked again")
|
||||||
|
}
|
||||||
|
if !question(st, "hosts").Asked {
|
||||||
|
t.Error("the instance-specific question must be asked")
|
||||||
|
}
|
||||||
|
if !hasMsg(st, "Big needs more memory") {
|
||||||
|
t.Error("rule message missing")
|
||||||
|
}
|
||||||
|
if !strings.Contains(file(st, "config/app/extra.yaml"), "on: true") || !strings.Contains(file(st, "config/app/app.yaml"), "max: 100") {
|
||||||
|
t.Error("profile inheritance (big extends base) not applied")
|
||||||
|
}
|
||||||
|
if c := capOf(st, "backup.files"); c == nil || c.Status != StExternal {
|
||||||
|
t.Errorf("backup by own tool must be external: %+v", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExplainAndOverride(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
|
||||||
|
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
|
||||||
|
in.Spec.Overrides = []Override{{File: "app/app.yaml", Path: "limits.min", Value: 5}}
|
||||||
|
st, err := e.Evaluate(in, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ex := Explain(st, "app/app.yaml", "owner")
|
||||||
|
if !ex.Found || ex.Origin.Source != "solution:app-run#main" || ex.Origins["owner"] != "default" {
|
||||||
|
t.Errorf("explain owner: %+v", ex)
|
||||||
|
}
|
||||||
|
if ex := Explain(st, "config/app/app.yaml", "limits.max"); ex.Origin.Source != "profile:app/base" {
|
||||||
|
t.Errorf("explain limits.max: %+v", ex)
|
||||||
|
}
|
||||||
|
if ex := Explain(st, "app/app.yaml", "limits.min"); ex.Origin.Layer != "override" {
|
||||||
|
t.Errorf("explain override: %+v", ex)
|
||||||
|
}
|
||||||
|
if !strings.Contains(file(st, "config/app/app.yaml"), "min: 5") {
|
||||||
|
t.Error("override not applied")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeterministicAndJSON(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
p := map[string]any{"hosts": []any{"a.example.org", "b.example.org"}, "identity": "central", "realm": "r"}
|
||||||
|
a, _ := json.Marshal(eval(t, e, catalog.LevelGuided, p, nil))
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
b, _ := json.Marshal(eval(t, e, catalog.LevelGuided, p, nil))
|
||||||
|
if string(a) != string(b) {
|
||||||
|
t.Fatal("evaluation is not deterministic")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateWriteAndProtect(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
|
||||||
|
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
|
||||||
|
st, _ := e.Evaluate(in, nil)
|
||||||
|
out, err := e.Generate(st, in, nil, false)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := Write(dir, out, false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// regenerating unchanged is fine
|
||||||
|
if err := Write(dir, out, false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// a hand edit blocks regeneration (CONF-06)
|
||||||
|
cfg := filepath.Join(dir, "config", "app", "app.yaml")
|
||||||
|
if err := os.WriteFile(cfg, []byte("# mine\n"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := Write(dir, out, false); !errors.Is(err, ErrModified) {
|
||||||
|
t.Fatalf("hand edit overwritten: %v", err)
|
||||||
|
}
|
||||||
|
if err := Write(dir, out, true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// an incomplete state does not generate
|
||||||
|
in2 := NewInstance("t2", e.Cat.Solutions["app-run"], catalog.LevelQuick)
|
||||||
|
st2, _ := e.Evaluate(in2, nil)
|
||||||
|
if _, err := e.Generate(st2, in2, nil, false); !errors.Is(err, ErrIncomplete) {
|
||||||
|
t.Errorf("incomplete generated: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLockDrift(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
|
||||||
|
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
|
||||||
|
st, _ := e.Evaluate(in, nil)
|
||||||
|
out, _ := e.Generate(st, in, nil, false)
|
||||||
|
out2, _ := e.Generate(st, in, nil, false)
|
||||||
|
if d := LockDrift(out.Lock, out2.Lock); len(d) != 0 {
|
||||||
|
t.Errorf("drift without change: %v", d)
|
||||||
|
}
|
||||||
|
changed := *out.Lock
|
||||||
|
changed.Spec.Profiles = append([]Pinned{}, out.Lock.Spec.Profiles...)
|
||||||
|
changed.Spec.Profiles[0].Hash = "x"
|
||||||
|
if d := LockDrift(&changed, out2.Lock); len(d) != 1 || !strings.Contains(d[0], "profile app/base changed") {
|
||||||
|
t.Errorf("profile change not detected: %v", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStepsChecksGraph(t *testing.T) {
|
||||||
|
e := New(testCat(t))
|
||||||
|
st := eval(t, e, catalog.LevelQuick, map[string]any{"hosts": []any{"a.example.org"}, "size": "big"}, nil)
|
||||||
|
if st.Steps[0].Phase != "install" || len(st.Steps) != 3 {
|
||||||
|
t.Errorf("steps: %+v", st.Steps)
|
||||||
|
}
|
||||||
|
if st.Steps[0].Run != "yet install app-server" || st.Steps[1].Run != "yet install app-extra" {
|
||||||
|
t.Errorf("module steps: %+v", st.Steps)
|
||||||
|
}
|
||||||
|
for _, c := range st.Checks {
|
||||||
|
switch c.ID {
|
||||||
|
case "port":
|
||||||
|
if c.Status != CheckNotChecked || c.Params["port"] != "8080" {
|
||||||
|
t.Errorf("port check: %+v", c)
|
||||||
|
}
|
||||||
|
case "bigonly":
|
||||||
|
if c.Status != CheckNotChecked {
|
||||||
|
t.Errorf("bigonly: %+v", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, n := range st.Graph.Nodes {
|
||||||
|
found = found || n.Title == "Users of a.example.org"
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Error("node title not interpolated")
|
||||||
|
}
|
||||||
|
if !strings.Contains(GraphText(st.Graph), "app-extra") {
|
||||||
|
t.Error(GraphText(st.Graph))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConditionOrderIsEnforced(t *testing.T) {
|
||||||
|
c := testCat(t)
|
||||||
|
s := c.Solutions["app-run"]
|
||||||
|
q, _ := s.Question("size")
|
||||||
|
q.VisibleWhen = catalog.Cond{"hosts": map[string]any{"set": true}}
|
||||||
|
defer func() { q.VisibleWhen = nil }()
|
||||||
|
found := false
|
||||||
|
for _, i := range c.Validate() {
|
||||||
|
found = found || i.Code == "condition-order"
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Error("a condition on a later question is not reported")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,998 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GeneratorVersion is stamped into lock files; the program embedding the
|
||||||
|
// engine may set it to its own version.
|
||||||
|
var GeneratorVersion = "dev"
|
||||||
|
|
||||||
|
// ErrNotFound is returned for unknown solutions, tasks, examples.
|
||||||
|
var ErrNotFound = errors.New("not found")
|
||||||
|
|
||||||
|
// Engine evaluates instances against one catalog. It is safe for
|
||||||
|
// concurrent use: Evaluate does not modify the catalog.
|
||||||
|
type Engine struct {
|
||||||
|
Cat *catalog.Catalog
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns an engine for a validated catalog.
|
||||||
|
func New(c *catalog.Catalog) *Engine { return &Engine{Cat: c} }
|
||||||
|
|
||||||
|
type evaluation struct {
|
||||||
|
e *Engine
|
||||||
|
s *catalog.Solution
|
||||||
|
in *Instance
|
||||||
|
preset *Preset
|
||||||
|
st *State
|
||||||
|
answers map[string]any
|
||||||
|
env catalog.Env
|
||||||
|
|
||||||
|
reqPkg, recPkg, discPkg, conflPkg map[string][]string
|
||||||
|
reqCap, recCap, discCap, exclCap, implCap map[string][]string
|
||||||
|
extCap map[string]string
|
||||||
|
exclMod, reqMod map[string][]string
|
||||||
|
|
||||||
|
pkgs map[string]*PackageState
|
||||||
|
mods map[string]map[string]*ModuleState // pkg -> module -> state
|
||||||
|
caps map[string]*CapState
|
||||||
|
pkgSeen []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Evaluate computes the full State of an instance (and an optional preset).
|
||||||
|
func (e *Engine) Evaluate(in *Instance, preset *Preset) (*State, error) {
|
||||||
|
s := e.Cat.Lookup(in.Spec.Solution.ID)
|
||||||
|
if s == nil {
|
||||||
|
return nil, fmt.Errorf("%w: solution or task %q", ErrNotFound, in.Spec.Solution.ID)
|
||||||
|
}
|
||||||
|
mode := in.Spec.Mode
|
||||||
|
if mode == "" {
|
||||||
|
mode = catalog.LevelQuick
|
||||||
|
}
|
||||||
|
loc := in.Spec.Locale
|
||||||
|
if loc == "" {
|
||||||
|
loc = "en"
|
||||||
|
}
|
||||||
|
st := &State{
|
||||||
|
Solution: SolutionInfo{
|
||||||
|
ID: s.Meta.ID, Kind: s.Kind, TaskKind: s.Spec.Kind, Version: s.Meta.Version,
|
||||||
|
Title: e.title(s, loc), Summary: e.summary(s, loc), Status: statusOf(s.Meta.Status),
|
||||||
|
Category: s.Meta.Category, BigPicture: s.Spec.BigPicture,
|
||||||
|
},
|
||||||
|
Instance: in.Metadata.Name, Mode: mode, Locale: loc, Platform: in.Spec.Platform,
|
||||||
|
Answers: map[string]Answer{},
|
||||||
|
Messages: []Message{}, Rules: []AppliedRule{}, Packages: []PackageState{},
|
||||||
|
Capabilities: []CapState{}, Files: []FilePreview{}, Steps: []PlannedStep{},
|
||||||
|
Checks: []CheckResult{}, References: []string{},
|
||||||
|
}
|
||||||
|
ev := &evaluation{
|
||||||
|
e: e, s: s, in: in, preset: preset, st: st, answers: map[string]any{},
|
||||||
|
reqPkg: map[string][]string{}, recPkg: map[string][]string{}, discPkg: map[string][]string{}, conflPkg: map[string][]string{},
|
||||||
|
reqCap: map[string][]string{}, recCap: map[string][]string{}, discCap: map[string][]string{},
|
||||||
|
exclCap: map[string][]string{}, implCap: map[string][]string{}, extCap: map[string]string{},
|
||||||
|
exclMod: map[string][]string{}, reqMod: map[string][]string{},
|
||||||
|
pkgs: map[string]*PackageState{}, mods: map[string]map[string]*ModuleState{}, caps: map[string]*CapState{},
|
||||||
|
}
|
||||||
|
ev.env = catalog.Env{Answers: ev.answers, Mode: mode, Platform: in.Spec.Platform}
|
||||||
|
if in.Spec.Solution.Version != "" && in.Spec.Solution.Version != s.Meta.Version {
|
||||||
|
ev.msg("warning", "version", fmt.Sprintf("these answers were made for %s %s; the catalog now has %s. Review the answers (LOCK-02).", s.Meta.ID, in.Spec.Solution.Version, s.Meta.Version), "")
|
||||||
|
}
|
||||||
|
if preset != nil && preset.Spec.Solution != "" && preset.Spec.Solution != s.Meta.ID {
|
||||||
|
ev.msg("warning", "preset", fmt.Sprintf("preset %q is for %s, not %s; only matching answers are used", preset.Metadata.Name, preset.Spec.Solution, s.Meta.ID), "")
|
||||||
|
}
|
||||||
|
for k := range in.Spec.Parameters {
|
||||||
|
if q, _ := s.Question(k); q == nil {
|
||||||
|
ev.msg("warning", "unknown-parameter", fmt.Sprintf("parameter %q is not a question of %s and is ignored", k, s.Meta.ID), "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ev.questions()
|
||||||
|
ev.effects()
|
||||||
|
ev.packages()
|
||||||
|
ev.capabilities()
|
||||||
|
ev.finishModules()
|
||||||
|
ev.config()
|
||||||
|
ev.steps()
|
||||||
|
ev.checks()
|
||||||
|
ev.graph()
|
||||||
|
ev.finish()
|
||||||
|
return st, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func statusOf(s catalog.Support) catalog.Support {
|
||||||
|
if s == "" {
|
||||||
|
return catalog.Supported
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- text ----------------------------------------------------------------
|
||||||
|
|
||||||
|
// Tr returns the translation of field in loc, or base.
|
||||||
|
func Tr(t catalog.Translations, loc, field, base string) string {
|
||||||
|
if loc != "" && loc != "en" {
|
||||||
|
if m, ok := t[loc]; ok {
|
||||||
|
if v, ok := m[field]; ok && v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return base
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *Engine) title(s *catalog.Solution, loc string) string {
|
||||||
|
base := s.Meta.Title
|
||||||
|
if base == "" && e.Cat.BigPicture != nil {
|
||||||
|
if g, ok := e.Cat.BigPicture.Stories[s.Spec.BigPicture]; ok {
|
||||||
|
base = g.Title
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Tr(s.Meta.Translations, loc, "title", base)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *Engine) summary(s *catalog.Solution, loc string) string {
|
||||||
|
base := s.Meta.Summary
|
||||||
|
if base == "" && e.Cat.BigPicture != nil {
|
||||||
|
if g, ok := e.Cat.BigPicture.Stories[s.Spec.BigPicture]; ok {
|
||||||
|
base = g.Intent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Tr(s.Meta.Translations, loc, "summary", base)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PackageTitle and PackageSummary come from the Big Picture (ADR-0002).
|
||||||
|
func (e *Engine) PackageSummary(id string) string {
|
||||||
|
p := e.Cat.Packages[id]
|
||||||
|
if p == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if p.Meta.Summary != "" {
|
||||||
|
return p.Meta.Summary
|
||||||
|
}
|
||||||
|
if e.Cat.BigPicture != nil {
|
||||||
|
if bp, ok := e.Cat.BigPicture.Products[p.Spec.BigPicture]; ok {
|
||||||
|
return bp.Summary
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) msg(sev, code, text, source string) {
|
||||||
|
ev.st.Messages = append(ev.st.Messages, Message{Severity: sev, Code: code, Text: text, Source: source})
|
||||||
|
}
|
||||||
|
|
||||||
|
func add(m map[string][]string, k, reason string) {
|
||||||
|
for _, r := range m[k] {
|
||||||
|
if r == reason {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m[k] = append(m[k], reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- questions -------------------------------------------------------------
|
||||||
|
|
||||||
|
func platformOK(list []string, p string) bool {
|
||||||
|
if len(list) == 0 || p == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, x := range list {
|
||||||
|
if x == p {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) stale(q string, v any, reason string) {
|
||||||
|
ev.st.Stale = append(ev.st.Stale, StaleAnswer{Question: q, Value: v, Reason: reason})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) questions() {
|
||||||
|
s, st, loc := ev.s, ev.st, ev.st.Locale
|
||||||
|
mode := st.Mode
|
||||||
|
askedIdx := 0
|
||||||
|
for i := range s.Spec.Questions {
|
||||||
|
q := &s.Spec.Questions[i]
|
||||||
|
qs := QuestionState{
|
||||||
|
ID: q.ID, Type: q.Type, Item: q.Item, Group: q.Group, Level: levelOf(q.Level),
|
||||||
|
Title: Tr(q.Translations, loc, "title", q.Title),
|
||||||
|
Help: Tr(q.Translations, loc, "help", q.Help),
|
||||||
|
Description: Tr(q.Translations, loc, "description", q.Description),
|
||||||
|
Decide: Tr(q.Translations, loc, "decide", q.Decide),
|
||||||
|
Placeholder: Tr(q.Translations, loc, "placeholder", q.Placeholder),
|
||||||
|
Examples: q.Examples, InstanceSpecific: q.InstanceSpecific,
|
||||||
|
Recommended: q.Recommended, Reason: Tr(q.Translations, loc, "reason", q.Reason),
|
||||||
|
References: q.References,
|
||||||
|
}
|
||||||
|
explicit, hasExplicit := ev.in.Spec.Parameters[q.ID]
|
||||||
|
qs.Visible = q.VisibleWhen.Holds(ev.env) && platformOK(q.Platforms, ev.in.Spec.Platform)
|
||||||
|
if !qs.Visible {
|
||||||
|
if hasExplicit {
|
||||||
|
ev.stale(q.ID, explicit, "the question does not apply to the current answers")
|
||||||
|
}
|
||||||
|
st.Questions = append(st.Questions, qs)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
qs.Required = q.Required || (len(q.RequiredWhen) > 0 && q.RequiredWhen.Holds(ev.env))
|
||||||
|
|
||||||
|
// options and their availability
|
||||||
|
enabled := map[string]bool{}
|
||||||
|
for _, o := range q.Options {
|
||||||
|
os := OptionState{
|
||||||
|
ID: o.ID, Title: Tr(o.Translations, loc, "title", o.Title),
|
||||||
|
Description: Tr(o.Translations, loc, "description", o.Description),
|
||||||
|
Recommended: o.Recommended, Reason: Tr(o.Translations, loc, "reason", o.Reason),
|
||||||
|
Support: statusOf(o.Support), SupportNote: Tr(o.Translations, loc, "supportNote", o.SupportNote),
|
||||||
|
References: o.References,
|
||||||
|
}
|
||||||
|
os.Enabled = o.Support.Selectable()
|
||||||
|
if !os.Enabled {
|
||||||
|
os.Disabled = os.SupportNote
|
||||||
|
} else if len(o.EnabledWhen) > 0 && !o.EnabledWhen.Holds(ev.env) {
|
||||||
|
os.Enabled = false
|
||||||
|
os.Disabled = "not available with the answers given before"
|
||||||
|
}
|
||||||
|
enabled[o.ID] = os.Enabled
|
||||||
|
for _, t := range []*catalog.Targets{o.Effects.Requires, o.Effects.Implies} {
|
||||||
|
if t != nil {
|
||||||
|
for _, p := range t.Packages {
|
||||||
|
os.Adds = append(os.Adds, "package:"+p)
|
||||||
|
}
|
||||||
|
for _, c := range t.Capabilities {
|
||||||
|
os.Adds = append(os.Adds, "capability:"+c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
qs.Options = append(qs.Options, os)
|
||||||
|
}
|
||||||
|
checkOpts := func(v any) string {
|
||||||
|
if q.Type != "select" && q.Type != "multiselect" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for _, x := range listOf(v) {
|
||||||
|
if !enabled[catalog.Scalar(x)] {
|
||||||
|
for _, o := range qs.Options {
|
||||||
|
if o.ID == catalog.Scalar(x) {
|
||||||
|
return fmt.Sprintf("option %q is not available: %s", o.ID, o.Disabled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// default (defaultWhen first match wins)
|
||||||
|
def := q.Default
|
||||||
|
for _, dw := range q.DefaultWhen {
|
||||||
|
if dw.When.Holds(ev.env) {
|
||||||
|
def = dw.Value
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ds, ok := def.(string); ok && strings.Contains(ds, "${") {
|
||||||
|
// a default built from earlier answers (postmaster@${domains[0]})
|
||||||
|
if x, err := expand(ds, ev.vars()); err == nil {
|
||||||
|
def = strings.Trim(x, "'")
|
||||||
|
} else {
|
||||||
|
def = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if def != nil {
|
||||||
|
if n, err := Normalize(q, def); err == nil {
|
||||||
|
def = n
|
||||||
|
if bad := checkOpts(def); bad != "" {
|
||||||
|
def = ev.fallbackOption(q, enabled)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ev.msg("error", "default", fmt.Sprintf("question %s: default %v is invalid: %v", q.ID, def, err), "catalog")
|
||||||
|
def = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
qs.Default = def
|
||||||
|
|
||||||
|
var val any
|
||||||
|
origin := ""
|
||||||
|
if hasExplicit {
|
||||||
|
n, err := Normalize(q, explicit)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
qs.Errors = append(qs.Errors, err.Error())
|
||||||
|
case checkOpts(n) != "":
|
||||||
|
ev.stale(q.ID, explicit, checkOpts(n))
|
||||||
|
default:
|
||||||
|
val, origin = n, "instance"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if origin == "" && ev.preset != nil && !q.InstanceSpecific && q.Type != "secret" &&
|
||||||
|
(ev.preset.Spec.Solution == "" || ev.preset.Spec.Solution == ev.s.Meta.ID) {
|
||||||
|
if pv, ok := ev.preset.Spec.Parameters[q.ID]; ok {
|
||||||
|
if n, err := Normalize(q, pv); err == nil && checkOpts(n) == "" {
|
||||||
|
val, origin = n, "preset:"+ev.preset.Metadata.Name
|
||||||
|
} else {
|
||||||
|
ev.msg("warning", "preset", fmt.Sprintf("preset value for %s is not valid any more and is ignored", q.ID), "preset:"+ev.preset.Metadata.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if origin == "" && len(qs.Errors) == 0 && def != nil {
|
||||||
|
val, origin = def, "default"
|
||||||
|
}
|
||||||
|
if val != nil && len(qs.Errors) == 0 {
|
||||||
|
for _, vw := range q.ValidateWhen {
|
||||||
|
if vw.When.Holds(ev.env) {
|
||||||
|
var err error
|
||||||
|
if l, isList := val.([]any); isList {
|
||||||
|
err = checkCount(vw.Validation, len(l))
|
||||||
|
} else {
|
||||||
|
err = checkValue(vw.Validation, val)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
qs.Errors = append(qs.Errors, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
levelAsked := qs.Level.Rank() <= mode.Rank()
|
||||||
|
missing := qs.Required && (!catalog.IsSet(val) || len(qs.Errors) > 0)
|
||||||
|
qs.Asked = (levelAsked && !strings.HasPrefix(origin, "preset:")) || missing || len(qs.Errors) > 0
|
||||||
|
if qs.Asked && q.InstanceSpecific {
|
||||||
|
qs.Asked = true
|
||||||
|
}
|
||||||
|
if val != nil && len(qs.Errors) == 0 {
|
||||||
|
ev.answers[q.ID] = val
|
||||||
|
st.Answers[q.ID] = Answer{Value: val, Origin: origin}
|
||||||
|
qs.Value, qs.Origin = val, origin
|
||||||
|
}
|
||||||
|
for j := range qs.Options {
|
||||||
|
for _, x := range listOf(qs.Value) {
|
||||||
|
if catalog.Scalar(x) == qs.Options[j].ID {
|
||||||
|
qs.Options[j].Selected = true
|
||||||
|
if sup := qs.Options[j].Support; sup == catalog.Experimental || sup == catalog.Untested || sup == catalog.Discouraged || sup == catalog.NeedsPrereq {
|
||||||
|
ev.msg("warning", "support-"+string(sup), fmt.Sprintf("%s: %q is %s. %s", qs.Title, qs.Options[j].Title, sup, qs.Options[j].SupportNote), "question:"+q.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, w := range q.Warnings {
|
||||||
|
if w.When.Holds(ev.env) {
|
||||||
|
sev := w.Severity
|
||||||
|
if sev == "" {
|
||||||
|
sev = "warning"
|
||||||
|
}
|
||||||
|
m := Message{Severity: sev, Code: "question", Text: Tr(q.Translations, loc, "warning", w.Text), Source: "question:" + q.ID}
|
||||||
|
qs.Warnings = append(qs.Warnings, m)
|
||||||
|
st.Messages = append(st.Messages, m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if missing {
|
||||||
|
st.Progress.Missing = append(st.Progress.Missing, q.ID)
|
||||||
|
}
|
||||||
|
if qs.Asked {
|
||||||
|
st.Progress.Asked++
|
||||||
|
askedIdx++
|
||||||
|
if origin == "instance" {
|
||||||
|
st.Progress.Answered++
|
||||||
|
} else if st.Next == "" {
|
||||||
|
st.Next = q.ID
|
||||||
|
st.Progress.Step = askedIdx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
st.Questions = append(st.Questions, qs)
|
||||||
|
}
|
||||||
|
if st.Next == "" {
|
||||||
|
st.Progress.Step = askedIdx
|
||||||
|
}
|
||||||
|
// what needs attention first: a missing or invalid answer
|
||||||
|
idx := 0
|
||||||
|
for _, q := range st.Questions {
|
||||||
|
if q.Visible && q.Asked {
|
||||||
|
idx++
|
||||||
|
if len(q.Errors) > 0 || (q.Required && !catalog.IsSet(q.Value)) {
|
||||||
|
st.Next, st.Progress.Step = q.ID, idx
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func levelOf(l catalog.Level) catalog.Level {
|
||||||
|
if l == "" {
|
||||||
|
return catalog.LevelQuick
|
||||||
|
}
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
// fallbackOption: the recommended enabled option, else the first enabled.
|
||||||
|
func (ev *evaluation) fallbackOption(q *catalog.Question, enabled map[string]bool) any {
|
||||||
|
for _, o := range q.Options {
|
||||||
|
if o.Recommended && enabled[o.ID] {
|
||||||
|
return o.ID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, o := range q.Options {
|
||||||
|
if enabled[o.ID] {
|
||||||
|
return o.ID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- effects of options and rules ----------------------------------------
|
||||||
|
|
||||||
|
func (ev *evaluation) effects() {
|
||||||
|
for i := range ev.s.Spec.Questions {
|
||||||
|
q := &ev.s.Spec.Questions[i]
|
||||||
|
v, ok := ev.answers[q.ID]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, o := range q.Options {
|
||||||
|
for _, x := range listOf(v) {
|
||||||
|
if catalog.Scalar(x) == o.ID {
|
||||||
|
ev.apply("option "+q.ID+"="+o.ID, "option", o.Effects, o.Reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, r := range ev.s.Spec.Rules {
|
||||||
|
if !r.When.Holds(ev.env) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ev.apply("rule "+r.ID, "rule", r.Effects, r.Reason)
|
||||||
|
if r.Message != "" {
|
||||||
|
sev := r.Severity
|
||||||
|
if sev == "" {
|
||||||
|
sev = "warning"
|
||||||
|
}
|
||||||
|
ev.msg(sev, "rule", r.Message, "rule:"+r.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) apply(source, kind string, fx catalog.Effects, reason string) {
|
||||||
|
var parts []string
|
||||||
|
put := func(t *catalog.Targets, pk, cp map[string][]string, verb string) {
|
||||||
|
if t == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, p := range t.Packages {
|
||||||
|
if pk != nil {
|
||||||
|
add(pk, p, source)
|
||||||
|
}
|
||||||
|
parts = append(parts, verb+" package "+p)
|
||||||
|
}
|
||||||
|
for _, c := range t.Capabilities {
|
||||||
|
if cp != nil {
|
||||||
|
add(cp, c, source)
|
||||||
|
}
|
||||||
|
parts = append(parts, verb+" "+c)
|
||||||
|
}
|
||||||
|
for _, m := range t.Modules {
|
||||||
|
if verb == "excludes" {
|
||||||
|
add(ev.exclMod, m, source)
|
||||||
|
} else if verb == "requires" || verb == "implies" {
|
||||||
|
add(ev.reqMod, m, source)
|
||||||
|
}
|
||||||
|
parts = append(parts, verb+" module "+m)
|
||||||
|
}
|
||||||
|
for q, want := range t.Answers {
|
||||||
|
parts = append(parts, fmt.Sprintf("%s %s=%v", verb, q, want))
|
||||||
|
if verb == "excludes" || verb == "conflicts" {
|
||||||
|
if have, ok := ev.answers[q]; ok && matchesAnswer(have, want) {
|
||||||
|
ev.msg("error", "conflict", fmt.Sprintf("%s=%v cannot be combined with this choice (%s)", q, catalog.Scalar(want), source), source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if verb == "requires" {
|
||||||
|
if have, ok := ev.answers[q]; !ok || !matchesAnswer(have, want) {
|
||||||
|
ev.msg("error", "requires-answer", fmt.Sprintf("%s requires %s=%v", source, q, catalog.Scalar(want)), source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
put(fx.Requires, ev.reqPkg, ev.reqCap, "requires")
|
||||||
|
put(fx.Implies, ev.reqPkg, ev.implCap, "implies")
|
||||||
|
put(fx.Excludes, nil, ev.exclCap, "excludes")
|
||||||
|
put(fx.Conflicts, ev.conflPkg, ev.exclCap, "conflicts")
|
||||||
|
put(fx.Recommends, ev.recPkg, ev.recCap, "recommends")
|
||||||
|
put(fx.Discourages, ev.discPkg, ev.discCap, "discourages")
|
||||||
|
for _, c := range fx.Provides {
|
||||||
|
ev.extCap[c] = source
|
||||||
|
parts = append(parts, "provides "+c+" (external)")
|
||||||
|
}
|
||||||
|
if len(parts) == 0 && kind == "option" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sort.Strings(parts)
|
||||||
|
ev.st.Rules = append(ev.st.Rules, AppliedRule{ID: source, Source: kind, Effect: strings.Join(parts, "; "), Reason: reason})
|
||||||
|
}
|
||||||
|
|
||||||
|
func matchesAnswer(have, want any) bool {
|
||||||
|
for _, h := range listOf(have) {
|
||||||
|
for _, w := range listOf(want) {
|
||||||
|
if catalog.Equal(h, w) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- packages, capabilities, modules ---------------------------------------
|
||||||
|
|
||||||
|
func (ev *evaluation) pkg(id, status, reason string) *PackageState {
|
||||||
|
p, ok := ev.pkgs[id]
|
||||||
|
if !ok {
|
||||||
|
cp := ev.e.Cat.Packages[id]
|
||||||
|
title := id
|
||||||
|
_ = cp
|
||||||
|
p = &PackageState{ID: id, Title: title, Summary: ev.e.PackageSummary(id), Status: status, Reasons: []string{}}
|
||||||
|
ev.pkgs[id] = p
|
||||||
|
ev.pkgSeen = append(ev.pkgSeen, id)
|
||||||
|
}
|
||||||
|
if rank(status) > rank(p.Status) {
|
||||||
|
p.Status = status
|
||||||
|
}
|
||||||
|
if status == StRequired || status == StSelected || status == StOptional {
|
||||||
|
p.Selected = true
|
||||||
|
}
|
||||||
|
for _, r := range p.Reasons {
|
||||||
|
if r == reason {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if reason != "" {
|
||||||
|
p.Reasons = append(p.Reasons, reason)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func rank(s string) int {
|
||||||
|
switch s {
|
||||||
|
case StRequired:
|
||||||
|
return 4
|
||||||
|
case StSelected:
|
||||||
|
return 3
|
||||||
|
case StOptional:
|
||||||
|
return 2
|
||||||
|
case StRecommended:
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) packages() {
|
||||||
|
for _, pu := range ev.s.Spec.Packages {
|
||||||
|
holds := len(pu.When) == 0 || pu.When.Holds(ev.env)
|
||||||
|
if pu.Recommended {
|
||||||
|
// a recommendation never selects a package
|
||||||
|
if holds {
|
||||||
|
ev.pkg(pu.ID, StRecommended, firstNonEmpty(pu.Reason, "recommended for this solution"))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !holds {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
status := StRequired
|
||||||
|
if pu.Role == "optional" {
|
||||||
|
status = StOptional
|
||||||
|
}
|
||||||
|
p := ev.pkg(pu.ID, status, firstNonEmpty(pu.Reason, "part of this solution"))
|
||||||
|
if pu.Profile != "" {
|
||||||
|
p.Profile = pu.Profile
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(ev.reqPkg) {
|
||||||
|
for _, r := range ev.reqPkg[id] {
|
||||||
|
ev.pkg(id, StRequired, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(ev.recPkg) {
|
||||||
|
for _, r := range ev.recPkg[id] {
|
||||||
|
ev.pkg(id, StRecommended, r)
|
||||||
|
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Package: id, Reason: r, Source: r})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// modules from profiles
|
||||||
|
for _, id := range ev.pkgSeen {
|
||||||
|
p := ev.pkgs[id]
|
||||||
|
if !p.Selected {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ev.mods[id] = map[string]*ModuleState{}
|
||||||
|
cp := ev.e.Cat.Packages[id]
|
||||||
|
for _, m := range cp.Spec.Modules {
|
||||||
|
ev.mods[id][m.ID] = &ModuleState{ID: m.ID, Title: m.Title, Program: m.Program, Kind: m.Kind, Support: statusOf(m.Support)}
|
||||||
|
}
|
||||||
|
if p.Profile == "" {
|
||||||
|
// no profile: every selectable module of the package is used
|
||||||
|
for _, m := range cp.Spec.Modules {
|
||||||
|
if m.Support.Selectable() {
|
||||||
|
ms := ev.mods[id][m.ID]
|
||||||
|
ms.Enabled = true
|
||||||
|
ms.Reason = "package " + id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
chain, err := ev.e.Cat.ProfileChain(id, p.Profile)
|
||||||
|
if err != nil {
|
||||||
|
ev.msg("error", "profile", err.Error(), "package:"+id)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, prof := range chain {
|
||||||
|
for mid, state := range prof.Spec.Modules {
|
||||||
|
if ms := ev.mods[id][mid]; ms != nil {
|
||||||
|
ms.Enabled = state == "enabled"
|
||||||
|
ms.Reason = "profile " + prof.Key()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, r := range prof.Spec.Recommendations {
|
||||||
|
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Package: r.Package, Capability: r.Capability, Reason: r.Reason, Source: "profile:" + prof.Key()})
|
||||||
|
if r.Package != "" {
|
||||||
|
ev.pkg(r.Package, StRecommended, r.Reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, m := range catalog.SortedIDs(ev.reqMod) {
|
||||||
|
pkg, mod, _ := strings.Cut(m, "/")
|
||||||
|
ev.pkg(pkg, StRequired, ev.reqMod[m][0])
|
||||||
|
ev.ensureMods(pkg)
|
||||||
|
if ms := ev.mods[pkg][mod]; ms != nil {
|
||||||
|
ms.Enabled = true
|
||||||
|
ms.Reason = ev.reqMod[m][0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, m := range catalog.SortedIDs(ev.exclMod) {
|
||||||
|
pkg, mod, _ := strings.Cut(m, "/")
|
||||||
|
if ms := ev.mods[pkg][mod]; ms != nil {
|
||||||
|
if _, needed := ev.reqMod[m]; needed {
|
||||||
|
ev.msg("error", "module-conflict", fmt.Sprintf("module %s is both required and excluded (%s)", m, ev.exclMod[m][0]), ev.exclMod[m][0])
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ms.Enabled = false
|
||||||
|
ms.Reason = "excluded by " + ev.exclMod[m][0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) ensureMods(pkg string) {
|
||||||
|
if ev.mods[pkg] != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ev.mods[pkg] = map[string]*ModuleState{}
|
||||||
|
cp := ev.e.Cat.Packages[pkg]
|
||||||
|
if cp == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
profile := ""
|
||||||
|
if p := ev.pkgs[pkg]; p != nil {
|
||||||
|
profile = p.Profile
|
||||||
|
}
|
||||||
|
for _, m := range cp.Spec.Modules {
|
||||||
|
ms := &ModuleState{ID: m.ID, Title: m.Title, Program: m.Program, Kind: m.Kind, Support: statusOf(m.Support)}
|
||||||
|
if profile == "" && m.Support.Selectable() {
|
||||||
|
ms.Enabled, ms.Reason = true, "package "+pkg
|
||||||
|
}
|
||||||
|
ev.mods[pkg][m.ID] = ms
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstNonEmpty(a ...string) string {
|
||||||
|
for _, s := range a {
|
||||||
|
if s != "" {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) capTitle(id string) string {
|
||||||
|
if c, ok := ev.e.Cat.Capabilities[id]; ok {
|
||||||
|
return Tr(c.Translations, ev.st.Locale, "title", c.Title)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) capState(id string) *CapState {
|
||||||
|
c, ok := ev.caps[id]
|
||||||
|
if !ok {
|
||||||
|
c = &CapState{ID: id, Title: ev.capTitle(id), Reasons: []string{}}
|
||||||
|
ev.caps[id] = c
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) capabilities() {
|
||||||
|
type need struct{ id, reason string }
|
||||||
|
var queue []need
|
||||||
|
for _, c := range ev.s.Spec.Capabilities.Required {
|
||||||
|
queue = append(queue, need{c, "required by the solution"})
|
||||||
|
}
|
||||||
|
for _, m := range []map[string][]string{ev.reqCap, ev.implCap} {
|
||||||
|
for _, c := range catalog.SortedIDs(m) {
|
||||||
|
queue = append(queue, need{c, m[c][0]})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// requirements of modules the profiles enabled
|
||||||
|
for _, pid := range ev.pkgSeen {
|
||||||
|
cp := ev.e.Cat.Packages[pid]
|
||||||
|
for _, m := range cp.Spec.Modules {
|
||||||
|
if ms := ev.mods[pid][m.ID]; ms != nil && ms.Enabled {
|
||||||
|
for _, r := range m.Requires {
|
||||||
|
queue = append(queue, need{r, "needed by " + pid + "/" + m.ID})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
done := map[string]bool{}
|
||||||
|
for steps := 0; len(queue) > 0 && steps < 10000; steps++ {
|
||||||
|
n := queue[0]
|
||||||
|
queue = queue[1:]
|
||||||
|
cs := ev.capState(n.id)
|
||||||
|
add2(&cs.Reasons, n.reason)
|
||||||
|
if done[n.id] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
done[n.id] = true
|
||||||
|
cs.Status = StRequired
|
||||||
|
if src, ok := ev.exclCap[n.id]; ok {
|
||||||
|
cs.Status = StConflicting
|
||||||
|
ev.msg("error", "capability-conflict", fmt.Sprintf("%s is needed (%s) but excluded (%s)", n.id, n.reason, src[0]), src[0])
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if src, ok := ev.extCap[n.id]; ok {
|
||||||
|
cs.Status = StExternal
|
||||||
|
cs.Provider = "external:" + src
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var chosen *catalog.ModuleRef
|
||||||
|
var alts []string
|
||||||
|
providers := ev.e.Cat.ProvidersOf(n.id)
|
||||||
|
// a module that already provides it wins, then a selected package
|
||||||
|
pick := func(f func(catalog.ModuleRef) bool) {
|
||||||
|
for i := range providers {
|
||||||
|
if chosen == nil && providers[i].Support.Selectable() && f(providers[i]) {
|
||||||
|
chosen = &providers[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pick(func(r catalog.ModuleRef) bool {
|
||||||
|
ms := ev.mods[r.Package][r.Module]
|
||||||
|
return ms != nil && ms.Enabled
|
||||||
|
})
|
||||||
|
pick(func(r catalog.ModuleRef) bool { return ev.pkgs[r.Package] != nil && ev.pkgs[r.Package].Selected })
|
||||||
|
pick(func(r catalog.ModuleRef) bool { return true })
|
||||||
|
for _, pr := range providers {
|
||||||
|
if chosen == nil || pr != *chosen {
|
||||||
|
alts = append(alts, pr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c, ok := ev.e.Cat.Capabilities[n.id]; ok {
|
||||||
|
for _, x := range c.External {
|
||||||
|
alts = append(alts, "external:"+x.ID)
|
||||||
|
}
|
||||||
|
for _, r := range c.Requires {
|
||||||
|
queue = append(queue, need{r, "needed by " + n.id})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cs.Alternatives = alts
|
||||||
|
if chosen == nil {
|
||||||
|
cs.Status = StMissing
|
||||||
|
ev.msg("error", "capability-missing", fmt.Sprintf("no available provider for %s (%s)", n.id, n.reason), "")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cs.Provider = chosen.String()
|
||||||
|
p := ev.pkg(chosen.Package, StRequired, "provides "+n.id)
|
||||||
|
_ = p
|
||||||
|
ev.ensureMods(chosen.Package)
|
||||||
|
ms := ev.mods[chosen.Package][chosen.Module]
|
||||||
|
if !ms.Enabled {
|
||||||
|
if src, excluded := ev.exclMod[chosen.String()]; excluded {
|
||||||
|
cs.Status = StConflicting
|
||||||
|
ev.msg("error", "module-conflict", fmt.Sprintf("%s needs module %s, which is excluded (%s)", n.id, chosen, src[0]), src[0])
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ms.Enabled = true
|
||||||
|
ms.Reason = "provides " + n.id
|
||||||
|
}
|
||||||
|
cm := ev.e.Cat.Packages[chosen.Package].Module(chosen.Module)
|
||||||
|
for _, r := range cm.Requires {
|
||||||
|
queue = append(queue, need{r, "needed by " + chosen.String()})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// capabilities provided as a side effect, recommended, optional, excluded
|
||||||
|
for _, pid := range ev.pkgSeen {
|
||||||
|
for _, m := range ev.e.Cat.Packages[pid].Spec.Modules {
|
||||||
|
if ms := ev.mods[pid][m.ID]; ms != nil && ms.Enabled {
|
||||||
|
for _, c := range m.Provides {
|
||||||
|
if !ev.requiresMet(c) {
|
||||||
|
continue // e.g. AI analysis without an AI server
|
||||||
|
}
|
||||||
|
cs := ev.capState(c)
|
||||||
|
if cs.Status == "" {
|
||||||
|
cs.Status = StSelected
|
||||||
|
cs.Provider = pid + "/" + m.ID
|
||||||
|
add2(&cs.Reasons, "provided by "+pid+"/"+m.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// capabilities the user's answers say exist outside Yetano
|
||||||
|
for _, c := range catalog.SortedIDs(ev.extCap) {
|
||||||
|
cs := ev.capState(c)
|
||||||
|
if cs.Status == "" {
|
||||||
|
cs.Status = StExternal
|
||||||
|
cs.Provider = "external:" + ev.extCap[c]
|
||||||
|
add2(&cs.Reasons, "provided outside Yetano ("+ev.extCap[c]+")")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
soft := func(list []string, m map[string][]string, status, why string) {
|
||||||
|
ids := append([]string{}, list...)
|
||||||
|
ids = append(ids, catalog.SortedIDs(m)...)
|
||||||
|
for _, c := range ids {
|
||||||
|
cs := ev.capState(c)
|
||||||
|
if cs.Status != "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cs.Status = status
|
||||||
|
r := why
|
||||||
|
if rs, ok := m[c]; ok {
|
||||||
|
r = rs[0]
|
||||||
|
}
|
||||||
|
add2(&cs.Reasons, r)
|
||||||
|
for _, pr := range ev.e.Cat.ProvidersOf(c) {
|
||||||
|
cs.Alternatives = append(cs.Alternatives, pr.String())
|
||||||
|
}
|
||||||
|
if status == StRecommended {
|
||||||
|
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Capability: c, Reason: r, Source: r})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
soft(ev.s.Spec.Capabilities.Recommended, ev.recCap, StRecommended, "recommended by the solution")
|
||||||
|
soft(ev.s.Spec.Capabilities.Optional, nil, StOptional, "optional for this solution")
|
||||||
|
for _, c := range catalog.SortedIDs(ev.exclCap) {
|
||||||
|
cs := ev.capState(c)
|
||||||
|
// required and excluded was reported above; a capability an enabled
|
||||||
|
// module merely could provide is just not used
|
||||||
|
if cs.Status == "" || cs.Status == StSelected {
|
||||||
|
cs.Status = StExcluded
|
||||||
|
cs.Provider = ""
|
||||||
|
add2(&cs.Reasons, "excluded by "+ev.exclCap[c][0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// capability-level conflicts between provided capabilities
|
||||||
|
for _, id := range catalog.SortedIDs(ev.caps) {
|
||||||
|
cs := ev.caps[id]
|
||||||
|
if c, ok := ev.e.Cat.Capabilities[id]; ok && provided(cs.Status) {
|
||||||
|
for _, other := range c.Conflicts {
|
||||||
|
if o, ok := ev.caps[other]; ok && provided(o.Status) && id < other {
|
||||||
|
ev.msg("error", "capability-conflict", fmt.Sprintf("%s and %s cannot be combined", id, other), "capability:"+id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, c := range catalog.SortedIDs(ev.discCap) {
|
||||||
|
if cs, ok := ev.caps[c]; ok && provided(cs.Status) {
|
||||||
|
ev.msg("warning", "discouraged", fmt.Sprintf("%s is possible but not recommended here (%s)", c, ev.discCap[c][0]), ev.discCap[c][0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// requiresMet: every capability c requires is required/provided already.
|
||||||
|
func (ev *evaluation) requiresMet(c string) bool {
|
||||||
|
cp, ok := ev.e.Cat.Capabilities[c]
|
||||||
|
if !ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, r := range cp.Requires {
|
||||||
|
if cs, ok := ev.caps[r]; !ok || !provided(cs.Status) {
|
||||||
|
if _, ext := ev.extCap[r]; !ext {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func provided(s string) bool {
|
||||||
|
return s == StRequired || s == StSelected || s == StExternal
|
||||||
|
}
|
||||||
|
|
||||||
|
func add2(list *[]string, s string) {
|
||||||
|
for _, x := range *list {
|
||||||
|
if x == s {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*list = append(*list, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) finishModules() {
|
||||||
|
for _, id := range catalog.SortedIDs(ev.conflPkg) {
|
||||||
|
if p, ok := ev.pkgs[id]; ok && p.Selected {
|
||||||
|
ev.msg("error", "package-conflict", fmt.Sprintf("package %s cannot be used with this choice (%s)", id, ev.conflPkg[id][0]), ev.conflPkg[id][0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(ev.discPkg) {
|
||||||
|
if p, ok := ev.pkgs[id]; ok && p.Selected {
|
||||||
|
ev.msg("warning", "discouraged", fmt.Sprintf("package %s is possible but not recommended here (%s)", id, ev.discPkg[id][0]), ev.discPkg[id][0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ids := append([]string{}, ev.pkgSeen...)
|
||||||
|
sort.Strings(ids)
|
||||||
|
for _, id := range ids {
|
||||||
|
p := ev.pkgs[id]
|
||||||
|
if p.Selected {
|
||||||
|
cp := ev.e.Cat.Packages[id]
|
||||||
|
for _, m := range cp.Spec.Modules {
|
||||||
|
ms := ev.mods[id][m.ID]
|
||||||
|
if ms == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ms.Enabled && (m.Support == catalog.Experimental || m.Support == catalog.Untested) {
|
||||||
|
ev.msg("warning", "support-"+string(m.Support), fmt.Sprintf("module %s/%s is %s", id, m.ID, m.Support), "package:"+id)
|
||||||
|
}
|
||||||
|
p.Modules = append(p.Modules, *ms)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ev.st.Packages = append(ev.st.Packages, *p)
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(ev.caps) {
|
||||||
|
ev.st.Capabilities = append(ev.st.Capabilities, *ev.caps[id])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// moduleEnabled reports whether pkg/module is enabled in this evaluation.
|
||||||
|
func (ev *evaluation) moduleEnabled(pkg, mod string) bool {
|
||||||
|
ms := ev.mods[pkg][mod]
|
||||||
|
return ms != nil && ms.Enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) pkgSelected(id string) bool {
|
||||||
|
p, ok := ev.pkgs[id]
|
||||||
|
return ok && p.Selected
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) finish() {
|
||||||
|
st := ev.st
|
||||||
|
refs := append([]string{}, ev.s.Spec.References.All()...)
|
||||||
|
for _, q := range st.Questions {
|
||||||
|
if q.Visible {
|
||||||
|
refs = append(refs, q.References...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, r := range refs {
|
||||||
|
if !seen[r] {
|
||||||
|
seen[r] = true
|
||||||
|
st.References = append(st.References, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
st.Related = ev.s.Spec.Related
|
||||||
|
sort.SliceStable(st.Messages, func(i, j int) bool { return sevRank(st.Messages[i].Severity) > sevRank(st.Messages[j].Severity) })
|
||||||
|
errs := 0
|
||||||
|
for _, m := range st.Messages {
|
||||||
|
if m.Severity == "error" {
|
||||||
|
errs++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
st.Complete = len(st.Progress.Missing) == 0 && errs == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func sevRank(s string) int {
|
||||||
|
switch s {
|
||||||
|
case "error":
|
||||||
|
return 2
|
||||||
|
case "warning":
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Graph is the resolved architecture of a state (BP-03/BP-04). Node IDs:
|
||||||
|
// "pkg:<id>", "mod:<pkg>/<module>", "cap:<id>", "ext:<id>" and the
|
||||||
|
// solution's own node IDs ("n:<id>").
|
||||||
|
type Graph struct {
|
||||||
|
Nodes []GraphNode `json:"nodes"`
|
||||||
|
Edges []GraphEdge `json:"edges"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GraphNode is one node with its state (required, selected, ...).
|
||||||
|
type GraphNode struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Type string `json:"type"` // package | module | capability | external | client | storage | network | identity | target | solution
|
||||||
|
Title string `json:"title"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Parent string `json:"parent,omitempty"` // module -> package
|
||||||
|
Ref string `json:"ref,omitempty"` // yetano: reference to open
|
||||||
|
}
|
||||||
|
|
||||||
|
// GraphEdge is a typed relation (requires, provides, connectsTo, ...).
|
||||||
|
type GraphEdge struct {
|
||||||
|
From string `json:"from"`
|
||||||
|
To string `json:"to"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Label string `json:"label,omitempty"`
|
||||||
|
Status string `json:"status,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) graph() {
|
||||||
|
g := Graph{Nodes: []GraphNode{}, Edges: []GraphEdge{}}
|
||||||
|
have := map[string]bool{}
|
||||||
|
node := func(n GraphNode) {
|
||||||
|
if !have[n.ID] {
|
||||||
|
have[n.ID] = true
|
||||||
|
g.Nodes = append(g.Nodes, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
edge := func(e GraphEdge) { g.Edges = append(g.Edges, e) }
|
||||||
|
solID := "sol:" + ev.s.Meta.ID
|
||||||
|
node(GraphNode{ID: solID, Type: "solution", Title: ev.st.Solution.Title, Status: StSelected, Ref: "yetano:solution/" + ev.s.Meta.ID})
|
||||||
|
for _, p := range ev.st.Packages {
|
||||||
|
status := p.Status
|
||||||
|
switch {
|
||||||
|
case !p.Selected:
|
||||||
|
status = StRecommended
|
||||||
|
case status == StOptional:
|
||||||
|
status = StSelected // an optional package the answers chose
|
||||||
|
}
|
||||||
|
pid := "pkg:" + p.ID
|
||||||
|
node(GraphNode{ID: pid, Type: "package", Title: p.ID, Status: status, Ref: "yetano:package/" + p.ID})
|
||||||
|
if p.Selected {
|
||||||
|
edge(GraphEdge{From: solID, To: pid, Type: "requires", Status: status})
|
||||||
|
} else {
|
||||||
|
edge(GraphEdge{From: solID, To: pid, Type: "optional", Label: "recommended", Status: StRecommended})
|
||||||
|
}
|
||||||
|
for _, m := range p.Modules {
|
||||||
|
st := StDisabled
|
||||||
|
if m.Enabled {
|
||||||
|
st = StSelected
|
||||||
|
}
|
||||||
|
if !m.Support.Selectable() {
|
||||||
|
st = StUnsupported
|
||||||
|
}
|
||||||
|
if !m.Enabled {
|
||||||
|
continue // disabled modules stay out of the picture; the package detail lists them
|
||||||
|
}
|
||||||
|
mid := "mod:" + p.ID + "/" + m.ID
|
||||||
|
node(GraphNode{ID: mid, Type: "module", Title: firstNonEmpty(m.Program, m.ID), Status: st, Parent: pid, Ref: "yetano:module/" + p.ID + "/" + m.ID})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, c := range ev.st.Capabilities {
|
||||||
|
cid := "cap:" + c.ID
|
||||||
|
node(GraphNode{ID: cid, Type: "capability", Title: c.Title, Status: c.Status, Ref: "yetano:capability/" + c.ID})
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(c.Provider, "external:"):
|
||||||
|
xid := "ext:" + c.ID
|
||||||
|
node(GraphNode{ID: xid, Type: "external", Title: "existing " + c.Title, Status: StExternal})
|
||||||
|
edge(GraphEdge{From: xid, To: cid, Type: "provides", Status: StExternal})
|
||||||
|
case c.Provider != "":
|
||||||
|
pkg, _, _ := strings.Cut(c.Provider, "/")
|
||||||
|
from := "mod:" + c.Provider
|
||||||
|
if !have[from] {
|
||||||
|
from = "pkg:" + pkg
|
||||||
|
}
|
||||||
|
edge(GraphEdge{From: from, To: cid, Type: "provides", Status: c.Status})
|
||||||
|
}
|
||||||
|
if c.Status == StRecommended || c.Status == StOptional || c.Status == StMissing {
|
||||||
|
for _, alt := range c.Alternatives {
|
||||||
|
if strings.HasPrefix(alt, "external:") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pkg, _, _ := strings.Cut(alt, "/")
|
||||||
|
if !have["pkg:"+pkg] {
|
||||||
|
node(GraphNode{ID: "pkg:" + pkg, Type: "package", Title: pkg, Status: StAlternative, Ref: "yetano:package/" + pkg})
|
||||||
|
}
|
||||||
|
edge(GraphEdge{From: "pkg:" + pkg, To: cid, Type: "alternativeTo", Status: StAlternative})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.Status == StRequired || c.Status == StMissing || c.Status == StConflicting {
|
||||||
|
edge(GraphEdge{From: solID, To: cid, Type: "requires", Status: c.Status})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// not implemented options of visible questions: shown as unsupported alternatives
|
||||||
|
for _, q := range ev.st.Questions {
|
||||||
|
if !q.Visible {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, o := range q.Options {
|
||||||
|
if o.Support.Selectable() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, a := range o.Adds {
|
||||||
|
if p, ok := strings.CutPrefix(a, "package:"); ok && !have["pkg:"+p] {
|
||||||
|
node(GraphNode{ID: "pkg:" + p, Type: "package", Title: p, Status: StUnsupported, Ref: "yetano:package/" + p})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// solution-specific nodes and edges
|
||||||
|
for _, n := range ev.s.Spec.Architecture.Nodes {
|
||||||
|
if len(n.When) > 0 && !n.When.Holds(ev.env) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
st := StSelected
|
||||||
|
if n.Type == "external" || n.Type == "client" {
|
||||||
|
st = StExternal
|
||||||
|
}
|
||||||
|
title, err := expand(n.Title, ev.vars())
|
||||||
|
if err != nil {
|
||||||
|
title = n.Title
|
||||||
|
}
|
||||||
|
node(GraphNode{ID: "n:" + n.ID, Type: n.Type, Title: strings.Trim(title, "'"), Status: st})
|
||||||
|
}
|
||||||
|
resolve := func(id string) string {
|
||||||
|
if strings.Contains(id, ":") {
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
return "n:" + id
|
||||||
|
}
|
||||||
|
for _, e := range ev.s.Spec.Architecture.Edges {
|
||||||
|
if len(e.When) > 0 && !e.When.Holds(ev.env) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
from, to := resolve(e.From), resolve(e.To)
|
||||||
|
if !have[from] || !have[to] || !inUse(g, from) || !inUse(g, to) {
|
||||||
|
continue // an end that is not part of this resolution
|
||||||
|
}
|
||||||
|
edge(GraphEdge{From: from, To: to, Type: e.Type, Label: e.Label})
|
||||||
|
}
|
||||||
|
// confirmed Big Picture connections between selected packages
|
||||||
|
if bp := ev.e.Cat.BigPicture; bp != nil {
|
||||||
|
byProduct := map[string]string{}
|
||||||
|
for _, p := range ev.st.Packages {
|
||||||
|
if cp := ev.e.Cat.Packages[p.ID]; cp != nil && p.Selected {
|
||||||
|
byProduct[cp.Spec.BigPicture] = "pkg:" + p.ID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, c := range bp.Connections {
|
||||||
|
f, okf := byProduct[c.From]
|
||||||
|
t, okt := byProduct[c.To]
|
||||||
|
if okf && okt && c.Review == "confirmed" {
|
||||||
|
edge(GraphEdge{From: f, To: t, Type: c.Type, Label: c.Label})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.SliceStable(g.Edges, func(i, j int) bool {
|
||||||
|
a, b := g.Edges[i], g.Edges[j]
|
||||||
|
return fmt.Sprint(a.From, a.To, a.Type) < fmt.Sprint(b.From, b.To, b.Type)
|
||||||
|
})
|
||||||
|
ev.st.Graph = g
|
||||||
|
}
|
||||||
|
|
||||||
|
// inUse: the node is part of the solution (not only an alternative).
|
||||||
|
func inUse(g Graph, id string) bool {
|
||||||
|
for _, n := range g.Nodes {
|
||||||
|
if n.ID == id {
|
||||||
|
switch n.Status {
|
||||||
|
case StRequired, StSelected, StExternal:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// GraphText renders a graph as indented text for the CLI (BP-06).
|
||||||
|
func GraphText(g Graph) string {
|
||||||
|
var b strings.Builder
|
||||||
|
byID := map[string]GraphNode{}
|
||||||
|
for _, n := range g.Nodes {
|
||||||
|
byID[n.ID] = n
|
||||||
|
}
|
||||||
|
mark := func(status string) string {
|
||||||
|
switch status {
|
||||||
|
case StRequired, StSelected:
|
||||||
|
return "+"
|
||||||
|
case StRecommended, StOptional, StAlternative:
|
||||||
|
return "?"
|
||||||
|
case StExternal:
|
||||||
|
return "~"
|
||||||
|
case StMissing, StConflicting, StUnsupported:
|
||||||
|
return "!"
|
||||||
|
}
|
||||||
|
return " "
|
||||||
|
}
|
||||||
|
for _, n := range g.Nodes {
|
||||||
|
if n.Type != "package" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&b, "%s %s [%s]\n", mark(n.Status), n.Title, n.Status)
|
||||||
|
for _, m := range g.Nodes {
|
||||||
|
if m.Parent == n.ID {
|
||||||
|
fmt.Fprintf(&b, " %s %s\n", mark(m.Status), m.Title)
|
||||||
|
for _, e := range g.Edges {
|
||||||
|
if e.From == m.ID && e.Type == "provides" {
|
||||||
|
fmt.Fprintf(&b, " provides %s\n", byID[e.To].Title)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var other []string
|
||||||
|
for _, n := range g.Nodes {
|
||||||
|
switch n.Type {
|
||||||
|
case "external", "client", "storage", "network", "identity", "target":
|
||||||
|
other = append(other, fmt.Sprintf("%s %s (%s)", mark(n.Status), n.Title, n.Type))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(other) > 0 {
|
||||||
|
b.WriteString("around it:\n")
|
||||||
|
for _, o := range other {
|
||||||
|
fmt.Fprintf(&b, " %s\n", o)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var rel []string
|
||||||
|
for _, e := range g.Edges {
|
||||||
|
f, t := byID[e.From], byID[e.To]
|
||||||
|
if e.Type == "provides" || e.Type == "requires" || e.Type == "optional" || f.Type == "solution" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
label := e.Type
|
||||||
|
if e.Label != "" {
|
||||||
|
label += " (" + e.Label + ")"
|
||||||
|
}
|
||||||
|
rel = append(rel, fmt.Sprintf(" %s --%s--> %s", f.Title, label, t.Title))
|
||||||
|
}
|
||||||
|
if len(rel) > 0 {
|
||||||
|
b.WriteString("connections:\n")
|
||||||
|
b.WriteString(strings.Join(rel, "\n"))
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
b.WriteString("legend: + used ? recommended/optional ~ external ! missing/unsupported\n")
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ = catalog.Supported
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HandbookPage is one Markdown page of a solution handbook (HB-01).
|
||||||
|
type HandbookPage struct {
|
||||||
|
Path string
|
||||||
|
Content []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handbook composes the handbook of a state from the solution, the
|
||||||
|
// decisions, the generated files and existing manual text (via mr). It
|
||||||
|
// covers only what was chosen (HB-02) and never prints secret values
|
||||||
|
// (HB-04): secret answers are references and are shown as such.
|
||||||
|
func (e *Engine) Handbook(st *State, mr ManualReader) []HandbookPage {
|
||||||
|
s := e.Cat.Lookup(st.Solution.ID)
|
||||||
|
link := func(ref string) string {
|
||||||
|
if mr != nil {
|
||||||
|
if l := mr.Link(ref); l != "" {
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "`" + ref + "`"
|
||||||
|
}
|
||||||
|
excerpt := func(b *strings.Builder, ref string) {
|
||||||
|
if mr == nil {
|
||||||
|
fmt.Fprintf(b, "- %s\n", link(ref))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
title, md, ok := mr.Excerpt(ref, 40)
|
||||||
|
if !ok {
|
||||||
|
fmt.Fprintf(b, "- %s\n", link(ref))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(b, "> From the manual: **%s** (%s)\n>\n", title, link(ref))
|
||||||
|
for _, line := range strings.Split(strings.TrimRight(md, "\n"), "\n") {
|
||||||
|
fmt.Fprintf(b, "> %s\n", line)
|
||||||
|
}
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
var pages []HandbookPage
|
||||||
|
page := func(name, title string, body func(b *strings.Builder)) {
|
||||||
|
var b strings.Builder
|
||||||
|
fmt.Fprintf(&b, "# %s\n\n", title)
|
||||||
|
body(&b)
|
||||||
|
pages = append(pages, HandbookPage{Path: "handbook/" + name, Content: []byte(b.String())})
|
||||||
|
}
|
||||||
|
selected := []PackageState{}
|
||||||
|
for _, p := range st.Packages {
|
||||||
|
if p.Selected {
|
||||||
|
selected = append(selected, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hasCap := func(prefix string) bool {
|
||||||
|
for _, c := range st.Capabilities {
|
||||||
|
if strings.HasPrefix(c.ID, prefix) && provided(c.Status) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
secretQ := map[string]bool{}
|
||||||
|
for _, q := range s.Spec.Questions {
|
||||||
|
if q.Type == "secret" {
|
||||||
|
secretQ[q.ID] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
page("index.md", "Handbook: "+firstNonEmpty(st.Instance, st.Solution.Title), func(b *strings.Builder) {
|
||||||
|
fmt.Fprintf(b, "%s\n\n", st.Solution.Summary)
|
||||||
|
fmt.Fprintf(b, "Solution `%s` %s, status **%s**.\n\n", st.Solution.ID, st.Solution.Version, st.Solution.Status)
|
||||||
|
b.WriteString("1. [Your architecture](architecture.md)\n2. [Installation and configuration](installation.md)\n3. [Configuration reference](configuration.md)\n4. [Security](security.md)\n5. [Operations and maintenance](operations.md)\n")
|
||||||
|
if hasCap("backup.") {
|
||||||
|
b.WriteString("6. [Backup and restore](backup-restore.md)\n7. [Troubleshooting](troubleshooting.md)\n")
|
||||||
|
} else {
|
||||||
|
b.WriteString("6. [Troubleshooting](troubleshooting.md)\n")
|
||||||
|
}
|
||||||
|
b.WriteString("\n## Your decisions\n\n| Question | Answer | From |\n|---|---|---|\n")
|
||||||
|
for _, q := range st.Questions {
|
||||||
|
if !q.Visible || q.Value == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val := answerText(q)
|
||||||
|
if secretQ[q.ID] {
|
||||||
|
val = "(secret reference)"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(b, "| %s | %s | %s |\n", q.Title, val, q.Origin)
|
||||||
|
}
|
||||||
|
if len(st.Messages) > 0 {
|
||||||
|
b.WriteString("\n## Notes and warnings\n\n")
|
||||||
|
for _, m := range st.Messages {
|
||||||
|
fmt.Fprintf(b, "- **%s**: %s\n", m.Severity, m.Text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
page("architecture.md", "Your architecture", func(b *strings.Builder) {
|
||||||
|
b.WriteString("```text\n")
|
||||||
|
b.WriteString(GraphText(st.Graph))
|
||||||
|
b.WriteString("```\n\n## Packages\n\n")
|
||||||
|
for _, p := range selected {
|
||||||
|
fmt.Fprintf(b, "### %s\n\n%s\n\n", p.ID, p.Summary)
|
||||||
|
if p.Profile != "" {
|
||||||
|
fmt.Fprintf(b, "Profile: `%s`. ", p.Profile)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(b, "Why: %s.\n\n", strings.Join(p.Reasons, "; "))
|
||||||
|
var on []string
|
||||||
|
for _, m := range p.Modules {
|
||||||
|
if m.Enabled {
|
||||||
|
on = append(on, fmt.Sprintf("`%s`", firstNonEmpty(m.Program, m.ID)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(on) > 0 {
|
||||||
|
fmt.Fprintf(b, "Programs used: %s.\n\n", strings.Join(on, ", "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.WriteString("## Capabilities\n\n| Capability | Status | Provided by |\n|---|---|---|\n")
|
||||||
|
for _, c := range st.Capabilities {
|
||||||
|
if c.Status == StExcluded {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fmt.Fprintf(b, "| %s | %s | %s |\n", c.Title, c.Status, firstNonEmpty(c.Provider, "–"))
|
||||||
|
}
|
||||||
|
if st.Solution.BigPicture != "" {
|
||||||
|
fmt.Fprintf(b, "\nIn the Big Picture: %s\n", link("yetano:bigpicture/"+st.Solution.BigPicture))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
page("installation.md", "Installation and configuration", func(b *strings.Builder) {
|
||||||
|
b.WriteString("The guide has not changed any system. These are the steps, in order;\n" +
|
||||||
|
"`deployment-plan.yaml` has the same list in machine-readable form.\n\n")
|
||||||
|
phase := ""
|
||||||
|
n := 0
|
||||||
|
for _, sp := range st.Steps {
|
||||||
|
if sp.Phase != phase {
|
||||||
|
phase = sp.Phase
|
||||||
|
fmt.Fprintf(b, "## %s\n\n", strings.ToUpper(phase[:1])+phase[1:])
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
fmt.Fprintf(b, "%d. %s\n", n, sp.Title)
|
||||||
|
if sp.Run != "" {
|
||||||
|
fmt.Fprintf(b, "\n ```sh\n %s\n ```\n", sp.Run)
|
||||||
|
}
|
||||||
|
if sp.Note != "" {
|
||||||
|
fmt.Fprintf(b, "\n %s\n", sp.Note)
|
||||||
|
}
|
||||||
|
if sp.Reversible != nil && !*sp.Reversible {
|
||||||
|
b.WriteString("\n **Cannot be undone automatically.**\n")
|
||||||
|
}
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
page("configuration.md", "Configuration reference", func(b *strings.Builder) {
|
||||||
|
for _, f := range st.Files {
|
||||||
|
fmt.Fprintf(b, "## `%s`\n\n```yaml\n%s```\n\n", f.Path, f.Content)
|
||||||
|
keys := make([]string, 0, len(f.Origins))
|
||||||
|
for k := range f.Origins {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
b.WriteString("| Setting | Comes from | Uses answers |\n|---|---|---|\n")
|
||||||
|
for _, k := range keys {
|
||||||
|
o := f.Origins[k]
|
||||||
|
fmt.Fprintf(b, "| `%s` | %s | %s |\n", k, o.Source, strings.Join(o.Params, ", "))
|
||||||
|
}
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
for _, p := range selected {
|
||||||
|
if cp := e.Cat.Packages[p.ID]; cp != nil {
|
||||||
|
for _, m := range cp.Spec.Modules {
|
||||||
|
if ms := findModule(p, m.ID); ms != nil && ms.Enabled && m.Manual != "" {
|
||||||
|
fmt.Fprintf(b, "- Full option list of %s: %s\n", firstNonEmpty(m.Program, m.ID), link("yetano:manual/"+m.Manual+"/configuration"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
page("security.md", "Security", func(b *strings.Builder) {
|
||||||
|
b.WriteString("Secrets are never written into these files: secret answers are\nreferences (`secret://…` resolved by yaseva, `env:`, `file:`).\n\n")
|
||||||
|
for _, c := range st.Checks {
|
||||||
|
if c.Status == CheckNotApplicable {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if c.Kind == "tls" || c.Kind == "dns" || strings.Contains(c.ID, "tls") || strings.Contains(c.ID, "relay") {
|
||||||
|
fmt.Fprintf(b, "- **%s** (%s): %s", c.Title, c.Severity, c.Hint)
|
||||||
|
if c.Run != "" {
|
||||||
|
fmt.Fprintf(b, " Check: `%s`", c.Run)
|
||||||
|
}
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, r := range s.Spec.References.Manuals {
|
||||||
|
if strings.Contains(r, "dkim") || strings.Contains(r, "tls") || strings.Contains(r, "security") {
|
||||||
|
b.WriteString("\n")
|
||||||
|
excerpt(b, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
page("operations.md", "Operations and maintenance", func(b *strings.Builder) {
|
||||||
|
for _, op := range s.Spec.Operations {
|
||||||
|
fmt.Fprintf(b, "- %s\n", op)
|
||||||
|
}
|
||||||
|
b.WriteString("\n## Health checks\n\n")
|
||||||
|
for _, p := range selected {
|
||||||
|
if cp := e.Cat.Packages[p.ID]; cp != nil {
|
||||||
|
for _, m := range cp.Spec.Modules {
|
||||||
|
if ms := findModule(p, m.ID); ms != nil && ms.Enabled {
|
||||||
|
for _, d := range m.Doctor {
|
||||||
|
fmt.Fprintf(b, "- `%s`\n", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(st.Related) > 0 {
|
||||||
|
b.WriteString("\n## Related tasks and solutions\n\n")
|
||||||
|
for _, r := range st.Related {
|
||||||
|
kind := "solution"
|
||||||
|
if e.Cat.Tasks[r] != nil {
|
||||||
|
kind = "task"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(b, "- `yet %s show %s`\n", kind, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if hasCap("backup.") {
|
||||||
|
page("backup-restore.md", "Backup and restore", func(b *strings.Builder) {
|
||||||
|
for _, c := range st.Capabilities {
|
||||||
|
if strings.HasPrefix(c.ID, "backup.") && provided(c.Status) {
|
||||||
|
fmt.Fprintf(b, "- %s: %s\n", c.Title, c.Provider)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
page("troubleshooting.md", "Troubleshooting", func(b *strings.Builder) {
|
||||||
|
b.WriteString("Run the health checks from [operations](operations.md) first: they name\nthe failing area and give a hint.\n\n## Manuals\n\n")
|
||||||
|
refs := append([]string{}, st.References...)
|
||||||
|
for _, r := range refs {
|
||||||
|
if strings.HasPrefix(r, "yetano:manual/") {
|
||||||
|
fmt.Fprintf(b, "- %s\n", link(r))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return pages
|
||||||
|
}
|
||||||
|
|
||||||
|
func findModule(p PackageState, id string) *ModuleState {
|
||||||
|
for i := range p.Modules {
|
||||||
|
if p.Modules[i].ID == id {
|
||||||
|
return &p.Modules[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func answerText(q QuestionState) string {
|
||||||
|
if l, ok := q.Value.([]any); ok {
|
||||||
|
var parts []string
|
||||||
|
for _, x := range l {
|
||||||
|
parts = append(parts, optTitle(q, catalog.Scalar(x)))
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ", ")
|
||||||
|
}
|
||||||
|
return optTitle(q, catalog.Scalar(q.Value))
|
||||||
|
}
|
||||||
|
|
||||||
|
func optTitle(q QuestionState, v string) string {
|
||||||
|
for _, o := range q.Options {
|
||||||
|
if o.ID == v {
|
||||||
|
return o.Title
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
// Package engine is the Solutions Engine: it evaluates a solution's
|
||||||
|
// questions and rules against a user's answers, resolves packages,
|
||||||
|
// modules, capabilities and providers, generates native configuration
|
||||||
|
// with the origin of every value, and builds the architecture graph,
|
||||||
|
// the plan, the lock file and the handbook.
|
||||||
|
//
|
||||||
|
// The engine is pure: it reads a loaded catalog and values, and returns
|
||||||
|
// values. It never touches the network, never runs a command and writes
|
||||||
|
// files only in Write, into the directory it is given.
|
||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"sort"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Instance is a user's answers for one solution: a draft wizard session
|
||||||
|
// (kind WizardSession) or a saved solution instance (SolutionInstance).
|
||||||
|
// It never contains plain-text secrets (secret answers are references).
|
||||||
|
type Instance struct {
|
||||||
|
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
|
||||||
|
Kind string `yaml:"kind" json:"kind"`
|
||||||
|
Metadata InstanceMeta `yaml:"metadata" json:"metadata"`
|
||||||
|
Spec InstanceSpec `yaml:"spec" json:"spec"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// InstanceMeta names an instance.
|
||||||
|
type InstanceMeta struct {
|
||||||
|
Name string `yaml:"name" json:"name"`
|
||||||
|
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||||
|
Created string `yaml:"created,omitempty" json:"created,omitempty"`
|
||||||
|
Updated string `yaml:"updated,omitempty" json:"updated,omitempty"`
|
||||||
|
Favorite bool `yaml:"favorite,omitempty" json:"favorite,omitempty"`
|
||||||
|
Archived bool `yaml:"archived,omitempty" json:"archived,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// InstanceSpec holds the decisions.
|
||||||
|
type InstanceSpec struct {
|
||||||
|
Solution SolutionPin `yaml:"solution" json:"solution"`
|
||||||
|
Mode catalog.Level `yaml:"mode,omitempty" json:"mode,omitempty"`
|
||||||
|
Preset string `yaml:"preset,omitempty" json:"preset,omitempty"`
|
||||||
|
Locale string `yaml:"locale,omitempty" json:"locale,omitempty"`
|
||||||
|
Platform string `yaml:"platform,omitempty" json:"platform,omitempty"`
|
||||||
|
Target string `yaml:"target,omitempty" json:"target,omitempty"`
|
||||||
|
Parameters map[string]any `yaml:"parameters" json:"parameters"`
|
||||||
|
Overrides []Override `yaml:"overrides,omitempty" json:"overrides,omitempty"`
|
||||||
|
// Cursor is the question a wizard session was at (sessions only).
|
||||||
|
Cursor string `yaml:"cursor,omitempty" json:"cursor,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SolutionPin names the solution and the version the answers were made for.
|
||||||
|
type SolutionPin struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Version string `yaml:"version,omitempty" json:"version,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Override sets one value in a generated file directly (layer 6 of
|
||||||
|
// ARCHITECTURE.md): path is dot-separated map keys.
|
||||||
|
type Override struct {
|
||||||
|
File string `yaml:"file" json:"file"`
|
||||||
|
Path string `yaml:"path" json:"path"`
|
||||||
|
Value any `yaml:"value" json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preset is a reusable set of answers (PRE-01). Instance-specific and
|
||||||
|
// secret questions are never taken from a preset.
|
||||||
|
type Preset struct {
|
||||||
|
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
|
||||||
|
Kind string `yaml:"kind" json:"kind"`
|
||||||
|
Metadata InstanceMeta `yaml:"metadata" json:"metadata"`
|
||||||
|
Spec PresetSpec `yaml:"spec" json:"spec"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PresetSpec holds a preset's answers.
|
||||||
|
type PresetSpec struct {
|
||||||
|
Solution string `yaml:"solution,omitempty" json:"solution,omitempty"`
|
||||||
|
Version string `yaml:"version,omitempty" json:"version,omitempty"`
|
||||||
|
Mode catalog.Level `yaml:"mode,omitempty" json:"mode,omitempty"`
|
||||||
|
Parameters map[string]any `yaml:"parameters" json:"parameters"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewInstance starts a session for a solution.
|
||||||
|
func NewInstance(name string, s *catalog.Solution, mode catalog.Level) *Instance {
|
||||||
|
if mode == "" {
|
||||||
|
mode = catalog.LevelQuick
|
||||||
|
}
|
||||||
|
return &Instance{
|
||||||
|
APIVersion: catalog.APIVersion, Kind: catalog.KindSession,
|
||||||
|
Metadata: InstanceMeta{Name: name},
|
||||||
|
Spec: InstanceSpec{
|
||||||
|
Solution: SolutionPin{ID: s.Meta.ID, Version: s.Meta.Version},
|
||||||
|
Mode: mode,
|
||||||
|
Parameters: map[string]any{},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MaxInstanceSize bounds instance and preset files.
|
||||||
|
const MaxInstanceSize = 1 << 20
|
||||||
|
|
||||||
|
// ReadInstance decodes an instance or session (strict).
|
||||||
|
func ReadInstance(r io.Reader) (*Instance, error) {
|
||||||
|
var in Instance
|
||||||
|
if err := strict(r, &in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if in.APIVersion != catalog.APIVersion {
|
||||||
|
return nil, fmt.Errorf("apiVersion %q, want %q", in.APIVersion, catalog.APIVersion)
|
||||||
|
}
|
||||||
|
if in.Kind != catalog.KindInstance && in.Kind != catalog.KindSession {
|
||||||
|
return nil, fmt.Errorf("kind %q, want %s or %s", in.Kind, catalog.KindInstance, catalog.KindSession)
|
||||||
|
}
|
||||||
|
if in.Spec.Parameters == nil {
|
||||||
|
in.Spec.Parameters = map[string]any{}
|
||||||
|
}
|
||||||
|
return &in, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadPreset decodes a preset (strict).
|
||||||
|
func ReadPreset(r io.Reader) (*Preset, error) {
|
||||||
|
var p Preset
|
||||||
|
if err := strict(r, &p); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if p.APIVersion != catalog.APIVersion || p.Kind != catalog.KindPreset {
|
||||||
|
return nil, fmt.Errorf("not a %s %s", catalog.APIVersion, catalog.KindPreset)
|
||||||
|
}
|
||||||
|
if p.Spec.Parameters == nil {
|
||||||
|
p.Spec.Parameters = map[string]any{}
|
||||||
|
}
|
||||||
|
return &p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func strict(r io.Reader, v any) error {
|
||||||
|
b, err := io.ReadAll(io.LimitReader(r, MaxInstanceSize+1))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(b) > MaxInstanceSize {
|
||||||
|
return fmt.Errorf("larger than %d bytes", MaxInstanceSize)
|
||||||
|
}
|
||||||
|
d := yaml.NewDecoder(bytes.NewReader(b))
|
||||||
|
d.KnownFields(true)
|
||||||
|
if err := d.Decode(v); err != nil && !errors.Is(err, io.EOF) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Marshal renders any of the user files as YAML with sorted parameters.
|
||||||
|
func Marshal(v any) ([]byte, error) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
enc := yaml.NewEncoder(&buf)
|
||||||
|
enc.SetIndent(2)
|
||||||
|
if err := enc.Encode(v); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
enc.Close()
|
||||||
|
return buf.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PresetFrom derives a preset from an instance: all answers except
|
||||||
|
// instance-specific and secret ones (PRE-02, PRE-04).
|
||||||
|
func PresetFrom(name string, in *Instance, s *catalog.Solution) *Preset {
|
||||||
|
p := &Preset{
|
||||||
|
APIVersion: catalog.APIVersion, Kind: catalog.KindPreset,
|
||||||
|
Metadata: InstanceMeta{Name: name},
|
||||||
|
Spec: PresetSpec{Solution: s.Meta.ID, Version: s.Meta.Version, Mode: in.Spec.Mode, Parameters: map[string]any{}},
|
||||||
|
}
|
||||||
|
keys := make([]string, 0, len(in.Spec.Parameters))
|
||||||
|
for k := range in.Spec.Parameters {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
for _, k := range keys {
|
||||||
|
q, _ := s.Question(k)
|
||||||
|
if q == nil || q.InstanceSpecific || q.Type == "secret" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p.Spec.Parameters[k] = in.Spec.Parameters[k]
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
@@ -0,0 +1,379 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Lock pins what a generation was made from (LOCK-01). It has no
|
||||||
|
// timestamps, so the same inputs give the same file.
|
||||||
|
type Lock struct {
|
||||||
|
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
|
||||||
|
Kind string `yaml:"kind" json:"kind"`
|
||||||
|
Spec LockSpec `yaml:"spec" json:"spec"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LockSpec is the content of a lock.
|
||||||
|
type LockSpec struct {
|
||||||
|
Generator string `yaml:"generator" json:"generator"`
|
||||||
|
Catalog Pinned `yaml:"catalog" json:"catalog"`
|
||||||
|
Solution Pinned `yaml:"solution" json:"solution"`
|
||||||
|
Profiles []Pinned `yaml:"profiles,omitempty" json:"profiles,omitempty"`
|
||||||
|
Packages []Pinned `yaml:"packages,omitempty" json:"packages,omitempty"`
|
||||||
|
Capability string `yaml:"capabilities" json:"capabilities"` // hash of the capability files
|
||||||
|
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
|
||||||
|
Answers string `yaml:"answers" json:"answers"`
|
||||||
|
Files []FileHash `yaml:"files" json:"files"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pinned is an entity with version and content hash.
|
||||||
|
type Pinned struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Version string `yaml:"version,omitempty" json:"version,omitempty"`
|
||||||
|
Hash string `yaml:"sha256" json:"sha256"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileHash is a generated file and its hash.
|
||||||
|
type FileHash = catalog.FileHash
|
||||||
|
|
||||||
|
// OutFile is one file of a generated solution directory.
|
||||||
|
type OutFile struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
Kind string `json:"kind"` // instance | lock | config | architecture | handbook | plan | readme
|
||||||
|
Content []byte `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output is everything Generate produces.
|
||||||
|
type Output struct {
|
||||||
|
Files []OutFile `json:"files"`
|
||||||
|
Lock *Lock `json:"lock"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManualReader gives the handbook existing manual text (implemented by
|
||||||
|
// package knowledge). It may be nil: the handbook then links instead.
|
||||||
|
type ManualReader interface {
|
||||||
|
// Excerpt returns the title and Markdown of a manual reference
|
||||||
|
// (yetano:manual/...#section), shortened to at most maxLines lines.
|
||||||
|
Excerpt(ref string, maxLines int) (title, markdown string, ok bool)
|
||||||
|
// Link returns a human link for a reference (web URL or CLI command).
|
||||||
|
Link(ref string) string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate renders all output files of a complete state. It refuses an
|
||||||
|
// incomplete state unless allowIncomplete is set.
|
||||||
|
func (e *Engine) Generate(st *State, in *Instance, mr ManualReader, allowIncomplete bool) (*Output, error) {
|
||||||
|
if !st.Complete && !allowIncomplete {
|
||||||
|
return nil, fmt.Errorf("%w: %s", ErrIncomplete, incompleteText(st))
|
||||||
|
}
|
||||||
|
s := e.Cat.Lookup(st.Solution.ID)
|
||||||
|
out := &Output{}
|
||||||
|
addf := func(path, kind string, b []byte) {
|
||||||
|
out.Files = append(out.Files, OutFile{Path: path, Kind: kind, Content: b})
|
||||||
|
}
|
||||||
|
inst := *in
|
||||||
|
inst.Kind = catalog.KindInstance
|
||||||
|
inst.Spec.Solution.Version = s.Meta.Version
|
||||||
|
inst.Spec.Cursor = ""
|
||||||
|
b, err := Marshal(&inst)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
addf("solution.yaml", "instance", b)
|
||||||
|
for _, f := range st.Files {
|
||||||
|
addf(f.Path, "config", []byte(f.Content))
|
||||||
|
}
|
||||||
|
gj, _ := json.MarshalIndent(st.Graph, "", " ")
|
||||||
|
addf("architecture/graph.json", "architecture", append(gj, '\n'))
|
||||||
|
addf("architecture/graph.txt", "architecture", []byte(GraphText(st.Graph)))
|
||||||
|
pb, err := Marshal(PlanOf(st))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
addf("deployment-plan.yaml", "plan", pb)
|
||||||
|
for _, h := range e.Handbook(st, mr) {
|
||||||
|
addf(h.Path, "handbook", h.Content)
|
||||||
|
}
|
||||||
|
addf("README.md", "readme", []byte(readme(st)))
|
||||||
|
sort.Slice(out.Files, func(i, j int) bool { return out.Files[i].Path < out.Files[j].Path })
|
||||||
|
for _, f := range out.Files {
|
||||||
|
if !catalog.SafeRelPath(f.Path) {
|
||||||
|
return nil, fmt.Errorf("refusing unsafe output path %q", f.Path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.Lock = e.lock(st, s, in, out.Files)
|
||||||
|
lb, err := Marshal(out.Lock)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out.Files = append(out.Files, OutFile{Path: "solution.lock.yaml", Kind: "lock", Content: lb})
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrIncomplete: required answers are missing or errors remain.
|
||||||
|
var ErrIncomplete = errors.New("the solution is not complete")
|
||||||
|
|
||||||
|
func incompleteText(st *State) string {
|
||||||
|
var parts []string
|
||||||
|
if len(st.Progress.Missing) > 0 {
|
||||||
|
parts = append(parts, "missing: "+strings.Join(st.Progress.Missing, ", "))
|
||||||
|
}
|
||||||
|
for _, m := range st.Messages {
|
||||||
|
if m.Severity == "error" {
|
||||||
|
parts = append(parts, m.Text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, q := range st.Questions {
|
||||||
|
for _, e := range q.Errors {
|
||||||
|
parts = append(parts, q.ID+": "+e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "; ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func hashBytes(b []byte) string {
|
||||||
|
h := sha256.Sum256(b)
|
||||||
|
return hex.EncodeToString(h[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *Engine) lock(st *State, s *catalog.Solution, in *Instance, files []OutFile) *Lock {
|
||||||
|
c := e.Cat
|
||||||
|
l := &Lock{APIVersion: catalog.APIVersion, Kind: "SolutionLock"}
|
||||||
|
l.Spec.Generator = GeneratorVersion
|
||||||
|
l.Spec.Catalog = Pinned{ID: c.Meta.ID, Version: c.Meta.Version, Hash: c.Hash()}
|
||||||
|
l.Spec.Solution = Pinned{ID: s.Meta.ID, Version: s.Meta.Version, Hash: s.Hash}
|
||||||
|
for _, p := range st.Packages {
|
||||||
|
if !p.Selected {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if cp := c.Packages[p.ID]; cp != nil {
|
||||||
|
l.Spec.Packages = append(l.Spec.Packages, Pinned{ID: p.ID, Hash: cp.Hash})
|
||||||
|
}
|
||||||
|
if p.Profile != "" {
|
||||||
|
chain, _ := c.ProfileChain(p.ID, p.Profile)
|
||||||
|
for _, pr := range chain {
|
||||||
|
l.Spec.Profiles = append(l.Spec.Profiles, Pinned{ID: pr.Key(), Hash: pr.Hash})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var capFiles, bpFiles []string
|
||||||
|
for _, f := range c.Files {
|
||||||
|
if strings.HasPrefix(f.Path, "bigpicture:") {
|
||||||
|
bpFiles = append(bpFiles, f.Path+" "+f.Hash)
|
||||||
|
} else if strings.HasPrefix(f.Path, "capabilities") {
|
||||||
|
capFiles = append(capFiles, f.Path+" "+f.Hash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
l.Spec.Capability = hashBytes([]byte(strings.Join(capFiles, "\n")))
|
||||||
|
if len(bpFiles) > 0 {
|
||||||
|
l.Spec.BigPicture = hashBytes([]byte(strings.Join(bpFiles, "\n")))
|
||||||
|
}
|
||||||
|
ab, _ := json.Marshal(in.Spec.Parameters) // map keys are sorted by encoding/json
|
||||||
|
ob, _ := json.Marshal(in.Spec.Overrides)
|
||||||
|
l.Spec.Answers = hashBytes(append(append(ab, '\n'), ob...))
|
||||||
|
for _, f := range files {
|
||||||
|
l.Spec.Files = append(l.Spec.Files, FileHash{Path: f.Path, Hash: hashBytes(f.Content)})
|
||||||
|
}
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
// LockDrift lists what changed meaning between a previous lock and now
|
||||||
|
// (LOCK-02/03): a changed solution, profile or package definition.
|
||||||
|
func LockDrift(prev, cur *Lock) []string {
|
||||||
|
var out []string
|
||||||
|
if prev.Spec.Solution.Hash != cur.Spec.Solution.Hash {
|
||||||
|
out = append(out, fmt.Sprintf("solution %s changed (%s -> %s)", cur.Spec.Solution.ID, prev.Spec.Solution.Version, cur.Spec.Solution.Version))
|
||||||
|
}
|
||||||
|
cmp := func(kind string, a, b []Pinned) {
|
||||||
|
m := map[string]string{}
|
||||||
|
for _, p := range a {
|
||||||
|
m[p.ID] = p.Hash
|
||||||
|
}
|
||||||
|
for _, p := range b {
|
||||||
|
if h, ok := m[p.ID]; !ok {
|
||||||
|
out = append(out, fmt.Sprintf("%s %s is new", kind, p.ID))
|
||||||
|
} else if h != p.Hash {
|
||||||
|
out = append(out, fmt.Sprintf("%s %s changed", kind, p.ID))
|
||||||
|
}
|
||||||
|
delete(m, p.ID)
|
||||||
|
}
|
||||||
|
for id := range m {
|
||||||
|
out = append(out, fmt.Sprintf("%s %s is no longer used", kind, id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cmp("profile", prev.Spec.Profiles, cur.Spec.Profiles)
|
||||||
|
cmp("package", prev.Spec.Packages, cur.Spec.Packages)
|
||||||
|
if prev.Spec.Capability != cur.Spec.Capability {
|
||||||
|
out = append(out, "the capability catalog changed")
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadLock reads dir/solution.lock.yaml; a missing file is (nil, nil).
|
||||||
|
func ReadLock(dir string) (*Lock, error) {
|
||||||
|
f, err := os.Open(filepath.Join(dir, "solution.lock.yaml"))
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
var l Lock
|
||||||
|
if err := strict(f, &l); err != nil {
|
||||||
|
return nil, fmt.Errorf("solution.lock.yaml: %w", err)
|
||||||
|
}
|
||||||
|
return &l, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrModified: a file in the output directory was changed by hand.
|
||||||
|
var ErrModified = errors.New("output directory has changes that would be overwritten")
|
||||||
|
|
||||||
|
// Write writes out into dir (CONF-05, CONF-06). Without force it refuses
|
||||||
|
// to overwrite a file that differs from what the previous lock recorded
|
||||||
|
// (a hand edit) or a file the previous generation did not write. Files of
|
||||||
|
// the previous generation that are no longer produced are removed only
|
||||||
|
// when they are unchanged.
|
||||||
|
func Write(dir string, out *Output, force bool) error {
|
||||||
|
prev, err := ReadLock(dir)
|
||||||
|
if err != nil && !force {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
known := map[string]string{}
|
||||||
|
if prev != nil {
|
||||||
|
for _, f := range prev.Spec.Files {
|
||||||
|
known[f.Path] = f.Hash
|
||||||
|
}
|
||||||
|
known["solution.lock.yaml"] = "*"
|
||||||
|
}
|
||||||
|
var conflicts []string
|
||||||
|
for _, f := range out.Files {
|
||||||
|
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||||
|
cur, err := os.ReadFile(p)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
h, isKnown := known[f.Path]
|
||||||
|
switch {
|
||||||
|
case h == "*":
|
||||||
|
case !isKnown && hashBytes(cur) != hashBytes(f.Content):
|
||||||
|
conflicts = append(conflicts, f.Path+" (not written by the guide)")
|
||||||
|
case isKnown && hashBytes(cur) != h:
|
||||||
|
conflicts = append(conflicts, f.Path+" (changed by hand)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(conflicts) > 0 && !force {
|
||||||
|
return fmt.Errorf("%w: %s; use --force to overwrite", ErrModified, strings.Join(conflicts, ", "))
|
||||||
|
}
|
||||||
|
for _, f := range out.Files {
|
||||||
|
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tmp := p + ".tmp"
|
||||||
|
if err := os.WriteFile(tmp, f.Content, 0o644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.Rename(tmp, p); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// stale files of the previous generation
|
||||||
|
now := map[string]bool{}
|
||||||
|
for _, f := range out.Files {
|
||||||
|
now[f.Path] = true
|
||||||
|
}
|
||||||
|
if prev != nil {
|
||||||
|
for _, f := range prev.Spec.Files {
|
||||||
|
if now[f.Path] || !catalog.SafeRelPath(f.Path) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p := filepath.Join(dir, filepath.FromSlash(f.Path))
|
||||||
|
if cur, err := os.ReadFile(p); err == nil && hashBytes(cur) == f.Hash {
|
||||||
|
os.Remove(p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Plan is the deployment plan: what an operator (or a later apply) does,
|
||||||
|
// in order. It is never executed by the engine (LIFE-01).
|
||||||
|
type Plan struct {
|
||||||
|
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
|
||||||
|
Kind string `yaml:"kind" json:"kind"`
|
||||||
|
Spec PlanSpec `yaml:"spec" json:"spec"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PlanSpec lists files, steps and checks.
|
||||||
|
type PlanSpec struct {
|
||||||
|
Solution string `yaml:"solution" json:"solution"`
|
||||||
|
Instance string `yaml:"instance" json:"instance"`
|
||||||
|
Target string `yaml:"target" json:"target"`
|
||||||
|
Apply string `yaml:"apply" json:"apply"`
|
||||||
|
Packages []string `yaml:"packages" json:"packages"`
|
||||||
|
Files []string `yaml:"files" json:"files"`
|
||||||
|
Steps []PlannedStep `yaml:"steps" json:"steps"`
|
||||||
|
Checks []PlanCheck `yaml:"checks" json:"checks"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PlanCheck is a check to run after applying.
|
||||||
|
type PlanCheck struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Title string `yaml:"title" json:"title"`
|
||||||
|
Run string `yaml:"run,omitempty" json:"run,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PlanOf builds the plan of a state.
|
||||||
|
func PlanOf(st *State) *Plan {
|
||||||
|
p := &Plan{APIVersion: catalog.APIVersion, Kind: "DeploymentPlan"}
|
||||||
|
p.Spec.Solution = st.Solution.ID + " " + st.Solution.Version
|
||||||
|
p.Spec.Instance = st.Instance
|
||||||
|
p.Spec.Target = firstNonEmpty(st.Platform, "local")
|
||||||
|
p.Spec.Apply = "manual: the guide does not apply plans yet; run the steps yourself (LIFE-01)"
|
||||||
|
for _, pk := range st.Packages {
|
||||||
|
if pk.Selected {
|
||||||
|
p.Spec.Packages = append(p.Spec.Packages, pk.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, f := range st.Files {
|
||||||
|
p.Spec.Files = append(p.Spec.Files, f.Path)
|
||||||
|
}
|
||||||
|
p.Spec.Steps = st.Steps
|
||||||
|
if p.Spec.Steps == nil {
|
||||||
|
p.Spec.Steps = []PlannedStep{}
|
||||||
|
}
|
||||||
|
for _, c := range st.Checks {
|
||||||
|
if c.Status != CheckNotApplicable {
|
||||||
|
p.Spec.Checks = append(p.Spec.Checks, PlanCheck{ID: c.ID, Title: c.Title, Run: c.Run})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func readme(st *State) string {
|
||||||
|
var b strings.Builder
|
||||||
|
fmt.Fprintf(&b, "# %s\n\n", firstNonEmpty(st.Instance, st.Solution.Title))
|
||||||
|
fmt.Fprintf(&b, "Solution: %s (`%s` %s), generated by the Yetano Solutions Guide.\n\n", st.Solution.Title, st.Solution.ID, st.Solution.Version)
|
||||||
|
b.WriteString("| Path | Content |\n|---|---|\n")
|
||||||
|
b.WriteString("| `solution.yaml` | your answers (SolutionInstance); regenerate with `yet solution generate --file solution.yaml --output .` |\n")
|
||||||
|
b.WriteString("| `solution.lock.yaml` | what this was generated from (catalog, profiles, file hashes) |\n")
|
||||||
|
b.WriteString("| `config/` | native configuration files, one directory per package |\n")
|
||||||
|
b.WriteString("| `deployment-plan.yaml` | the steps to install, configure and check it (not executed by the guide) |\n")
|
||||||
|
b.WriteString("| `architecture/` | the resolved architecture (`graph.json`, `graph.txt`) |\n")
|
||||||
|
b.WriteString("| `handbook/` | your handbook: start with `handbook/index.md` |\n\n")
|
||||||
|
b.WriteString("Nothing here has been installed or changed on any system.\n")
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// phases in plan order.
|
||||||
|
var phaseOrder = map[string]int{"install": 0, "configure": 1, "data": 2, "dns": 3, "start": 4, "verify": 5}
|
||||||
|
|
||||||
|
func (ev *evaluation) steps() {
|
||||||
|
vars := ev.vars()
|
||||||
|
for _, s := range ev.s.Spec.Steps {
|
||||||
|
if len(s.When) > 0 && !s.When.Holds(ev.env) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if s.Package != "" && !ev.pkgSelected(s.Package) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if s.Package != "" && s.Module != "" && s.ForEach != "$modules" && !ev.moduleEnabled(s.Package, s.Module) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
items := []any{nil}
|
||||||
|
switch {
|
||||||
|
case s.ForEach == "$modules":
|
||||||
|
// every enabled module of the step's package that is a program
|
||||||
|
items = nil
|
||||||
|
if cp := ev.e.Cat.Packages[s.Package]; cp != nil {
|
||||||
|
for _, m := range cp.Spec.Modules {
|
||||||
|
if m.Program != "" && ev.moduleEnabled(s.Package, m.ID) && (s.Module == "" || m.Kind == s.Module) {
|
||||||
|
items = append(items, m.Program)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case s.ForEach != "":
|
||||||
|
items = listOf(ev.answers[s.ForEach])
|
||||||
|
}
|
||||||
|
for i, it := range items {
|
||||||
|
v := vars
|
||||||
|
if s.ForEach != "" {
|
||||||
|
v = map[string]any{}
|
||||||
|
for k, x := range vars {
|
||||||
|
v[k] = x
|
||||||
|
}
|
||||||
|
v["item"] = it
|
||||||
|
}
|
||||||
|
run, err := expand(s.Run, v)
|
||||||
|
if err != nil {
|
||||||
|
ev.msg("error", "step", fmt.Sprintf("step %s: %v", s.ID, err), "step:"+s.ID)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
title, _ := expand(s.Title, v)
|
||||||
|
note, _ := expand(s.Note, v)
|
||||||
|
id := s.ID
|
||||||
|
if s.ForEach != "" {
|
||||||
|
id = fmt.Sprintf("%s-%d", s.ID, i+1)
|
||||||
|
}
|
||||||
|
phase := s.Phase
|
||||||
|
if phase == "" {
|
||||||
|
phase = "configure"
|
||||||
|
}
|
||||||
|
ev.st.Steps = append(ev.st.Steps, PlannedStep{
|
||||||
|
ID: id, Title: title, Phase: phase, Package: s.Package, Module: s.Module,
|
||||||
|
Run: run, Note: note, Mutating: s.Mutating, Reversible: s.Reversible, References: s.References,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.SliceStable(ev.st.Steps, func(i, j int) bool {
|
||||||
|
return phaseOrder[ev.st.Steps[i].Phase] < phaseOrder[ev.st.Steps[j].Phase]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// expand fills placeholders into a text (steps, notes). Values are
|
||||||
|
// inserted as text; steps are shown to the operator, never run.
|
||||||
|
func expand(s string, vars map[string]any) (string, error) {
|
||||||
|
if !strings.Contains(s, "${") {
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
var firstErr error
|
||||||
|
used := map[string]bool{}
|
||||||
|
out := placeholderRE.ReplaceAllStringFunc(s, func(m string) string {
|
||||||
|
if m == "$${" {
|
||||||
|
return "${"
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(m, "${item") {
|
||||||
|
if it, ok := vars["item"]; ok {
|
||||||
|
return catalog.Scalar(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v, err := lookup(m, vars, used)
|
||||||
|
if err != nil && firstErr == nil {
|
||||||
|
firstErr = err
|
||||||
|
}
|
||||||
|
return shellWord(text(v))
|
||||||
|
})
|
||||||
|
return out, firstErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// shellWord quotes a value for display in a command line if needed.
|
||||||
|
func shellWord(s string) string {
|
||||||
|
if s == "" {
|
||||||
|
return "''"
|
||||||
|
}
|
||||||
|
for _, r := range s {
|
||||||
|
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("@%+=:,./_-", r)) {
|
||||||
|
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ev *evaluation) checks() {
|
||||||
|
vars := ev.vars()
|
||||||
|
for _, c := range ev.s.Spec.Requirements {
|
||||||
|
r := CheckResult{ID: c.ID, Title: c.Title, Kind: c.Kind, Severity: firstNonEmpty(c.Severity, "error"),
|
||||||
|
Local: c.Local, Hint: c.Hint, References: c.References, Params: map[string]string{}}
|
||||||
|
if len(c.When) > 0 && !c.When.Holds(ev.env) {
|
||||||
|
r.Status = CheckNotApplicable
|
||||||
|
ev.st.Checks = append(ev.st.Checks, r)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for k, v := range c.Params {
|
||||||
|
x, err := expand(v, vars)
|
||||||
|
if err != nil {
|
||||||
|
x = v
|
||||||
|
}
|
||||||
|
r.Params[k] = strings.Trim(x, "'")
|
||||||
|
}
|
||||||
|
r.Run, _ = expand(c.Run, vars)
|
||||||
|
// The engine itself never inspects a system: every check starts
|
||||||
|
// as NOT_CHECKED; a doctor runner fills in results (DR-03).
|
||||||
|
r.Status = CheckNotChecked
|
||||||
|
ev.st.Checks = append(ev.st.Checks, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SEC-02: the catalog, the engine and the knowledge index never run a
|
||||||
|
// program or open a network connection; the CLI may (doctor checks).
|
||||||
|
// core/secretref links os/exec for resolving secret:// through yaseva;
|
||||||
|
// the engine only uses its Validate, so os/exec is checked on the
|
||||||
|
// packages' own imports, network packages on all dependencies.
|
||||||
|
func TestNoExecOrNetwork(t *testing.T) {
|
||||||
|
for _, pkg := range []string{"../catalog", "../engine", "../knowledge", "../ref"} {
|
||||||
|
own, err := exec.Command("go", "list", "-f", "{{join .Imports \" \"}}", pkg).Output()
|
||||||
|
if err != nil {
|
||||||
|
t.Skip("go list not available")
|
||||||
|
}
|
||||||
|
for _, dep := range strings.Fields(string(own)) {
|
||||||
|
if dep == "os/exec" || dep == "syscall" || dep == "plugin" || dep == "unsafe" {
|
||||||
|
t.Errorf("%s imports %s", pkg, dep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
all, _ := exec.Command("go", "list", "-deps", "-f", "{{.ImportPath}}", pkg).Output()
|
||||||
|
for _, dep := range strings.Fields(string(all)) {
|
||||||
|
switch dep {
|
||||||
|
case "net/http", "net/rpc", "net/smtp", "crypto/tls":
|
||||||
|
t.Errorf("%s depends on %s", pkg, dep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import "yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
|
||||||
|
// State is the complete result of evaluating an instance: everything a
|
||||||
|
// client shows. Clients never compute visibility, options or resolution
|
||||||
|
// themselves (API-02); they render a State.
|
||||||
|
type State struct {
|
||||||
|
Solution SolutionInfo `json:"solution"`
|
||||||
|
Instance string `json:"instance"`
|
||||||
|
Mode catalog.Level `json:"mode"`
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
Platform string `json:"platform,omitempty"`
|
||||||
|
Questions []QuestionState `json:"questions"`
|
||||||
|
Next string `json:"next,omitempty"`
|
||||||
|
Progress Progress `json:"progress"`
|
||||||
|
Complete bool `json:"complete"`
|
||||||
|
Answers map[string]Answer `json:"answers"`
|
||||||
|
Stale []StaleAnswer `json:"stale,omitempty"`
|
||||||
|
Packages []PackageState `json:"packages"`
|
||||||
|
Capabilities []CapState `json:"capabilities"`
|
||||||
|
Rules []AppliedRule `json:"rules"`
|
||||||
|
Messages []Message `json:"messages"`
|
||||||
|
Recommended []Recommendation `json:"recommendations,omitempty"`
|
||||||
|
Files []FilePreview `json:"files"`
|
||||||
|
Steps []PlannedStep `json:"steps"`
|
||||||
|
Checks []CheckResult `json:"checks"`
|
||||||
|
Graph Graph `json:"graph"`
|
||||||
|
References []string `json:"references"`
|
||||||
|
Related []string `json:"related,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SolutionInfo identifies the evaluated solution or task.
|
||||||
|
type SolutionInfo struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
TaskKind string `json:"taskKind,omitempty"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Summary string `json:"summary,omitempty"`
|
||||||
|
Status catalog.Support `json:"status"`
|
||||||
|
Category string `json:"category,omitempty"`
|
||||||
|
BigPicture string `json:"bigpicture,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QuestionState is one question as the client shows it.
|
||||||
|
type QuestionState struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Item string `json:"item,omitempty"`
|
||||||
|
Group string `json:"group,omitempty"`
|
||||||
|
Level catalog.Level `json:"level"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Help string `json:"help,omitempty"`
|
||||||
|
Description string `json:"description,omitempty"`
|
||||||
|
Decide string `json:"decide,omitempty"`
|
||||||
|
Placeholder string `json:"placeholder,omitempty"`
|
||||||
|
Examples []string `json:"examples,omitempty"`
|
||||||
|
Visible bool `json:"visible"`
|
||||||
|
Asked bool `json:"asked"` // shown in the current mode
|
||||||
|
Required bool `json:"required"`
|
||||||
|
InstanceSpecific bool `json:"instanceSpecific,omitempty"`
|
||||||
|
Value any `json:"value,omitempty"`
|
||||||
|
Origin string `json:"origin,omitempty"` // default | preset | instance | ""
|
||||||
|
Default any `json:"default,omitempty"`
|
||||||
|
Recommended any `json:"recommended,omitempty"`
|
||||||
|
Reason string `json:"reason,omitempty"`
|
||||||
|
Options []OptionState `json:"options,omitempty"`
|
||||||
|
Errors []string `json:"errors,omitempty"`
|
||||||
|
Warnings []Message `json:"warnings,omitempty"`
|
||||||
|
References []string `json:"references,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OptionState is one option with whether and why it can be chosen.
|
||||||
|
type OptionState struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Description string `json:"description,omitempty"`
|
||||||
|
Recommended bool `json:"recommended,omitempty"`
|
||||||
|
Reason string `json:"reason,omitempty"`
|
||||||
|
Support catalog.Support `json:"support"`
|
||||||
|
SupportNote string `json:"supportNote,omitempty"`
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
Disabled string `json:"disabledReason,omitempty"`
|
||||||
|
Selected bool `json:"selected"`
|
||||||
|
Adds []string `json:"adds,omitempty"` // packages/capabilities it brings in
|
||||||
|
References []string `json:"references,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Progress counts asked questions.
|
||||||
|
type Progress struct {
|
||||||
|
Asked int `json:"asked"`
|
||||||
|
Answered int `json:"answered"`
|
||||||
|
Missing []string `json:"missing,omitempty"`
|
||||||
|
Step int `json:"step"` // 1-based index of Next among asked questions
|
||||||
|
}
|
||||||
|
|
||||||
|
// Answer is an effective answer and where it came from.
|
||||||
|
type Answer struct {
|
||||||
|
Value any `json:"value"`
|
||||||
|
Origin string `json:"origin"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StaleAnswer is an explicit answer that no longer counts (RULE-06).
|
||||||
|
type StaleAnswer struct {
|
||||||
|
Question string `json:"question"`
|
||||||
|
Value any `json:"value"`
|
||||||
|
Reason string `json:"reason"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status values of packages, modules and capabilities in a state and a graph (BP-04).
|
||||||
|
const (
|
||||||
|
StRequired = "required"
|
||||||
|
StSelected = "selected"
|
||||||
|
StRecommended = "recommended"
|
||||||
|
StOptional = "optional"
|
||||||
|
StExternal = "external"
|
||||||
|
StAlternative = "alternative"
|
||||||
|
StDisabled = "disabled"
|
||||||
|
StUnsupported = "unsupported"
|
||||||
|
StMissing = "missing"
|
||||||
|
StConflicting = "conflicting"
|
||||||
|
StExcluded = "excluded"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PackageState is a package in the resolved solution.
|
||||||
|
type PackageState struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Summary string `json:"summary,omitempty"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Profile string `json:"profile,omitempty"`
|
||||||
|
Reasons []string `json:"reasons"`
|
||||||
|
Modules []ModuleState `json:"modules,omitempty"`
|
||||||
|
Selected bool `json:"selected"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ModuleState is a module of a selected package.
|
||||||
|
type ModuleState struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Program string `json:"program,omitempty"`
|
||||||
|
Kind string `json:"kind,omitempty"`
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
Support catalog.Support `json:"support,omitempty"`
|
||||||
|
Reason string `json:"reason,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CapState is a capability in the resolved solution.
|
||||||
|
type CapState struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Provider string `json:"provider,omitempty"` // pkg/module or external:<id>
|
||||||
|
Alternatives []string `json:"alternatives,omitempty"`
|
||||||
|
Reasons []string `json:"reasons"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppliedRule records a rule (or an option's effects) that fired.
|
||||||
|
type AppliedRule struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Source string `json:"source"` // rule | option | package | capability
|
||||||
|
Effect string `json:"effect"`
|
||||||
|
Reason string `json:"reason,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Message is a warning, error or note.
|
||||||
|
type Message struct {
|
||||||
|
Severity string `json:"severity"` // info | warning | error
|
||||||
|
Code string `json:"code"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Source string `json:"source,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recommendation suggests an extension.
|
||||||
|
type Recommendation struct {
|
||||||
|
Package string `json:"package,omitempty"`
|
||||||
|
Capability string `json:"capability,omitempty"`
|
||||||
|
Reason string `json:"reason"`
|
||||||
|
Source string `json:"source,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilePreview is one generated file.
|
||||||
|
type FilePreview struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
Package string `json:"package"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
Origins map[string]Origin `json:"origins"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Origin says where a configuration value came from (PROF-05).
|
||||||
|
type Origin struct {
|
||||||
|
Layer string `json:"layer"` // profile | solution | override
|
||||||
|
Source string `json:"source"` // profile:yamase/mailbox, solution:mail-server#tls, override
|
||||||
|
Params []string `json:"params,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PlannedStep is a setup step (never executed by the engine).
|
||||||
|
type PlannedStep struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Phase string `json:"phase"`
|
||||||
|
Package string `json:"package,omitempty"`
|
||||||
|
Module string `json:"module,omitempty"`
|
||||||
|
Run string `json:"run,omitempty"`
|
||||||
|
Note string `json:"note,omitempty"`
|
||||||
|
Mutating bool `json:"mutating"`
|
||||||
|
Reversible *bool `json:"reversible,omitempty"`
|
||||||
|
References []string `json:"references,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check status values (DR-03).
|
||||||
|
const (
|
||||||
|
CheckPass = "PASS"
|
||||||
|
CheckInfo = "INFO"
|
||||||
|
CheckWarning = "WARNING"
|
||||||
|
CheckError = "ERROR"
|
||||||
|
CheckBlocked = "BLOCKED"
|
||||||
|
CheckNotApplicable = "NOT_APPLICABLE"
|
||||||
|
CheckNotChecked = "NOT_CHECKED"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CheckResult is a requirement/doctor check and its result.
|
||||||
|
type CheckResult struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Severity string `json:"severity"`
|
||||||
|
Local bool `json:"local"`
|
||||||
|
Params map[string]string `json:"params,omitempty"`
|
||||||
|
Run string `json:"run,omitempty"`
|
||||||
|
Hint string `json:"hint,omitempty"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Note string `json:"note,omitempty"`
|
||||||
|
References []string `json:"references,omitempty"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
interfaces: []
|
||||||
|
connections:
|
||||||
|
- {id: connection.app-idp, from: product.app, to: product.idp, type: authenticatesVia, label: signs in through, scope: general, review: confirmed}
|
||||||
+2
@@ -0,0 +1,2 @@
|
|||||||
|
title: Test Big Picture
|
||||||
|
content: {topics: topics.yaml, products: products, stories: stories, connections: connections.yaml}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
id: product.app
|
||||||
|
name: app
|
||||||
|
summary: The test application.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
id: product.idp
|
||||||
|
name: idp
|
||||||
|
summary: An identity provider.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
id: story.run-app
|
||||||
|
title: Run the app
|
||||||
|
intent: I want to run the app.
|
||||||
|
outcome: The app runs.
|
||||||
|
primaryTopic: topic.t
|
||||||
+2
@@ -0,0 +1,2 @@
|
|||||||
|
topics:
|
||||||
|
- {id: topic.t, title: Testing, summary: Test topic}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
apiVersion: yetano.dev/v1
|
||||||
|
kind: Catalog
|
||||||
|
metadata: {id: test, version: 1.0.0}
|
||||||
|
spec:
|
||||||
|
bigpicture: ../bp
|
||||||
|
webBase: https://example.test/
|
||||||
|
categories: [{id: t, topic: topic.t}]
|
||||||
|
---
|
||||||
|
apiVersion: yetano.dev/v1
|
||||||
|
kind: Capabilities
|
||||||
|
metadata: {id: caps}
|
||||||
|
spec:
|
||||||
|
capabilities:
|
||||||
|
- {id: app.serve, title: Serve the app, requires: [auth.users]}
|
||||||
|
- {id: auth.users, title: Users}
|
||||||
|
- {id: auth.sso, title: Single sign-on}
|
||||||
|
- {id: backup.files, title: Backups, external: [{id: tool, title: Your tool}]}
|
||||||
|
- {id: feature.x, title: Feature X}
|
||||||
+48
@@ -0,0 +1,48 @@
|
|||||||
|
apiVersion: yetano.dev/v1
|
||||||
|
kind: Package
|
||||||
|
metadata: {id: app}
|
||||||
|
spec:
|
||||||
|
bigpicture: product.app
|
||||||
|
sources: [test]
|
||||||
|
modules:
|
||||||
|
- {id: server, title: Server, program: app-server, kind: daemon, provides: [app.serve]}
|
||||||
|
- {id: users, title: Local users, kind: library, provides: [auth.users], priority: 10}
|
||||||
|
- {id: extra, title: Extra, program: app-extra, kind: daemon, provides: [feature.x]}
|
||||||
|
- {id: ghost, title: Not built, support: not-implemented, provides: [auth.sso]}
|
||||||
|
---
|
||||||
|
apiVersion: yetano.dev/v1
|
||||||
|
kind: Package
|
||||||
|
metadata: {id: idp}
|
||||||
|
spec:
|
||||||
|
bigpicture: product.idp
|
||||||
|
sources: [test]
|
||||||
|
modules:
|
||||||
|
- {id: sso, title: SSO, program: idp, kind: daemon, provides: [auth.sso, auth.users], priority: 1}
|
||||||
|
---
|
||||||
|
apiVersion: yetano.dev/v1
|
||||||
|
kind: Package
|
||||||
|
metadata: {id: bak, summary: Backups}
|
||||||
|
spec:
|
||||||
|
sources: [test]
|
||||||
|
modules:
|
||||||
|
- {id: b, title: Backup, program: bak, provides: [backup.files], support: experimental}
|
||||||
|
---
|
||||||
|
apiVersion: yetano.dev/v1
|
||||||
|
kind: Profile
|
||||||
|
metadata: {id: base, package: app}
|
||||||
|
spec:
|
||||||
|
modules: {server: enabled, users: enabled, extra: disabled}
|
||||||
|
config:
|
||||||
|
- file: app/app.yaml
|
||||||
|
set: {log: info, listen: ":8080", limits: {max: 10, min: 1}}
|
||||||
|
---
|
||||||
|
apiVersion: yetano.dev/v1
|
||||||
|
kind: Profile
|
||||||
|
metadata: {id: big, package: app}
|
||||||
|
spec:
|
||||||
|
extends: base
|
||||||
|
modules: {extra: enabled}
|
||||||
|
config:
|
||||||
|
- file: app/app.yaml
|
||||||
|
set: {limits: {max: 100}}
|
||||||
|
- {file: app/extra.yaml, module: extra, set: {on: true}}
|
||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
apiVersion: yetano.dev/v1
|
||||||
|
kind: Solution
|
||||||
|
metadata: {id: app-run, version: 1.0.0, category: t, status: supported}
|
||||||
|
spec:
|
||||||
|
bigpicture: story.run-app
|
||||||
|
capabilities: {required: [app.serve], recommended: [backup.files]}
|
||||||
|
packages:
|
||||||
|
- {id: app, profile: base, role: core, when: {size: small}}
|
||||||
|
- {id: app, profile: big, role: core, when: {size: big}}
|
||||||
|
questions:
|
||||||
|
- id: size
|
||||||
|
type: select
|
||||||
|
title: How big?
|
||||||
|
default: small
|
||||||
|
options:
|
||||||
|
- {id: small, title: Small, recommended: true, reason: fits most}
|
||||||
|
- {id: big, title: Big}
|
||||||
|
- {id: hosts, type: list, item: hostname, title: Host names, required: true, instanceSpecific: true, validation: {minItems: 1}}
|
||||||
|
- id: identity
|
||||||
|
type: select
|
||||||
|
title: Users?
|
||||||
|
level: guided
|
||||||
|
default: local
|
||||||
|
options:
|
||||||
|
- {id: local, title: Local}
|
||||||
|
- {id: central, title: Central IdP, requires: {packages: [idp], capabilities: [auth.sso]}}
|
||||||
|
- {id: ghost, title: Ghost, support: not-implemented, supportNote: not built}
|
||||||
|
- {id: realm, type: string, title: Realm, visibleWhen: {identity: central}, required: true}
|
||||||
|
- {id: token, type: secret, level: advanced, title: Token}
|
||||||
|
- {id: owner, type: email, level: guided, title: Owner, default: "admin@${hosts[0]}"}
|
||||||
|
- id: backup
|
||||||
|
type: select
|
||||||
|
title: Backup
|
||||||
|
level: guided
|
||||||
|
default: none
|
||||||
|
options:
|
||||||
|
- {id: none, title: None}
|
||||||
|
- {id: mine, title: My tool, provides: [backup.files]}
|
||||||
|
- {id: bak, title: bak, requires: {packages: [bak]}}
|
||||||
|
- {id: port, type: port, level: advanced, title: Port, default: 8080}
|
||||||
|
rules:
|
||||||
|
- {id: big-warn, when: {size: big}, message: Big needs more memory., severity: warning}
|
||||||
|
- {id: no-x-small, when: {size: small}, excludes: {capabilities: [feature.x]}}
|
||||||
|
configuration:
|
||||||
|
- id: main
|
||||||
|
file: app/app.yaml
|
||||||
|
set: {hosts: "${hosts}", owner: "${owner}", listen: ":${port}", first: "${hosts[0]}", n: "${hosts.count}"}
|
||||||
|
- {id: sso, file: app/app.yaml, when: {identity: central}, set: {sso: {realm: "${realm}"}}}
|
||||||
|
- {id: tok, file: app/app.yaml, when: {token: {set: true}}, set: {token: "${token}"}}
|
||||||
|
- {id: idp, file: idp/idp.yaml, set: {realm: "${realm}"}, when: {identity: central}}
|
||||||
|
- {id: never, file: bak/bak.yaml, set: {x: 1}}
|
||||||
|
steps:
|
||||||
|
- {id: add, title: "Add ${item}", forEach: hosts, run: "app add ${item}", phase: data, mutating: true}
|
||||||
|
- {id: inst, title: "Install ${item}", package: app, forEach: $modules, run: "yet install ${item}", phase: install}
|
||||||
|
requirements:
|
||||||
|
- {id: port, title: Port free, kind: port, params: {port: "${port}"}, local: true}
|
||||||
|
- {id: bigonly, title: Memory, kind: manual, when: {size: big}}
|
||||||
|
architecture:
|
||||||
|
nodes: [{id: users, type: client, title: "Users of ${hosts[0]}"}]
|
||||||
|
edges: [{from: users, to: "mod:app/server", type: connectsTo}]
|
||||||
@@ -0,0 +1,306 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/secretref"
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxAnswerLen bounds a single text answer (SEC-03).
|
||||||
|
const MaxAnswerLen = 64 << 10
|
||||||
|
|
||||||
|
var (
|
||||||
|
hostnameRE = regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`)
|
||||||
|
emailRE = regexp.MustCompile(`^[^@\s]+@[^@\s]+$`)
|
||||||
|
dateRE = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// TypeValidator checks and normalizes one scalar answer of a type. New
|
||||||
|
// question types are added with RegisterType (WIZ-04).
|
||||||
|
type TypeValidator func(v any) (any, error)
|
||||||
|
|
||||||
|
var extraTypes = map[string]TypeValidator{}
|
||||||
|
|
||||||
|
// RegisterType adds a question type. It must be called before catalogs
|
||||||
|
// using the type are validated; built-in types cannot be replaced.
|
||||||
|
func RegisterType(name string, fn TypeValidator) error {
|
||||||
|
if catalog.QuestionTypes[name] {
|
||||||
|
return fmt.Errorf("type %q is built in", name)
|
||||||
|
}
|
||||||
|
extraTypes[name] = fn
|
||||||
|
catalog.QuestionTypes[name] = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize converts an answer given as text (CLI --set, interactive
|
||||||
|
// input) or as decoded YAML/JSON into the canonical value for the
|
||||||
|
// question and validates it. It does not check option enablement.
|
||||||
|
func Normalize(q *catalog.Question, v any) (any, error) {
|
||||||
|
switch q.Type {
|
||||||
|
case "multiselect", "list":
|
||||||
|
items := listOf(v)
|
||||||
|
out := make([]any, 0, len(items))
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, it := range items {
|
||||||
|
var n any
|
||||||
|
var err error
|
||||||
|
if q.Type == "multiselect" {
|
||||||
|
n, err = optionValue(q, it)
|
||||||
|
} else {
|
||||||
|
n, err = scalar(q.Item, it)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
k := catalog.Scalar(n)
|
||||||
|
if seen[k] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[k] = true
|
||||||
|
out = append(out, n)
|
||||||
|
}
|
||||||
|
if err := checkCount(q.Validation, len(out)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
case "select":
|
||||||
|
return optionValue(q, v)
|
||||||
|
case "keyvalue":
|
||||||
|
m, ok := v.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
s, isStr := v.(string)
|
||||||
|
if !isStr {
|
||||||
|
return nil, fmt.Errorf("want key=value pairs")
|
||||||
|
}
|
||||||
|
m = map[string]any{}
|
||||||
|
for _, part := range splitList(s) {
|
||||||
|
k, val, ok := strings.Cut(part, "=")
|
||||||
|
if !ok || strings.TrimSpace(k) == "" {
|
||||||
|
return nil, fmt.Errorf("%q: want key=value", part)
|
||||||
|
}
|
||||||
|
m[strings.TrimSpace(k)] = strings.TrimSpace(val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
n, err := scalar(q.Type, v)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return n, checkValue(q.Validation, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func optionValue(q *catalog.Question, v any) (any, error) {
|
||||||
|
s := strings.TrimSpace(catalog.Scalar(v))
|
||||||
|
for _, o := range q.Options {
|
||||||
|
if o.ID == s {
|
||||||
|
return o.ID, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// a number picks the n-th option (interactive CLI)
|
||||||
|
if n, err := strconv.Atoi(s); err == nil && n >= 1 && n <= len(q.Options) {
|
||||||
|
return q.Options[n-1].ID, nil
|
||||||
|
}
|
||||||
|
ids := make([]string, len(q.Options))
|
||||||
|
for i, o := range q.Options {
|
||||||
|
ids[i] = o.ID
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("%q is not one of %s", s, strings.Join(ids, ", "))
|
||||||
|
}
|
||||||
|
|
||||||
|
func listOf(v any) []any {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case []any:
|
||||||
|
return x
|
||||||
|
case []string:
|
||||||
|
out := make([]any, len(x))
|
||||||
|
for i, s := range x {
|
||||||
|
out[i] = s
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
case string:
|
||||||
|
var out []any
|
||||||
|
for _, p := range splitList(x) {
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
case nil:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return []any{v}
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitList(s string) []string {
|
||||||
|
var out []string
|
||||||
|
for _, p := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == '\n' || r == ' ' || r == ';' }) {
|
||||||
|
if p = strings.TrimSpace(p); p != "" {
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// scalar validates one value of a scalar type.
|
||||||
|
func scalar(typ string, v any) (any, error) {
|
||||||
|
if fn, ok := extraTypes[typ]; ok {
|
||||||
|
return fn(v)
|
||||||
|
}
|
||||||
|
if b, ok := v.(bool); ok && typ == "boolean" {
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
|
s := strings.TrimSpace(catalog.Scalar(v))
|
||||||
|
if len(s) > MaxAnswerLen || !utf8.ValidString(s) {
|
||||||
|
return nil, fmt.Errorf("value too long or not UTF-8")
|
||||||
|
}
|
||||||
|
switch typ {
|
||||||
|
case "boolean":
|
||||||
|
switch strings.ToLower(s) {
|
||||||
|
case "true", "yes", "y", "on", "1", "ja", "j":
|
||||||
|
return true, nil
|
||||||
|
case "false", "no", "n", "off", "0", "nein":
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("%q: want yes or no", s)
|
||||||
|
case "integer":
|
||||||
|
n, err := strconv.ParseInt(s, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%q: want a whole number", s)
|
||||||
|
}
|
||||||
|
return int(n), nil
|
||||||
|
case "decimal":
|
||||||
|
f, err := strconv.ParseFloat(s, 64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%q: want a number", s)
|
||||||
|
}
|
||||||
|
return f, nil
|
||||||
|
case "port":
|
||||||
|
n, err := strconv.Atoi(s)
|
||||||
|
if err != nil || n < 1 || n > 65535 {
|
||||||
|
return nil, fmt.Errorf("%q: want a port 1-65535", s)
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
case "hostname", "domain":
|
||||||
|
s = strings.ToLower(strings.TrimSuffix(s, "."))
|
||||||
|
if !hostnameRE.MatchString(s) || len(s) > 253 {
|
||||||
|
return nil, fmt.Errorf("%q: not a valid %s", s, typ)
|
||||||
|
}
|
||||||
|
if typ == "domain" && !strings.Contains(s, ".") {
|
||||||
|
return nil, fmt.Errorf("%q: a domain needs a dot (example.org)", s)
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
case "email":
|
||||||
|
if !emailRE.MatchString(s) {
|
||||||
|
return nil, fmt.Errorf("%q: not an e-mail address", s)
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
case "ip":
|
||||||
|
if net.ParseIP(s) == nil {
|
||||||
|
return nil, fmt.Errorf("%q: not an IP address", s)
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
case "cidr":
|
||||||
|
if _, _, err := net.ParseCIDR(s); err != nil {
|
||||||
|
if net.ParseIP(s) == nil {
|
||||||
|
return nil, fmt.Errorf("%q: not a network (CIDR) or address", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
case "url":
|
||||||
|
u, err := url.Parse(s)
|
||||||
|
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||||
|
return nil, fmt.Errorf("%q: not a URL", s)
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
case "duration":
|
||||||
|
if _, err := time.ParseDuration(s); err != nil {
|
||||||
|
return nil, fmt.Errorf("%q: want a duration like 30s, 5m, 4h", s)
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
case "date":
|
||||||
|
if !dateRE.MatchString(s) {
|
||||||
|
return nil, fmt.Errorf("%q: want YYYY-MM-DD", s)
|
||||||
|
}
|
||||||
|
if _, err := time.Parse("2006-01-02", s); err != nil {
|
||||||
|
return nil, fmt.Errorf("%q: not a date", s)
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
case "path", "dir":
|
||||||
|
if s == "" || strings.ContainsRune(s, 0) {
|
||||||
|
return nil, fmt.Errorf("want a path")
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
case "secret":
|
||||||
|
// SEC-01/WIZ-07: only references, never the secret itself.
|
||||||
|
if err := secretref.Validate(s); err != nil || s == "" {
|
||||||
|
return nil, fmt.Errorf("give a reference (secret://name, env:VAR, file:path), never the secret itself")
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
case "string", "text", "package", "profile", "capability", "provider", "target":
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("unknown type %q", typ)
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkValue(val catalog.Validation, v any) error {
|
||||||
|
msg := func(err string) error {
|
||||||
|
if val.Message != "" {
|
||||||
|
return fmt.Errorf("%s", val.Message)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%s", err)
|
||||||
|
}
|
||||||
|
if f, ok := v.(float64); ok {
|
||||||
|
return checkRange(val, f, msg)
|
||||||
|
}
|
||||||
|
if n, ok := v.(int); ok {
|
||||||
|
return checkRange(val, float64(n), msg)
|
||||||
|
}
|
||||||
|
if s, ok := v.(string); ok {
|
||||||
|
if val.MinLength > 0 && len(s) < val.MinLength {
|
||||||
|
return msg(fmt.Sprintf("at least %d characters", val.MinLength))
|
||||||
|
}
|
||||||
|
if val.MaxLength > 0 && len(s) > val.MaxLength {
|
||||||
|
return msg(fmt.Sprintf("at most %d characters", val.MaxLength))
|
||||||
|
}
|
||||||
|
if val.Pattern != "" {
|
||||||
|
re, err := regexp.Compile(val.Pattern)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("bad pattern in catalog: %v", err)
|
||||||
|
}
|
||||||
|
if !re.MatchString(s) {
|
||||||
|
return msg(fmt.Sprintf("%q does not match %s", s, val.Pattern))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkRange(val catalog.Validation, f float64, msg func(string) error) error {
|
||||||
|
if val.Min != nil && f < *val.Min {
|
||||||
|
return msg(fmt.Sprintf("at least %v", *val.Min))
|
||||||
|
}
|
||||||
|
if val.Max != nil && f > *val.Max {
|
||||||
|
return msg(fmt.Sprintf("at most %v", *val.Max))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkCount(val catalog.Validation, n int) error {
|
||||||
|
if val.MinItems > 0 && n < val.MinItems {
|
||||||
|
if val.Message != "" {
|
||||||
|
return fmt.Errorf("%s", val.Message)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("at least %d item(s)", val.MinItems)
|
||||||
|
}
|
||||||
|
if val.MaxItems > 0 && n > val.MaxItems {
|
||||||
|
return fmt.Errorf("at most %d item(s)", val.MaxItems)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestZZDump(t *testing.T) {
|
||||||
|
if os.Getenv("DUMP") == "" {
|
||||||
|
t.Skip()
|
||||||
|
}
|
||||||
|
c := assetsCatalog(t)
|
||||||
|
e := New(c)
|
||||||
|
x := c.Examples[os.Getenv("DUMP")]
|
||||||
|
in := NewInstance(x.Meta.ID, c.Lookup(x.Spec.Solution), x.Spec.Mode)
|
||||||
|
in.Spec.Parameters = x.Spec.Parameters
|
||||||
|
st, _ := e.Evaluate(in, nil)
|
||||||
|
for _, f := range st.Files {
|
||||||
|
t.Logf("=== %s\n%s", f.Path, f.Content)
|
||||||
|
}
|
||||||
|
for _, s := range st.Steps {
|
||||||
|
t.Logf("step %s [%s] %s", s.Phase, s.Run, s.Title)
|
||||||
|
}
|
||||||
|
for _, p := range st.Packages {
|
||||||
|
t.Logf("pkg %s %s %v", p.ID, p.Status, p.Reasons)
|
||||||
|
}
|
||||||
|
t.Log(GraphText(st.Graph))
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
module yetano.dev/yetano/core/solutions
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require gopkg.in/yaml.v3 v3.0.1
|
||||||
|
|
||||||
|
require yetano.dev/yetano/core v0.12.2
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
yetano.dev/yetano/core v0.12.2 h1:y8xkA1XjNTGiO9/JJRal5/IruoaqcE8aKJUYG8wVF6Q=
|
||||||
|
yetano.dev/yetano/core v0.12.2/go.mod h1:T2TdFvZiHbYVgcRmRXk9NC82AYL8krGVxxtLyedWuJE=
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package knowledge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
)
|
||||||
|
|
||||||
|
func assetsIndex(t *testing.T) *Index {
|
||||||
|
t.Helper()
|
||||||
|
dir, _ := filepath.Abs("../../../assets/solutions")
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, "catalog.yaml")); err != nil {
|
||||||
|
t.Skip("assets/solutions not present")
|
||||||
|
}
|
||||||
|
c, err := catalog.Load(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return Build(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAssetsLint(t *testing.T) {
|
||||||
|
ix := assetsIndex(t)
|
||||||
|
for _, i := range Lint(ix) {
|
||||||
|
if i.Severity == "error" {
|
||||||
|
t.Error(i)
|
||||||
|
} else {
|
||||||
|
t.Log(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("%d entries, %d manual topics, missing sources: %v", len(ix.Entries), len(ix.Topics), ix.Missing)
|
||||||
|
}
|
||||||
@@ -0,0 +1,441 @@
|
|||||||
|
// Package knowledge is the Knowledge Engine: one local index over the
|
||||||
|
// catalog, the Big Picture and the existing manuals, with reference
|
||||||
|
// resolution per client, backlinks, search, lint and coverage. The index
|
||||||
|
// is derived data: it is rebuilt from the sources and never edited.
|
||||||
|
package knowledge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
"yetano.dev/yetano/core/solutions/ref"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Entry is one searchable, linkable thing.
|
||||||
|
type Entry struct {
|
||||||
|
Ref string `json:"ref"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Summary string `json:"summary,omitempty"`
|
||||||
|
Package string `json:"package,omitempty"`
|
||||||
|
Category string `json:"category,omitempty"`
|
||||||
|
Tags []string `json:"tags,omitempty"`
|
||||||
|
Synonyms []string `json:"synonyms,omitempty"`
|
||||||
|
Capabilities []string `json:"capabilities,omitempty"`
|
||||||
|
Status string `json:"status,omitempty"`
|
||||||
|
File string `json:"file,omitempty"` // local file (manuals)
|
||||||
|
Line int `json:"line,omitempty"`
|
||||||
|
Body string `json:"-"` // searchable text
|
||||||
|
Translations catalog.Translations `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Section is a heading of a manual topic.
|
||||||
|
type Section struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Level int `json:"level"`
|
||||||
|
Start int `json:"start"` // first line (1-based)
|
||||||
|
End int `json:"end"` // last line
|
||||||
|
}
|
||||||
|
|
||||||
|
// Topic is one manual document.
|
||||||
|
type Topic struct {
|
||||||
|
Source string `json:"source"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
File string `json:"file"`
|
||||||
|
Sections []Section `json:"sections"`
|
||||||
|
lines []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Index is the knowledge index of one catalog.
|
||||||
|
type Index struct {
|
||||||
|
Cat *catalog.Catalog
|
||||||
|
Entries []*Entry
|
||||||
|
byRef map[string]*Entry
|
||||||
|
Topics map[string]*Topic // "<source>/<slug>"
|
||||||
|
Backlinks map[string][]string // target ref -> refs that point to it
|
||||||
|
// Missing lists knowledge sources whose files are not checked out.
|
||||||
|
Missing []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build indexes the catalog, the Big Picture and the manuals that are
|
||||||
|
// available locally under the catalog's sourcesRoot.
|
||||||
|
func Build(c *catalog.Catalog) *Index {
|
||||||
|
ix := &Index{Cat: c, byRef: map[string]*Entry{}, Topics: map[string]*Topic{}, Backlinks: map[string][]string{}}
|
||||||
|
ix.catalogEntries()
|
||||||
|
ix.bigPictureEntries()
|
||||||
|
ix.manuals()
|
||||||
|
ix.links()
|
||||||
|
sort.Slice(ix.Entries, func(i, j int) bool { return ix.Entries[i].Ref < ix.Entries[j].Ref })
|
||||||
|
return ix
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ix *Index) add(e *Entry) {
|
||||||
|
if _, dup := ix.byRef[e.Ref]; dup {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ix.byRef[e.Ref] = e
|
||||||
|
ix.Entries = append(ix.Entries, e)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entry returns the entry for a reference target (no section/version).
|
||||||
|
func (ix *Index) Entry(r string) *Entry { return ix.byRef[r] }
|
||||||
|
|
||||||
|
func (ix *Index) catalogEntries() {
|
||||||
|
c := ix.Cat
|
||||||
|
for _, id := range catalog.SortedIDs(c.Solutions) {
|
||||||
|
ix.add(solutionEntry(c, c.Solutions[id], ref.Solution))
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(c.Tasks) {
|
||||||
|
ix.add(solutionEntry(c, c.Tasks[id], ref.Task))
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(c.Packages) {
|
||||||
|
p := c.Packages[id]
|
||||||
|
e := &Entry{Ref: ref.For(ref.Package, id), Kind: ref.Package, Title: id, Package: id, Summary: p.Meta.Summary}
|
||||||
|
if bp := c.BigPicture; bp != nil {
|
||||||
|
if pr, ok := bp.Products[p.Spec.BigPicture]; ok {
|
||||||
|
e.Summary = firstNonEmpty(e.Summary, pr.Summary)
|
||||||
|
e.Body = strings.Join(pr.Tasks, "\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, m := range p.Spec.Modules {
|
||||||
|
e.Capabilities = append(e.Capabilities, m.Provides...)
|
||||||
|
e.Body += "\n" + m.Title + " " + m.Program
|
||||||
|
ix.add(&Entry{Ref: ref.For(ref.Module, id, m.ID), Kind: ref.Module, Title: firstNonEmpty(m.Program, m.ID) + ": " + m.Title,
|
||||||
|
Summary: m.Description, Package: id, Capabilities: m.Provides, Status: string(m.Support)})
|
||||||
|
}
|
||||||
|
if p.Spec.Microsite != "" {
|
||||||
|
ix.add(&Entry{Ref: ref.For(ref.Microsite, id), Kind: ref.Microsite, Title: id + " microsite", Package: id, Summary: e.Summary})
|
||||||
|
}
|
||||||
|
ix.add(e)
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(c.Capabilities) {
|
||||||
|
cp := c.Capabilities[id]
|
||||||
|
ix.add(&Entry{Ref: ref.For(ref.Capability, id), Kind: ref.Capability, Title: cp.Title, Summary: cp.Description, Capabilities: []string{id}, Translations: cp.Translations})
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(c.Profiles) {
|
||||||
|
p := c.Profiles[id]
|
||||||
|
ix.add(&Entry{Ref: ref.For(ref.Profile, p.Meta.Package, p.Meta.ID), Kind: ref.Profile, Title: firstNonEmpty(p.Meta.Title, p.Meta.ID),
|
||||||
|
Summary: p.Meta.Description, Package: p.Meta.Package})
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(c.Examples) {
|
||||||
|
x := c.Examples[id]
|
||||||
|
ix.add(&Entry{Ref: ref.For(ref.Example, x.Spec.Solution, x.Meta.ID), Kind: ref.Example, Title: x.Meta.Title, Summary: x.Meta.Summary,
|
||||||
|
Translations: x.Meta.Translations, Body: x.Spec.Scenario})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func solutionEntry(c *catalog.Catalog, s *catalog.Solution, kind string) *Entry {
|
||||||
|
e := &Entry{Ref: ref.For(kind, s.Meta.ID), Kind: kind, Title: s.Meta.Title, Summary: s.Meta.Summary, Category: s.Meta.Category,
|
||||||
|
Tags: s.Meta.Tags, Synonyms: s.Meta.Synonyms, Status: string(s.Meta.Status), Translations: s.Meta.Translations}
|
||||||
|
if bp := c.BigPicture; bp != nil {
|
||||||
|
if g, ok := bp.Stories[s.Spec.BigPicture]; ok {
|
||||||
|
e.Title = firstNonEmpty(e.Title, g.Title)
|
||||||
|
e.Summary = firstNonEmpty(e.Summary, g.Intent)
|
||||||
|
e.Body = g.Intent + "\n" + g.Outcome
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e.Body += "\n" + strings.Join(s.Spec.Goals, "\n") + "\n" + strings.Join(s.Spec.Scenarios, "\n")
|
||||||
|
for _, q := range s.Spec.Questions {
|
||||||
|
e.Body += "\n" + q.Title
|
||||||
|
for _, o := range q.Options {
|
||||||
|
e.Body += "\n" + o.Title
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e.Capabilities = append(append([]string{}, s.Spec.Capabilities.Required...), s.Spec.Capabilities.Recommended...)
|
||||||
|
for _, p := range s.Spec.Packages {
|
||||||
|
e.Body += "\n" + p.ID
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ix *Index) bigPictureEntries() {
|
||||||
|
bp := ix.Cat.BigPicture
|
||||||
|
if bp == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(bp.Topics) {
|
||||||
|
t := bp.Topics[id]
|
||||||
|
ix.add(&Entry{Ref: ref.For(ref.BigPicture, id), Kind: ref.BigPicture, Title: t.Title, Summary: t.Summary})
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(bp.Stories) {
|
||||||
|
s := bp.Stories[id]
|
||||||
|
ix.add(&Entry{Ref: ref.For(ref.BigPicture, id), Kind: ref.BigPicture, Title: s.Title, Summary: s.Intent, Body: s.Outcome + "\n" + s.Explanation})
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(bp.Products) {
|
||||||
|
p := bp.Products[id]
|
||||||
|
ix.add(&Entry{Ref: ref.For(ref.BigPicture, id), Kind: ref.BigPicture, Title: p.Name + " (Big Picture)", Summary: p.Summary})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- manuals ---------------------------------------------------------------
|
||||||
|
|
||||||
|
// SourceDir is where a knowledge source's files are, or "" if unknown.
|
||||||
|
func (ix *Index) SourceDir(k *catalog.KnowledgeSource) string {
|
||||||
|
if ix.Cat.Spec.SourcesRoot == "" || ix.Cat.Root == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
root := ix.Cat.Spec.SourcesRoot
|
||||||
|
if !filepath.IsAbs(root) {
|
||||||
|
root = filepath.Join(ix.Cat.Root, root)
|
||||||
|
}
|
||||||
|
return filepath.Join(root, filepath.FromSlash(k.Spec.Repository), filepath.FromSlash(k.Spec.Root))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MaxManualSize bounds one manual file.
|
||||||
|
const MaxManualSize = 2 << 20
|
||||||
|
|
||||||
|
func (ix *Index) manuals() {
|
||||||
|
for _, id := range catalog.SortedIDs(ix.Cat.Sources) {
|
||||||
|
k := ix.Cat.Sources[id]
|
||||||
|
dir := ix.SourceDir(k)
|
||||||
|
if dir == "" {
|
||||||
|
ix.Missing = append(ix.Missing, id)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, "README.md")); err != nil {
|
||||||
|
ix.Missing = append(ix.Missing, id)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
files := []string{"README.md"}
|
||||||
|
docs := filepath.Join(dir, "docs")
|
||||||
|
_ = filepath.WalkDir(docs, func(p string, d fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
rel, _ := filepath.Rel(dir, p)
|
||||||
|
rel = filepath.ToSlash(rel)
|
||||||
|
for _, ex := range k.Spec.Exclude {
|
||||||
|
if rel == ex || strings.HasPrefix(rel, ex+"/") {
|
||||||
|
if d.IsDir() {
|
||||||
|
return fs.SkipDir
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if d.IsDir() && strings.HasPrefix(d.Name(), ".") {
|
||||||
|
return fs.SkipDir
|
||||||
|
}
|
||||||
|
// *.conflict.md: a wiki-sync conflict copy (meta-repo
|
||||||
|
// AGENTS.md), never documentation of its own
|
||||||
|
if !d.IsDir() && strings.HasSuffix(p, ".md") && !strings.HasSuffix(p, ".conflict.md") {
|
||||||
|
files = append(files, rel)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
sort.Strings(files)
|
||||||
|
for _, f := range files {
|
||||||
|
b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(f)))
|
||||||
|
if err != nil || len(b) > MaxManualSize {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
t := parseTopic(id, TopicSlug(f), filepath.Join(dir, filepath.FromSlash(f)), b)
|
||||||
|
ix.Topics[id+"/"+t.Slug] = t
|
||||||
|
caps := []string{}
|
||||||
|
for _, st := range k.Spec.Topics {
|
||||||
|
if st.Slug == t.Slug {
|
||||||
|
caps = st.Capabilities
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r := ref.For(ref.Manual, id, t.Slug)
|
||||||
|
ix.add(&Entry{Ref: r, Kind: ref.Manual, Title: t.Title, Summary: firstLine(t), Package: k.Spec.Package,
|
||||||
|
Capabilities: caps, File: t.File, Body: strings.Join(t.lines, "\n")})
|
||||||
|
for _, s := range t.Sections[1:] {
|
||||||
|
ix.add(&Entry{Ref: r + "#" + s.ID, Kind: "section", Title: t.Title + " › " + s.Title, Package: k.Spec.Package,
|
||||||
|
File: t.File, Line: s.Start, Body: strings.Join(t.lines[s.Start-1:s.End], "\n")})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TopicSlug follows core/manual: README.md -> readme, docs/x.md -> x,
|
||||||
|
// docs/x/README.md -> x.
|
||||||
|
func TopicSlug(rel string) string {
|
||||||
|
if rel == "README.md" {
|
||||||
|
return "readme"
|
||||||
|
}
|
||||||
|
s := strings.TrimSuffix(strings.TrimPrefix(rel, "docs/"), ".md")
|
||||||
|
s = strings.TrimSuffix(s, "/README")
|
||||||
|
return strings.ReplaceAll(s, "/", ".")
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseTopic(source, slug, file string, b []byte) *Topic {
|
||||||
|
t := &Topic{Source: source, Slug: slug, File: file}
|
||||||
|
sc := bufio.NewScanner(bytes.NewReader(b))
|
||||||
|
sc.Buffer(make([]byte, 64<<10), MaxManualSize)
|
||||||
|
fence := false
|
||||||
|
seen := map[string]int{}
|
||||||
|
for sc.Scan() {
|
||||||
|
line := sc.Text()
|
||||||
|
t.lines = append(t.lines, line)
|
||||||
|
trimmed := strings.TrimSpace(line)
|
||||||
|
if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") {
|
||||||
|
fence = !fence
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if fence || !strings.HasPrefix(line, "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
level := len(line) - len(strings.TrimLeft(line, "#"))
|
||||||
|
title := strings.TrimSpace(line[level:])
|
||||||
|
if level > 6 || title == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
id := ref.Slug(title)
|
||||||
|
if n := seen[id]; n > 0 {
|
||||||
|
id = fmt.Sprintf("%s-%d", id, n)
|
||||||
|
}
|
||||||
|
seen[ref.Slug(title)]++
|
||||||
|
if len(t.Sections) > 0 {
|
||||||
|
t.Sections[len(t.Sections)-1].End = len(t.lines) - 1
|
||||||
|
}
|
||||||
|
t.Sections = append(t.Sections, Section{ID: id, Title: title, Level: level, Start: len(t.lines)})
|
||||||
|
if t.Title == "" && level == 1 {
|
||||||
|
t.Title = title
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(t.Sections) == 0 {
|
||||||
|
t.Sections = []Section{{ID: "", Title: slug, Level: 1, Start: 1}}
|
||||||
|
}
|
||||||
|
t.Sections[len(t.Sections)-1].End = len(t.lines)
|
||||||
|
if t.Title == "" {
|
||||||
|
t.Title = slug
|
||||||
|
}
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstLine(t *Topic) string {
|
||||||
|
for _, l := range t.lines {
|
||||||
|
l = strings.TrimSpace(l)
|
||||||
|
if l != "" && !strings.HasPrefix(l, "#") && !strings.HasPrefix(l, "```") && !strings.HasPrefix(l, "|") && !strings.HasPrefix(l, "<") {
|
||||||
|
if len(l) > 200 {
|
||||||
|
l = l[:200] + "…"
|
||||||
|
}
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstNonEmpty(a ...string) string {
|
||||||
|
for _, s := range a {
|
||||||
|
if s != "" {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// links collects every reference the catalog makes, for backlinks (REL-01/02).
|
||||||
|
func (ix *Index) links() {
|
||||||
|
c := ix.Cat
|
||||||
|
link := func(from string, to string) {
|
||||||
|
r, err := ref.Parse(to)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t := r.Target()
|
||||||
|
for _, x := range ix.Backlinks[t] {
|
||||||
|
if x == from {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ix.Backlinks[t] = append(ix.Backlinks[t], from)
|
||||||
|
}
|
||||||
|
for _, m := range []map[string]*catalog.Solution{c.Solutions, c.Tasks} {
|
||||||
|
for _, id := range catalog.SortedIDs(m) {
|
||||||
|
s := m[id]
|
||||||
|
kind := ref.Solution
|
||||||
|
if s.IsTask() {
|
||||||
|
kind = ref.Task
|
||||||
|
}
|
||||||
|
from := ref.For(kind, id)
|
||||||
|
for _, r := range RefsOf(s) {
|
||||||
|
link(from, r)
|
||||||
|
}
|
||||||
|
for _, p := range s.Spec.Packages {
|
||||||
|
link(from, ref.For(ref.Package, p.ID))
|
||||||
|
}
|
||||||
|
for _, cp := range append(append([]string{}, s.Spec.Capabilities.Required...), s.Spec.Capabilities.Recommended...) {
|
||||||
|
link(from, ref.For(ref.Capability, cp))
|
||||||
|
}
|
||||||
|
if s.Spec.BigPicture != "" {
|
||||||
|
link(from, ref.For(ref.BigPicture, s.Spec.BigPicture))
|
||||||
|
}
|
||||||
|
for _, r := range s.Spec.Related {
|
||||||
|
k := ref.Solution
|
||||||
|
if c.Tasks[r] != nil {
|
||||||
|
k = ref.Task
|
||||||
|
}
|
||||||
|
link(from, ref.For(k, r))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(c.Packages) {
|
||||||
|
p := c.Packages[id]
|
||||||
|
from := ref.For(ref.Package, id)
|
||||||
|
for _, m := range p.Spec.Modules {
|
||||||
|
for _, cp := range m.Provides {
|
||||||
|
link(ref.For(ref.Module, id, m.ID), ref.For(ref.Capability, cp))
|
||||||
|
link(from, ref.For(ref.Capability, cp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.Spec.BigPicture != "" {
|
||||||
|
link(from, ref.For(ref.BigPicture, p.Spec.BigPicture))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(c.Profiles) {
|
||||||
|
p := c.Profiles[id]
|
||||||
|
for _, r := range p.Spec.References {
|
||||||
|
link(ref.For(ref.Profile, p.Meta.Package, p.Meta.ID), r)
|
||||||
|
}
|
||||||
|
link(ref.For(ref.Profile, p.Meta.Package, p.Meta.ID), ref.For(ref.Package, p.Meta.Package))
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(c.Examples) {
|
||||||
|
x := c.Examples[id]
|
||||||
|
k := ref.Solution
|
||||||
|
if c.Tasks[x.Spec.Solution] != nil {
|
||||||
|
k = ref.Task
|
||||||
|
}
|
||||||
|
link(ref.For(ref.Example, x.Spec.Solution, x.Meta.ID), ref.For(k, x.Spec.Solution))
|
||||||
|
}
|
||||||
|
for k := range ix.Backlinks {
|
||||||
|
sort.Strings(ix.Backlinks[k])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RefsOf lists every yetano: reference a solution or task contains.
|
||||||
|
func RefsOf(s *catalog.Solution) []string {
|
||||||
|
var out []string
|
||||||
|
out = append(out, s.Spec.References.All()...)
|
||||||
|
for _, q := range s.Spec.Questions {
|
||||||
|
out = append(out, q.References...)
|
||||||
|
for _, o := range q.Options {
|
||||||
|
out = append(out, o.References...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, st := range s.Spec.Steps {
|
||||||
|
out = append(out, st.References...)
|
||||||
|
}
|
||||||
|
for _, c := range s.Spec.Requirements {
|
||||||
|
out = append(out, c.References...)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backlinks of a reference (its target), sorted.
|
||||||
|
func (ix *Index) BacklinksOf(r string) []string {
|
||||||
|
p, err := ref.Parse(r)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return ix.Backlinks[p.Target()]
|
||||||
|
}
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
package knowledge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/catalog"
|
||||||
|
"yetano.dev/yetano/core/solutions/ref"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Lint checks what catalog.Validate cannot: every yetano: reference
|
||||||
|
// resolves (manual topics and sections included), and catalog-wide
|
||||||
|
// advice (QS-03). It returns catalog.Validate's issues plus its own.
|
||||||
|
func Lint(ix *Index) []catalog.Issue {
|
||||||
|
c := ix.Cat
|
||||||
|
issues := c.Validate()
|
||||||
|
check := func(e *catalog.Entity, owner, r string) {
|
||||||
|
res, err := ix.Resolve(r)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
issues = append(issues, catalog.Issue{Severity: "error", File: e.File, Line: e.Line, ID: owner, Code: "reference", Message: err.Error()})
|
||||||
|
case !res.Exists:
|
||||||
|
issues = append(issues, catalog.Issue{Severity: "error", File: e.File, Line: e.Line, ID: owner, Code: "reference", Message: fmt.Sprintf("%s does not resolve", r)})
|
||||||
|
case !res.SectionExists:
|
||||||
|
issues = append(issues, catalog.Issue{Severity: "error", File: e.File, Line: e.Line, ID: owner, Code: "reference-section", Message: fmt.Sprintf("%s: the manual has no such section (renamed heading?)", r)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, m := range []map[string]*catalog.Solution{c.Solutions, c.Tasks} {
|
||||||
|
for _, id := range catalog.SortedIDs(m) {
|
||||||
|
s := m[id]
|
||||||
|
for _, r := range RefsOf(s) {
|
||||||
|
check(&s.Entity, id, r)
|
||||||
|
}
|
||||||
|
if s.Kind == catalog.KindSolution && len(c.Examples) > 0 {
|
||||||
|
has := false
|
||||||
|
for _, x := range c.Examples {
|
||||||
|
has = has || x.Spec.Solution == id
|
||||||
|
}
|
||||||
|
if !has {
|
||||||
|
issues = append(issues, catalog.Issue{Severity: "warning", File: s.File, ID: id, Code: "no-example", Message: "a solution should have at least one example (EX-01)"})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, q := range s.Spec.Questions {
|
||||||
|
if q.Type == "select" && q.Decide == "" && q.Level != catalog.LevelAdvanced && len(q.Options) > 2 {
|
||||||
|
issues = append(issues, catalog.Issue{Severity: "warning", File: s.File, ID: id + "." + q.ID, Code: "no-decide", Message: "a choice between several options should explain it (decide, HELP-01)"})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(c.Profiles) {
|
||||||
|
p := c.Profiles[id]
|
||||||
|
for _, r := range p.Spec.References {
|
||||||
|
check(&p.Entity, id, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, id := range ix.Missing {
|
||||||
|
issues = append(issues, catalog.Issue{Severity: "warning", ID: id, Code: "source-missing", Message: "documents not checked out under sourcesRoot; its references are not checked"})
|
||||||
|
}
|
||||||
|
return issues
|
||||||
|
}
|
||||||
|
|
||||||
|
// Coverage is the knowledge coverage report (COV-01), computed from data.
|
||||||
|
type Coverage struct {
|
||||||
|
Packages int `json:"packages"`
|
||||||
|
Metrics []Metric `json:"metrics"`
|
||||||
|
GoalsWithout []string `json:"goalsWithoutSolution"`
|
||||||
|
ProgramsWithout []string `json:"bigPictureProgramsWithoutPackage"`
|
||||||
|
ByPackage map[string]PackageCoverage `json:"byPackage"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metric is one percentage.
|
||||||
|
type Metric struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Have int `json:"have"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Pct float64 `json:"percent"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PackageCoverage is what exists for one package.
|
||||||
|
type PackageCoverage struct {
|
||||||
|
Manual bool `json:"manual"`
|
||||||
|
Microsite bool `json:"microsite"`
|
||||||
|
Provides int `json:"capabilities"`
|
||||||
|
Profiles int `json:"profiles"`
|
||||||
|
Solutions int `json:"solutions"`
|
||||||
|
Tasks int `json:"tasks"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ComputeCoverage builds the report.
|
||||||
|
func ComputeCoverage(ix *Index) Coverage {
|
||||||
|
c := ix.Cat
|
||||||
|
cov := Coverage{ByPackage: map[string]PackageCoverage{}}
|
||||||
|
for _, id := range catalog.SortedIDs(c.Packages) {
|
||||||
|
p := c.Packages[id]
|
||||||
|
pc := PackageCoverage{Microsite: p.Spec.Microsite != ""}
|
||||||
|
for _, m := range p.Spec.Modules {
|
||||||
|
pc.Provides += len(m.Provides)
|
||||||
|
}
|
||||||
|
for _, k := range c.Sources {
|
||||||
|
pc.Manual = pc.Manual || k.Spec.Package == id
|
||||||
|
}
|
||||||
|
for _, pr := range c.Profiles {
|
||||||
|
if pr.Meta.Package == id {
|
||||||
|
pc.Profiles++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, s := range c.Solutions {
|
||||||
|
for _, pu := range s.Spec.Packages {
|
||||||
|
if pu.ID == id {
|
||||||
|
pc.Solutions++
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, s := range c.Tasks {
|
||||||
|
for _, pu := range s.Spec.Packages {
|
||||||
|
if pu.ID == id {
|
||||||
|
pc.Tasks++
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cov.ByPackage[id] = pc
|
||||||
|
}
|
||||||
|
cov.Packages = len(c.Packages)
|
||||||
|
count := func(name string, f func(PackageCoverage) bool) {
|
||||||
|
m := Metric{Name: name, Total: len(cov.ByPackage)}
|
||||||
|
for _, pc := range cov.ByPackage {
|
||||||
|
if f(pc) {
|
||||||
|
m.Have++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cov.Metrics = append(cov.Metrics, pct(m))
|
||||||
|
}
|
||||||
|
count("Packages with a manual source", func(p PackageCoverage) bool { return p.Manual })
|
||||||
|
count("Packages with a microsite", func(p PackageCoverage) bool { return p.Microsite })
|
||||||
|
count("Packages with capabilities", func(p PackageCoverage) bool { return p.Provides > 0 })
|
||||||
|
count("Packages with profiles", func(p PackageCoverage) bool { return p.Profiles > 0 })
|
||||||
|
count("Packages used by a solution", func(p PackageCoverage) bool { return p.Solutions > 0 })
|
||||||
|
count("Packages with a task", func(p PackageCoverage) bool { return p.Tasks > 0 })
|
||||||
|
// references
|
||||||
|
refs, ok := 0, 0
|
||||||
|
for _, m := range []map[string]*catalog.Solution{c.Solutions, c.Tasks} {
|
||||||
|
for _, s := range m {
|
||||||
|
for _, r := range RefsOf(s) {
|
||||||
|
refs++
|
||||||
|
if res, err := ix.Resolve(r); err == nil && res.Exists && res.SectionExists {
|
||||||
|
ok++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cov.Metrics = append(cov.Metrics, pct(Metric{Name: "Valid references", Have: ok, Total: refs}))
|
||||||
|
tested := 0
|
||||||
|
for _, x := range c.Examples {
|
||||||
|
if x.Spec.Tested {
|
||||||
|
tested++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cov.Metrics = append(cov.Metrics, pct(Metric{Name: "Examples marked tested", Have: tested, Total: len(c.Examples)}))
|
||||||
|
// translations of solution titles
|
||||||
|
tr, total := 0, 0
|
||||||
|
for _, loc := range c.Spec.Locales {
|
||||||
|
if loc == "en" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, m := range []map[string]*catalog.Solution{c.Solutions, c.Tasks} {
|
||||||
|
for _, s := range m {
|
||||||
|
total++
|
||||||
|
if s.Meta.Translations[loc]["title"] != "" {
|
||||||
|
tr++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cov.Metrics = append(cov.Metrics, pct(Metric{Name: "Solution titles translated", Have: tr, Total: total}))
|
||||||
|
if bp := c.BigPicture; bp != nil {
|
||||||
|
used := map[string]bool{}
|
||||||
|
for _, s := range c.Solutions {
|
||||||
|
used[s.Spec.BigPicture] = true
|
||||||
|
}
|
||||||
|
goals := 0
|
||||||
|
for _, id := range catalog.SortedIDs(bp.Stories) {
|
||||||
|
if used[id] {
|
||||||
|
goals++
|
||||||
|
} else {
|
||||||
|
cov.GoalsWithout = append(cov.GoalsWithout, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cov.Metrics = append(cov.Metrics, pct(Metric{Name: "Big Picture goals with a solution", Have: goals, Total: len(bp.Stories)}))
|
||||||
|
pk := map[string]bool{}
|
||||||
|
for _, p := range c.Packages {
|
||||||
|
pk[p.Spec.BigPicture] = true
|
||||||
|
}
|
||||||
|
for _, id := range catalog.SortedIDs(bp.Products) {
|
||||||
|
if !pk[id] {
|
||||||
|
cov.ProgramsWithout = append(cov.ProgramsWithout, strings.TrimPrefix(id, "product."))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cov.Metrics = append(cov.Metrics, pct(Metric{Name: "Big Picture programs in the catalog", Have: len(bp.Products) - len(cov.ProgramsWithout), Total: len(bp.Products)}))
|
||||||
|
}
|
||||||
|
sort.SliceStable(cov.Metrics, func(i, j int) bool { return false })
|
||||||
|
return cov
|
||||||
|
}
|
||||||
|
|
||||||
|
func pct(m Metric) Metric {
|
||||||
|
if m.Total > 0 {
|
||||||
|
m.Pct = float64(int(float64(m.Have)*1000/float64(m.Total)+0.5)) / 10
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ = ref.Solution
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
package knowledge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/ref"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Resolution says what a reference points at and how each client opens
|
||||||
|
// it (REF-02). Exists is false for targets the index does not know.
|
||||||
|
type Resolution struct {
|
||||||
|
Ref string `json:"ref"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Title string `json:"title,omitempty"`
|
||||||
|
Summary string `json:"summary,omitempty"`
|
||||||
|
Exists bool `json:"exists"`
|
||||||
|
// SectionExists is false when the ref names a section that is not there.
|
||||||
|
SectionExists bool `json:"sectionExists"`
|
||||||
|
Web string `json:"web,omitempty"` // URL on yetano.app (only for pages that exist)
|
||||||
|
CLI string `json:"cli,omitempty"` // command that shows it in a terminal
|
||||||
|
File string `json:"file,omitempty"` // local Markdown file (manuals)
|
||||||
|
Line int `json:"line,omitempty"`
|
||||||
|
View string `json:"view"` // how a UI shows it: wizard | reader | graph | package | code | list
|
||||||
|
Note string `json:"note,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve resolves a reference against the index.
|
||||||
|
func (ix *Index) Resolve(s string) (Resolution, error) {
|
||||||
|
r, err := ref.Parse(s)
|
||||||
|
if err != nil {
|
||||||
|
return Resolution{}, err
|
||||||
|
}
|
||||||
|
res := Resolution{Ref: s, Kind: r.Kind, SectionExists: r.Section == ""}
|
||||||
|
web := strings.TrimRight(ix.Cat.Spec.WebBase, "/") + "/"
|
||||||
|
if e := ix.byRef[r.Target()]; e != nil {
|
||||||
|
res.Exists, res.Title, res.Summary = true, e.Title, e.Summary
|
||||||
|
}
|
||||||
|
switch r.Kind {
|
||||||
|
case ref.Solution, ref.Task:
|
||||||
|
res.View = "wizard"
|
||||||
|
cmd := "solution"
|
||||||
|
if r.Kind == ref.Task {
|
||||||
|
cmd = "task"
|
||||||
|
}
|
||||||
|
res.CLI = fmt.Sprintf("yet %s show %s", cmd, r.Path[0])
|
||||||
|
case ref.Package:
|
||||||
|
res.View = "package"
|
||||||
|
res.CLI = "yet solution package " + r.Path[0]
|
||||||
|
if p := ix.Cat.Packages[r.Path[0]]; p != nil && p.Spec.Microsite != "" {
|
||||||
|
res.Web = web + p.Spec.Microsite
|
||||||
|
}
|
||||||
|
case ref.Module:
|
||||||
|
res.View = "package"
|
||||||
|
res.CLI = "yet solution package " + r.Path[0]
|
||||||
|
case ref.Microsite:
|
||||||
|
res.View = "package"
|
||||||
|
if p := ix.Cat.Packages[r.Path[0]]; p != nil && p.Spec.Microsite != "" {
|
||||||
|
res.Web = web + p.Spec.Microsite
|
||||||
|
res.Exists = true
|
||||||
|
}
|
||||||
|
case ref.Capability:
|
||||||
|
res.View = "list"
|
||||||
|
res.CLI = "yet knowledge show " + s
|
||||||
|
case ref.Profile, ref.Example:
|
||||||
|
res.View = "code"
|
||||||
|
res.CLI = "yet knowledge show " + s
|
||||||
|
case ref.BigPicture:
|
||||||
|
res.View = "graph"
|
||||||
|
if bp := ix.Cat.BigPicture; bp != nil && bp.Has(r.Path[0]) {
|
||||||
|
res.Exists = true
|
||||||
|
res.Web = web + bp.WebPath + "#" + bp.Fragment(r.Path[0])
|
||||||
|
}
|
||||||
|
case ref.Manual:
|
||||||
|
res.View = "reader"
|
||||||
|
source := r.Path[0]
|
||||||
|
slug := strings.Join(r.Path[1:], ".")
|
||||||
|
k := ix.Cat.Sources[source]
|
||||||
|
if k == nil {
|
||||||
|
res.Note = "unknown knowledge source " + source
|
||||||
|
break
|
||||||
|
}
|
||||||
|
realSlug := strings.ReplaceAll(slug, ".", "/")
|
||||||
|
if k.Spec.Program != "" {
|
||||||
|
res.CLI = fmt.Sprintf("%s manual %s", k.Spec.Program, realSlug)
|
||||||
|
} else {
|
||||||
|
res.CLI = "yet knowledge show " + s
|
||||||
|
}
|
||||||
|
if k.Spec.Web != "" {
|
||||||
|
res.Web = k.Spec.Web
|
||||||
|
}
|
||||||
|
t := ix.Topics[source+"/"+slug]
|
||||||
|
if t == nil {
|
||||||
|
if ix.missing(source) {
|
||||||
|
res.Note = "the documents of " + source + " are not available locally; the reference is not checked"
|
||||||
|
res.Exists = true // cannot tell; do not report as broken
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
res.Exists, res.Title, res.File = true, t.Title, t.File
|
||||||
|
if r.Section != "" {
|
||||||
|
for _, sec := range t.Sections {
|
||||||
|
if sec.ID == r.Section {
|
||||||
|
res.SectionExists, res.Title, res.Line = true, t.Title+" › "+sec.Title, sec.Start
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if res.Web != "" {
|
||||||
|
if _, err := url.Parse(res.Web); err != nil {
|
||||||
|
res.Web = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ix *Index) missing(source string) bool {
|
||||||
|
for _, m := range ix.Missing {
|
||||||
|
if m == source {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read returns the Markdown of a manual reference: the whole topic, or
|
||||||
|
// just the section (with its subsections).
|
||||||
|
func (ix *Index) Read(s string) (title, markdown string, err error) {
|
||||||
|
r, err := ref.Parse(s)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
if r.Kind != ref.Manual {
|
||||||
|
return "", "", fmt.Errorf("%s is not a manual reference", s)
|
||||||
|
}
|
||||||
|
t := ix.Topics[r.Path[0]+"/"+strings.Join(r.Path[1:], ".")]
|
||||||
|
if t == nil {
|
||||||
|
return "", "", fmt.Errorf("manual %s is not available locally", s)
|
||||||
|
}
|
||||||
|
if r.Section == "" {
|
||||||
|
return t.Title, strings.Join(t.lines, "\n") + "\n", nil
|
||||||
|
}
|
||||||
|
for i, sec := range t.Sections {
|
||||||
|
if sec.ID != r.Section {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
end := len(t.lines)
|
||||||
|
for _, next := range t.Sections[i+1:] {
|
||||||
|
if next.Level <= sec.Level {
|
||||||
|
end = next.Start - 1
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sec.Title, strings.Join(t.lines[sec.Start-1:end], "\n") + "\n", nil
|
||||||
|
}
|
||||||
|
return "", "", fmt.Errorf("%s: no section %q", s, r.Section)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Excerpt implements engine.ManualReader.
|
||||||
|
func (ix *Index) Excerpt(s string, maxLines int) (string, string, bool) {
|
||||||
|
title, md, err := ix.Read(s)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
lines := strings.Split(strings.TrimRight(md, "\n"), "\n")
|
||||||
|
if len(lines) > 0 && strings.HasPrefix(lines[0], "#") {
|
||||||
|
lines = lines[1:]
|
||||||
|
}
|
||||||
|
for len(lines) > 0 && strings.TrimSpace(lines[0]) == "" {
|
||||||
|
lines = lines[1:]
|
||||||
|
}
|
||||||
|
if len(lines) > maxLines {
|
||||||
|
lines = append(lines[:maxLines], "…")
|
||||||
|
}
|
||||||
|
return title, strings.Join(lines, "\n"), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Link implements engine.ManualReader: a web URL, else the CLI command.
|
||||||
|
func (ix *Index) Link(s string) string {
|
||||||
|
res, err := ix.Resolve(s)
|
||||||
|
if err != nil {
|
||||||
|
return "`" + s + "`"
|
||||||
|
}
|
||||||
|
label := firstNonEmpty(res.Title, s)
|
||||||
|
switch {
|
||||||
|
case res.Web != "" && res.Kind != ref.Manual:
|
||||||
|
return fmt.Sprintf("[%s](%s)", label, res.Web)
|
||||||
|
case res.CLI != "":
|
||||||
|
return fmt.Sprintf("%s (`%s`)", label, res.CLI)
|
||||||
|
}
|
||||||
|
return "`" + s + "`"
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package knowledge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/ref"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Hit is one search result.
|
||||||
|
type Hit struct {
|
||||||
|
Ref string `json:"ref"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Summary string `json:"summary,omitempty"`
|
||||||
|
Score float64 `json:"score"`
|
||||||
|
Status string `json:"status,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group collects the hits of one kind (SEARCH-01).
|
||||||
|
type Group struct {
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Hits []Hit `json:"hits"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SearchOptions narrow a search.
|
||||||
|
type SearchOptions struct {
|
||||||
|
Kinds []string // only these kinds (solution, task, package, manual, ...)
|
||||||
|
Limit int // per group; 0 = 10
|
||||||
|
Locale string
|
||||||
|
Package string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group order: use cases first (SEARCH-04).
|
||||||
|
var groupOrder = []struct{ kind, title string }{
|
||||||
|
{ref.Solution, "Solutions"}, {ref.Task, "Tasks"}, {ref.Example, "Examples"},
|
||||||
|
{ref.Package, "Packages"}, {ref.Module, "Modules"}, {ref.Capability, "Capabilities"},
|
||||||
|
{ref.Manual, "Manuals"}, {"section", "Manual sections"}, {ref.Microsite, "Microsites"},
|
||||||
|
{ref.BigPicture, "Big Picture"}, {ref.Profile, "Profiles"},
|
||||||
|
}
|
||||||
|
|
||||||
|
var stop = map[string]bool{"i": true, "a": true, "an": true, "the": true, "to": true, "want": true, "my": true, "own": true,
|
||||||
|
"with": true, "for": true, "of": true, "and": true, "run": false, "ich": true, "will": true, "einen": true, "ein": true, "mit": true, "möchte": true}
|
||||||
|
|
||||||
|
// Tokens splits text into lower-case search words.
|
||||||
|
func Tokens(s string) []string {
|
||||||
|
f := strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '.' })
|
||||||
|
var out []string
|
||||||
|
for _, w := range f {
|
||||||
|
w = strings.Trim(w, ".")
|
||||||
|
if w != "" && !stop[w] {
|
||||||
|
out = append(out, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search runs a deterministic full-text search over the index: titles,
|
||||||
|
// IDs, tags and synonyms weigh most, then summaries, then body text.
|
||||||
|
// No embeddings and no network (SEARCH-05).
|
||||||
|
func (ix *Index) Search(q string, opt SearchOptions) []Group {
|
||||||
|
words := Tokens(q)
|
||||||
|
if len(words) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
limit := opt.Limit
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = 10
|
||||||
|
}
|
||||||
|
allowed := map[string]bool{}
|
||||||
|
for _, k := range opt.Kinds {
|
||||||
|
allowed[k] = true
|
||||||
|
}
|
||||||
|
byKind := map[string][]Hit{}
|
||||||
|
for _, e := range ix.Entries {
|
||||||
|
if len(allowed) > 0 && !allowed[e.Kind] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if opt.Package != "" && e.Package != opt.Package {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
title := e.Title
|
||||||
|
summary := e.Summary
|
||||||
|
if opt.Locale != "" && e.Translations != nil {
|
||||||
|
if m, ok := e.Translations[opt.Locale]; ok {
|
||||||
|
title = firstNonEmpty(m["title"], title)
|
||||||
|
summary = firstNonEmpty(m["summary"], summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fields := []struct {
|
||||||
|
text string
|
||||||
|
weight float64
|
||||||
|
}{
|
||||||
|
{title + " " + e.Title, 6}, {e.Ref, 4}, {strings.Join(e.Tags, " ") + " " + strings.Join(e.Synonyms, " "), 5},
|
||||||
|
{strings.Join(e.Capabilities, " ") + " " + e.Package, 3}, {summary + " " + e.Summary, 2}, {e.Body, 0.5},
|
||||||
|
}
|
||||||
|
score := 0.0
|
||||||
|
matched := 0
|
||||||
|
phrase := strings.ToLower(strings.Join(words, " "))
|
||||||
|
for _, w := range words {
|
||||||
|
best := 0.0
|
||||||
|
for _, f := range fields {
|
||||||
|
lt := strings.ToLower(f.text)
|
||||||
|
if strings.Contains(lt, w) {
|
||||||
|
s := f.weight
|
||||||
|
if hasWord(lt, w) {
|
||||||
|
s *= 1.5
|
||||||
|
}
|
||||||
|
if s > best {
|
||||||
|
best = s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if best > 0 {
|
||||||
|
matched++
|
||||||
|
}
|
||||||
|
score += best
|
||||||
|
}
|
||||||
|
if matched == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
score *= float64(matched) / float64(len(words))
|
||||||
|
if strings.Contains(strings.ToLower(title+" "+strings.Join(e.Synonyms, " ")), phrase) && len(words) > 1 {
|
||||||
|
score += 5
|
||||||
|
}
|
||||||
|
switch e.Kind {
|
||||||
|
case ref.Solution, ref.Task:
|
||||||
|
score *= 1.5
|
||||||
|
case "section":
|
||||||
|
score *= 0.6
|
||||||
|
}
|
||||||
|
byKind[e.Kind] = append(byKind[e.Kind], Hit{Ref: e.Ref, Kind: e.Kind, Title: title, Summary: summary, Score: round(score), Status: e.Status})
|
||||||
|
}
|
||||||
|
var out []Group
|
||||||
|
for _, g := range groupOrder {
|
||||||
|
hits := byKind[g.kind]
|
||||||
|
if len(hits) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sort.SliceStable(hits, func(i, j int) bool {
|
||||||
|
if hits[i].Score != hits[j].Score {
|
||||||
|
return hits[i].Score > hits[j].Score
|
||||||
|
}
|
||||||
|
return hits[i].Ref < hits[j].Ref
|
||||||
|
})
|
||||||
|
if len(hits) > limit {
|
||||||
|
hits = hits[:limit]
|
||||||
|
}
|
||||||
|
out = append(out, Group{Kind: g.kind, Title: g.title, Hits: hits})
|
||||||
|
}
|
||||||
|
// groups with the best hit first, but solutions and tasks keep the lead
|
||||||
|
sort.SliceStable(out, func(i, j int) bool {
|
||||||
|
pi, pj := lead(out[i].Kind), lead(out[j].Kind)
|
||||||
|
if pi != pj {
|
||||||
|
return pi > pj
|
||||||
|
}
|
||||||
|
return out[i].Hits[0].Score > out[j].Hits[0].Score
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func lead(kind string) int {
|
||||||
|
if kind == ref.Solution || kind == ref.Task {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasWord(text, w string) bool {
|
||||||
|
for _, t := range Tokens(text) {
|
||||||
|
if t == w {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func round(f float64) float64 { return float64(int(f*100+0.5)) / 100 }
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
// Package ref parses and formats yetano: references (ADR-0004):
|
||||||
|
//
|
||||||
|
// yetano:<kind>/<path>[#<section>][@<version>]
|
||||||
|
//
|
||||||
|
// It only knows the syntax; resolving a reference against a catalog and
|
||||||
|
// rendering it for a client lives in package knowledge.
|
||||||
|
package ref
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Kinds of references.
|
||||||
|
const (
|
||||||
|
Package = "package"
|
||||||
|
Module = "module"
|
||||||
|
Manual = "manual"
|
||||||
|
Microsite = "microsite"
|
||||||
|
Solution = "solution"
|
||||||
|
Task = "task"
|
||||||
|
Profile = "profile"
|
||||||
|
Capability = "capability"
|
||||||
|
Example = "example"
|
||||||
|
BigPicture = "bigpicture"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Kinds lists the valid kinds and how many path segments each takes.
|
||||||
|
var Kinds = map[string]int{
|
||||||
|
Package: 1, Module: 2, Manual: -2, Microsite: 1, Solution: 1, Task: 1,
|
||||||
|
Profile: 2, Capability: 1, Example: 2, BigPicture: 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ref is a parsed reference.
|
||||||
|
type Ref struct {
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Path []string `json:"path"`
|
||||||
|
Section string `json:"section,omitempty"`
|
||||||
|
Version string `json:"version,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrSyntax is returned for malformed references.
|
||||||
|
var ErrSyntax = errors.New("invalid yetano reference")
|
||||||
|
|
||||||
|
var segRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
|
||||||
|
|
||||||
|
// MaxLen bounds a reference (SEC-03).
|
||||||
|
const MaxLen = 512
|
||||||
|
|
||||||
|
// Parse parses s.
|
||||||
|
func Parse(s string) (Ref, error) {
|
||||||
|
if len(s) > MaxLen {
|
||||||
|
return Ref{}, fmt.Errorf("%w: longer than %d bytes", ErrSyntax, MaxLen)
|
||||||
|
}
|
||||||
|
rest, ok := strings.CutPrefix(s, "yetano:")
|
||||||
|
if !ok {
|
||||||
|
return Ref{}, fmt.Errorf("%w %q: must start with yetano:", ErrSyntax, s)
|
||||||
|
}
|
||||||
|
var r Ref
|
||||||
|
if i := strings.LastIndex(rest, "@"); i >= 0 {
|
||||||
|
r.Version, rest = rest[i+1:], rest[:i]
|
||||||
|
if r.Version == "" {
|
||||||
|
return Ref{}, fmt.Errorf("%w %q: empty version", ErrSyntax, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if i := strings.Index(rest, "#"); i >= 0 {
|
||||||
|
r.Section, rest = rest[i+1:], rest[:i]
|
||||||
|
if !segRE.MatchString(r.Section) {
|
||||||
|
return Ref{}, fmt.Errorf("%w %q: bad section", ErrSyntax, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parts := strings.Split(rest, "/")
|
||||||
|
r.Kind = parts[0]
|
||||||
|
r.Path = parts[1:]
|
||||||
|
want, ok := Kinds[r.Kind]
|
||||||
|
if !ok {
|
||||||
|
return Ref{}, fmt.Errorf("%w %q: unknown kind %q", ErrSyntax, s, r.Kind)
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case want > 0 && len(r.Path) != want:
|
||||||
|
return Ref{}, fmt.Errorf("%w %q: %s takes %d path segment(s)", ErrSyntax, s, r.Kind, want)
|
||||||
|
case want < 0 && (len(r.Path) < 2):
|
||||||
|
return Ref{}, fmt.Errorf("%w %q: %s takes <package>/<topic>", ErrSyntax, s, r.Kind)
|
||||||
|
}
|
||||||
|
for _, p := range r.Path {
|
||||||
|
if !segRE.MatchString(p) {
|
||||||
|
return Ref{}, fmt.Errorf("%w %q: bad path segment %q", ErrSyntax, s, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MustParse is Parse for constants in tests.
|
||||||
|
func MustParse(s string) Ref {
|
||||||
|
r, err := Parse(s)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// String formats r.
|
||||||
|
func (r Ref) String() string {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString("yetano:")
|
||||||
|
b.WriteString(r.Kind)
|
||||||
|
for _, p := range r.Path {
|
||||||
|
b.WriteByte('/')
|
||||||
|
b.WriteString(p)
|
||||||
|
}
|
||||||
|
if r.Section != "" {
|
||||||
|
b.WriteByte('#')
|
||||||
|
b.WriteString(r.Section)
|
||||||
|
}
|
||||||
|
if r.Version != "" {
|
||||||
|
b.WriteByte('@')
|
||||||
|
b.WriteString(r.Version)
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Target is the reference without section and version (what Backlinks index).
|
||||||
|
func (r Ref) Target() string {
|
||||||
|
r.Section, r.Version = "", ""
|
||||||
|
return r.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// For builds a reference.
|
||||||
|
func For(kind string, path ...string) string {
|
||||||
|
return Ref{Kind: kind, Path: path}.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
var translit = strings.NewReplacer("ä", "ae", "ö", "oe", "ü", "ue", "ß", "ss", "é", "e", "è", "e", "à", "a", "ç", "c")
|
||||||
|
|
||||||
|
// Slug turns a heading into a section ID: lower case ASCII letters and
|
||||||
|
// digits; every run of anything else becomes one "-", trimmed.
|
||||||
|
func Slug(heading string) string {
|
||||||
|
var b strings.Builder
|
||||||
|
dash := false
|
||||||
|
heading = translit.Replace(strings.ToLower(heading))
|
||||||
|
for _, r := range heading {
|
||||||
|
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
|
||||||
|
b.WriteRune(r)
|
||||||
|
dash = false
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !dash && b.Len() > 0 {
|
||||||
|
b.WriteByte('-')
|
||||||
|
dash = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.TrimRight(b.String(), "-")
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package ref
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestParse(t *testing.T) {
|
||||||
|
for _, s := range []string{
|
||||||
|
"yetano:package/yamase", "yetano:module/yamase/smtpd", "yetano:manual/yamase/mail-domain#dkim",
|
||||||
|
"yetano:manual/yamase-ctl/backup", "yetano:solution/mail-server@1.0.0", "yetano:task/mail.add-domain",
|
||||||
|
"yetano:capability/mail.smtp.inbound", "yetano:bigpicture/story.mail-groupware", "yetano:example/mail-server/personal",
|
||||||
|
} {
|
||||||
|
r, err := Parse(s)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("%s: %v", s, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if r.String() != s {
|
||||||
|
t.Errorf("round trip %s -> %s", s, r.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"package/yamase", "yetano:", "yetano:nope/x", "yetano:package", "yetano:package/a/b",
|
||||||
|
"yetano:module/x", "yetano:package/../x", "yetano:manual/x", "yetano:package/x#", "yetano:package/x@"} {
|
||||||
|
if _, err := Parse(bad); err == nil {
|
||||||
|
t.Errorf("%q accepted", bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSlug(t *testing.T) {
|
||||||
|
for in, want := range map[string]string{
|
||||||
|
"Schritt 2: Schlüssel erzeugen": "schritt-2-schluessel-erzeugen",
|
||||||
|
"4. Trusted relays, SRS bounces and ereject": "4-trusted-relays-srs-bounces-and-ereject",
|
||||||
|
" Hello World! ": "hello-world",
|
||||||
|
} {
|
||||||
|
if got := Slug(in); got != want {
|
||||||
|
t.Errorf("%q: %q, want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
// Package store keeps a user's solution instances, wizard sessions,
|
||||||
|
// presets, favorites and recently used items as plain files in one
|
||||||
|
// directory (the embedding program's data directory, from core/paths):
|
||||||
|
//
|
||||||
|
// <dir>/instances/<name>.yaml SolutionInstance
|
||||||
|
// <dir>/sessions/<name>.yaml WizardSession (drafts)
|
||||||
|
// <dir>/presets/<name>.yaml Preset
|
||||||
|
// <dir>/state.json favorites and recent
|
||||||
|
//
|
||||||
|
// Nothing is created until something is saved (core rule: no silent
|
||||||
|
// filesystem mutation).
|
||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/engine"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Store is a directory.
|
||||||
|
type Store struct{ Dir string }
|
||||||
|
|
||||||
|
// ErrNotFound for unknown names.
|
||||||
|
var ErrNotFound = errors.New("not found")
|
||||||
|
|
||||||
|
var nameRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$`)
|
||||||
|
|
||||||
|
// ValidName reports whether name can be a file name in the store.
|
||||||
|
func ValidName(name string) error {
|
||||||
|
if !nameRE.MatchString(name) || strings.Contains(name, "..") {
|
||||||
|
return fmt.Errorf("name %q: letters, digits, '.', '_' and '-', at most 80", name)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Store) path(kind, name string) (string, error) {
|
||||||
|
if err := ValidName(name); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(s.Dir, kind, name+".yaml"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Store) write(kind, name string, v any) error {
|
||||||
|
p, err := s.path(kind, name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b, err := engine.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tmp := p + ".tmp"
|
||||||
|
if err := os.WriteFile(tmp, b, 0o600); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Rename(tmp, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Store) list(kind string) ([]string, error) {
|
||||||
|
ents, err := os.ReadDir(filepath.Join(s.Dir, kind))
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for _, e := range ents {
|
||||||
|
if n, ok := strings.CutSuffix(e.Name(), ".yaml"); ok && !e.IsDir() {
|
||||||
|
out = append(out, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Store) remove(kind, name string) error {
|
||||||
|
p, err := s.path(kind, name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.Remove(p); errors.Is(err, os.ErrNotExist) {
|
||||||
|
return fmt.Errorf("%w: %s %s", ErrNotFound, strings.TrimSuffix(kind, "s"), name)
|
||||||
|
} else {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveInstance stores an instance (kind SolutionInstance) or a session
|
||||||
|
// (kind WizardSession) under its metadata name.
|
||||||
|
func (s Store) SaveInstance(in *engine.Instance) error {
|
||||||
|
now := time.Now().UTC().Format(time.RFC3339)
|
||||||
|
if in.Metadata.Created == "" {
|
||||||
|
in.Metadata.Created = now
|
||||||
|
}
|
||||||
|
in.Metadata.Updated = now
|
||||||
|
kind := "instances"
|
||||||
|
if in.Kind == "WizardSession" {
|
||||||
|
kind = "sessions"
|
||||||
|
}
|
||||||
|
return s.write(kind, in.Metadata.Name, in)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadInstance reads an instance, else a session, by name.
|
||||||
|
func (s Store) LoadInstance(name string) (*engine.Instance, error) {
|
||||||
|
for _, kind := range []string{"instances", "sessions"} {
|
||||||
|
p, err := s.path(kind, name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
f, err := os.Open(p)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
in, err := engine.ReadInstance(f)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", p, err)
|
||||||
|
}
|
||||||
|
return in, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("%w: instance %s", ErrNotFound, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Instances lists saved instances; Sessions lists drafts.
|
||||||
|
func (s Store) Instances() ([]string, error) { return s.list("instances") }
|
||||||
|
|
||||||
|
// Sessions lists drafts.
|
||||||
|
func (s Store) Sessions() ([]string, error) { return s.list("sessions") }
|
||||||
|
|
||||||
|
// DeleteInstance removes an instance (or session).
|
||||||
|
func (s Store) DeleteInstance(name string) error {
|
||||||
|
if err := s.remove("instances", name); err == nil || !errors.Is(err, ErrNotFound) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.remove("sessions", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteSession removes a draft only.
|
||||||
|
func (s Store) DeleteSession(name string) error { return s.remove("sessions", name) }
|
||||||
|
|
||||||
|
// SavePreset stores a preset.
|
||||||
|
func (s Store) SavePreset(p *engine.Preset) error { return s.write("presets", p.Metadata.Name, p) }
|
||||||
|
|
||||||
|
// LoadPreset reads a preset.
|
||||||
|
func (s Store) LoadPreset(name string) (*engine.Preset, error) {
|
||||||
|
p, err := s.path("presets", name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
f, err := os.Open(p)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, fmt.Errorf("%w: preset %s", ErrNotFound, name)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
return engine.ReadPreset(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Presets lists presets.
|
||||||
|
func (s Store) Presets() ([]string, error) { return s.list("presets") }
|
||||||
|
|
||||||
|
// DeletePreset removes a preset.
|
||||||
|
func (s Store) DeletePreset(name string) error { return s.remove("presets", name) }
|
||||||
|
|
||||||
|
// State holds favorites and recently used references (QA-01).
|
||||||
|
type State struct {
|
||||||
|
Favorites []string `json:"favorites"`
|
||||||
|
Recent []Recent `json:"recent"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recent is one recently used item.
|
||||||
|
type Recent struct {
|
||||||
|
Ref string `json:"ref"`
|
||||||
|
Name string `json:"name,omitempty"` // instance, if any
|
||||||
|
At string `json:"at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MaxRecent bounds the recent list.
|
||||||
|
const MaxRecent = 30
|
||||||
|
|
||||||
|
// LoadState reads state.json (empty when missing).
|
||||||
|
func (s Store) LoadState() (State, error) {
|
||||||
|
var st State
|
||||||
|
b, err := os.ReadFile(filepath.Join(s.Dir, "state.json"))
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return st, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return st, err
|
||||||
|
}
|
||||||
|
err = json.Unmarshal(b, &st)
|
||||||
|
return st, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Store) saveState(st State) error {
|
||||||
|
b, _ := json.MarshalIndent(st, "", " ")
|
||||||
|
if err := os.MkdirAll(s.Dir, 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tmp := filepath.Join(s.Dir, "state.json.tmp")
|
||||||
|
if err := os.WriteFile(tmp, b, 0o600); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Rename(tmp, filepath.Join(s.Dir, "state.json"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Touch records a use of ref (most recent first, no duplicates).
|
||||||
|
func (s Store) Touch(ref, name string) error {
|
||||||
|
st, err := s.LoadState()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out := []Recent{{Ref: ref, Name: name, At: time.Now().UTC().Format(time.RFC3339)}}
|
||||||
|
for _, r := range st.Recent {
|
||||||
|
if r.Ref != ref || r.Name != name {
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(out) > MaxRecent {
|
||||||
|
out = out[:MaxRecent]
|
||||||
|
}
|
||||||
|
st.Recent = out
|
||||||
|
return s.saveState(st)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetFavorite adds or removes a favorite.
|
||||||
|
func (s Store) SetFavorite(ref string, on bool) error {
|
||||||
|
st, err := s.LoadState()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for _, f := range st.Favorites {
|
||||||
|
if f != ref {
|
||||||
|
out = append(out, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if on {
|
||||||
|
out = append(out, ref)
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
st.Favorites = out
|
||||||
|
return s.saveState(st)
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/solutions/engine"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestStore(t *testing.T) {
|
||||||
|
s := Store{Dir: t.TempDir()}
|
||||||
|
if names, err := s.Instances(); err != nil || len(names) != 0 {
|
||||||
|
t.Fatal("empty store")
|
||||||
|
}
|
||||||
|
in := &engine.Instance{APIVersion: "yetano.dev/v1", Kind: "SolutionInstance", Metadata: engine.InstanceMeta{Name: "a"},
|
||||||
|
Spec: engine.InstanceSpec{Solution: engine.SolutionPin{ID: "x"}, Parameters: map[string]any{"k": "v"}}}
|
||||||
|
if err := s.SaveInstance(in); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := s.LoadInstance("a")
|
||||||
|
if err != nil || got.Spec.Parameters["k"] != "v" || got.Metadata.Created == "" {
|
||||||
|
t.Fatalf("%v %+v", err, got)
|
||||||
|
}
|
||||||
|
if _, err := s.LoadInstance("../a"); err == nil {
|
||||||
|
t.Error("path traversal accepted")
|
||||||
|
}
|
||||||
|
if _, err := s.LoadInstance("nope"); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
if err := s.Touch("yetano:solution/x", "a"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s.Touch("yetano:solution/y", "")
|
||||||
|
s.Touch("yetano:solution/x", "a")
|
||||||
|
st, _ := s.LoadState()
|
||||||
|
if len(st.Recent) != 2 || st.Recent[0].Ref != "yetano:solution/x" {
|
||||||
|
t.Errorf("recent: %+v", st.Recent)
|
||||||
|
}
|
||||||
|
if err := s.DeleteInstance("a"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user