content.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "html/template"
  8. "os"
  9. "path/filepath"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. )
  15. // ---------- api.json ----------
  16. // API mirrors src/web/Terminal/docs/api.json.
  17. type API struct {
  18. Version string `json:"_version"`
  19. Sections []*Section `json:"sections"`
  20. }
  21. type Section struct {
  22. ID string `json:"id"`
  23. Name string `json:"name"`
  24. Desc string `json:"desc"`
  25. Load string `json:"load"`
  26. Functions []*Function `json:"functions"`
  27. }
  28. type Function struct {
  29. Name string `json:"name"`
  30. Sig string `json:"sig"`
  31. Desc string `json:"desc"`
  32. Ret string `json:"ret"`
  33. Example string `json:"example"`
  34. names []string // Name split into the identifiers it covers
  35. }
  36. // Names lists every identifier an entry documents. "http.put / http.patch"
  37. // covers both, and "notification.PRIORITY_LOW / PRIORITY_HIGH" lends its
  38. // prefix to the bare names after it.
  39. func (f *Function) Names() []string {
  40. if f.names == nil {
  41. f.names = expandNames(f.Name)
  42. }
  43. return f.names
  44. }
  45. func expandNames(name string) []string {
  46. var out []string
  47. prefix := ""
  48. for _, part := range strings.Split(name, "/") {
  49. p := strings.TrimSpace(part)
  50. p = strings.TrimSuffix(p, "()")
  51. if p == "" {
  52. continue
  53. }
  54. if i := strings.LastIndex(p, "."); i >= 0 {
  55. prefix = p[:i+1]
  56. } else if prefix != "" {
  57. p = prefix + p
  58. }
  59. out = append(out, p)
  60. }
  61. return out
  62. }
  63. func loadAPI(path string) (*API, error) {
  64. raw, err := os.ReadFile(path)
  65. if err != nil {
  66. return nil, err
  67. }
  68. api := &API{}
  69. if err := json.Unmarshal(raw, api); err != nil {
  70. return nil, fmt.Errorf("%s: %w", path, err)
  71. }
  72. if len(api.Sections) == 0 {
  73. return nil, fmt.Errorf("%s has no sections", path)
  74. }
  75. seen := map[string]bool{}
  76. for _, s := range api.Sections {
  77. if s.ID == "" || seen[s.ID] {
  78. return nil, fmt.Errorf("%s: section id %q is empty or repeated", path, s.ID)
  79. }
  80. seen[s.ID] = true
  81. }
  82. return api, nil
  83. }
  84. var agiVersionRe = regexp.MustCompile(`AgiVersion\s+string\s*=\s*"([^"]+)"`)
  85. // readAgiVersion takes the runtime version from the AgiVersion constant, so
  86. // the docs always name the version they were built from.
  87. func readAgiVersion(path string) (string, error) {
  88. raw, err := os.ReadFile(path)
  89. if err != nil {
  90. return "", err
  91. }
  92. m := agiVersionRe.FindSubmatch(raw)
  93. if m == nil {
  94. return "", fmt.Errorf("%s: AgiVersion constant not found", path)
  95. }
  96. return string(m[1]), nil
  97. }
  98. // ---------- icons ----------
  99. // loadIcons reads every SVG of the given folders; an earlier folder wins, so
  100. // this tool's own icons/ can add to (or replace) the website's set.
  101. func loadIcons(dirs []string) (map[string]template.HTML, error) {
  102. icons := map[string]template.HTML{}
  103. for _, dir := range dirs {
  104. files, err := filepath.Glob(filepath.Join(dir, "*.svg"))
  105. if err != nil {
  106. return nil, err
  107. }
  108. for _, f := range files {
  109. name := strings.TrimSuffix(filepath.Base(f), ".svg")
  110. if _, ok := icons[name]; ok {
  111. continue
  112. }
  113. raw, err := os.ReadFile(f)
  114. if err != nil {
  115. return nil, err
  116. }
  117. icons[name] = template.HTML(strings.TrimSpace(string(raw)))
  118. }
  119. }
  120. if _, ok := icons["logo"]; !ok {
  121. return nil, errors.New("no logo.svg found in the icon folders")
  122. }
  123. return icons, nil
  124. }
  125. // ---------- front matter ----------
  126. // splitFrontMatter separates a "---" delimited block of "key: value" lines
  127. // from the Markdown after it.
  128. func splitFrontMatter(src string) (map[string]string, string, error) {
  129. src = strings.ReplaceAll(src, "\r\n", "\n")
  130. fm := map[string]string{}
  131. if !strings.HasPrefix(src, "---\n") {
  132. return fm, src, nil
  133. }
  134. end := strings.Index(src[4:], "\n---\n")
  135. if end < 0 {
  136. return nil, "", errors.New("front matter is not closed with ---")
  137. }
  138. for _, line := range strings.Split(src[4:4+end], "\n") {
  139. if strings.TrimSpace(line) == "" {
  140. continue
  141. }
  142. k, v, ok := strings.Cut(line, ":")
  143. if !ok {
  144. return nil, "", fmt.Errorf("front matter line %q has no colon", line)
  145. }
  146. fm[strings.TrimSpace(k)] = strings.TrimSpace(v)
  147. }
  148. return fm, src[4+end+5:], nil
  149. }
  150. func atoiDefault(s string, def int) int {
  151. if n, err := strconv.Atoi(s); err == nil {
  152. return n
  153. }
  154. return def
  155. }
  156. // ---------- guides ----------
  157. type Guide struct {
  158. Slug string
  159. Title string
  160. Group string
  161. Summary string
  162. Order int
  163. Body string
  164. }
  165. // groupOrder is the sidebar order of guide groups; unknown groups follow.
  166. var groupOrder = []string{"Getting started", "Guides"}
  167. func loadGuides(dir string) ([]*Guide, error) {
  168. files, err := filepath.Glob(filepath.Join(dir, "*.md"))
  169. if err != nil {
  170. return nil, err
  171. }
  172. var out []*Guide
  173. for _, f := range files {
  174. raw, err := os.ReadFile(f)
  175. if err != nil {
  176. return nil, err
  177. }
  178. fm, body, err := splitFrontMatter(string(raw))
  179. if err != nil {
  180. return nil, fmt.Errorf("%s: %w", f, err)
  181. }
  182. g := &Guide{
  183. Slug: strings.TrimSuffix(filepath.Base(f), ".md"),
  184. Title: fm["title"],
  185. Group: fm["group"],
  186. Summary: fm["summary"],
  187. Order: atoiDefault(fm["order"], 1000),
  188. Body: body,
  189. }
  190. if g.Title == "" {
  191. return nil, fmt.Errorf("%s: front matter needs a title", f)
  192. }
  193. if g.Slug == "index" || g.Slug == "playground" {
  194. return nil, fmt.Errorf("%s: %q is reserved for a generated page", f, g.Slug)
  195. }
  196. if g.Group == "" {
  197. g.Group = "Guides"
  198. }
  199. out = append(out, g)
  200. }
  201. sort.SliceStable(out, func(i, j int) bool {
  202. gi, gj := indexOf(groupOrder, out[i].Group), indexOf(groupOrder, out[j].Group)
  203. if gi != gj {
  204. return gi < gj
  205. }
  206. if out[i].Order != out[j].Order {
  207. return out[i].Order < out[j].Order
  208. }
  209. return out[i].Slug < out[j].Slug
  210. })
  211. return out, nil
  212. }
  213. func indexOf(list []string, s string) int {
  214. for i, v := range list {
  215. if v == s {
  216. return i
  217. }
  218. }
  219. return len(list)
  220. }
  221. // ---------- samples ----------
  222. // Sample is a ready-made playground script from samples/*.agi. The file
  223. // starts with a /*--- ... ---*/ block of "key: value" lines.
  224. type Sample struct {
  225. ID string `json:"id"`
  226. Title string `json:"title"`
  227. Group string `json:"group"`
  228. Summary string `json:"summary"`
  229. Path string `json:"path"` // vpath the script is saved at, web:/... by default
  230. Setup json.RawMessage `json:"setup,omitempty"` // request, mocks and files the sample needs
  231. Code string `json:"code"`
  232. }
  233. func loadSamples(dir string) ([]*Sample, error) {
  234. files, err := filepath.Glob(filepath.Join(dir, "*.agi"))
  235. if err != nil {
  236. return nil, err
  237. }
  238. sort.Strings(files)
  239. var out []*Sample
  240. for _, f := range files {
  241. raw, err := os.ReadFile(f)
  242. if err != nil {
  243. return nil, err
  244. }
  245. src := strings.ReplaceAll(string(raw), "\r\n", "\n")
  246. if !strings.HasPrefix(src, "/*---\n") {
  247. return nil, fmt.Errorf("%s: must start with a /*--- header", f)
  248. }
  249. end := strings.Index(src, "\n---*/\n")
  250. if end < 0 {
  251. return nil, fmt.Errorf("%s: header is not closed with ---*/", f)
  252. }
  253. fm, _, err := splitFrontMatter("---\n" + src[6:end] + "\n---\n")
  254. if err != nil {
  255. return nil, fmt.Errorf("%s: %w", f, err)
  256. }
  257. id := strings.TrimSuffix(filepath.Base(f), ".agi")
  258. // A leading "NN-" orders the files and is not part of the id.
  259. if i := strings.Index(id, "-"); i > 0 {
  260. if _, err := strconv.Atoi(id[:i]); err == nil {
  261. id = id[i+1:]
  262. }
  263. }
  264. s := &Sample{
  265. ID: id,
  266. Title: fm["title"],
  267. Group: fm["group"],
  268. Summary: fm["summary"],
  269. Path: fm["path"],
  270. Code: strings.TrimLeft(src[end+7:], "\n"),
  271. }
  272. if s.Title == "" {
  273. return nil, fmt.Errorf("%s: header needs a title", f)
  274. }
  275. if s.Path == "" {
  276. s.Path = "Playground/" + id + ".agi"
  277. }
  278. if !strings.Contains(s.Path, ":/") {
  279. s.Path = "web:/" + strings.TrimPrefix(s.Path, "/")
  280. }
  281. // setup is one line of JSON: {"request":{...},"mocks":{...},"files":[{"path":"user:/a.txt","text":"..."}]}
  282. if p := fm["setup"]; p != "" {
  283. if !json.Valid([]byte(p)) {
  284. return nil, fmt.Errorf("%s: setup is not valid JSON", f)
  285. }
  286. s.Setup = json.RawMessage(p)
  287. }
  288. out = append(out, s)
  289. }
  290. return out, nil
  291. }
  292. // writeJSON writes v compactly; the playground reads these at run time.
  293. func writeJSON(path string, v any) error {
  294. var buf bytes.Buffer
  295. enc := json.NewEncoder(&buf)
  296. enc.SetEscapeHTML(false)
  297. if err := enc.Encode(v); err != nil {
  298. return err
  299. }
  300. return writeFile(path, buf.Bytes())
  301. }
  302. func writeFile(path string, data []byte) error {
  303. if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
  304. return err
  305. }
  306. return os.WriteFile(path, data, 0o644)
  307. }