hachem.wtf
aboutsummaryrefslogtreecommitdiff
path: root/gils/gils.rv
blob: 289e547f037cb58c9484bae3786d7bed416cb464 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# gils: better than Gnu utILS
global commands = {}

fn register(usage, group, help, handler) do
  const name = usage:split(" ")[0]
  commands:push({ name = name, usage = usage, group = group, help = help, handler = handler })
end

fn lookup(name) -> table | :nil do
  for index in 0..commands:len() do
    if (commands[index].name == name)
      return commands[index]
  end
  return :nil
end

fn make_ctx(line, argv) -> { line: string, argv: table, rest: string } do
  const name = argv[0]
  let rest = ""

  const cut = name:len() + 1
  if (line:len() > cut)
    rest = line[cut..]

  return { line = line, argv = argv, rest = rest }
end

# scripts read their args off env.ctx, stashed here before eval
global env = { ctx = :nil }

# first use of unless in revo history
global expand_path = fn(path) -> string do
  if (path:len() == 0)
    return wd.path

  unless (path[0] == "/") do
    const slash = unless (wd.path == "/") "/" else ""
    path = "#{wd.path}#{slash}#{path}"
  end

  # collapse . and .. segments
  const raw = path:split("/")
  let parts = {}
  for index in 0..raw:len() do
    const seg = raw[index]
    if seg == ".." do
      if (parts:len() > 0)
        parts:pop()
    end else if seg != "" and seg != "." do
      parts:push(seg)
    end
  end

  if (parts:len() == 0)
    return "/"

  let result = ""
  for index in 0..parts:len() do
    result = result ~ "/" ~ parts[index]
  end
  return result
end

fn run_script_path(path, label, ctx) -> bool do
  const size = fs:size(path)
  if (size < 0)
    return :false

  env.ctx = ctx
  const error_msg = eval_script(fs:read_bytes(path, 0, size))
  if (error_msg != :nil)
    fail("#{label}: #{error_msg}\n")

  return :true
end

fn run_script(name, ctx) -> bool do
  return run_script_path("/bin/#{name}.rv", name, ctx)
end