Debian Codegraph @

vicious/helpers.lua

raw symbols SCIP
1 -- helper functions
2 -- Copyright (C) 2009 Benedikt Sauer <[email protected]>
3 -- Copyright (C) 2009 Henning Glawe <[email protected]>
4 -- Copyright (C) 2009 Lucas de Vries <[email protected]>
5 -- Copyright (C) 2009 Rémy C. <[email protected]>
6 -- Copyright (C) 2009-2012 Adrian C. (anrxc) <[email protected]>
7 -- Copyright (C) 2011-2018 Jörg Thalheim <[email protected]>
8 -- Copyright (C) 2012 Arvydas Sidorenko <[email protected]>
9 -- Copyright (C) 2017,2019 mutlusun <[email protected]>
10 -- Copyright (C) 2018-2019 Nguyễn Gia Phong <[email protected]m>
11 -- Copyright (C) 2019 Alexander Koch <[email protected]>
12 -- Copyright (C) 2019 Enric Morales <[email protected]>
13 -- Copyright (C) 2022 Constantin Piber <[email protected]>
14 --
15 -- This file is part of Vicious.
16 --
17 -- Vicious is free software: you can redistribute it and/or modify
18 -- it under the terms of the GNU General Public License as
19 -- published by the Free Software Foundation, either version 2 of the
20 -- License, or (at your option) any later version.
21 --
22 -- Vicious is distributed in the hope that it will be useful,
23 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
24 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 -- GNU General Public License for more details.
26 --
27 -- You should have received a copy of the GNU General Public License
28 -- along with Vicious. If not, see <https://www.gnu.org/licenses/>.
29
30 -- {{{ Grab environment
31 local ipairs = ipairs
32 local pairs = pairs
33 local rawget = rawget
34 local require = require
35 local tonumber = tonumber
36 local tostring = tostring
37 local type = type
38 local io = { open = io.open, popen = io.popen }
39 local setmetatable = setmetatable
40 local getmetatable = getmetatable
41 local string = {
42 upper = string.upper,
43 lower = string.lower,
44 format = string.format,
45 match = string.match,
46 find = string.find,
47 }
48 local table = { concat = table.concat }
49 local pcall = pcall
50 local assert = assert
51 local spawn = require("vicious.spawn")
52 -- }}}
53
54
55 -- Helpers: provides helper functions for vicious widgets
56 -- vicious.helpers
57 local helpers = {}
58
59 -- {{{ Constants definitions
60 local OS_UNSUPPORTED_ERR = "Vicious: platform not supported: %s"
61 local NOT_FOUND_MSG = "module '%s' not found"
62 local NOT_FOUND_ERR = [[
63 Vicious: %s is not available for the current platform or does not exist]]
64 -- }}}
65
66 -- {{{ Variable definitions
67 local scroller = {}
68 -- }}}
69
70 -- {{{ Helper functions
71 -- {{{ Determine operating system
72 local kernel_name
73 function helpers.getos()
74 if kernel_name ~= nil then
75 return kernel_name
76 end
77
78 local f = io.popen("uname -s")
79 kernel_name = string.lower(f:read("*line"))
80 f:close()
81
82 return kernel_name
83 end
84 -- }}}
85
86 -- {{{ Loader of vicious modules
87 function helpers.wrequire(collection, key)
88 local ret = rawget(collection, key)
89
90 if ret then
91 return ret
92 end
93
94 local ostable = {
95 linux = { "linux", "all" },
96 freebsd = { "freebsd", "bsd", "all" },
97 openbsd = { "openbsd", "bsd", "all" }
98 }
99
100 local platform = ostable[helpers.getos()]
101 assert(platform, OS_UNSUPPORTED_ERR:format(helpers.getos()))
102
103 local basename = collection._NAME .. '.' .. key
104 for i = 1, #platform do
105 local name = basename .. '_' .. platform[i]
106 local status, value = pcall(require, name)
107 if status then
108 ret = value
109 break
110 end
111
112 -- This is ugly but AFAWK there is no other way to check for
113 -- the type of error. If other error get caught, raise it.
114 if value:find(NOT_FOUND_MSG:format(name), 1, true) == nil then
115 require(name)
116 end
117 end
118
119 assert(ret, NOT_FOUND_ERR:format(basename))
120 return ret
121 end
122 -- }}}
123
124 -- {{{ Set widget type's __call metamethod to given worker function
125 function helpers.setcall(worker)
126 return setmetatable(
127 {}, { __call = function(_, ...) return worker(...) end })
128 end
129 -- }}}
130
131 -- {{{ Set __call metamethod to widget type table having async key
132 function helpers.setasyncall(wtype)
133 local function worker(format, warg)
134 local ret
135 wtype.async(format, warg, function (data) ret = data end)
136 while ret == nil do end
137 return ret
138 end
139 local metatable = { __call = function (_, ...) return worker(...) end }
140 return setmetatable(wtype, metatable)
141 end
142 -- }}}
143
144 -- {{{ Expose path as a Lua table
145 function helpers.pathtotable(dir)
146 return setmetatable({ _path = dir },
147 { __index = function(self, index)
148 local path = self._path .. '/' .. index
149 local f = io.open(path)
150 if f then
151 local s = f:read("*all")
152 f:close()
153 if s then
154 return s
155 else
156 local o = { _path = path }
157 setmetatable(o, getmetatable(self))
158 return o
159 end
160 end
161 end
162 })
163 end
164 -- }}}
165
166 -- {{{ Format a string with args
167 function helpers.format(format, args)
168 for var, val in pairs(args) do
169 if tonumber(var) == nil then
170 var = var:gsub("[-+?*]", function(i) return "%"..i end)
171 end
172 if type(val) == "string" then val = val:gsub("%%", "%%%%") end
173 format = format:gsub("$" .. var, val)
174 end
175 return format
176 end
177 -- }}}
178
179 -- {{{ Format units to one decimal point
180 function helpers.uformat(array, key, value, unit)
181 for u, v in pairs(unit) do
182 array["{"..key.."_"..u.."}"] = string.format("%.1f", value/v)
183 end
184
185 return array
186 end
187 -- }}}
188
189 -- {{{ Escape a string
190 function helpers.escape(text)
191 local xml_entities = {
192 ["\""] = "&quot;",
193 ["&"] = "&amp;",
194 ["'"] = "&apos;",
195 ["<"] = "&lt;",
196 [">"] = "&gt;"
197 }
198
199 return text and text:gsub("[\"&'<>]", xml_entities)
200 end
201 -- }}}
202
203 -- {{{ Escape a string for safe usage on the command line
204 function helpers.shellquote(arg)
205 local s = tostring(arg)
206 if s == nil then return "" end
207 -- use single quotes, and put single quotes into double quotes
208 -- the string $'b is then quoted as '$'"'"'b'"'"'
209 return "'" .. s:gsub("'", "'\"'\"'") .. "'"
210 end
211 -- }}}
212
213 -- {{{ Capitalize a string
214 function helpers.capitalize(text)
215 return text and text:gsub("([%w])([%w]*)", function(c, s)
216 return string.upper(c) .. s
217 end)
218 end
219 -- }}}
220
221 -- {{{ Truncate a string
222 function helpers.truncate(text, maxlen)
223 local txtlen = text:len()
224
225 if txtlen > maxlen then
226 text = text:sub(1, maxlen - 3) .. "..."
227 end
228
229 return text
230 end
231 -- }}}
232
233 -- {{{ Scroll through a string
234 function helpers.scroll(text, maxlen, widget)
235 if not scroller[widget] then
236 scroller[widget] = { i = 1, d = true }
237 end
238
239 local txtlen = text:len()
240 local state = scroller[widget]
241
242 if txtlen > maxlen then
243 if state.d then
244 text = text:sub(state.i, state.i + maxlen) .. "..."
245 state.i = state.i + 3
246
247 if maxlen + state.i >= txtlen then
248 state.d = false
249 end
250 else
251 text = "..." .. text:sub(state.i, state.i + maxlen)
252 state.i = state.i - 3
253
254 if state.i <= 1 then
255 state.d = true
256 end
257 end
258 end
259
260 return text
261 end
262 -- }}}
263
264 -- {{{ Parse output of sysctl command calling the `parse` function
265 function helpers.sysctl_async(path_table, parse)
266 local ret = {}
267 local path = {}
268
269 for i=1,#path_table do
270 path[i] = helpers.shellquote(path_table[i])
271 end
272
273 path = table.concat(path, " ")
274
275 spawn.with_line_callback("sysctl " .. path, {
276 stdout = function (line)
277 local separators = {
278 freebsd = ": ",
279 linux = " = ",
280 openbsd = "="
281 }
282 local pattern = ("(.+)%s(.+)"):format(separators[helpers.getos()])
283 local key, value = string.match(line, pattern)
284 ret[key] = value
285 end,
286 stderr = function (line)
287 local messages = {
288 openbsd = { "level name .+ in (.+) is invalid" },
289 linux = { "cannot stat /proc/sys/(.+):",
290 "permission denied on key '(.+)'" },
291 freebsd = { "unknown oid '(.+)'" }
292 }
293
294 for _, error_message in ipairs(messages[helpers.getos()]) do
295 local key = line:match(error_message)
296 if key then
297 key = key:gsub("/", ".")
298 ret[key] = "N/A"
299 end
300 end
301 end,
302 output_done = function () parse(ret) end
303 })
304 end
305 -- }}}
306
307 return helpers
308 -- }}}