89 changes: 72 additions & 17 deletions lmod/pythonic/optparse.lua
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,13 +41,18 @@ API

Create command line parser.

opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help}
opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help, default=default}

Add command line option specification. This may be called multiple times.
action: 'store'|'store_true'|'store_false'. Default is 'store'
dest: name of returned option table field. Default is the last option-name.
'-' is replaced with '_'
metavar: name used in help text
type: 'int'|'float'|'number'. Default is string

opt.parse_args() --> options, args
opt.parse_args(arglist) --> options, args

Perform argument parsing.
Perform argument parsing. arglist is optional, defaults to global varable 'arg'

DEPENDENCIES

Expand DownExpand Up@@ -85,15 +90,10 @@ LICENSE

--]]

local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.3.20111128'}
local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.4.20120827'}

local ipairs = ipairs
local unpack = unpack
local io = io
local table = table
local os = os
local arg = arg

local arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack
= arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack

local function OptionParser(t)
local usage = t.usage
Expand All@@ -108,17 +108,34 @@ local function OptionParser(t)
os.exit(1)
end

local function is_in_list(list,val)
for _,v in ipairs(list) do
if v == val then return true end
end
end

local function luatype(otype)
if (otype == 'int' or otype == 'float' or otype == 'number' ) then return 'number' end
return 'string'
end

function o.add_option(optdesc)
option_descriptions[#option_descriptions+1] = optdesc
for _,v in ipairs(optdesc) do
option_of[v] = optdesc
end
local dest = optdesc.dest or optdesc[#optdesc]:match('^%-+(.*)') -- fallback to last option
optdesc.dest = dest:gsub('-','_')
optdesc.metavar = optdesc.metavar or dest:upper()
if optdesc.default then
assert( type( optdesc.default) == luatype(optdesc.type), 'default type mismatch, option '..optdesc[#optdesc] )
end
end
function o.parse_args()
function o.parse_args(_arg)
-- expand options (e.g. "--input=file" -> "--input", "file")
local arg = {unpack(arg)}
local arg = {unpack(_arg or arg)}
for i=#arg,1,-1 do local v = arg[i]
local flag, val = v:match('^(%-%-%w+)=(.*)')
local flag, val = v:match('^(%-%-[%w_-]+)=(.*)')
if flag then
arg[i] = flag
table.insert(arg, i+1, val)
Expand All@@ -137,6 +154,22 @@ local function OptionParser(t)
i = i + 1
val = arg[i]
if not val then o.fail('option requires an argument ' .. v) end
if luatype(optdesc.type) == 'number' then
local num = tonumber(val)
if num then
if optdesc.type == 'int' and (num ~= math.floor(num)) then
o.fail(('option %s: number %s not an int'):format(v,val))
num = nil
end
else
o.fail(('option %s: %s not a %s'):format(v,val,optdesc.type))
end
val = num
end
if optdesc.choices and not is_in_list(optdesc.choices, val) then
o.fail(('illegal value for option %s: %s'):format(v,val))
val = nil
end
elseif action == 'store_true' then
val = true
elseif action == 'store_false' then
Expand All@@ -157,6 +190,12 @@ local function OptionParser(t)
io.stdout:write(t.version .. "\n")
os.exit()
end
for _,optdesc in ipairs(option_descriptions) do
local name = optdesc.dest
if optdesc.default and (options[name] == nil) then
options[name] = optdesc.default
end
end
return options, args
end

Expand All@@ -166,7 +205,7 @@ local function OptionParser(t)
for _,flag in ipairs(optdesc) do
local sflagend
if action == nil or action == 'store' then
local metavar = optdesc.metavar or optdesc.dest:upper()
local metavar = optdesc.metavar
sflagend = #flag == 2 and ' ' .. metavar
or '=' .. metavar
else
Expand All@@ -178,16 +217,32 @@ local function OptionParser(t)
end

function o.print_help()
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n")
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0] or '') .. "\n")
io.stdout:write("\n")
io.stdout:write("Options:\n")
local maxwidth = 0
for _,optdesc in ipairs(option_descriptions) do
maxwidth = math.max(maxwidth, #flags_str(optdesc))
end
for _,optdesc in ipairs(option_descriptions) do
local help = optdesc.help or ''
if optdesc.choices or optdesc.default then
if #help>0 then help = help .. ' ' end
help = help .. '('
if optdesc.choices then
for i,v in ipairs(optdesc.choices) do
if i>1 then help = help.. '|' end
help = help..tostring(v)
end
end
if optdesc.choices and optdesc.default then help = help..' ; ' end
if optdesc.default then
help = help .. 'default: '.. tostring(optdesc.default)
end
help = help .. ')'
end
io.stdout:write(" " .. ('%-'..maxwidth..'s '):format(flags_str(optdesc))
.. optdesc.help .. "\n")
.. help .. "\n")
end
end
if t.add_help_option == nil or t.add_help_option == true then
Expand Down
57 changes: 56 additions & 1 deletion test/test.lua
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,62 @@
package.path = './lmod/?.lua;'..package.path

arg = { '-d', '-l', 'DEBUG' , 'localhost', '60000', [0] = 'testdeamon'} -- set global arg

local OP = require 'pythonic.optparse'

-- TODO: add tests
local opt = OP.OptionParser{usage="%prog [options] address port \n", version='0.0', add_help_option=false}
opt.add_option{'-h', '--help', help = 'show this help message and exit', action='store_true' }
opt.add_option{'-d', '--daemon', help = 'Run as daemon', action='store_true' }
opt.add_option{'-l', '--log-level', choices = {'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'}, default = 'INFO', metavar='LEVEL' }
opt.add_option{ '--logfile', help = 'Name of logfile', metavar='FILE' }
opt.add_option{'-c', '--config', help = 'Name of configfile', default = '/etc/opt/test', metavar='FILE' }
opt.add_option{'-s', '--check-interval',help = 'Seconds between checking config', type='int', dest='ci', default = 15 , metavar='SEC'}
opt.add_option{ '--check-float', help = 'Check floating raft', type='float', metavar='liters'}
--opt.print_help()

local options, args = opt.parse_args() -- use global arg

assert(options.log_level=='DEBUG')
assert(options.config=='/etc/opt/test') -- default value
assert(options.daemon==true) -- -d
assert(options.logfile == nil)
assert(options.ci == 15) -- dest, default
assert(options.check_float == nil)
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60000')

-- Next case, now passing arg as paramenter
options, args = opt.parse_args{ 'localhost', '60001', '-l', 'FATAL', '-s', '60' ,
'--config', '/home/test/config', '--logfile', '/var/log/test', '--check-float=3.14' }
assert(options.log_level=='FATAL')
assert(options.config=='/home/test/config') -- config
assert(options.logfile == '/var/log/test')
assert(options.daemon==nil)
assert(options.ci == 60) -- dest, default
assert(options.check_float == 3.14) -- float and --name=var syntax
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60001')


-- harness for error cases:
opt.fail=error
local function check_errorcase(args, errtext)
local res, err = pcall(opt.parse_args, args)
assert(res==false, 'Illegal parameter not caught')
if errtext then
assert(err:find(errtext, nil, true), 'Unexpected error text')
else
print("'"..err.."'")
end
end

-- test error cases:
check_errorcase({ '--bogous', 'foo'}, 'invalid option --bogous')
check_errorcase({ '-l' }, 'option requires an argument -l')
check_errorcase({ '-l', 'DEADLY' }, 'illegal value for option -l: DEADLY')
check_errorcase({ '-s', '6f' }, 'option -s: 6f not a int')
check_errorcase({ '-s', '3.14' }, 'option -s: number 3.14 not an int')

print 'DONE'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
89 changes: 72 additions & 17 deletions lmod/pythonic/optparse.lua
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,13 +41,18 @@ API

Create command line parser.

opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help}
opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help, default=default}

