manual: the shared "<program> manual" command (ADR-0012)

FromFS turns embedded README.md + docs/**/*.md into topics (README is
"readme", titles from the first heading); Run serves "manual",
"manual <topic>" and "manual --json [topic]" -- the JSON shape yet
reads for an installed program's manual (yet manual --package, TUI,
yet-gui), same as "yet manual --json".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Opus 5.5 committed 2026-10-07 16:22:03 +02:00
1 parent e8bf23a064
commit a6360f5f43
3 files changed
+294

No files matched your search

+24
View File
@@ -13,6 +13,7 @@ configuration resolution**: `core/paths` and `core/config`.
yetano.dev/yetano/core yetano.dev/yetano/core
yetano.dev/yetano/core/paths yetano.dev/yetano/core/paths
yetano.dev/yetano/core/config yetano.dev/yetano/core/config
yetano.dev/yetano/core/manual
``` ```
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
@@ -244,6 +245,29 @@ ecosystem-wide, shared settings (`repositories.yaml`, `trust.yaml`,
layered into, any one application's own configuration. An application layered into, any one application's own configuration. An application
opts in explicitly with `config.WithYetanoDefaults(true)`. opts in explicitly with `config.WithYetanoDefaults(true)`.
## core/manual: the "<program> manual" command
Every Yetano program serves its own documentation (ADR-0012), embedded
in the binary. `core/manual` is that command in one shared shape:
```go
// at the module root (go:embed can't reach parent directories):
//go:embed README.md docs
var docsFS embed.FS
var Manual = manual.MustFromFS("yasl", docsFS)
// in the CLI dispatch:
case "manual", "doc":
if err := yasl.Manual.Run(args[1:], os.Stdout); err != nil { ... exit non-zero ... }
```
`FromFS` makes `README.md` the topic `readme` and every `docs/**/*.md`
a topic (slug = path below `docs/` without `.md`, title = first `#`
heading). `Run` serves `manual`, `manual <topic>` and `manual --json
[topic]`; the JSON form (`[{slug,title,path}]` / `{slug,title,path,
markdown}`) is what yet reads to show an installed program's manual
(`yet manual --package`, its TUI and yet-gui).
## Security ## Security
- Environment expansion is variable substitution only -- never shell - Environment expansion is variable substitution only -- never shell
+183
View File
@@ -0,0 +1,183 @@
// Package manual gives a Yetano program its embedded, self-served manual:
// the "<program> manual" command of ADR-0012, in one shared shape.
//
// A program embeds its documentation -- usually README.md and docs/*.md,
// with a //go:embed in a Go file at the module root, since go:embed cannot
// reach parent directories -- and hands it to FromFS; Run then serves
//
// <program> manual topic list
// <program> manual <topic> one topic's Markdown
// <program> manual --json [{"slug", "title", "path"}, ...]
// <program> manual --json <topic> {"slug", "title", "path", "markdown"}
//
// The --json form is what yet reads to show an installed program's manual
// in "yet manual --package", its TUI and yet-gui (yet's own "yet manual
// --json" uses the same shape). path is the page's source path in the
// repository, so relative links between pages resolve against it.
package manual
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"path"
"regexp"
"sort"
"strings"
)
// Topic is one manual page.
type Topic struct {
Slug string `json:"slug"`
Title string `json:"title"`
Path string `json:"path"`
}
// Manual is a program's embedded manual.
type Manual struct {
// Name is the program name, used in the plain-text listing.
Name string
FS fs.FS
Topics []Topic
}
var heading = regexp.MustCompile(`(?m)^#\s+(.+?)\s*#*\s*$`)
// FromFS builds a Manual from fsys: README.md first (slug "readme"), then
// every *.md under docs/ (recursively, by path; slug: the path below docs/
// without ".md", e.g. "configuration" or "adr/0001-x"). A page's title is
// its first "# " heading, else its slug. Other files are ignored.
func FromFS(name string, fsys fs.FS) (Manual, error) {
m := Manual{Name: name, FS: fsys}
if data, err := fs.ReadFile(fsys, "README.md"); err == nil {
m.Topics = append(m.Topics, Topic{Slug: "readme", Title: titleOf(data, "Overview"), Path: "README.md"})
}
var docs []Topic
err := fs.WalkDir(fsys, "docs", func(p string, d fs.DirEntry, err error) error {
if err != nil {
if errors.Is(err, fs.ErrNotExist) && p == "docs" {
return fs.SkipDir
}
return err
}
if d.IsDir() || !strings.EqualFold(path.Ext(p), ".md") {
return nil
}
data, err := fs.ReadFile(fsys, p)
if err != nil {
return err
}
slug := strings.TrimSuffix(strings.TrimPrefix(p, "docs/"), path.Ext(p))
docs = append(docs, Topic{Slug: slug, Title: titleOf(data, slug), Path: p})
return nil
})
if err != nil {
return Manual{}, err
}
sort.Slice(docs, func(i, j int) bool { return docs[i].Path < docs[j].Path })
m.Topics = append(m.Topics, docs...)
if len(m.Topics) == 0 {
return Manual{}, errors.New("manual: no README.md and no docs/*.md in the embedded files")
}
return m, nil
}
// MustFromFS is FromFS for a package-level variable; it panics on error
// (a missing embed is a build mistake).
func MustFromFS(name string, fsys fs.FS) Manual {
m, err := FromFS(name, fsys)
if err != nil {
panic(err)
}
return m
}
func titleOf(data []byte, fallback string) string {
if m := heading.FindSubmatch(data); m != nil {
return string(m[1])
}
return fallback
}
// Lookup returns the topic with slug.
func (m Manual) Lookup(slug string) (Topic, bool) {
for _, t := range m.Topics {
if t.Slug == slug {
return t, true
}
}
return Topic{}, false
}
// Markdown returns a topic's source.
func (m Manual) Markdown(t Topic) (string, error) {
data, err := fs.ReadFile(m.FS, t.Path)
return string(data), err
}
// ErrUsage is returned by Run for bad arguments; the caller should print
// it and exit with its usage exit code.
var ErrUsage = errors.New("usage: manual [--json] [topic]")
// Run serves "<program> manual [--json] [topic]" -- args are the
// arguments after "manual" -- writing to w. An unknown topic is an error
// (the caller exits non-zero).
func (m Manual) Run(args []string, w io.Writer) error {
asJSON := false
var rest []string
for _, a := range args {
switch a {
case "--json", "-json":
asJSON = true
case "-h", "--help", "-help":
fmt.Fprintf(w, "usage: %s manual [--json] [topic]\n", m.Name)
return nil
default:
if strings.HasPrefix(a, "-") {
return fmt.Errorf("%w (unknown flag %q)", ErrUsage, a)
}
rest = append(rest, a)
}
}
if len(rest) > 1 {
return ErrUsage
}
if len(rest) == 0 {
if asJSON {
return writeJSON(w, m.Topics)
}
fmt.Fprintf(w, "%s manual topics:\n", m.Name)
for _, t := range m.Topics {
fmt.Fprintf(w, " %-28s %s\n", t.Slug, t.Title)
}
fmt.Fprintf(w, "\nrun \"%s manual <topic>\" to read one\n", m.Name)
return nil
}
t, ok := m.Lookup(rest[0])
if !ok {
return fmt.Errorf("unknown manual topic %q (run \"%s manual\" for the list)", rest[0], m.Name)
}
md, err := m.Markdown(t)
if err != nil {
return err
}
if asJSON {
return writeJSON(w, struct {
Topic
Markdown string `json:"markdown"`
}{t, md})
}
_, err = io.WriteString(w, md)
if err == nil && !strings.HasSuffix(md, "\n") {
_, err = io.WriteString(w, "\n")
}
return err
}
func writeJSON(w io.Writer, v any) error {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(v)
}
+87
View File
@@ -0,0 +1,87 @@
package manual
import (
"encoding/json"
"errors"
"strings"
"testing"
"testing/fstest"
)
func testFS() fstest.MapFS {
return fstest.MapFS{
"README.md": {Data: []byte("# Tool\n\nIntro.\n")},
"docs/configuration.md": {Data: []byte("# Configuration\n\nKeys.")},
"docs/adr/0001-decision.md": {Data: []byte("no heading here")},
"docs/image.png": {Data: []byte("x")},
}
}
func TestFromFSAndJSON(t *testing.T) {
m, err := FromFS("tool", testFS())
if err != nil {
t.Fatal(err)
}
want := []Topic{
{Slug: "readme", Title: "Tool", Path: "README.md"},
{Slug: "adr/0001-decision", Title: "adr/0001-decision", Path: "docs/adr/0001-decision.md"},
{Slug: "configuration", Title: "Configuration", Path: "docs/configuration.md"},
}
if len(m.Topics) != len(want) {
t.Fatalf("topics = %+v", m.Topics)
}
for i := range want {
if m.Topics[i] != want[i] {
t.Errorf("topic %d = %+v, want %+v", i, m.Topics[i], want[i])
}
}
var b strings.Builder
if err := m.Run([]string{"--json"}, &b); err != nil {
t.Fatal(err)
}
var list []Topic
if err := json.Unmarshal([]byte(b.String()), &list); err != nil || len(list) != 3 {
t.Fatalf("list json: %v %s", err, b.String())
}
b.Reset()
if err := m.Run([]string{"--json", "configuration"}, &b); err != nil {
t.Fatal(err)
}
var page struct {
Topic
Markdown string `json:"markdown"`
}
if err := json.Unmarshal([]byte(b.String()), &page); err != nil || page.Markdown != "# Configuration\n\nKeys." || page.Path != "docs/configuration.md" {
t.Fatalf("page json: %v %+v", err, page)
}
b.Reset()
if err := m.Run([]string{"readme"}, &b); err != nil || b.String() != "# Tool\n\nIntro.\n" {
t.Fatalf("plain page: %v %q", err, b.String())
}
b.Reset()
if err := m.Run(nil, &b); err != nil || !strings.Contains(b.String(), "configuration") {
t.Fatalf("plain list: %v %q", err, b.String())
}
}
func TestRunErrors(t *testing.T) {
m := MustFromFS("tool", testFS())
var b strings.Builder
if err := m.Run([]string{"nope"}, &b); err == nil {
t.Error("unknown topic should fail")
}
if err := m.Run([]string{"--bogus"}, &b); !errors.Is(err, ErrUsage) {
t.Errorf("unknown flag: %v", err)
}
if err := m.Run([]string{"a", "b"}, &b); !errors.Is(err, ErrUsage) {
t.Errorf("two topics: %v", err)
}
if _, err := FromFS("empty", fstestEmpty()); err == nil {
t.Error("an empty manual should be an error")
}
}
func fstestEmpty() fstest.MapFS { return fstest.MapFS{"x.txt": {Data: []byte("x")}} }