fs.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. // Package playground runs AGI scripts the way ArozOS does, on the same Otto
  2. // interpreter, against an in-memory drive and mocked external services. It is
  3. // compiled to WebAssembly (cmd/agiwasm) for the docs playground, and runs
  4. // natively in its tests.
  5. package playground
  6. import (
  7. "errors"
  8. "io/fs"
  9. "path"
  10. "sort"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. // File is one entry of the playground drive as the page stores it.
  16. type File struct {
  17. Path string `json:"path"` // vpath, e.g. "user:/Desktop/a.txt"
  18. Dir bool `json:"dir,omitempty"`
  19. Data []byte `json:"data,omitempty"`
  20. Mtime int64 `json:"mtime,omitempty"` // unix milliseconds
  21. }
  22. // Roots the drive knows. user:/ and tmp:/ are the drives a script may use
  23. // through filelib; web:/ holds the WebApp's own files (./web on a server),
  24. // which scripts reach only through includes(), execd() and appdata.
  25. var Roots = []string{"user", "tmp", "web"}
  26. var (
  27. errNotExist = fs.ErrNotExist
  28. errIsDir = errors.New("is a directory")
  29. errNotDir = errors.New("not a directory")
  30. errNoRoot = errors.New("unknown root")
  31. errNotEmpty = errors.New("directory not empty")
  32. )
  33. type node struct {
  34. dir bool
  35. data []byte
  36. mtime time.Time
  37. }
  38. // memFS is the drive: every entry keyed by its clean vpath. A root's own key
  39. // is "user:/". It is safe for concurrent use (execd children share it).
  40. type memFS struct {
  41. mu sync.Mutex
  42. nodes map[string]*node
  43. touched map[string]bool // vpaths written or removed during the run
  44. }
  45. func newMemFS(files []File) *memFS {
  46. m := &memFS{nodes: map[string]*node{}, touched: map[string]bool{}}
  47. for _, r := range Roots {
  48. m.nodes[r+":/"] = &node{dir: true}
  49. }
  50. for _, f := range files {
  51. root, rel, err := splitVpath(f.Path)
  52. if err != nil {
  53. continue
  54. }
  55. key := joinKey(root, rel)
  56. mt := time.UnixMilli(f.Mtime)
  57. if f.Mtime == 0 {
  58. mt = time.Now()
  59. }
  60. m.mkdirAllLocked(root, path.Dir(rel), mt, false)
  61. if f.Dir {
  62. m.nodes[key] = &node{dir: true, mtime: mt}
  63. } else {
  64. m.nodes[key] = &node{data: f.Data, mtime: mt}
  65. }
  66. }
  67. return m
  68. }
  69. // splitVpath cleans a vpath into its root and a slash path inside it ("" for
  70. // the root itself). "user:" alone is the root.
  71. func splitVpath(vpath string) (string, string, error) {
  72. vpath = strings.ReplaceAll(vpath, "\\", "/")
  73. i := strings.Index(vpath, ":")
  74. if i <= 0 {
  75. return "", "", errNoRoot
  76. }
  77. root := vpath[:i]
  78. ok := false
  79. for _, r := range Roots {
  80. if r == root {
  81. ok = true
  82. }
  83. }
  84. if !ok {
  85. return "", "", errNoRoot
  86. }
  87. rel := strings.TrimPrefix(path.Clean("/"+vpath[i+1:]), "/")
  88. return root, rel, nil
  89. }
  90. func joinKey(root, rel string) string {
  91. if rel == "" || rel == "." {
  92. return root + ":/"
  93. }
  94. return root + ":/" + rel
  95. }
  96. // Clean returns the canonical form of a vpath, or "" when it names no root.
  97. func Clean(vpath string) string {
  98. root, rel, err := splitVpath(vpath)
  99. if err != nil {
  100. return ""
  101. }
  102. return joinKey(root, rel)
  103. }
  104. func (m *memFS) lookup(vpath string) (string, *node, error) {
  105. root, rel, err := splitVpath(vpath)
  106. if err != nil {
  107. return "", nil, err
  108. }
  109. key := joinKey(root, rel)
  110. return key, m.nodes[key], nil
  111. }
  112. func (m *memFS) Stat(vpath string) (dir bool, size int64, mtime time.Time, err error) {
  113. m.mu.Lock()
  114. defer m.mu.Unlock()
  115. _, n, err := m.lookup(vpath)
  116. if err != nil {
  117. return false, 0, time.Time{}, err
  118. }
  119. if n == nil {
  120. return false, 0, time.Time{}, errNotExist
  121. }
  122. return n.dir, int64(len(n.data)), n.mtime, nil
  123. }
  124. func (m *memFS) Exists(vpath string) bool {
  125. _, _, _, err := m.Stat(vpath)
  126. return err == nil
  127. }
  128. func (m *memFS) IsDir(vpath string) bool {
  129. d, _, _, err := m.Stat(vpath)
  130. return err == nil && d
  131. }
  132. func (m *memFS) ReadFile(vpath string) ([]byte, error) {
  133. m.mu.Lock()
  134. defer m.mu.Unlock()
  135. _, n, err := m.lookup(vpath)
  136. if err != nil {
  137. return nil, err
  138. }
  139. if n == nil {
  140. return nil, errNotExist
  141. }
  142. if n.dir {
  143. return nil, errIsDir
  144. }
  145. return append([]byte(nil), n.data...), nil
  146. }
  147. // WriteFile behaves like os.WriteFile: the parent folder must exist.
  148. func (m *memFS) WriteFile(vpath string, data []byte) error {
  149. m.mu.Lock()
  150. defer m.mu.Unlock()
  151. key, n, err := m.lookup(vpath)
  152. if err != nil {
  153. return err
  154. }
  155. if n != nil && n.dir {
  156. return errIsDir
  157. }
  158. if parent := m.nodes[parentKey(key)]; parent == nil {
  159. return errNotExist
  160. } else if !parent.dir {
  161. return errNotDir
  162. }
  163. m.nodes[key] = &node{data: append([]byte(nil), data...), mtime: time.Now()}
  164. m.touched[key] = true
  165. return nil
  166. }
  167. func parentKey(key string) string {
  168. i := strings.Index(key, ":/")
  169. root, rel := key[:i], key[i+2:]
  170. return joinKey(root, strings.TrimPrefix(path.Dir("/"+rel), "/"))
  171. }
  172. // MkdirAll behaves like os.MkdirAll.
  173. func (m *memFS) MkdirAll(vpath string) error {
  174. m.mu.Lock()
  175. defer m.mu.Unlock()
  176. root, rel, err := splitVpath(vpath)
  177. if err != nil {
  178. return err
  179. }
  180. return m.mkdirAllLocked(root, rel, time.Now(), true)
  181. }
  182. func (m *memFS) mkdirAllLocked(root, rel string, mt time.Time, track bool) error {
  183. if rel == "" || rel == "." {
  184. return nil
  185. }
  186. parts := strings.Split(rel, "/")
  187. for i := range parts {
  188. key := joinKey(root, strings.Join(parts[:i+1], "/"))
  189. if n := m.nodes[key]; n != nil {
  190. if !n.dir {
  191. return errNotDir
  192. }
  193. continue
  194. }
  195. m.nodes[key] = &node{dir: true, mtime: mt}
  196. if track {
  197. m.touched[key] = true
  198. }
  199. }
  200. return nil
  201. }
  202. // Remove behaves like os.Remove: a folder must be empty.
  203. func (m *memFS) Remove(vpath string) error {
  204. m.mu.Lock()
  205. defer m.mu.Unlock()
  206. key, n, err := m.lookup(vpath)
  207. if err != nil {
  208. return err
  209. }
  210. if n == nil {
  211. return errNotExist
  212. }
  213. if strings.HasSuffix(key, ":/") {
  214. return errors.New("cannot remove a root")
  215. }
  216. if n.dir && len(m.childrenLocked(key)) > 0 {
  217. return errNotEmpty
  218. }
  219. delete(m.nodes, key)
  220. m.touched[key] = true
  221. return nil
  222. }
  223. // RemoveAll removes a path and everything below it.
  224. func (m *memFS) RemoveAll(vpath string) error {
  225. m.mu.Lock()
  226. defer m.mu.Unlock()
  227. key, n, err := m.lookup(vpath)
  228. if err != nil || n == nil {
  229. return err
  230. }
  231. if strings.HasSuffix(key, ":/") {
  232. return errors.New("cannot remove a root")
  233. }
  234. prefix := key + "/"
  235. for k := range m.nodes {
  236. if k == key || strings.HasPrefix(k, prefix) {
  237. delete(m.nodes, k)
  238. m.touched[k] = true
  239. }
  240. }
  241. return nil
  242. }
  243. // childrenLocked lists the direct children of a folder key, sorted by name.
  244. func (m *memFS) childrenLocked(key string) []string {
  245. prefix := key
  246. if !strings.HasSuffix(prefix, "/") {
  247. prefix += "/"
  248. }
  249. var out []string
  250. for k := range m.nodes {
  251. if k == key || !strings.HasPrefix(k, prefix) {
  252. continue
  253. }
  254. if !strings.Contains(k[len(prefix):], "/") {
  255. out = append(out, k)
  256. }
  257. }
  258. sort.Strings(out)
  259. return out
  260. }
  261. // Entry describes a file for listings.
  262. type Entry struct {
  263. Vpath string
  264. Name string
  265. Dir bool
  266. Size int64
  267. Mtime time.Time
  268. }
  269. func (m *memFS) entryLocked(key string) Entry {
  270. n := m.nodes[key]
  271. name := path.Base(key[strings.Index(key, ":/")+1:])
  272. if strings.HasSuffix(key, ":/") {
  273. name = strings.TrimSuffix(key, ":/")
  274. }
  275. return Entry{Vpath: key, Name: name, Dir: n.dir, Size: int64(len(n.data)), Mtime: n.mtime}
  276. }
  277. // ReadDir lists a folder, sorted by name like os.ReadDir.
  278. func (m *memFS) ReadDir(vpath string) ([]Entry, error) {
  279. m.mu.Lock()
  280. defer m.mu.Unlock()
  281. key, n, err := m.lookup(vpath)
  282. if err != nil {
  283. return nil, err
  284. }
  285. if n == nil {
  286. return nil, errNotExist
  287. }
  288. if !n.dir {
  289. return nil, errNotDir
  290. }
  291. var out []Entry
  292. for _, k := range m.childrenLocked(key) {
  293. out = append(out, m.entryLocked(k))
  294. }
  295. return out, nil
  296. }
  297. // Walk lists a path and everything below it in lexical order, the path
  298. // itself first, like filepath.Walk.
  299. func (m *memFS) Walk(vpath string) ([]Entry, error) {
  300. m.mu.Lock()
  301. defer m.mu.Unlock()
  302. key, n, err := m.lookup(vpath)
  303. if err != nil {
  304. return nil, err
  305. }
  306. if n == nil {
  307. return nil, errNotExist
  308. }
  309. var out []Entry
  310. var visit func(k string)
  311. visit = func(k string) {
  312. out = append(out, m.entryLocked(k))
  313. if m.nodes[k].dir {
  314. for _, c := range m.childrenLocked(k) {
  315. visit(c)
  316. }
  317. }
  318. }
  319. visit(key)
  320. return out, nil
  321. }
  322. // Glob matches the last element of pattern against the entries of its
  323. // folder, like filepath.Glob for a pattern with wildcards in the file name
  324. // only (what filelib.glob supports).
  325. func (m *memFS) Glob(pattern string) ([]Entry, error) {
  326. root, rel, err := splitVpath(pattern)
  327. if err != nil {
  328. return nil, err
  329. }
  330. if _, err := path.Match(path.Base("/"+rel), ""); err != nil {
  331. return nil, err
  332. }
  333. dir := joinKey(root, strings.TrimPrefix(path.Dir("/"+rel), "/"))
  334. base := path.Base("/" + rel)
  335. m.mu.Lock()
  336. defer m.mu.Unlock()
  337. if n := m.nodes[dir]; n == nil || !n.dir {
  338. return nil, nil
  339. }
  340. var out []Entry
  341. for _, k := range m.childrenLocked(dir) {
  342. e := m.entryLocked(k)
  343. if ok, _ := path.Match(base, e.Name); ok {
  344. out = append(out, e)
  345. }
  346. }
  347. return out, nil
  348. }
  349. // UsedBytes is the size of every file under a root.
  350. func (m *memFS) UsedBytes(root string) int64 {
  351. m.mu.Lock()
  352. defer m.mu.Unlock()
  353. var total int64
  354. for k, n := range m.nodes {
  355. if strings.HasPrefix(k, root+":/") {
  356. total += int64(len(n.data))
  357. }
  358. }
  359. return total
  360. }
  361. // Changes reports what the run created, changed or removed: the files to
  362. // send back to the page (with their data) and the vpaths that are gone.
  363. func (m *memFS) Changes() (written []File, removed []string) {
  364. m.mu.Lock()
  365. defer m.mu.Unlock()
  366. keys := make([]string, 0, len(m.touched))
  367. for k := range m.touched {
  368. keys = append(keys, k)
  369. }
  370. sort.Strings(keys)
  371. for _, k := range keys {
  372. n := m.nodes[k]
  373. if n == nil {
  374. removed = append(removed, k)
  375. continue
  376. }
  377. written = append(written, File{Path: k, Dir: n.dir, Data: n.data, Mtime: n.mtime.UnixMilli()})
  378. }
  379. return written, removed
  380. }
  381. // isHiddenPath mirrors hidden.IsHidden(path, true): any element starting
  382. // with a dot hides the entry.
  383. func isHiddenPath(vpath string) bool {
  384. _, rel, err := splitVpath(vpath)
  385. if err != nil {
  386. return false
  387. }
  388. for _, p := range strings.Split(rel, "/") {
  389. if strings.HasPrefix(strings.TrimSpace(p), ".") {
  390. return true
  391. }
  392. }
  393. return false
  394. }