code / scripts

Lines748 Shell528 Python72 Lua67 Bourne Again Shell62 make15
1 others 4
Markdown4
(71 lines)
1 #!/usr/bin/env lua
2 --[[
3 -- Draw a bar using unicode
4 --]]
5 local width
6 local colors = {black=0, red=1, green=2, yellow=3, blue=4, magenta=5, cyan=6, white=7}
7 local function fail(msg)
8 io.stderr:write(msg..'\n')
9 os.exit(1)
10 end
12 local function get_color(str)
13 if colors[str] then return ("\x1b[%dm"):format(colors[str]) end
14 local r,g,b = str:match("^(%x%x)(%x%x)(%x%x)$")
15 if not r then
16 r,g,b = str:match("^(%x)(%x)(%x)$")
17 r = r.."0"
18 g = g.."0"
19 b = b.."0"
20 end
21 if not r then fail("Not a recognized color: "..str) end
22 return ("2;%d;%d;%d"):format(tonumber(r,16), tonumber(g,16), tonumber(b,16))
23 end
24 local percent
25 local fg, bg
26 local before, after = {}, {}
27 local dest = before
28 local bits = {" ","▏","▎","▍","▌","▋","▊","▉","█"}
29 for i,a in ipairs(arg) do
30 local num, den = a:match("^([%d.]+)/([%d.]+)$")
31 if num then
32 percent = tonumber(num)/tonumber(den)
33 dest = after
34 elseif a:match("^([%d.]+)%%$") then
35 percent = tonumber(a:match("^([%d.]+)%%$"))/100
36 dest = after
37 elseif a:match("^([%d.]+)$") then
38 percent = tonumber(a:match("^([%d.]+)"))
39 dest = after
40 elseif a:match("^--fg=") then
41 fg = "\x1b[38;"..get_color(a:match("^--fg=(.*)")).."m"
42 elseif a:match("^--bg=") then
43 bg = "\x1b[48;"..get_color(a:match("^--bg=(.*)")).."m"
44 elseif a:match("^--width=") then
45 width = tonumber(a:match("^--width=(.*)"))
46 elseif a:match("^-w=") then
47 width = tonumber(a:match("^-w=(.*)"))
48 elseif a:match("^--scale=") then
49 bits = {}
50 local delim, rest = a:match("^--scale=(.)(.*)")
51 for bit in rest:gmatch("[^"..delim.."]*") do
52 table.insert(bits, bit)
53 end
54 else
55 table.insert(dest, a)
56 end
57 end
58 width = width or 20
59 if not percent then
60 fail("Usage: bar [--width <w>] <percent|a/b>")
61 end
62 local x = percent * width
63 if x < 0 then x = 0 elseif x > width then x = width end
64 local middle = x == width and "" or bits[1+math.floor(#bits * (x % 1))]
65 io.write(table.concat(before,''))
66 if fg then io.write(fg) end
67 if bg then io.write(bg) end
68 io.write(bits[#bits]:rep(math.floor(x))..middle..(" "):rep(width-math.floor(x)-1))
69 if fg or bg then io.write("\x1b[0m") end
70 io.write(table.concat(after,''))
71 io.write("\n")