From 3b13a7b11b9ef5a84c2c2c97c166babfa4757420 Mon Sep 17 00:00:00 2001 From: dvs1 Date: Fri, 25 Oct 2024 12:23:00 +1000 Subject: Support config files now. --- _.lua | 47 +++++++++++++++++++++++++++++++++-------------- test_.lua | 7 +++++-- 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/_.lua b/_.lua index 4de9923..3a92350 100755 --- a/_.lua +++ b/_.lua @@ -25,24 +25,43 @@ E = function(s) print('ERROR ' .. s); io.flush() end C = function(s) print('CRITICAL ' .. s); io.flush() end -_.parse = function(args, options) ---[[ TODO - use this for config files as well. - An optional argument, the base config file name to look for. In this order, with later ones overriding earlier ones - - defaults from the options table - /etc/base.conf.lua - ~/.base.conf.lua - command line arguments -]] +_.parse = function(args, options, confFile) local o = nil + + local doIt = function(name, val, a, args, i) + local o = options[name] + if nil ~= o then + if nil ~= val then o.value = val; D(name .. ' = ' .. tostring(val)) end + if nil ~= o.func then o:func(a, args, i) end + end + return o + end + + if nil ~= confFile then + for i,v in ipairs{'/etc/', '~/.', './.'} do + local p = v .. confFile .. '.conf.lua' + local h, e = io.open(p, "r") + if nil ~= h then + D('Found configuration file '.. p) + h:close() + local ar = dofile(p) + for k, w in pairs(ar) do + o = doIt(k, w, k .. '=' .. tostring(w), args, i) + if nil == o then E('config variable not found ' .. k .. ' = ' .. tostring(w)) end + end + end + end + end + if 0 ~= #args then for i,a in ipairs(args) do - local s, e = a:find("=") - if nil == s then e = 0 end - opt = a:sub(1, e - 1) - o = options[opt] D('Argument ' .. i .. ' = ' .. a) - if nil ~= o then - if nil ~= o.func then o:func(a, args, i) end + local s, e = a:find("=") + if nil == s then + e = 0 + o = doIt(a:sub(1, e - 1), nil, a, args, i) + else + o = doIt(a:sub(1, e - 1), a:sub(e + 1, -1), a, args, i) end end end diff --git a/test_.lua b/test_.lua index b5348f0..5876ed9 100755 --- a/test_.lua +++ b/test_.lua @@ -13,7 +13,7 @@ This is part of the blah blah blah... local options = { - start = {help = 'Command to start the scanning process, for Sys V init.',}, + start = {help = 'Command to start the scanning process, for Sys V init.', value = 'blah'}, restart = {start}, ['force-reload'] = {start}, status = {help = 'Command to check the status of the scanning process, for Sys V init.',}, @@ -55,7 +55,10 @@ local options = ['--help'] = {help}, } -_.parse(arg, options) +print("start = " .. options.start.value) +_.parse(arg, options, 'test_') +print("start = " .. options.start.value) +print("stop = " .. options.stop.value) -- cgit v1.1