Files
skillshare/internal/hooks/render.go
T
Willie f6e7265414 feat(hooks): read hook code and scripts from files next to the config (#586)
* feat(hooks): read hook code and scripts from files next to the config

Code Agent extensions and command scripts lived as strings in
config.yaml, so a longer Pi extension or shell script was edited inside
a YAML block scalar with no editor support, and nothing type-checked or
linted it. A breaking change in an Agent's extension API went unnoticed
because the generated file is not part of any tsconfig.

A binding now takes `codeFile: path` instead of `code`, and a `files`
value may be `{from: path}` instead of the contents. Paths resolve
against the folder of the config that holds the entry and are read
every time the config is read, so the regular typecheck or shellcheck
can cover the real source. The revision and drift checks use the
resolved contents, so a file edited after a preview fails the apply as
stale.

Saving keeps the references: enable/disable, `hooks edit` and the
dashboard write `codeFile` and `{from}` back instead of inlining the
contents. JSON carries the contents plus `codeFile`/`filesFrom`, and an
entry echoed back with both must match the file, so an edit is refused
rather than silently dropped. Paths must stay inside the config folder
without symlinks, so a cloned project cannot pull in files from
elsewhere. References are taken from the YAML tree before one strict
decode, which keeps unknown-field checks and anchors shared across
bindings working.

Closes #585

* fix(hooks): refuse an emptied file sent with its reference

An empty files value stood for "contents not sent", so a file cleared in
the dashboard's Git YAML editor while its filesFrom reference stayed was
treated as unsent: the file was read again from disk and the save
reported success with the user's edit discarded.

A value read from {from: path} now keeps a dedicated mark until it is
resolved, so an empty value is compared with the file like any other
contents and refused when they differ. Code keeps using empty as unsent,
since a code binding can never be empty.

* fix(hooks): render referenced files as they are on disk

RenderNative rendered the contents the caller sent. The dashboard sends
the entry it loaded, so after a referenced file changed, View
configuration still showed the old contents while describing them as
what sync would write.

Render now drops sent contents for codeFile and {from} references and
reads every reference again, like preview and save. Draft, render and
config decoding are the only paths that take an entry, and all three now
resolve references.

* fix(hooks): accept file references in JSON entries and anchored values

Two inputs that config.yaml accepts failed to load elsewhere.

A `{from}` value carrying its own YAML anchor, aliased from another
binding, lost its anchor because the value node was replaced instead of
rewritten, so the alias no longer resolved. The node is now rewritten in
place with its anchor kept.

An entry JSON file (`hooks add|edit --file x.json`) could not write a
files value as `{"from": path}`, because JSON decoded straight into
string contents. Binding now decodes JSON files values as contents or a
reference, strictly, like YAML, so both entry formats and the Web API
take the same shapes.
2026-10-19 22:48:00 +08:00

123 lines
4.0 KiB
Go

package hooks
import (
"fmt"
"maps"
"path/filepath"
"slices"
"strings"
)
// RenderedFile is one native output of a single hook: its contribution to a shared
// hooks file in that file's native wrapper, or a whole file it owns.
type RenderedFile struct {
Target string `json:"target"`
Path string `json:"path,omitempty"`
Content string `json:"content"`
Error string `json:"error,omitempty"`
}
// RenderNative shows what one hook writes, per Agent, without the rest of any existing
// file. It reads no ownership state or native file contents, writes nothing and runs
// nothing. A disabled entry renders its stored bindings, which sync would not write.
// A binding whose path cannot be resolved or safely written reports its own error.
func (s *Service) RenderNative(m Mutation) ([]RenderedFile, error) {
if m.Remove || m.Replace {
return nil, fmt.Errorf("render takes a hook definition, not a remove or replace")
}
if m.Name == "" || m.Entry == nil {
return nil, fmt.Errorf("hook name and entry are required")
}
root := ""
scope := s
if m.Project != "" {
if s.ProjectRoot != "" {
return nil, fmt.Errorf("hooks.projects belongs in the global config")
}
var err error
if root, err = projectRoot(m.Project); err != nil {
return nil, err
}
scope = s.scoped(root)
}
entry := *m.Entry
if err := entry.normalize(); err != nil {
return nil, err
}
// The dashboard may send contents cached before a referenced file changed; show
// what sync would write by reading every reference again.
for target, b := range entry.Bindings {
if b.CodeFile != "" {
b.Code = ""
}
if len(b.FilesFrom) > 0 {
b.Files = maps.Clone(b.Files)
for name := range b.FilesFrom {
if _, kept := b.Files[name]; kept {
b.Files[name] = fileRefMark
}
}
}
entry.Bindings[target] = b
}
if err := entry.resolveRefs(filepath.Dir(s.ConfigPath)); err != nil {
return nil, fmt.Errorf("hook %s: %w", m.Name, err)
}
if err := s.validateEntry(m.Name, entry, root); err != nil {
return nil, err
}
entry.Enabled = nil
out := []RenderedFile{}
for _, target := range sortedKeys(entry.Bindings) {
one := Entry{Bindings: map[string]Binding{target: entry.Bindings[target]}}
d := &desired{elements: map[string][]wantElement{}, targets: map[string]string{}, roots: map[string]string{}, files: map[string]wantFile{}}
if err := scope.renderScope(d, root, map[string]Entry{m.Name: one}); err != nil {
out = append(out, RenderedFile{Target: target, Error: err.Error()})
continue
}
// A skipped account home writes nothing; say why instead of rendering no file.
if len(d.warnings) > 0 {
out = append(out, RenderedFile{Target: target, Error: strings.Join(d.warnings, "; ")})
continue
}
base, err := scope.base(target, root)
if err != nil {
out = append(out, RenderedFile{Target: target, Error: err.Error()})
continue
}
var files []RenderedFile
for _, w := range d.git {
files = append(files, RenderedFile{Target: target, Path: w.destination.hooksFile, Content: string(w.content)})
}
if len(d.notes) > 0 {
out = append(out, RenderedFile{Target: target, Error: d.notes[0].Message})
continue
}
for path, want := range d.elements {
f := RenderedFile{Target: target, Path: path}
ops := make([]elementOp, len(want))
for i, w := range want {
ops[i] = elementOp{Event: w.event, Index: -1, Value: w.value}
}
doc, _ := parseNative(scope.agentOf(target), nil)
if data, _, err := doc.edit(ops, nil, false); err != nil {
f.Error = err.Error()
} else {
f.Content = string(data)
}
files = append(files, f)
}
for path, want := range d.files {
files = append(files, RenderedFile{Target: target, Path: path, Content: string(want.content)})
}
for i := range files {
if err := checkPath(base, files[i].Path); err != nil && files[i].Error == "" {
files[i].Error = err.Error()
}
}
slices.SortFunc(files, func(a, b RenderedFile) int { return strings.Compare(a.Path, b.Path) })
out = append(out, files...)
}
return out, nil
}