Add command line option specification. This may be called multiple times.
action: 'store'|'store_true'|'store_false'. Default is 'store'
dest: name of returned option table field. Default is the last option-name.
'-' is replaced with '_'
metavar: name used in help text
type: 'int'|'float'|'number'. Default is string

opt.parse_args() --> options, args
opt.parse_args(arglist) --> options, args

Perform argument parsing.
Perform argument parsing. arglist is optional, defaults to global varable 'arg'

DEPENDENCIES

Expand DownExpand Up@@ -85,15 +90,10 @@ LICENSE

--]]

local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.3.20111128'}
local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.4.20120827'}

local ipairs = ipairs
local unpack = unpack
local io = io
local table = table
local os = os
local arg = arg

local arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack
= arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack

local function OptionParser(t)
local usage = t.usage
Expand All@@ -108,17 +108,34 @@ local function OptionParser(t)
os.exit(1)
end

local function is_in_list(list,val)
for _,v in ipairs(list) do
if v == val then return true end
end
end

local function luatype(otype)
if (otype == 'int' or otype == 'float' or otype == 'number' ) then return 'number' end
return 'string'
end

function o.add_option(optdesc)
option_descriptions[#option_descriptions+1] = optdesc
for _,v in ipairs(optdesc) do
option_of[v] = optdesc
end
local dest = optdesc.dest or optdesc[#optdesc]:match('^%-+(.*)') -- fallback to last option
optdesc.dest = dest:gsub('-','_')
optdesc.metavar = optdesc.metavar or dest:upper()
if optdesc.default then
assert( type( optdesc.default) == luatype(optdesc.type), 'default type mismatch, option '..optdesc[#optdesc] )
end
end
function o.parse_args()
function o.parse_args(_arg)
-- expand options (e.g. "--input=file" -> "--input", "file")
local arg = {unpack(arg)}
local arg = {unpack(_arg or arg)}
for i=#arg,1,-1 do local v = arg[i]
local flag, val = v:match('^(%-%-%w+)=(.*)')
local flag, val = v:match('^(%-%-[%w_-]+)=(.*)')
if flag then
arg[i] = flag
table.insert(arg, i+1, val)
Expand All@@ -137,6 +154,22 @@ local function OptionParser(t)
i = i + 1
val = arg[i]
if not val then o.fail('option requires an argument ' .. v) end
if luatype(optdesc.type) == 'number' then
local num = tonumber(val)
if num then
if optdesc.type == 'int' and (num ~= math.floor(num)) then
o.fail(('option %s: number %s not an int'):format(v,val))
num = nil
end
else
o.fail(('option %s: %s not a %s'):format(v,val,optdesc.type))
end
val = num
end
if optdesc.choices and not is_in_list(optdesc.choices, val) then
o.fail(('illegal value for option %s: %s'):format(v,val))
val = nil
end
elseif action == 'store_true' then
val = true
elseif action == 'store_false' then
Expand All@@ -157,6 +190,12 @@ local function OptionParser(t)
io.stdout:write(t.version .. "\n")
os.exit()
end
for _,optdesc in ipairs(option_descriptions) do
local name = optdesc.dest
if optdesc.default and (options[name] == nil) then
options[name] = optdesc.default
end
end
return options, args
end

Expand All@@ -166,7 +205,7 @@ local function OptionParser(t)
for _,flag in ipairs(optdesc) do
local sflagend
if action == nil or action == 'store' then
local metavar = optdesc.metavar or optdesc.dest:upper()
local metavar = optdesc.metavar
sflagend = #flag == 2 and ' ' .. metavar
or '=' .. metavar
else
Expand All@@ -178,16 +217,32 @@ local function OptionParser(t)
end

function o.print_help()
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n")
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0] or '') .. "\n")
io.stdout:write("\n")
io.stdout:write("Options:\n")
local maxwidth = 0
for _,optdesc in ipairs(option_descriptions) do
maxwidth = math.max(maxwidth, #flags_str(optdesc))
end
for _,optdesc in ipairs(option_descriptions) do
local help = optdesc.help or ''
if optdesc.choices or optdesc.default then
if #help>0 then help = help .. ' ' end
help = help .. '('
if optdesc.choices then
for i,v in ipairs(optdesc.choices) do
if i>1 then help = help.. '|' end
help = help..tostring(v)
end
end
if optdesc.choices and optdesc.default then help = help..' ; ' end
if optdesc.default then
help = help .. 'default: '.. tostring(optdesc.default)
end
help = help .. ')'
end
io.stdout:write(" " .. ('%-'..maxwidth..'s '):format(flags_str(optdesc))
.. optdesc.help .. "\n")
.. help .. "\n")
end
end
if t.add_help_option == nil or t.add_help_option == true then
Expand Down
57 changes: 56 additions & 1 deletion test/test.lua
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,62 @@
package.path = './lmod/?.lua;'..package.path

arg = { '-d', '-l', 'DEBUG' , 'localhost', '60000', [0] = 'testdeamon'} -- set global arg

local OP = require 'pythonic.optparse'

-- TODO: add tests
local opt = OP.OptionParser{usage="%prog [options] address port \n", version='0.0', add_help_option=false}
opt.add_option{'-h', '--help', help = 'show this help message and exit', action='store_true' }
opt.add_option{'-d', '--daemon', help = 'Run as daemon', action='store_true' }
opt.add_option{'-l', '--log-level', choices = {'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'}, default = 'INFO', metavar='LEVEL' }
opt.add_option{ '--logfile', help = 'Name of logfile', metavar='FILE' }
opt.add_option{'-c', '--config', help = 'Name of configfile', default = '/etc/opt/test', metavar='FILE' }
opt.add_option{'-s', '--check-interval',help = 'Seconds between checking config', type='int', dest='ci', default = 15 , metavar='SEC'}
opt.add_option{ '--check-float', help = 'Check floating raft', type='float', metavar='liters'}
--opt.print_help()

local options, args = opt.parse_args() -- use global arg

assert(options.log_level=='DEBUG')
assert(options.config=='/etc/opt/test') -- default value
assert(options.daemon==true) -- -d
assert(options.logfile == nil)
assert(options.ci == 15) -- dest, default
assert(options.check_float == nil)
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60000')

-- Next case, now passing arg as paramenter
options, args = opt.parse_args{ 'localhost', '60001', '-l', 'FATAL', '-s', '60' ,
'--config', '/home/test/config', '--logfile', '/var/log/test', '--check-float=3.14' }
assert(options.log_level=='FATAL')
assert(options.config=='/home/test/config') -- config
assert(options.logfile == '/var/log/test')
assert(options.daemon==nil)
assert(options.ci == 60) -- dest, default
assert(options.check_float == 3.14) -- float and --name=var syntax
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60001')


-- harness for error cases:
opt.fail=error
local function check_errorcase(args, errtext)
local res, err = pcall(opt.parse_args, args)
assert(res==false, 'Illegal parameter not caught')
if errtext then
assert(err:find(errtext, nil, true), 'Unexpected error text')
else
print("'"..err.."'")
end
end

-- test error cases:
check_errorcase({ '--bogous', 'foo'}, 'invalid option --bogous')
check_errorcase({ '-l' }, 'option requires an argument -l')
check_errorcase({ '-l', 'DEADLY' }, 'illegal value for option -l: DEADLY')
check_errorcase({ '-s', '6f' }, 'option -s: 6f not a int')
check_errorcase({ '-s', '3.14' }, 'option -s: number 3.14 not an int')

print 'DONE'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
89 changes: 72 additions & 17 deletions lmod/pythonic/optparse.lua
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,13 +41,18 @@ API

Create command line parser.

opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help}
opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help, default=default}

