2024-09-06 21:26:30 -07:00
|
|
|
_USAGE := "
|
2024-09-06 09:19:52 -07:00
|
|
|
Usage: ini <filename> "[section[/key]]"
|
|
|
|
"
|
2024-09-06 21:26:30 -07:00
|
|
|
_HELP := "
|
2024-09-06 09:19:52 -07:00
|
|
|
ini: A .ini config file reader tool.
|
2024-09-06 21:26:30 -07:00
|
|
|
$_USAGE
|
2024-09-06 09:19:52 -07:00
|
|
|
"
|
|
|
|
|
2024-09-09 12:02:47 -07:00
|
|
|
func parse_ini(path:Path)->{Text:{Text:Text}}:
|
|
|
|
text := path:read()
|
2024-09-06 11:16:45 -07:00
|
|
|
sections := {:Text:@{Text:Text}}
|
|
|
|
current_section := @{:Text:Text}
|
|
|
|
sections:set("", current_section)
|
|
|
|
|
|
|
|
# Line wraps:
|
|
|
|
text = text:replace($/\{1 nl}{0+space}/, " ")
|
|
|
|
|
|
|
|
for line in text:lines():
|
|
|
|
line = line:trim()
|
2024-09-09 12:02:47 -07:00
|
|
|
skip if line:starts_with(";") or line:starts_with("#")
|
2024-09-13 10:05:04 -07:00
|
|
|
if line:matches($/[?]/):
|
2024-09-09 12:02:47 -07:00
|
|
|
section_name := line:replace($/[?]/, "\1"):trim():lower()
|
2024-09-06 11:16:45 -07:00
|
|
|
current_section = @{:Text:Text}
|
|
|
|
sections:set(section_name, current_section)
|
|
|
|
else if line:matches($/{..}={..}/):
|
|
|
|
key := line:replace($/{..}={..}/, "\1"):trim():lower()
|
|
|
|
value := line:replace($/{..}={..}/, "\2"):trim()
|
|
|
|
current_section:set(key, value)
|
|
|
|
|
|
|
|
return {k:v[] for k,v in sections}
|
2024-09-06 09:19:52 -07:00
|
|
|
|
2024-09-09 12:02:47 -07:00
|
|
|
func main(path:Path, key:Text):
|
2024-09-06 09:19:52 -07:00
|
|
|
keys := key:split($Pattern"/")
|
|
|
|
if keys.length > 2:
|
2024-09-06 21:48:13 -07:00
|
|
|
exit(1, message="
|
2024-09-06 09:19:52 -07:00
|
|
|
Too many arguments!
|
2024-09-06 21:26:30 -07:00
|
|
|
$_USAGE
|
2024-09-06 09:19:52 -07:00
|
|
|
")
|
|
|
|
|
2024-09-09 12:02:47 -07:00
|
|
|
if not path:is_file() or path:is_pipe():
|
|
|
|
exit(code=1, "Could not read file: $(path.text_content)")
|
|
|
|
|
|
|
|
data := parse_ini(path)
|
2024-09-06 09:19:52 -07:00
|
|
|
if keys.length < 1 or keys[1] == '*':
|
|
|
|
!! $data
|
|
|
|
return
|
|
|
|
|
|
|
|
section := keys[1]:lower()
|
|
|
|
if not data:has(section):
|
2024-09-06 21:48:13 -07:00
|
|
|
exit(1, message="Invalid section name: $section; valid names: $(", ":join([k:quoted() for k in data.keys]))")
|
2024-09-06 09:19:52 -07:00
|
|
|
|
|
|
|
section_data := data:get(section)
|
|
|
|
if keys.length < 2 or keys[2] == '*':
|
|
|
|
!! $section_data
|
|
|
|
return
|
|
|
|
|
|
|
|
section_key := keys[2]:lower()
|
|
|
|
if not section_data:has(section_key):
|
2024-09-06 21:48:13 -07:00
|
|
|
exit(1, message="Invalid key: $section_key; valid keys: $(", ":join(section_data.keys))")
|
2024-09-06 09:19:52 -07:00
|
|
|
|
|
|
|
say(section_data:get(section_key))
|