| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333 |
- package main
- import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "html/template"
- "os"
- "path/filepath"
- "regexp"
- "sort"
- "strconv"
- "strings"
- )
- // ---------- api.json ----------
- // API mirrors src/web/Terminal/docs/api.json.
- type API struct {
- Version string `json:"_version"`
- Sections []*Section `json:"sections"`
- }
- type Section struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Desc string `json:"desc"`
- Load string `json:"load"`
- Functions []*Function `json:"functions"`
- }
- type Function struct {
- Name string `json:"name"`
- Sig string `json:"sig"`
- Desc string `json:"desc"`
- Ret string `json:"ret"`
- Example string `json:"example"`
- names []string // Name split into the identifiers it covers
- }
- // Names lists every identifier an entry documents. "http.put / http.patch"
- // covers both, and "notification.PRIORITY_LOW / PRIORITY_HIGH" lends its
- // prefix to the bare names after it.
- func (f *Function) Names() []string {
- if f.names == nil {
- f.names = expandNames(f.Name)
- }
- return f.names
- }
- func expandNames(name string) []string {
- var out []string
- prefix := ""
- for _, part := range strings.Split(name, "/") {
- p := strings.TrimSpace(part)
- p = strings.TrimSuffix(p, "()")
- if p == "" {
- continue
- }
- if i := strings.LastIndex(p, "."); i >= 0 {
- prefix = p[:i+1]
- } else if prefix != "" {
- p = prefix + p
- }
- out = append(out, p)
- }
- return out
- }
- func loadAPI(path string) (*API, error) {
- raw, err := os.ReadFile(path)
- if err != nil {
- return nil, err
- }
- api := &API{}
- if err := json.Unmarshal(raw, api); err != nil {
- return nil, fmt.Errorf("%s: %w", path, err)
- }
- if len(api.Sections) == 0 {
- return nil, fmt.Errorf("%s has no sections", path)
- }
- seen := map[string]bool{}
- for _, s := range api.Sections {
- if s.ID == "" || seen[s.ID] {
- return nil, fmt.Errorf("%s: section id %q is empty or repeated", path, s.ID)
- }
- seen[s.ID] = true
- }
- return api, nil
- }
- var agiVersionRe = regexp.MustCompile(`AgiVersion\s+string\s*=\s*"([^"]+)"`)
- // readAgiVersion takes the runtime version from the AgiVersion constant, so
- // the docs always name the version they were built from.
- func readAgiVersion(path string) (string, error) {
- raw, err := os.ReadFile(path)
- if err != nil {
- return "", err
- }
- m := agiVersionRe.FindSubmatch(raw)
- if m == nil {
- return "", fmt.Errorf("%s: AgiVersion constant not found", path)
- }
- return string(m[1]), nil
- }
- // ---------- icons ----------
- // loadIcons reads every SVG of the given folders; an earlier folder wins, so
- // this tool's own icons/ can add to (or replace) the website's set.
- func loadIcons(dirs []string) (map[string]template.HTML, error) {
- icons := map[string]template.HTML{}
- for _, dir := range dirs {
- files, err := filepath.Glob(filepath.Join(dir, "*.svg"))
- if err != nil {
- return nil, err
- }
- for _, f := range files {
- name := strings.TrimSuffix(filepath.Base(f), ".svg")
- if _, ok := icons[name]; ok {
- continue
- }
- raw, err := os.ReadFile(f)
- if err != nil {
- return nil, err
- }
- icons[name] = template.HTML(strings.TrimSpace(string(raw)))
- }
- }
- if _, ok := icons["logo"]; !ok {
- return nil, errors.New("no logo.svg found in the icon folders")
- }
- return icons, nil
- }
- // ---------- front matter ----------
- // splitFrontMatter separates a "---" delimited block of "key: value" lines
- // from the Markdown after it.
- func splitFrontMatter(src string) (map[string]string, string, error) {
- src = strings.ReplaceAll(src, "\r\n", "\n")
- fm := map[string]string{}
- if !strings.HasPrefix(src, "---\n") {
- return fm, src, nil
- }
- end := strings.Index(src[4:], "\n---\n")
- if end < 0 {
- return nil, "", errors.New("front matter is not closed with ---")
- }
- for _, line := range strings.Split(src[4:4+end], "\n") {
- if strings.TrimSpace(line) == "" {
- continue
- }
- k, v, ok := strings.Cut(line, ":")
- if !ok {
- return nil, "", fmt.Errorf("front matter line %q has no colon", line)
- }
- fm[strings.TrimSpace(k)] = strings.TrimSpace(v)
- }
- return fm, src[4+end+5:], nil
- }
- func atoiDefault(s string, def int) int {
- if n, err := strconv.Atoi(s); err == nil {
- return n
- }
- return def
- }
- // ---------- guides ----------
- type Guide struct {
- Slug string
- Title string
- Group string
- Summary string
- Order int
- Body string
- }
- // groupOrder is the sidebar order of guide groups; unknown groups follow.
- var groupOrder = []string{"Getting started", "Guides"}
- func loadGuides(dir string) ([]*Guide, error) {
- files, err := filepath.Glob(filepath.Join(dir, "*.md"))
- if err != nil {
- return nil, err
- }
- var out []*Guide
- for _, f := range files {
- raw, err := os.ReadFile(f)
- if err != nil {
- return nil, err
- }
- fm, body, err := splitFrontMatter(string(raw))
- if err != nil {
- return nil, fmt.Errorf("%s: %w", f, err)
- }
- g := &Guide{
- Slug: strings.TrimSuffix(filepath.Base(f), ".md"),
- Title: fm["title"],
- Group: fm["group"],
- Summary: fm["summary"],
- Order: atoiDefault(fm["order"], 1000),
- Body: body,
- }
- if g.Title == "" {
- return nil, fmt.Errorf("%s: front matter needs a title", f)
- }
- if g.Slug == "index" || g.Slug == "playground" {
- return nil, fmt.Errorf("%s: %q is reserved for a generated page", f, g.Slug)
- }
- if g.Group == "" {
- g.Group = "Guides"
- }
- out = append(out, g)
- }
- sort.SliceStable(out, func(i, j int) bool {
- gi, gj := indexOf(groupOrder, out[i].Group), indexOf(groupOrder, out[j].Group)
- if gi != gj {
- return gi < gj
- }
- if out[i].Order != out[j].Order {
- return out[i].Order < out[j].Order
- }
- return out[i].Slug < out[j].Slug
- })
- return out, nil
- }
- func indexOf(list []string, s string) int {
- for i, v := range list {
- if v == s {
- return i
- }
- }
- return len(list)
- }
- // ---------- samples ----------
- // Sample is a ready-made playground script from samples/*.agi. The file
- // starts with a /*--- ... ---*/ block of "key: value" lines.
- type Sample struct {
- ID string `json:"id"`
- Title string `json:"title"`
- Group string `json:"group"`
- Summary string `json:"summary"`
- Path string `json:"path"` // vpath the script is saved at, web:/... by default
- Setup json.RawMessage `json:"setup,omitempty"` // request, mocks and files the sample needs
- Code string `json:"code"`
- }
- func loadSamples(dir string) ([]*Sample, error) {
- files, err := filepath.Glob(filepath.Join(dir, "*.agi"))
- if err != nil {
- return nil, err
- }
- sort.Strings(files)
- var out []*Sample
- for _, f := range files {
- raw, err := os.ReadFile(f)
- if err != nil {
- return nil, err
- }
- src := strings.ReplaceAll(string(raw), "\r\n", "\n")
- if !strings.HasPrefix(src, "/*---\n") {
- return nil, fmt.Errorf("%s: must start with a /*--- header", f)
- }
- end := strings.Index(src, "\n---*/\n")
- if end < 0 {
- return nil, fmt.Errorf("%s: header is not closed with ---*/", f)
- }
- fm, _, err := splitFrontMatter("---\n" + src[6:end] + "\n---\n")
- if err != nil {
- return nil, fmt.Errorf("%s: %w", f, err)
- }
- id := strings.TrimSuffix(filepath.Base(f), ".agi")
- // A leading "NN-" orders the files and is not part of the id.
- if i := strings.Index(id, "-"); i > 0 {
- if _, err := strconv.Atoi(id[:i]); err == nil {
- id = id[i+1:]
- }
- }
- s := &Sample{
- ID: id,
- Title: fm["title"],
- Group: fm["group"],
- Summary: fm["summary"],
- Path: fm["path"],
- Code: strings.TrimLeft(src[end+7:], "\n"),
- }
- if s.Title == "" {
- return nil, fmt.Errorf("%s: header needs a title", f)
- }
- if s.Path == "" {
- s.Path = "Playground/" + id + ".agi"
- }
- if !strings.Contains(s.Path, ":/") {
- s.Path = "web:/" + strings.TrimPrefix(s.Path, "/")
- }
- // setup is one line of JSON: {"request":{...},"mocks":{...},"files":[{"path":"user:/a.txt","text":"..."}]}
- if p := fm["setup"]; p != "" {
- if !json.Valid([]byte(p)) {
- return nil, fmt.Errorf("%s: setup is not valid JSON", f)
- }
- s.Setup = json.RawMessage(p)
- }
- out = append(out, s)
- }
- return out, nil
- }
- // writeJSON writes v compactly; the playground reads these at run time.
- func writeJSON(path string, v any) error {
- var buf bytes.Buffer
- enc := json.NewEncoder(&buf)
- enc.SetEscapeHTML(false)
- if err := enc.Encode(v); err != nil {
- return err
- }
- return writeFile(path, buf.Bytes())
- }
- func writeFile(path string, data []byte) error {
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- return err
- }
- return os.WriteFile(path, data, 0o644)
- }
|