(71 lines)
1 #!/usr/bin/env lua2 --[[3 -- Draw a bar using unicode4 --]]5 local width6 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 end12 local function get_color(str)13 if colors[str] then return ("\x1b[%dm"):format(colors[str]) end14 local r,g,b = str:match("^(%x%x)(%x%x)(%x%x)$")15 if not r then16 r,g,b = str:match("^(%x)(%x)(%x)$")17 r = r.."0"18 g = g.."0"19 b = b.."0"20 end21 if not r then fail("Not a recognized color: "..str) end22 return ("2;%d;%d;%d"):format(tonumber(r,16), tonumber(g,16), tonumber(b,16))23 end24 local percent25 local fg, bg26 local before, after = {}, {}27 local dest = before28 local bits = {" ","▏","▎","▍","▌","▋","▊","▉","█"}29 for i,a in ipairs(arg) do30 local num, den = a:match("^([%d.]+)/([%d.]+)$")31 if num then32 percent = tonumber(num)/tonumber(den)33 dest = after34 elseif a:match("^([%d.]+)%%$") then35 percent = tonumber(a:match("^([%d.]+)%%$"))/10036 dest = after37 elseif a:match("^([%d.]+)$") then38 percent = tonumber(a:match("^([%d.]+)"))39 dest = after40 elseif a:match("^--fg=") then41 fg = "\x1b[38;"..get_color(a:match("^--fg=(.*)")).."m"42 elseif a:match("^--bg=") then43 bg = "\x1b[48;"..get_color(a:match("^--bg=(.*)")).."m"44 elseif a:match("^--width=") then45 width = tonumber(a:match("^--width=(.*)"))46 elseif a:match("^-w=") then47 width = tonumber(a:match("^-w=(.*)"))48 elseif a:match("^--scale=") then49 bits = {}50 local delim, rest = a:match("^--scale=(.)(.*)")51 for bit in rest:gmatch("[^"..delim.."]*") do52 table.insert(bits, bit)53 end54 else55 table.insert(dest, a)56 end57 end58 width = width or 2059 if not percent then60 fail("Usage: bar [--width <w>] <percent|a/b>")61 end62 local x = percent * width63 if x < 0 then x = 0 elseif x > width then x = width end64 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) end67 if bg then io.write(bg) end68 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") end70 io.write(table.concat(after,''))71 io.write("\n")