Add command line option specification. This may be called multiple times.
action: 'store'|'store_true'|'store_false'. Default is 'store'
dest: name of returned option table field. Default is the last option-name.
'-' is replaced with '_'
metavar: name used in help text
type: 'int'|'float'|'number'. Default is string

opt.parse_args() --> options, args
opt.parse_args(arglist) --> options, args

Perform argument parsing.
Perform argument parsing. arglist is optional, defaults to global varable 'arg'

DEPENDENCIES

Expand DownExpand Up@@ -85,15 +90,10 @@ LICENSE

--]]

local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.3.20111128'}
local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.4.20120827'}

local ipairs = ipairs
local unpack = unpack
local io = io
local table = table
local os = os
local arg = arg

local arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack
= arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack

local function OptionParser(t)
local usage = t.usage
Expand All@@ -108,17 +108,34 @@ local function OptionParser(t)
os.exit(1)
end

local function is_in_list(list,val)
for _,v in ipairs(list) do
if v == val then return true end
end
end

local function luatype(otype)
if (otype == 'int' or otype == 'float' or otype == 'number' ) then return 'number' end
return 'string'
end

function o.add_option(optdesc)
option_descriptions[#option_descriptions+1] = optdesc
for _,v in ipairs(optdesc) do
option_of[v] = optdesc
end
local dest = optdesc.dest or optdesc[#optdesc]:match('^%-+(.*)') -- fallback to last option
optdesc.dest = dest:gsub('-','_')
optdesc.metavar = optdesc.metavar or dest:upper()
if optdesc.default then
assert( type( optdesc.default) == luatype(optdesc.type), 'default type mismatch, option '..optdesc[#optdesc] )
end
end
function o.parse_args()
function o.parse_args(_arg)
-- expand options (e.g. "--input=file" -> "--input", "file")
local arg = {unpack(arg)}
local arg = {unpack(_arg or arg)}
for i=#arg,1,-1 do local v = arg[i]
local flag, val = v:match('^(%-%-%w+)=(.*)')
local flag, val = v:match('^(%-%-[%w_-]+)=(.*)')
if flag then
arg[i] = flag
table.insert(arg, i+1, val)
Expand All@@ -137,6 +154,22 @@ local function OptionParser(t)
i = i + 1
val = arg[i]
if not val then o.fail('option requires an argument ' .. v) end
if luatype(optdesc.type) == 'number' then
local num = tonumber(val)
if num then
if optdesc.type == 'int' and (num ~= math.floor(num)) then
o.fail(('option %s: number %s not an int'):format(v,val))
num = nil
end
else
o.fail(('option %s: %s not a %s'):format(v,val,optdesc.type))
end
val = num
end
if optdesc.choices and not is_in_list(optdesc.choices, val) then
o.fail(('illegal value for option %s: %s'):format(v,val))
val = nil
end
elseif action == 'store_true' then
val = true
elseif action == 'store_false' then
Expand All@@ -157,6 +190,12 @@ local function OptionParser(t)
io.stdout:write(t.version .. "\n")
os.exit()
end
for _,optdesc in ipairs(option_descriptions) do
local name = optdesc.dest
if optdesc.default and (options[name] == nil) then
options[name] = optdesc.default
end
end
return options, args
end

Expand All@@ -166,7 +205,7 @@ local function OptionParser(t)
for _,flag in ipairs(optdesc) do
local sflagend
if action == nil or action == 'store' then
local metavar = optdesc.metavar or optdesc.dest:upper()
local metavar = optdesc.metavar
sflagend = #flag == 2 and ' ' .. metavar
or '=' .. metavar
else
Expand All@@ -178,16 +217,32 @@ local function OptionParser(t)
end

function o.print_help()
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n")
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0] or '') .. "\n")
io.stdout:write("\n")
io.stdout:write("Options:\n")
local maxwidth = 0
for _,optdesc in ipairs(option_descriptions) do
maxwidth = math.max(maxwidth, #flags_str(optdesc))
end
for _,optdesc in ipairs(option_descriptions) do
local help = optdesc.help or ''
if optdesc.choices or optdesc.default then
if #help>0 then help = help .. ' ' end
help = help .. '('
if optdesc.choices then
for i,v in ipairs(optdesc.choices) do
if i>1 then help = help.. '|' end
help = help..tostring(v)
end
end
if optdesc.choices and optdesc.default then help = help..' ; ' end
if optdesc.default then
help = help .. 'default: '.. tostring(optdesc.default)
end
help = help .. ')'
end
io.stdout:write(" " .. ('%-'..maxwidth..'s '):format(flags_str(optdesc))
.. optdesc.help .. "\n")
.. help .. "\n")
end
end
if t.add_help_option == nil or t.add_help_option == true then
Expand Down
57 changes: 56 additions & 1 deletion test/test.lua
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,62 @@
package.path = './lmod/?.lua;'..package.path

arg = { '-d', '-l', 'DEBUG' , 'localhost', '60000', [0] = 'testdeamon'} -- set global arg

local OP = require 'pythonic.optparse'

-- TODO: add tests
local opt = OP.OptionParser{usage="%prog [options] address port \n", version='0.0', add_help_option=false}
opt.add_option{'-h', '--help', help = 'show this help message and exit', action='store_true' }
opt.add_option{'-d', '--daemon', help = 'Run as daemon', action='store_true' }
opt.add_option{'-l', '--log-level', choices = {'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'}, default = 'INFO', metavar='LEVEL' }
opt.add_option{ '--logfile', help = 'Name of logfile', metavar='FILE' }
opt.add_option{'-c', '--config', help = 'Name of configfile', default = '/etc/opt/test', metavar='FILE' }
opt.add_option{'-s', '--check-interval',help = 'Seconds between checking config', type='int', dest='ci', default = 15 , metavar='SEC'}
opt.add_option{ '--check-float', help = 'Check floating raft', type='float', metavar='liters'}
--opt.print_help()

local options, args = opt.parse_args() -- use global arg

assert(options.log_level=='DEBUG')
assert(options.config=='/etc/opt/test') -- default value
assert(options.daemon==true) -- -d
assert(options.logfile == nil)
assert(options.ci == 15) -- dest, default
assert(options.check_float == nil)
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60000')

-- Next case, now passing arg as paramenter
options, args = opt.parse_args{ 'localhost', '60001', '-l', 'FATAL', '-s', '60' ,
'--config', '/home/test/config', '--logfile', '/var/log/test', '--check-float=3.14' }
assert(options.log_level=='FATAL')
assert(options.config=='/home/test/config') -- config
assert(options.logfile == '/var/log/test')
assert(options.daemon==nil)
assert(options.ci == 60) -- dest, default
assert(options.check_float == 3.14) -- float and --name=var syntax
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60001')


-- harness for error cases:
opt.fail=error
local function check_errorcase(args, errtext)
local res, err = pcall(opt.parse_args, args)
assert(res==false, 'Illegal parameter not caught')
if errtext then
assert(err:find(errtext, nil, true), 'Unexpected error text')
else
print("'"..err.."'")
end
end

-- test error cases:
check_errorcase({ '--bogous', 'foo'}, 'invalid option --bogous')
check_errorcase({ '-l' }, 'option requires an argument -l')
check_errorcase({ '-l', 'DEADLY' }, 'illegal value for option -l: DEADLY')
check_errorcase({ '-s', '6f' }, 'option -s: 6f not a int')
check_errorcase({ '-s', '3.14' }, 'option -s: number 3.14 not an int')

print 'DONE'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
89 changes: 72 additions & 17 deletions lmod/pythonic/optparse.lua
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,13 +41,18 @@ API

Create command line parser.

opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help}
opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help, default=default}

