package api
import (
"sort"
"strings"
"craftdesign.group/quarry/internal/index"
)
// armedStackOf reads the stack an armed rung lands with: the open rungs
// from the base up to l, bottom first, as landStack's walk takes them,
// and the branch the base lands on (where its target has already
// landed, that landing's target), which is where the stack's required
// checks are read. ok is false for a landing with no rung below it: it
// lands on its own target, and that target's checks are its own.
func (d Deps) armedStackOf(repoName string, repo *Repo, l index.LandingSummary) (names []string, final string, ok bool) {
all, err := repo.Index.Landings("", 0)
if err != nil {
return nil, "", false
}
d.numberAll(repoName, repo, all)
index.AttachStrata(all)
var me *index.LandingSummary
for i := range all {
if all[i].ID == l.ID {
me = &all[i]
}
}
if me == nil || me.Stack == "" || me.Position < 2 {
return nil, "", false
}
var chain []index.LandingSummary
for _, a := range all {
if a.Stack == me.Stack && a.State == "open" && a.Position >= 1 && a.Position <= me.Position {
chain = append(chain, a)
}
}
sort.Slice(chain, func(i, j int) bool { return chain[i].Position < chain[j].Position })
final = chain[0].Target
if to := landedBaseTarget(repo, chain[0]); to != "" {
final = to
}
for _, a := range chain {
names = append(names, bangName(a.Number, a.Branch))
}
return names, final, true
}
// armSay is what landing.auto answers for an arm: the rung's own target
// for a landing on its own, the stack's final target for a rung that
// lands with the rungs below it.
func (d Deps) armSay(repoName string, repo *Repo, l index.LandingSummary) (say string, stack []string, final string) {
required := func(branch string) bool {
return d.Checks != nil && len(d.Checks.RequiredChecks(repoName, branch)) > 0
}
names, final, ok := d.armedStackOf(repoName, repo, l)
if !ok {
if required(l.Target) {
return "armed: lands when checks are green", nil, ""
}
return "armed: lands at the next sweep; the target has no required checks", nil, ""
}
path := strings.Join(append(append([]string{}, names...), final), " → ")
if required(final) {
return "armed: lands with its stack (" + path + ") when checks are green", names, final
}
return "armed: lands with its stack (" + path + ") at the next sweep; " + final + " has no required checks", names, final
}