From 8b512adbbcf62f49b3e92410e643c86f2e70908a Mon Sep 17 00:00:00 2001 From: Bruce Hill Date: Sun, 15 Sep 2024 17:50:43 -0400 Subject: Move each example to its own folder --- examples/ini/example.ini | 8 +++++++ examples/ini/ini.tm | 59 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 examples/ini/example.ini create mode 100644 examples/ini/ini.tm (limited to 'examples/ini') diff --git a/examples/ini/example.ini b/examples/ini/example.ini new file mode 100644 index 00000000..782dc76f --- /dev/null +++ b/examples/ini/example.ini @@ -0,0 +1,8 @@ +[ Book ] +title = Dirk Gently's Holistic Detective Agency +author = Douglas Adams +published = 1987 + +[ Protagonist ] +name = Dirk Gently +age = 42 diff --git a/examples/ini/ini.tm b/examples/ini/ini.tm new file mode 100644 index 00000000..c0d490cb --- /dev/null +++ b/examples/ini/ini.tm @@ -0,0 +1,59 @@ +_USAGE := " + Usage: ini "[section[/key]]" +" +_HELP := " + ini: A .ini config file reader tool. + $_USAGE +" + +func parse_ini(path:Path)->{Text:{Text:Text}}: + text := path:read():or_exit("Could not read INI file: $\[31;1]$(path.text_content)$\[]") + 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() + skip if line:starts_with(";") or line:starts_with("#") + if line:matches($/[?]/): + section_name := line:replace($/[?]/, "\1"):trim():lower() + 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} + +func main(path:Path, key:Text): + keys := key:split($Pattern"/") + if keys.length > 2: + exit(" + Too many arguments! + $_USAGE + ") + + data := parse_ini(path) + if keys.length < 1 or keys[1] == '*': + !! $data + return + + section := keys[1]:lower() + section_data := data:get(section):or_exit(" + Invalid section name: $\[31;1]$section$\[] + Valid names: $\[1]$(", ":join([k:quoted() for k in data.keys]))$\[] + ") + if keys.length < 2 or keys[2] == '*': + !! $section_data + return + + section_key := keys[2]:lower() + value := section_data:get(section_key):or_exit(" + Invalid key: $\[31;1]$section_key$\[] + Valid keys: $\[1]$(", ":join([s:quoted() for s in section_data.keys]))$\[] + ") + say(value) -- cgit v1.2.3