mirror of
https://github.com/RubyMetric/chsrc
synced 2025-07-17 12:47:28 +08:00
Add ConfigParser
This commit is contained in:
parent
f8473dfac7
commit
659fbc53ce
235
rawstr4c/lib/ConfigParser.rakumod
Normal file
235
rawstr4c/lib/ConfigParser.rakumod
Normal file
@ -0,0 +1,235 @@
|
||||
#!/usr/bin/env raku
|
||||
# ---------------------------------------------------------------
|
||||
# File Name : ConfigParser.rakumod
|
||||
# File Authors : Aoran Zeng <ccmywish@qq.com>
|
||||
# Contributors : Nul None <nul@none.org>
|
||||
# Created On : <2025-07-12>
|
||||
# Last Modified : <2025-07-13>
|
||||
#
|
||||
# Configuration parsing
|
||||
# ---------------------------------------------------------------
|
||||
|
||||
unit module ConfigParser;
|
||||
|
||||
enum ConfigValueType <String Mode Boolean>;
|
||||
|
||||
#
|
||||
# @brief 配置项的值
|
||||
#
|
||||
class ConfigValue {
|
||||
has ConfigValueType $.type;
|
||||
has $.raw-value;
|
||||
has $.parsed-value;
|
||||
|
||||
method new($raw-text) {
|
||||
my $type;
|
||||
my $parsed;
|
||||
|
||||
given $raw-text {
|
||||
when /^ ':' (.+) $/ {
|
||||
# 模式值 :mode
|
||||
$type = Mode;
|
||||
$parsed = ~$0;
|
||||
}
|
||||
when /^ ('true'|'false'|'yes'|'no') $/ {
|
||||
# 特殊字面量 - true/false/yes/no 都是 literal
|
||||
$type = Boolean;
|
||||
$parsed = ~$0 ~~ /^('true'|'yes')$/ ?? True !! False;
|
||||
}
|
||||
default {
|
||||
# 普通字符串
|
||||
$type = String;
|
||||
$parsed = $raw-text;
|
||||
}
|
||||
}
|
||||
|
||||
self.bless(:$type, :raw-value($raw-text), :parsed-value($parsed));
|
||||
}
|
||||
|
||||
method as-string() {
|
||||
return $.parsed-value.Str;
|
||||
}
|
||||
|
||||
method as-bool() {
|
||||
given $.type {
|
||||
when Boolean { return $.parsed-value; }
|
||||
when String {
|
||||
# 尝试将字符串解析为布尔值
|
||||
return $.parsed-value ~~ /^('true'|'yes')$/;
|
||||
}
|
||||
default { return False; }
|
||||
}
|
||||
}
|
||||
|
||||
# 获取模式值(去掉冒号前缀)
|
||||
method as-mode() {
|
||||
return $.type == Mode ?? $.parsed-value !! $.raw-value;
|
||||
}
|
||||
|
||||
# 类型检查方法
|
||||
method is-mode() { return $.type == Mode; }
|
||||
method is-bool() { return $.type == Boolean; }
|
||||
method is-string() { return $.type == String; }
|
||||
}
|
||||
|
||||
|
||||
#
|
||||
# @brief 承载 config items 的容器
|
||||
#
|
||||
class Config {
|
||||
|
||||
has %.items;
|
||||
|
||||
method set($k, $raw-value) {
|
||||
%.items{$k} = ConfigValue.new($raw-value);
|
||||
}
|
||||
|
||||
method get($k, $default = Nil) {
|
||||
return %.items{$k} // ($default ?? ConfigValue.new($default) !! ConfigValue.new(''));
|
||||
}
|
||||
|
||||
method exist($k) {
|
||||
return %.items{$k}:exists;
|
||||
}
|
||||
|
||||
# 配置项名称
|
||||
# @danger: 把这个函数命名为 items,会让我的机器蓝屏.....
|
||||
method keys() {
|
||||
return %.items.keys;
|
||||
}
|
||||
}
|
||||
|
||||