summaryrefslogtreecommitdiffstats
path: root/lib/getopts.lua
blob: 45aca7be06f4d63c772e0302dabbe350d35c1517 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
module (..., package.seeall)

function getoptsfromfile (file, search, filter)
	local opts = nil
	local conf_file = fs.read_file_as_array ( file )
	for i=1,table.maxn(conf_file) do
		local l = conf_file[i]
		if not string.find ( l, "^[;#].*" ) then
			local a = string.match ( l, "^%s*(%S*)=" )
			if (a) then
				if not (search) or (search == a) then
					local b = string.match ( l, '^%s*%S*%=%"?(.-)%s*%"?%s*$' )
					local optstable = getopts.opts_to_table(b,filter)
					if (optstable) or not (filter) then
						if not (opts) then
							opts = {}
						end
						if (optstable) then
							opts[a] = optstable
						else
							opts[a] = b
						end
					end
				end
			end
		end
	end
	return opts
end

function opts_to_table ( optstring, filter )
	local optsparams = nil
	local optstr = string.match(optstring, "^\"?(.*)%\"?")		-- Filter away leading/trailing "
	if optstr then
	local option = ""
	local optvalue = ""
		for j = 1, string.len(optstr) do
		if (string.sub(optstr, j, j) == "-") then
			option=string.sub(optstr, j, j+1)
				if not (filter) or (filter == option) then
					for k = j+1, string.len(optstr) do
						if not (optsparams) then
							optsparams = {}
						end
						if (string.sub(optstr, k, k) == "-") then
							optsparams[option] = string.match(string.sub(optstr, j+2, k-1),"^%s*(.*)%s?")
							break
						end
						if (k == string.len(optstr)) then
							optsparams[option] = string.match(string.sub(optstr, j+2, k),"^%s*(.*)%s?")
							break
						end
					end
				end
			end
		end
	end
	return optsparams
end