1 # walk/disk: an effect (CPU event loop only): the names directly in a 2 # directory, whether a path is a directory, and the working directory 3 # relative paths are named from. A name that is itself a directory ends in 4 # "/"; "." and ".." are never in the list, and a directory that cannot be 5 # opened lists as empty. Order is the file system's; the lint planner 6 # (src/lint/plan.bend) sorts what it keeps. 7 # 8 # It is the real file system, through a foreign effect (dir.c, dir.js) that 9 # lists one directory: its names, one a line, a directory's name ending in 10 # "/"; one (cwd.c, cwd.js) that names the working directory; and Base's 11 # File, which tells a directory from a file. 12 import Base 13 14 # every name directly in the directory, one a line 15 def walkdir.entries(dir: String) -> IO(String): 16 import "./dir.c" 17 import "./dir.js" 18 19 # the named lines: the text ends in a newline, so the last line is empty 20 def named(ls: List<&2, String>) -> List<&2, String>: 21 match ls: 22 case Nil{}: 23 Nil{} 24 case Con{+l, t}: 25 +more = named(t) 26 Bool.pick(List<&2, String>, String.is_empty(l), more, l <> more) 27 28 # a directory's entries, a directory marked by a `/` 29 def entries(dir: String) -> IO(List<&2, String>): # noqa: L001 disk effect 30 do IO>: 31 text : String <- walkdir.entries(dir) 32 return named(String.lines(text)) 33 34 # whether a first read failed as a directory's does (EISDIR, 21, in C and 35 # in node alike) 36 def is_dir.code(rr: Result<&1, &1, U32 & String, List<&2, U32>>) -> Bool: 37 match rr: 38 case Fail{e}: 39 (code, _msg) = e 40 U32.is_eq(code, 21) 41 case Done{_bytes}: 42 False{} 43 44 # the file closed, and what its first read said 45 def is_dir.got(got: File & Result<&1, &1, U32 & String, List<&2, U32>>) -> IO(Bool): 46 (file, rr) = got 47 do IO: 48 File.close(file) 49 return is_dir.code(rr) 50 51 # a path that opened: read one byte and see; one that did not is no directory 52 def is_dir.opened(rr: Result<&1, &1, U32 & String, File>) -> IO(Bool): 53 match rr: 54 case Fail{_e}: 55 IO.pure(Bool, False{}) 56 case Done{file}: 57 do IO: 58 got : File & Result<&1, &1, U32 & String, List<&2, U32>> <- File.read_bytes(file, 1) 59 is_dir.got(got) 60 61 # whether a path is a directory: it opens, and reading it fails as a 62 # directory's read does. Base's File has no stat, and a directory opens for 63 # reading on both lanes. 64 def is_dir(path: String) -> IO(Bool): # noqa: L001 disk effect 65 do IO: 66 r : Result<&1, &1, U32 & String, File> <- File.open(path, "r") 67 is_dir.opened(r) 68 69 # the working directory, from the root; "" when it cannot be named 70 def walkdir.cwd() -> IO(String): 71 import "./cwd.c" 72 import "./cwd.js" 73 74 # the working directory, from the root ("" when it cannot be named) 75 def cwd() -> IO(String): # noqa: L001 disk effect 76 walkdir.cwd()