Add command line option specification. This may be called multiple times.
action: 'store'|'store_true'|'store_false'. Default is 'store'
dest: name of returned option table field. Default is the last option-name.
'-' is replaced with '_'
metavar: name used in help text
type: 'int'|'float'|'number'. Default is string

opt.parse_args() --> options, args
opt.parse_args(arglist) --> options, args

Perform argument parsing.
Perform argument parsing. arglist is optional, defaults to global varable 'arg'

DEPENDENCIES

Expand DownExpand Up@@ -85,15 +90,10 @@ LICENSE

--]]

local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.3.20111128'}
local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.4.20120827'}

local ipairs = ipairs
local unpack = unpack
local io = io
local table = table
local os = os
local arg = arg

local arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack
= arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack

local function OptionParser(t)
local usage = t.usage
Expand All@@ -108,17 +108,34 @@ local function OptionParser(t)
os.exit(1)
end

local function is_in_list(list,val)
for _,v in ipairs(list) do
if v == val then return true end
end
end

local function luatype(otype)
if (otype == 'int' or otype == 'float' or otype == 'number' ) then return 'number' end
return 'string'
end

function o.add_option(optdesc)
option_descriptions[#option_descriptions+1] = optdesc
for _,v in ipairs(optdesc) do
option_of[v] = optdesc
end
local dest = optdesc.dest or optdesc[#optdesc]:match('^%-+(.*)') -- fallback to last option
optdesc.dest = dest:gsub('-','_')
optdesc.metavar = optdesc.metavar or dest:upper()
if optdesc.default then
assert( type( optdesc.default) == luatype(optdesc.type), 'default type mismatch, option '..optdesc[#optdesc] )
end
end
function o.parse_args()
function o.parse_args(_arg)
-- expand options (e.g. "--input=file" -> "--input", "file")
local arg = {unpack(arg)}
local arg = {unpack(_arg or arg)}
for i=#arg,1,-1 do local v = arg[i]
local flag, val = v:match('^(%-%-%w+)=(.*)')
local flag, val = v:match('^(%-%-[%w_-]+)=(.*)')
if flag then
arg[i] = flag
table.insert(arg, i+1, val)
Expand All@@ -137,6 +154,22 @@ local function OptionParser(t)
i = i + 1
val = arg[i]
if not val then o.fail('option requires an argument ' .. v) end
if luatype(optdesc.type) == 'number' then
local num = tonumber(val)
if num then
if optdesc.type == 'int' and (num ~= math.floor(num)) then
o.fail(('option %s: number %s not an int'):format(v,val))
num = nil
end
else
o.fail(('option %s: %s not a %s'):format(v,val,optdesc.type))
end
val = num
end
if optdesc.choices and not is_in_list(optdesc.choices, val) then
o.fail(('illegal value for option %s: %s'):format(v,val))
val = nil
end
elseif action == 'store_true' then
val = true
elseif action == 'store_false' then
Expand All@@ -157,6 +190,12 @@ local function OptionParser(t)
io.stdout:write(t.version .. "\n")
os.exit()
end
for _,optdesc in ipairs(option_descriptions) do
local name = optdesc.dest
if optdesc.default and (options[name] == nil) then
options[name] = optdesc.default
end
end
return options, args
end

Expand All@@ -166,7 +205,7 @@ local function OptionParser(t)
for _,flag in ipairs(optdesc) do
local sflagend
if action == nil or action == 'store' then
local metavar = optdesc.metavar or optdesc.dest:upper()
local metavar = optdesc.metavar
sflagend = #flag == 2 and ' ' .. metavar
or '=' .. metavar
else
Expand All@@ -178,16 +217,32 @@ local function OptionParser(t)
end

function o.print_help()
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n")
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0] or '') .. "\n")
io.stdout:write("\n")
io.stdout:write("Options:\n")
local maxwidth = 0
for _,optdesc in ipairs(option_descriptions) do
maxwidth = math.max(maxwidth, #flags_str(optdesc))
end
for _,optdesc in ipairs(option_descriptions) do
local help = optdesc.help or ''
if optdesc.choices or optdesc.default then
if #help>0 then help = help .. ' ' end
help = help .. '('
if optdesc.choices then
for i,v in ipairs(optdesc.choices) do
if i>1 then help = help.. '|' end
help = help..tostring(v)
end
end
if optdesc.choices and optdesc.default then help = help..' ; ' end
if optdesc.default then
help = help .. 'default: '.. tostring(optdesc.default)
end
help = help .. ')'
end
io.stdout:write(" " .. ('%-'..maxwidth..'s '):format(flags_str(optdesc))
.. optdesc.help .. "\n")
.. help .. "\n")
end
end
if t.add_help_option == nil or t.add_help_option == true then
Expand Down
57 changes: 56 additions & 1 deletion test/test.lua
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,62 @@
package.path = './lmod/?.lua;'..package.path

arg = { '-d', '-l', 'DEBUG' , 'localhost', '60000', [0] = 'testdeamon'} -- set global arg

local OP = require 'pythonic.optparse'

-- TODO: add tests
local opt = OP.OptionParser{usage="%prog [options] address port \n", version='0.0', add_help_option=false}
opt.add_option{'-h', '--help', help = 'show this help message and exit', action='store_true' }
opt.add_option{'-d', '--daemon', help = 'Run as daemon', action='store_true' }
opt.add_option{'-l', '--log-level', choices = {'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'}, default = 'INFO', metavar='LEVEL' }
opt.add_option{ '--logfile', help = 'Name of logfile', metavar='FILE' }
opt.add_option{'-c', '--config', help = 'Name of configfile', default = '/etc/opt/test', metavar='FILE' }
opt.add_option{'-s', '--check-interval',help = 'Seconds between checking config', type='int', dest='ci', default = 15 , metavar='SEC'}
opt.add_option{ '--check-float', help = 'Check floating raft', type='float', metavar='liters'}
--opt.print_help()

local options, args = opt.parse_args() -- use global arg

assert(options.log_level=='DEBUG')
assert(options.config=='/etc/opt/test') -- default value
assert(options.daemon==true) -- -d
assert(options.logfile == nil)
assert(options.ci == 15) -- dest, default
assert(options.check_float == nil)
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60000')

-- Next case, now passing arg as paramenter
options, args = opt.parse_args{ 'localhost', '60001', '-l', 'FATAL', '-s', '60' ,
'--config', '/home/test/config', '--logfile', '/var/log/test', '--check-float=3.14' }
assert(options.log_level=='FATAL')
assert(options.config=='/home/test/config') -- config
assert(options.logfile == '/var/log/test')
assert(options.daemon==nil)
assert(options.ci == 60) -- dest, default
assert(options.check_float == 3.14) -- float and --name=var syntax
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60001')


-- harness for error cases:
opt.fail=error
local function check_errorcase(args, errtext)
local res, err = pcall(opt.parse_args, args)
assert(res==false, 'Illegal parameter not caught')
if errtext then
assert(err:find(errtext, nil, true), 'Unexpected error text')
else
print("'"..err.."'")
end
end

-- test error cases:
check_errorcase({ '--bogous', 'foo'}, 'invalid option --bogous')
check_errorcase({ '-l' }, 'option requires an argument -l')
check_errorcase({ '-l', 'DEADLY' }, 'illegal value for option -l: DEADLY')
check_errorcase({ '-s', '6f' }, 'option -s: 6f not a int')
check_errorcase({ '-s', '3.14' }, 'option -s: number 3.14 not an int')

print 'DONE'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
89 changes: 72 additions & 17 deletions lmod/pythonic/optparse.lua
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,13 +41,18 @@ API

Create command line parser.

opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help}
opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help, default=default}

