hachem.wtf
aboutsummaryrefslogtreecommitdiff
path: root/gils/head.rv
blob: c124ed301579ae224515315a36369408043501d4 (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
# gimme some head lung

fn file_lines(path) -> table | :nil do
  const size = vfs:size(path)
  if (size < 0)
    return :nil

  const contents = if (size > 0) vfs:read_bytes(path, 0, size) else ""
  const raw_lines = contents:split("\n")
  let result = {}
  for index in 0..raw_lines:len() do
    if (index < raw_lines:len() - 1 or raw_lines[index]:len() > 0)
      result:push(raw_lines[index])
  end
  return result
end

const context = env.ctx

if context.argv:len() < 2 do
  fail("usage: head [n] <path>\n")
end else do
  let limit = 10
  let path_arg = context.argv[1]
  if context.argv:len() >= 3 and parse_pid(context.argv[1]) >= 0 do
    limit = parse_pid(context.argv[1])
    path_arg = context.argv[2]
  end

  const lines = file_lines(expand_path(path_arg))
  if lines == :nil do
    fail("head: no such file\n")
  end else do
    let index = 0
    while (index < lines:len() and index < limit) do
      puts("#{lines[index]}\n")
      index += 1
    end
  end
end