lib/effs/io.bend

near-v-framework@0.2.0.0 · 50 lines · 0 definitions

1import Base
2
3# V's I/O: run a program (a C effect, see proc_run.c) and write a file (Bend's File API).
4
5def Proc.run(cmd: String) -> IO(Result<&1, &1, U32 & String, String>):
6  import "./proc_run.c"
7
8# Standard output of a command; "" if it failed.
9def out_of(r: Result<&1, &1, U32 & String, String>) -> String:
10  match r:
11    case Done{v}:
12      v
13    case Fail{_}:
14      ""
15
16def ok_of(r: Result<&1, &1, U32 & String, String>) -> Bool:
17  match r:
18    case Done{_}:
19      True{}
20    case Fail{_}:
21      False{}
22
23def sh(cmd: String) -> IO(String):
24  do IO<String>:
25    r : Result<&1, &1, U32 & String, String> <- Proc.run(cmd)
26    return out_of(r)
27
28def ok(cmd: String) -> IO(Bool):
29  do IO<Bool>:
30    r : Result<&1, &1, U32 & String, String> <- Proc.run(cmd)
31    return ok_of(r)
32
33def after_write(r: File & Result<&1, &1, U32 & String, Unit>) -> IO(Unit):
34  match r:
35    case (f, _):
36      File.close(f)
37
38def write_opened(r: Result<&1, &1, U32 & String, File>, text: String) -> IO(Unit):
39  match r:
40    case Done{f}:
41      do IO<Unit>:
42        w : File & Result<&1, &1, U32 & String, Unit> <- File.write(f, text)
43        after_write(w)
44    case Fail{_}:
45      IO.die(Unit, 1, "cannot write file")
46
47def write_file(path: String, text: String) -> IO(Unit):
48  do IO<Unit>:
49    r : Result<&1, &1, U32 & String, File> <- File.open(path, "w")
50    write_opened(r, text)