#!/usr/bin/env lua --[[ -- Draw a bar using unicode --]] local width local colors = {black=0, red=1, green=2, yellow=3, blue=4, magenta=5, cyan=6, white=7} local function fail(msg) io.stderr:write(msg..'\n') os.exit(1) end local function get_color(str) if colors[str] then return ("\x1b[%dm"):format(colors[str]) end local r,g,b = str:match("^(%x%x)(%x%x)(%x%x)$") if not r then r,g,b = str:match("^(%x)(%x)(%x)$") r = r.."0" g = g.."0" b = b.."0" end if not r then fail("Not a recognized color: "..str) end return ("2;%d;%d;%d"):format(tonumber(r,16), tonumber(g,16), tonumber(b,16)) end local percent local fg, bg local before, after = {}, {} local dest = before local bits = {" ","▏","▎","▍","▌","▋","▊","▉","█"} for i,a in ipairs(arg) do local num, den = a:match("^([%d.]+)/([%d.]+)$") if num then percent = tonumber(num)/tonumber(den) dest = after elseif a:match("^([%d.]+)%%$") then percent = tonumber(a:match("^([%d.]+)%%$"))/100 dest = after elseif a:match("^([%d.]+)$") then percent = tonumber(a:match("^([%d.]+)")) dest = after elseif a:match("^--fg=") then fg = "\x1b[38;"..get_color(a:match("^--fg=(.*)")).."m" elseif a:match("^--bg=") then bg = "\x1b[48;"..get_color(a:match("^--bg=(.*)")).."m" elseif a:match("^--width=") then width = tonumber(a:match("^--width=(.*)")) elseif a:match("^-w=") then width = tonumber(a:match("^-w=(.*)")) elseif a:match("^--scale=") then bits = {} local delim, rest = a:match("^--scale=(.)(.*)") for bit in rest:gmatch("[^"..delim.."]*") do table.insert(bits, bit) end else table.insert(dest, a) end end width = width or 20 if not percent then fail("Usage: bar [--width ] ") end local x = percent * width if x < 0 then x = 0 elseif x > width then x = width end local middle = x == width and "" or bits[1+math.floor(#bits * (x % 1))] io.write(table.concat(before,'')) if fg then io.write(fg) end if bg then io.write(bg) end io.write(bits[#bits]:rep(math.floor(x))..middle..(" "):rep(width-math.floor(x)-1)) if fg or bg then io.write("\x1b[0m") end io.write(table.concat(after,'')) io.write("\n")