Add command line option specification. This may be called multiple times.
action: 'store'|'store_true'|'store_false'. Default is 'store'
dest: name of returned option table field. Default is the last option-name.
'-' is replaced with '_'
metavar: name used in help text
type: 'int'|'float'|'number'. Default is string

opt.parse_args() --> options, args
opt.parse_args(arglist) --> options, args

Perform argument parsing.
Perform argument parsing. arglist is optional, defaults to global varable 'arg'

DEPENDENCIES

Expand DownExpand Up@@ -85,15 +90,10 @@ LICENSE

--]]

local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.3.20111128'}
local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.4.20120827'}

local ipairs = ipairs
local unpack = unpack
local io = io
local table = table
local os = os
local arg = arg

local arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack
= arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack

local function OptionParser(t)
local usage = t.usage
Expand All@@ -108,17 +108,34 @@ local function OptionParser(t)
os.exit(1)
end

local function is_in_list(list,val)
for _,v in ipairs(list) do
if v == val then return true end
end
end

local function luatype(otype)
if (otype == 'int' or otype == 'float' or otype == 'number' ) then return 'number' end
return 'string'
end

function o.add_option(optdesc)
option_descriptions[#option_descriptions+1] = optdesc
for _,v in ipairs(optdesc) do
option_of[v] = optdesc
end
local dest = optdesc.dest or optdesc[#optdesc]:match('^%-+(.*)') -- fallback to last option
optdesc.dest = dest:gsub('-','_')
optdesc.metavar = optdesc.metavar or dest:upper()
if optdesc.default then
assert( type( optdesc.default) == luatype(optdesc.type), 'default type mismatch, option '..optdesc[#optdesc] )
end
end
function o.parse_args()
function o.parse_args(_arg)
-- expand options (e.g. "--input=file" -> "--input", "file")
local arg = {unpack(arg)}
local arg = {unpack(_arg or arg)}
for i=#arg,1,-1 do local v = arg[i]
local flag, val = v:match('^(%-%-%w+)=(.*)')
local flag, val = v:match('^(%-%-[%w_-]+)=(.*)')
if flag then
arg[i] = flag
table.insert(arg, i+1, val)
Expand All@@ -137,6 +154,22 @@ local function OptionParser(t)
i = i + 1
val = arg[i]
if not val then o.fail('option requires an argument ' .. v) end
if luatype(optdesc.type) == 'number' then
local num = tonumber(val)
if num then
if optdesc.type == 'int' and (num ~= math.floor(num)) then
o.fail(('option %s: number %s not an int'):format(v,val))
num = nil
end
else
o.fail(('option %s: %s not a %s'):format(v,val,optdesc.type))
end
val = num
end
if optdesc.choices and not is_in_list(optdesc.choices, val) then
o.fail(('illegal value for option %s: %s'):format(v,val))
val = nil
end
elseif action == 'store_true' then
val = true
elseif action == 'store_false' then
Expand All@@ -157,6 +190,12 @@ local function OptionParser(t)
io.stdout:write(t.version .. "\n")
os.exit()
end
for _,optdesc in ipairs(option_descriptions) do
local name = optdesc.dest
if optdesc.default and (options[name] == nil) then
options[name] = optdesc.default
end
end
return options, args
end

Expand All@@ -166,7 +205,7 @@ local function OptionParser(t)
for _,flag in ipairs(optdesc) do
local sflagend
if action == nil or action == 'store' then
local metavar = optdesc.metavar or optdesc.dest:upper()
local metavar = optdesc.metavar
sflagend = #flag == 2 and ' ' .. metavar
or '=' .. metavar
else
Expand All@@ -178,16 +217,32 @@ local function OptionParser(t)
end

function o.print_help()
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n")
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0] or '') .. "\n")
io.stdout:write("\n")
io.stdout:write("Options:\n")
local maxwidth = 0
for _,optdesc in ipairs(option_descriptions) do
maxwidth = math.max(maxwidth, #flags_str(optdesc))
end
for _,optdesc in ipairs(option_descriptions) do
local help = optdesc.help or ''
if optdesc.choices or optdesc.default then
if #help>0 then help = help .. ' ' end
help = help .. '('
if optdesc.choices then
for i,v in ipairs(optdesc.choices) do
if i>1 then help = help.. '|' end
help = help..tostring(v)
end
end
if optdesc.choices and optdesc.default then help = help..' ; ' end
if optdesc.default then
help = help .. 'default: '.. tostring(optdesc.default)
end
help = help .. ')'
end
io.stdout:write(" " .. ('%-'..maxwidth..'s '):format(flags_str(optdesc))
.. optdesc.help .. "\n")
.. help .. "\n")
end
end
if t.add_help_option == nil or t.add_help_option == true then
Expand Down
57 changes: 56 additions & 1 deletion test/test.lua
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,62 @@
package.path = './lmod/?.lua;'..package.path

arg = { '-d', '-l', 'DEBUG' , 'localhost', '60000', [0] = 'testdeamon'} -- set global arg

local OP = require 'pythonic.optparse'

-- TODO: add tests
local opt = OP.OptionParser{usage="%prog [options] address port \n", version='0.0', add_help_option=false}
opt.add_option{'-h', '--help', help = 'show this help message and exit', action='store_true' }
opt.add_option{'-d', '--daemon', help = 'Run as daemon', action='store_true' }
opt.add_option{'-l', '--log-level', choices = {'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'}, default = 'INFO', metavar='LEVEL' }
opt.add_option{ '--logfile', help = 'Name of logfile', metavar='FILE' }
opt.add_option{'-c', '--config', help = 'Name of configfile', default = '/etc/opt/test', metavar='FILE' }
opt.add_option{'-s', '--check-interval',help = 'Seconds between checking config', type='int', dest='ci', default = 15 , metavar='SEC'}
opt.add_option{ '--check-float', help = 'Check floating raft', type='float', metavar='liters'}
--opt.print_help()

local options, args = opt.parse_args() -- use global arg

assert(options.log_level=='DEBUG')
assert(options.config=='/etc/opt/test') -- default value
assert(options.daemon==true) -- -d
assert(options.logfile == nil)
assert(options.ci == 15) -- dest, default
assert(options.check_float == nil)
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60000')

-- Next case, now passing arg as paramenter
options, args = opt.parse_args{ 'localhost', '60001', '-l', 'FATAL', '-s', '60' ,
'--config', '/home/test/config', '--logfile', '/var/log/test', '--check-float=3.14' }
assert(options.log_level=='FATAL')
assert(options.config=='/home/test/config') -- config
assert(options.logfile == '/var/log/test')
assert(options.daemon==nil)
assert(options.ci == 60) -- dest, default
assert(options.check_float == 3.14) -- float and --name=var syntax
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60001')


-- harness for error cases:
opt.fail=error
local function check_errorcase(args, errtext)
local res, err = pcall(opt.parse_args, args)
assert(res==false, 'Illegal parameter not caught')
if errtext then
assert(err:find(errtext, nil, true), 'Unexpected error text')
else
print("'"..err.."'")
end
end

-- test error cases:
check_errorcase({ '--bogous', 'foo'}, 'invalid option --bogous')
check_errorcase({ '-l' }, 'option requires an argument -l')
check_errorcase({ '-l', 'DEADLY' }, 'illegal value for option -l: DEADLY')
check_errorcase({ '-s', '6f' }, 'option -s: 6f not a int')
check_errorcase({ '-s', '3.14' }, 'option -s: number 3.14 not an int')

print 'DONE'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
89 changes: 72 additions & 17 deletions lmod/pythonic/optparse.lua
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,13 +41,18 @@ API

Create command line parser.

opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help}
opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help, default=default}

