tomo/examples/ini/ini.tm

59 lines
1.8 KiB
Plaintext
Raw Normal View History

_USAGE := "
2024-09-06 09:19:52 -07:00
Usage: ini <filename> "[section[/key]]"
"
_HELP := "
2024-09-06 09:19:52 -07:00
ini: A .ini config file reader tool.
$_USAGE
2024-09-06 09:19:52 -07:00
"
func parse_ini(path:Path -> {Text:{Text:Text}}):
text := path:read() or exit("Could not read INI file: $\[31;1]$(path.text_content)$\[]")
2024-09-06 11:16:45 -07:00
sections := {:Text:@{Text:Text}}
current_section := @{:Text:Text}
# 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
func main(path:Path, key:Text?):
keys := (key or ""):split($|/|)
2024-09-06 09:19:52 -07:00
if keys.length > 2:
2024-09-15 13:42:42 -07:00
exit("
2024-09-06 09:19:52 -07:00
Too many arguments!
$_USAGE
2024-09-06 09:19:52 -07:00
")
2024-09-09 12:02:47 -07:00
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()
section_data := data:get(section) or exit("
2024-09-15 13:53:42 -07:00
Invalid section name: $\[31;1]$section$\[]
Valid names: $\[1]$(", ":join([k:quoted() for k in data.keys]))$\[]
")
2024-09-06 09:19:52 -07:00
if keys.length < 2 or keys[2] == '*':
!! $section_data
return
section_key := keys[2]:lower()
value := section_data:get(section_key) or exit("
2024-09-15 13:53:42 -07:00
Invalid key: $\[31;1]$section_key$\[]
Valid keys: $\[1]$(", ":join([s:quoted() for s in section_data.keys]))$\[]
")
say(value)