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 }