Add command line option specification. This may be called multiple times.
action: 'store'|'store_true'|'store_false'. Default is 'store'
dest: name of returned option table field. Default is the last option-name.
'-' is replaced with '_'
metavar: name used in help text
type: 'int'|'float'|'number'. Default is string

opt.parse_args() --> options, args
opt.parse_args(arglist) --> options, args

Perform argument parsing.
Perform argument parsing. arglist is optional, defaults to global varable 'arg'

DEPENDENCIES

Expand DownExpand Up@@ -85,15 +90,10 @@ LICENSE

--]]

local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.3.20111128'}
local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.4.20120827'}

local ipairs = ipairs
local unpack = unpack
local io = io
local table = table
local os = os
local arg = arg

local arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack
= arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack

local function OptionParser(t)
local usage = t.usage
Expand All@@ -108,17 +108,34 @@ local function OptionParser(t)
os.exit(1)
end

local function is_in_list(list,val)
for _,v in ipairs(list) do
if v == val then return true end
end
end

local function luatype(otype)
if (otype == 'int' or otype == 'float' or otype == 'number' ) then return 'number' end
return 'string'
end

function o.add_option(optdesc)
option_descriptions[#option_descriptions+1] = optdesc
for _,v in ipairs(optdesc) do
option_of[v] = optdesc
end
local dest = optdesc.dest or optdesc[#optdesc]:match('^%-+(.*)') -- fallback to last option
optdesc.dest = dest:gsub('-','_')
optdesc.metavar = optdesc.metavar or dest:upper()
if optdesc.default then
assert( type( optdesc.default) == luatype(optdesc.type), 'default type mismatch, option '..optdesc[#optdesc] )
end
end
function o.parse_args()
function o.parse_args(_arg)
-- expand options (e.g. "--input=file" -> "--input", "file")
local arg = {unpack(arg)}
local arg = {unpack(_arg or arg)}
for i=#arg,1,-1 do local v = arg[i]
local flag, val = v:match('^(%-%-%w+)=(.*)')
local flag, val = v:match('^(%-%-[%w_-]+)=(.*)')
if flag then
arg[i] = flag
table.insert(arg, i+1, val)
Expand All@@ -137,6 +154,22 @@ local function OptionParser(t)
i = i + 1
val = arg[i]
if not val then o.fail('option requires an argument ' .. v) end
if luatype(optdesc.type) == 'number' then
local num = tonumber(val)
if num then
if optdesc.type == 'int' and (num ~= math.floor(num)) then
o.fail(('option %s: number %s not an int'):format(v,val))
num = nil
end
else
o.fail(('option %s: %s not a %s'):format(v,val,optdesc.type))
end
val = num
end
if optdesc.choices and not is_in_list(optdesc.choices, val) then
o.fail(('illegal value for option %s: %s'):format(v,val))
val = nil
end
elseif action == 'store_true' then
val = true
elseif action == 'store_false' then
Expand All@@ -157,6 +190,12 @@ local function OptionParser(t)
io.stdout:write(t.version .. "\n")
os.exit()
end
for _,optdesc in ipairs(option_descriptions) do
local name = optdesc.dest
if optdesc.default and (options[name] == nil) then
options[name] = optdesc.default
end
end
return options, args
end

Expand All@@ -166,7 +205,7 @@ local function OptionParser(t)
for _,flag in ipairs(optdesc) do
local sflagend
if action == nil or action == 'store' then
local metavar = optdesc.metavar or optdesc.dest:upper()
local metavar = optdesc.metavar
sflagend = #flag == 2 and ' ' .. metavar
or '=' .. metavar
else
Expand All@@ -178,16 +217,32 @@ local function OptionParser(t)
end

function o.print_help()
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n")
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0] or '') .. "\n")
io.stdout:write("\n")
io.stdout:write("Options:\n")
local maxwidth = 0
for _,optdesc in ipairs(option_descriptions) do
maxwidth = math.max(maxwidth, #flags_str(optdesc))
end
for _,optdesc in ipairs(option_descriptions) do
local help = optdesc.help or ''
if optdesc.choices or optdesc.default then
if #help>0 then help = help .. ' ' end
help = help .. '('
if optdesc.choices then
for i,v in ipairs(optdesc.choices) do
if i>1 then help = help.. '|' end
help = help..tostring(v)
end
end
if optdesc.choices and optdesc.default then help = help..' ; ' end
if optdesc.default then
help = help .. 'default: '.. tostring(optdesc.default)
end
help = help .. ')'
end
io.stdout:write(" " .. ('%-'..maxwidth..'s '):format(flags_str(optdesc))
.. optdesc.help .. "\n")
.. help .. "\n")
end
end
if t.add_help_option == nil or t.add_help_option == true then
Expand Down
57 changes: 56 additions & 1 deletion test/test.lua
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,62 @@
package.path = './lmod/?.lua;'..package.path

arg = { '-d', '-l', 'DEBUG' , 'localhost', '60000', [0] = 'testdeamon'} -- set global arg

local OP = require 'pythonic.optparse'

-- TODO: add tests
local opt = OP.OptionParser{usage="%prog [options] address port \n", version='0.0', add_help_option=false}
opt.add_option{'-h', '--help', help = 'show this help message and exit', action='store_true' }
opt.add_option{'-d', '--daemon', help = 'Run as daemon', action='store_true' }
opt.add_option{'-l', '--log-level', choices = {'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'}, default = 'INFO', metavar='LEVEL' }
opt.add_option{ '--logfile', help = 'Name of logfile', metavar='FILE' }
opt.add_option{'-c', '--config', help = 'Name of configfile', default = '/etc/opt/test', metavar='FILE' }
opt.add_option{'-s', '--check-interval',help = 'Seconds between checking config', type='int', dest='ci', default = 15 , metavar='SEC'}
opt.add_option{ '--check-float', help = 'Check floating raft', type='float', metavar='liters'}
--opt.print_help()

local options, args = opt.parse_args() -- use global arg

assert(options.log_level=='DEBUG')
assert(options.config=='/etc/opt/test') -- default value
assert(options.daemon==true) -- -d
assert(options.logfile == nil)
assert(options.ci == 15) -- dest, default
assert(options.check_float == nil)
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60000')

-- Next case, now passing arg as paramenter
options, args = opt.parse_args{ 'localhost', '60001', '-l', 'FATAL', '-s', '60' ,
'--config', '/home/test/config', '--logfile', '/var/log/test', '--check-float=3.14' }
assert(options.log_level=='FATAL')
assert(options.config=='/home/test/config') -- config
assert(options.logfile == '/var/log/test')
assert(options.daemon==nil)
assert(options.ci == 60) -- dest, default
assert(options.check_float == 3.14) -- float and --name=var syntax
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60001')


-- harness for error cases:
opt.fail=error
local function check_errorcase(args, errtext)
local res, err = pcall(opt.parse_args, args)
assert(res==false, 'Illegal parameter not caught')
if errtext then
assert(err:find(errtext, nil, true), 'Unexpected error text')
else
print("'"..err.."'")
end
end

-- test error cases:
check_errorcase({ '--bogous', 'foo'}, 'invalid option --bogous')
check_errorcase({ '-l' }, 'option requires an argument -l')
check_errorcase({ '-l', 'DEADLY' }, 'illegal value for option -l: DEADLY')
check_errorcase({ '-s', '6f' }, 'option -s: 6f not a int')
check_errorcase({ '-s', '3.14' }, 'option -s: number 3.14 not an int')

print 'DONE'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
89 changes: 72 additions & 17 deletions lmod/pythonic/optparse.lua
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,13 +41,18 @@ API

Create command line parser.

opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help}
opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help, default=default}

