# ls # it has some features but not all of them obv fn mode_string(type, mode) -> string do let out = "-" if (type == 2) out = "d" if (type == 3) out = "c" const chars = "rwxrwxrwx" for bit in 0..9 do if ((mode band (1 shl (8 - bit))) != 0) do out = out ~ chars[bit] end else do out = out ~ "-" end end return out end fn human_size(n) -> string do if (n < 1024) return "#{n}" if n < 1048576 do const whole = math.floor(n / 1024) const frac = math.floor((n - whole * 1024) * 10 / 1024) return "#{whole}.#{frac}K" end const whole = math.floor(n / 1048576) const frac = math.floor((n - whole * 1048576) * 10 / 1048576) return "#{whole}.#{frac}M" end fn pad_left(text, width) -> string do let out = text while (out:len() < width) do out = " " ~ out end return out end fn pad_right(text, width) -> string do let out = text while (out:len() < width) do out = out ~ " " end return out end const context = env.ctx let long = :false let all = :false let human = :false let target = :nil for ai in 1..context.argv:len() do const a = context.argv[ai] if (a:len() > 1 and a[0] == "-") do for ci in 1..a:len() do const c = a[ci] if (c == "l") long = :true if (c == "a") all = :true if (c == "h") human = :true end end else do target = a end end const path = if (target == :nil) wd.path else expand_path(target) let records = {} let failed = :false if vfs:is_dir(path) do const items = vfs:entries(path) if items == :nil do fail("ls: #{path}: cannot read\n") failed = :true end else do for idx in 0..items:len() do const e = items[idx] if (all or (e.name[0] != ".")) records:push(e) end end end else do const info = vfs:stat(path) if info == :nil do fail("ls: #{path}: no such file\n") failed = :true end else do const parts = path:split("/") records:push({ name = parts[parts:len() - 1], type = info.type, size = info.size, mode = info.mode, uid = info.uid }) end end fn decorate(record) -> string do if (record.type == 2) return record.name ~ "/" return record.name end if failed == :false do if records:len() == 0 do puts(" (empty)\n") end else if long do # precompute let owners = {} let sizes = {} let owner_w = 0 let size_w = 0 for idx in 0..records:len() do const r = records[idx] const owner = user_name(r.uid) const sz = if (human) human_size(r.size) else "#{r.size}" owners:push(owner) sizes:push(sz) if (owner:len() > owner_w) owner_w = owner:len() if (sz:len() > size_w) size_w = sz:len() end for idx in 0..records:len() do const r = records[idx] puts("#{mode_string(r.type, r.mode)} #{pad_right(owners[idx], owner_w)} #{pad_left(sizes[idx], size_w)} #{decorate(r)}\n") end end else do for idx in 0..records:len() do puts(" #{decorate(records[idx])}\n") end end end