Files
orbit/src/main/sys.mbt
T
nandiandClaude Haiku 5.5 a999db54a8 Fix spinner hang and use braille frames
The spinner ran as a background task that outlived the command, so a
terminal run of orbit search never returned. It is now a child task that
is cancelled once the command finishes, and it starts immediately with
braille frames. upgrade skips the metadata fetch for an unchanged build
whose description is already saved.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-26 22:59:16 -08:00

394 lines
8.6 KiB
MoonBit

// System access through process execution, MoonBit async fs/process, and small helpers.
///|
suberror OrbitError {
OrbitError(String)
}
///|
#borrow(name)
extern "C" fn c_getenv(name : Bytes) -> Bytes = "orbit_getenv"
///|
extern "C" fn c_exit(code : Int32) = "orbit_exit"
///|
extern "C" fn c_isatty(fd : Int32) -> Int32 = "isatty"
///|
#borrow(msg)
extern "C" fn c_print_err(msg : Bytes) -> Unit = "orbit_print_err"
///|
#borrow(target, linkpath)
extern "C" fn c_symlink(target : Bytes, linkpath : Bytes) -> Int32 = "orbit_symlink"
// ---------------------------------------------------------------- UTF-8
///|
fn utf8_encode(s : String) -> Bytes {
let out : Array[Byte] = []
for c in s {
let cp = c.to_int()
if cp < 0x80 {
out.push(cp.to_byte())
} else if cp < 0x800 {
out.push((0xC0 | (cp >> 6)).to_byte())
out.push((0x80 | (cp & 0x3F)).to_byte())
} else if cp < 0x10000 {
out.push((0xE0 | (cp >> 12)).to_byte())
out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte())
out.push((0x80 | (cp & 0x3F)).to_byte())
} else {
out.push((0xF0 | (cp >> 18)).to_byte())
out.push((0x80 | ((cp >> 12) & 0x3F)).to_byte())
out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte())
out.push((0x80 | (cp & 0x3F)).to_byte())
}
}
Bytes::makei(out.length(), fn(i) { out[i] })
}
///|
fn utf8_decode(b : Bytes) -> String {
let sb = StringBuilder()
let n = b.length()
let mut i = 0
while i < n {
let c0 = b[i].to_int()
if c0 < 0x80 {
sb.write_char(Int32::unsafe_to_char(c0))
i = i + 1
} else if c0 >= 0xC0 && c0 < 0xE0 && i + 1 < n {
let cp = ((c0 & 0x1F) << 6) | (b[i + 1].to_int() & 0x3F)
sb.write_char(Int32::unsafe_to_char(cp))
i = i + 2
} else if c0 >= 0xE0 && c0 < 0xF0 && i + 2 < n {
let cp = ((c0 & 0x0F) << 12) |
((b[i + 1].to_int() & 0x3F) << 6) |
(b[i + 2].to_int() & 0x3F)
sb.write_char(Int32::unsafe_to_char(cp))
i = i + 3
} else if c0 >= 0xF0 && i + 3 < n {
let cp = ((c0 & 0x07) << 18) |
((b[i + 1].to_int() & 0x3F) << 12) |
((b[i + 2].to_int() & 0x3F) << 6) |
(b[i + 3].to_int() & 0x3F)
sb.write_char(Int32::unsafe_to_char(cp))
i = i + 4
} else {
sb.write_char('\u{FFFD}')
i = i + 1
}
}
sb.to_string()
}
// ---------------------------------------------------------------- strings
///|
fn chars(s : String) -> Array[Char] {
let a : Array[Char] = []
for c in s {
a.push(c)
}
a
}
///|
fn slice(a : Array[Char], start : Int32, end : Int32) -> String {
let sb = StringBuilder()
for i = start; i < end; i = i + 1 {
sb.write_char(a[i])
}
sb.to_string()
}
///|
fn drop_chars(s : String, n : Int32) -> String {
let a = chars(s)
if n >= a.length() {
""
} else {
slice(a, n, a.length())
}
}
///|
fn has_prefix(s : String, p : String) -> Bool {
let a = chars(s)
let b = chars(p)
if b.length() > a.length() {
return false
}
for i = 0; i < b.length(); i = i + 1 {
if a[i] != b[i] {
return false
}
}
true
}
///|
fn has_char(s : String, ch : Char) -> Bool {
for c in s {
if c == ch {
return true
}
}
false
}
///|
fn contains_str(s : String, sub : String) -> Bool {
let a = chars(s)
let b = chars(sub)
if b.length() == 0 {
return true
}
for i = 0; i + b.length() <= a.length(); i = i + 1 {
let mut ok = true
for j = 0; j < b.length(); j = j + 1 {
if a[i + j] != b[j] {
ok = false
break
}
}
if ok {
return true
}
}
false
}
///|
fn split_on(s : String, sep : Char) -> Array[String] {
let out : Array[String] = []
let sb = StringBuilder()
let mut cur = sb
for c in s {
if c == sep {
out.push(cur.to_string())
cur = StringBuilder()
} else {
cur.write_char(c)
}
}
out.push(cur.to_string())
out
}
///|
/// Split at the first `sep`; the second part is "" when `sep` is absent.
fn split_first(s : String, sep : Char) -> (String, String) {
let a = chars(s)
for i = 0; i < a.length(); i = i + 1 {
if a[i] == sep {
return (slice(a, 0, i), slice(a, i + 1, a.length()))
}
}
(s, "")
}
///|
fn is_space(c : Char) -> Bool {
c == ' ' || c == '\n' || c == '\t' || c == '\r'
}
///|
fn trim(s : String) -> String {
let a = chars(s)
let mut start = 0
let mut end = a.length()
while start < end && is_space(a[start]) {
start = start + 1
}
while end > start && is_space(a[end - 1]) {
end = end - 1
}
slice(a, start, end)
}
///|
/// Non-empty, trimmed lines.
fn lines(s : String) -> Array[String] {
let out : Array[String] = []
for l in split_on(s, '\n') {
let t = trim(l)
if t != "" {
out.push(t)
}
}
out
}
///|
fn join(xs : Array[String], sep : String) -> String {
let sb = StringBuilder()
for i = 0; i < xs.length(); i = i + 1 {
if i > 0 {
sb.write_string(sep)
}
sb.write_string(xs[i])
}
sb.to_string()
}
///|
fn basename(p : String) -> String {
let parts = split_on(p, '/')
parts[parts.length() - 1]
}
///|
/// Single-quote a string for /bin/sh.
fn sq(s : String) -> String {
let sb = StringBuilder()
sb.write_char('\'')
for c in s {
if c == '\'' {
sb.write_string("'\\''")
} else {
sb.write_char(c)
}
}
sb.write_char('\'')
sb.to_string()
}
// ---------------------------------------------------------------- process / fs (async)
///|
async fn sh(cmd : String) -> Int32 noraise {
try {
@process.run("sh", ["-c", cmd])
} catch {
_ => 128
}
}
///|
async fn sh_ok(cmd : String) -> Unit raise OrbitError {
let code = sh(cmd)
if code != 0 {
raise OrbitError("command failed (exit \{code}): \{cmd}")
}
}
///|
/// Braille spinner on stderr until cancelled.
async fn spin(label : String) -> Unit noraise {
let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
let mut i = 0
while true {
c_print_err(utf8_encode("\r\u001B[2K" + frames[i % 10] + " " + label))
i = i + 1
@async.sleep(80)
}
}
///|
/// Return stdout; stderr goes to the terminal unless captured. A label shows a
/// braille spinner on a terminal while the command runs. The spinner is a child
/// task that is cancelled as soon as the command finishes, so nothing keeps the
/// group alive.
async fn capture(cmd : String, progress~ : String = "") -> String raise OrbitError {
let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb"
let spinning = is_tty && progress != ""
let res : Result[String, Error] = try {
let out = @async.with_task_group(group => {
let spinner = if spinning {
Some(group.spawn(() => {
ignore(@async.handle_cancellation(() => spin(progress)))
}))
} else {
None
}
let (code, stdout, _) = @process.collect_output("sh", ["-c", cmd])
match spinner {
Some(task) => task.cancel()
None => ()
}
if spinning {
c_print_err(utf8_encode("\r\u001B[2K"))
}
if code != 0 {
raise OrbitError("command failed (exit \{code}): \{cmd}")
}
stdout.text()
})
Ok(out)
} catch {
e => Err(e)
}
match res {
Ok(s) => s
Err(OrbitError(msg)) => raise OrbitError(msg)
Err(e) => raise OrbitError(e.to_string())
}
}
///|
async fn exists(path : String) -> Bool noraise {
try {
@fs.exists(path)
} catch {
_ => false
}
}
///|
async fn read_text(path : String) -> String? noraise {
try {
let data = @fs.read_file(path)
Some(data.text())
} catch {
_ => None
}
}
///|
/// Write via a temp file and rename, so readers never see a half-written file.
async fn write_text_atomic(path : String, text : String) -> Unit raise OrbitError {
let tmp = path + ".tmp"
try {
@fs.write_file(tmp, text, create_mode=CreateOrTruncate)
@fs.rename(tmp, path)
} catch {
e => raise OrbitError("cannot write " + path + ": " + e.to_string())
}
}
///|
fn getenv(name : String) -> String {
utf8_decode(c_getenv(utf8_encode(name)))
}
///|
/// Command-line arguments without the program name (Linux: /proc/self/cmdline).
async fn cli_args() -> Array[String] noraise {
let raw = try {
@fs.read_file("/proc/self/cmdline").binary()
} catch {
_ => Default::default()
}
let out : Array[String] = []
let cur : Array[Byte] = []
for i = 0; i < raw.length(); i = i + 1 {
if raw[i].to_int() == 0 {
out.push(utf8_decode(Bytes::makei(cur.length(), fn(k) { cur[k] })))
cur.clear()
} else {
cur.push(raw[i])
}
}
if cur.length() > 0 {
out.push(utf8_decode(Bytes::makei(cur.length(), fn(k) { cur[k] })))
}
let args : Array[String] = []
for i = 1; i < out.length(); i = i + 1 {
args.push(out[i])
}
args
}