Add command line option specification. This may be called multiple times.
action: 'store'|'store_true'|'store_false'. Default is 'store'
dest: name of returned option table field. Default is the last option-name.
'-' is replaced with '_'
metavar: name used in help text
type: 'int'|'float'|'number'. Default is string

opt.parse_args() --> options, args
opt.parse_args(arglist) --> options, args

Perform argument parsing.
Perform argument parsing. arglist is optional, defaults to global varable 'arg'

DEPENDENCIES

Expand DownExpand Up@@ -85,15 +90,10 @@ LICENSE

--]]

local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.3.20111128'}
local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.4.20120827'}

local ipairs = ipairs
local unpack = unpack
local io = io
local table = table
local os = os
local arg = arg

local arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack
= arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack

local function OptionParser(t)
local usage = t.usage
Expand All@@ -108,17 +108,34 @@ local function OptionParser(t)
os.exit(1)
end

local function is_in_list(list,val)
for _,v in ipairs(list) do
if v == val then return true end
end
end

local function luatype(otype)
if (otype == 'int' or otype == 'float' or otype == 'number' ) then return 'number' end
return 'string'
end

function o.add_option(optdesc)
option_descriptions[#option_descriptions+1] = optdesc
for _,v in ipairs(optdesc) do
option_of[v] = optdesc
end
local dest = optdesc.dest or optdesc[#optdesc]:match('^%-+(.*)') -- fallback to last option
optdesc.dest = dest:gsub('-','_')
optdesc.metavar = optdesc.metavar or dest:upper()
if optdesc.default then
assert( type( optdesc.default) == luatype(optdesc.type), 'default type mismatch, option '..optdesc[#optdesc] )
end
end
function o.parse_args()
function o.parse_args(_arg)
-- expand options (e.g. "--input=file" -> "--input", "file")
local arg = {unpack(arg)}
local arg = {unpack(_arg or arg)}
for i=#arg,1,-1 do local v = arg[i]
local flag, val = v:match('^(%-%-%w+)=(.*)')
local flag, val = v:match('^(%-%-[%w_-]+)=(.*)')
if flag then
arg[i] = flag
table.insert(arg, i+1, val)
Expand All@@ -137,6 +154,22 @@ local function OptionParser(t)
i = i + 1
val = arg[i]
if not val then o.fail('option requires an argument ' .. v) end
if luatype(optdesc.type) == 'number' then
local num = tonumber(val)
if num then
if optdesc.type == 'int' and (num ~= math.floor(num)) then
o.fail(('option %s: number %s not an int'):format(v,val))
num = nil
end
else
o.fail(('option %s: %s not a %s'):format(v,val,optdesc.type))
end
val = num
end
if optdesc.choices and not is_in_list(optdesc.choices, val) then
o.fail(('illegal value for option %s: %s'):format(v,val))
val = nil
end
elseif action == 'store_true' then
val = true
elseif action == 'store_false' then
Expand All@@ -157,6 +190,12 @@ local function OptionParser(t)
io.stdout:write(t.version .. "\n")
os.exit()
end
for _,optdesc in ipairs(option_descriptions) do
local name = optdesc.dest
if optdesc.default and (options[name] == nil) then
options[name] = optdesc.default
end
end
return options, args
end

Expand All@@ -166,7 +205,7 @@ local function OptionParser(t)
for _,flag in ipairs(optdesc) do
local sflagend
if action == nil or action == 'store' then
local metavar = optdesc.metavar or optdesc.dest:upper()
local metavar = optdesc.metavar
sflagend = #flag == 2 and ' ' .. metavar
or '=' .. metavar
else
Expand All@@ -178,16 +217,32 @@ local function OptionParser(t)
end

function o.print_help()
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n")
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0] or '') .. "\n")
io.stdout:write("\n")
io.stdout:write("Options:\n")
local maxwidth = 0
for _,optdesc in ipairs(option_descriptions) do
maxwidth = math.max(maxwidth, #flags_str(optdesc))
end
for _,optdesc in ipairs(option_descriptions) do
local help = optdesc.help or ''
if optdesc.choices or optdesc.default then
if #help>0 then help = help .. ' ' end
help = help .. '('
if optdesc.choices then
for i,v in ipairs(optdesc.choices) do
if i>1 then help = help.. '|' end
help = help..tostring(v)
end
end
if optdesc.choices and optdesc.default then help = help..' ; ' end
if optdesc.default then
help = help .. 'default: '.. tostring(optdesc.default)
end
help = help .. ')'
end
io.stdout:write(" " .. ('%-'..maxwidth..'s '):format(flags_str(optdesc))
.. optdesc.help .. "\n")
.. help .. "\n")
end
end
if t.add_help_option == nil or t.add_help_option == true then
Expand Down
57 changes: 56 additions & 1 deletion test/test.lua
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,62 @@
package.path = './lmod/?.lua;'..package.path

arg = { '-d', '-l', 'DEBUG' , 'localhost', '60000', [0] = 'testdeamon'} -- set global arg

local OP = require 'pythonic.optparse'

-- TODO: add tests
local opt = OP.OptionParser{usage="%prog [options] address port \n", version='0.0', add_help_option=false}
opt.add_option{'-h', '--help', help = 'show this help message and exit', action='store_true' }
opt.add_option{'-d', '--daemon', help = 'Run as daemon', action='store_true' }
opt.add_option{'-l', '--log-level', choices = {'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'}, default = 'INFO', metavar='LEVEL' }
opt.add_option{ '--logfile', help = 'Name of logfile', metavar='FILE' }
opt.add_option{'-c', '--config', help = 'Name of configfile', default = '/etc/opt/test', metavar='FILE' }
opt.add_option{'-s', '--check-interval',help = 'Seconds between checking config', type='int', dest='ci', default = 15 , metavar='SEC'}
opt.add_option{ '--check-float', help = 'Check floating raft', type='float', metavar='liters'}
--opt.print_help()

local options, args = opt.parse_args() -- use global arg

assert(options.log_level=='DEBUG')
assert(options.config=='/etc/opt/test') -- default value
assert(options.daemon==true) -- -d
assert(options.logfile == nil)
assert(options.ci == 15) -- dest, default
assert(options.check_float == nil)
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60000')

-- Next case, now passing arg as paramenter
options, args = opt.parse_args{ 'localhost', '60001', '-l', 'FATAL', '-s', '60' ,
'--config', '/home/test/config', '--logfile', '/var/log/test', '--check-float=3.14' }
assert(options.log_level=='FATAL')
assert(options.config=='/home/test/config') -- config
assert(options.logfile == '/var/log/test')
assert(options.daemon==nil)
assert(options.ci == 60) -- dest, default
assert(options.check_float == 3.14) -- float and --name=var syntax
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60001')


-- harness for error cases:
opt.fail=error
local function check_errorcase(args, errtext)
local res, err = pcall(opt.parse_args, args)
assert(res==false, 'Illegal parameter not caught')
if errtext then
assert(err:find(errtext, nil, true), 'Unexpected error text')
else
print("'"..err.."'")
end
end

-- test error cases:
check_errorcase({ '--bogous', 'foo'}, 'invalid option --bogous')
check_errorcase({ '-l' }, 'option requires an argument -l')
check_errorcase({ '-l', 'DEADLY' }, 'illegal value for option -l: DEADLY')
check_errorcase({ '-s', '6f' }, 'option -s: 6f not a int')
check_errorcase({ '-s', '3.14' }, 'option -s: number 3.14 not an int')

print 'DONE'
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
89 changes: 72 additions & 17 deletions lmod/pythonic/optparse.lua
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,13 +41,18 @@ API

Create command line parser.

opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help}
opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help, default=default}

