mirror of
https://github.com/Nexoniarz/Finch.git
synced 2026-11-03 08:54:25 +00:00
import json import path import time import proc -- found in std/ after the program's own files, so a program's own json.fch always wins. path: join, base, dir, ext, stem, parts, clean, is_abs. time: now, millis, sleep, date, local, format, days_in_month (clock_gettime, strftime through C import). proc: run, output (an error with the command's output when it fails), env, pid, cwd. json: parse (errors with line and column), stringify, pretty, new_*, get/at/set/push/has/names and str_or/int_or/float_or/bool_or; \u escapes with surrogate pairs. The C importer now leaves a plain (non-const) char * parameter a ptr[char], a buffer C writes into; only const char * is text going in. str(ptr) and str([]u8) are in the self-hosted compiler. boot.sh: 40 passed, 0 failed.
48 lines
1.4 KiB
Text
48 lines
1.4 KiB
Text
// Programs: run a command, read what it printed, look at the environment.
|
|
//
|
|
// import proc
|
|
// code := proc.run("make") the exit code; what the command prints goes to the screen
|
|
// text := try proc.output("git describe") what the command printed; an error if it failed
|
|
// proc.env("HOME", "/") an environment variable, or the second value if it is not set
|
|
import "stdlib.h"
|
|
import "unistd.h"
|
|
import "time.h"
|
|
|
|
// run a command; its output goes to the screen. Gives its exit code.
|
|
fn run(str command) -> int {
|
|
return shell(command)
|
|
}
|
|
|
|
// run a command and give what it printed. Fails, with its output as the message, if it exits with an error.
|
|
fn output(str command) -> str! {
|
|
tmp := "/tmp/finch_out_" + str(getpid()) + "_" + str(int(time(null)))
|
|
code := shell("(" + command + ") > '" + tmp + "' 2>&1")
|
|
text := read_file(tmp) or ""
|
|
delete_file(tmp)
|
|
if code != 0 {
|
|
return error("'" + command + "' exited with code " + str(code) + ": " + text.trim())
|
|
}
|
|
return text
|
|
}
|
|
|
|
fn env(str name, str fallback) -> str {
|
|
v := getenv(name)
|
|
if v.len == 0 {
|
|
return fallback
|
|
}
|
|
return v
|
|
}
|
|
|
|
fn pid() -> int {
|
|
return int(getpid())
|
|
}
|
|
|
|
// the folder the program is running in
|
|
fn cwd() -> str {
|
|
[]char buf
|
|
for i in 0..4096 {
|
|
buf.push(char(0))
|
|
}
|
|
getcwd(buf.ptr, 4096)
|
|
return str(buf.ptr)
|
|
}
|