government / src / policy / layers.go

@ a94ce18dbaa3c27d01f1491d51ec12c5767daf6d | history


package policy

import (
	"fmt"

	"nmyk.io/government/ast"
)

// Layers turns the graph into the decoder's input: every node below the
// root, decoded from its OID, with its depth and edges. The validator's
// copies stay in as nodes of their own; ast.Unlayer recognizes and skips
// them.
func (g *Graph) Layers() (ast.Layers, error) {
	n := g.Depth()
	l := ast.Layers{Nodes: make([][]*ast.Node, n), Edges: make([][]ast.Edge, n)}
	decoded := map[*Node]*ast.Node{}
	for d := 1; d <= n; d++ {
		for _, gn := range g.Levels[d] {
			ns, id, text, err := ast.DecodeOID(gn.Policy)
			if err != nil {
				return ast.Layers{}, fmt.Errorf("depth %d: %w", d, err)
			}
			an := &ast.Node{ID: id, NS: ns, Text: text, Note: gn.Note}
			decoded[gn] = an
			l.Nodes[d-1] = append(l.Nodes[d-1], an)
		}
	}
	for d := 1; d < n; d++ {
		for _, parent := range g.Levels[d] {
			for _, child := range parent.Children {
				l.Edges[d-1] = append(l.Edges[d-1], ast.Edge{Parent: decoded[parent], Child: decoded[child]})
			}
		}
	}
	return l, nil
}