Add command line option specification. This may be called multiple times.
action: 'store'|'store_true'|'store_false'. Default is 'store'
dest: name of returned option table field. Default is the last option-name.
'-' is replaced with '_'
metavar: name used in help text
type: 'int'|'float'|'number'. Default is string

opt.parse_args() --> options, args
opt.parse_args(arglist) --> options, args

Perform argument parsing.
Perform argument parsing. arglist is optional, defaults to global varable 'arg'

DEPENDENCIES

Expand DownExpand Up@@ -85,15 +90,10 @@ LICENSE

--]]

local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.3.20111128'}
local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.4.20120827'}

local ipairs = ipairs
local unpack = unpack
local io = io
local table = table
local os = os
local arg = arg

local arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack
= arg,assert,io,ipairs,math,os,table,tonumber,tostring,type,unpack

local function OptionParser(t)
local usage = t.usage
Expand All@@ -108,17 +108,34 @@ local function OptionParser(t)
os.exit(1)
end

local function is_in_list(list,val)
for _,v in ipairs(list) do
if v == val then return true end
end
end

local function luatype(otype)
if (otype == 'int' or otype == 'float' or otype == 'number' ) then return 'number' end
return 'string'
end

function o.add_option(optdesc)
option_descriptions[#option_descriptions+1] = optdesc
for _,v in ipairs(optdesc) do
option_of[v] = optdesc
end
local dest = optdesc.dest or optdesc[#optdesc]:match('^%-+(.*)') -- fallback to last option
optdesc.dest = dest:gsub('-','_')
optdesc.metavar = optdesc.metavar or dest:upper()
if optdesc.default then
assert( type( optdesc.default) == luatype(optdesc.type), 'default type mismatch, option '..optdesc[#optdesc] )
end
end
function o.parse_args()
function o.parse_args(_arg)
-- expand options (e.g. "--input=file" -> "--input", "file")
local arg = {unpack(arg)}
local arg = {unpack(_arg or arg)}
for i=#arg,1,-1 do local v = arg[i]
local flag, val = v:match('^(%-%-%w+)=(.*)')
local flag, val = v:match('^(%-%-[%w_-]+)=(.*)')
if flag then
arg[i] = flag
table.insert(arg, i+1, val)
Expand All@@ -137,6 +154,22 @@ local function OptionParser(t)
i = i + 1
val = arg[i]
if not val then o.fail('option requires an argument ' .. v) end
if luatype(optdesc.type) == 'number' then
local num = tonumber(val)
if num then
if optdesc.type == 'int' and (num ~= math.floor(num)) then
o.fail(('option %s: number %s not an int'):format(v,val))
num = nil
end
else
o.fail(('option %s: %s not a %s'):format(v,val,optdesc.type))
end
val = num
end
if optdesc.choices and not is_in_list(optdesc.choices, val) then
o.fail(('illegal value for option %s: %s'):format(v,val))
val = nil
end
elseif action == 'store_true' then
val = true
elseif action == 'store_false' then
Expand All@@ -157,6 +190,12 @@ local function OptionParser(t)
io.stdout:write(t.version .. "\n")
os.exit()
end
for _,optdesc in ipairs(option_descriptions) do
local name = optdesc.dest
if optdesc.default and (options[name] == nil) then
options[name] = optdesc.default
end
end
return options, args
end

Expand All@@ -166,7 +205,7 @@ local function OptionParser(t)
for _,flag in ipairs(optdesc) do
local sflagend
if action == nil or action == 'store' then
local metavar = optdesc.metavar or optdesc.dest:upper()
local metavar = optdesc.metavar
sflagend = #flag == 2 and ' ' .. metavar
or '=' .. metavar
else
Expand All@@ -178,16 +217,32 @@ local function OptionParser(t)
end

function o.print_help()
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n")
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0] or '') .. "\n")
io.stdout:write("\n")
io.stdout:write("Options:\n")
local maxwidth = 0
for _,optdesc in ipairs(option_descriptions) do
maxwidth = math.max(maxwidth, #flags_str(optdesc))
end
for _,optdesc in ipairs(option_descriptions) do
local help = optdesc.help or ''
if optdesc.choices or optdesc.default then
if #help>0 then help = help .. ' ' end
help = help .. '('
if optdesc.choices then
for i,v in ipairs(optdesc.choices) do
if i>1 then help = help.. '|' end
help = help..tostring(v)
end
end
if optdesc.choices and optdesc.default then help = help..' ; ' end
if optdesc.default then
help = help .. 'default: '.. tostring(optdesc.default)
end
help = help .. ')'
end
io.stdout:write(" " .. ('%-'..maxwidth..'s '):format(flags_str(optdesc))
.. optdesc.help .. "\n")
.. help .. "\n")
end
end
if t.add_help_option == nil or t.add_help_option == true then
Expand Down
57 changes: 56 additions & 1 deletion test/test.lua
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,62 @@
package.path = './lmod/?.lua;'..package.path

arg = { '-d', '-l', 'DEBUG' , 'localhost', '60000', [0] = 'testdeamon'} -- set global arg

local OP = require 'pythonic.optparse'

-- TODO: add tests
local opt = OP.OptionParser{usage="%prog [options] address port \n", version='0.0', add_help_option=false}
opt.add_option{'-h', '--help', help = 'show this help message and exit', action='store_true' }
opt.add_option{'-d', '--daemon', help = 'Run as daemon', action='store_true' }
opt.add_option{'-l', '--log-level', choices = {'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'}, default = 'INFO', metavar='LEVEL' }
opt.add_option{ '--logfile', help = 'Name of logfile', metavar='FILE' }
opt.add_option{'-c', '--config', help = 'Name of configfile', default = '/etc/opt/test', metavar='FILE' }
opt.add_option{'-s', '--check-interval',help = 'Seconds between checking config', type='int', dest='ci', default = 15 , metavar='SEC'}
opt.add_option{ '--check-float', help = 'Check floating raft', type='float', metavar='liters'}
--opt.print_help()

local options, args = opt.parse_args() -- use global arg

assert(options.log_level=='DEBUG')
assert(options.config=='/etc/opt/test') -- default value
assert(options.daemon==true) -- -d
assert(options.logfile == nil)
assert(options.ci == 15) -- dest, default
assert(options.check_float == nil)
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60000')

-- Next case, now passing arg as paramenter
options, args = opt.parse_args{ 'localhost', '60001', '-l', 'FATAL', '-s', '60' ,
'--config', '/home/test/config', '--logfile', '/var/log/test', '--check-float=3.14' }
assert(options.log_level=='FATAL')
assert(options.config=='/home/test/config') -- config
assert(options.logfile == '/var/log/test')
assert(options.daemon==nil)
assert(options.ci == 60) -- dest, default
assert(options.check_float == 3.14) -- float and --name=var syntax
assert(#args == 2)
assert(args[1] == 'localhost')
assert(args[2] == '60001')


-- harness for error cases:
opt.fail=error
local function check_errorcase(args, errtext)
local res, err = pcall(opt.parse_args, args)
assert(res==false, 'Illegal parameter not caught')
if errtext then
assert(err:find(errtext, nil, true), 'Unexpected error text')
else
print("'"..err.."'")
end
end

-- test error cases:
check_errorcase({ '--bogous', 'foo'}, 'invalid option --bogous')
check_errorcase({ '-l' }, 'option requires an argument -l')
check_errorcase({ '-l', 'DEADLY' }, 'illegal value for option -l: DEADLY')
check_errorcase({ '-s', '6f' }, 'option -s: 6f not a int')
check_errorcase({ '-s', '3.14' }, 'option -s: number 3.14 not an int')

print 'DONE'