26 namespace eval Context {
28 if {![
info exists _ctx]} {
set _ctx [dict create]}
32 set _ctx [dict create]
36 proc Load {inputDict} {
37 if {![
_isDict $inputDict]} { error "ERR_INVALID_DICT" "" ERR_INVALID_DICT}
43 proc GetFullContext {} {
53 set value [
lindex $args end]
54 set keyPath [
lrange $args 0 end-1]
56 if {[
catch {dict set _ctx {*}$keyPath $value}]} { error "ERR_TYPE_CONFLICT" "" ERR_TYPE_CONFLICT}
64 if {![dict exists $_ctx {*}$args]} { error "ERR_NOT_FOUND" "" ERR_NOT_FOUND}
65 return [dict get $_ctx {*}$args]
68 proc GetOr {defaultValue args} {
72 if {[dict exists $_ctx {*}$args]} {
return [dict get $_ctx {*}$args]}
80 return [dict exists $_ctx {*}$args]
87 if {[dict exists $_ctx {*}$args]} {
88 dict unset _ctx {*}$args
99 set suffix [
lindex $args end]
100 set keyPath [
lrange $args 0 end-1]
102 if {[dict exists $_ctx {*}$keyPath]} {
103 set current [dict get $_ctx {*}$keyPath]
108 set updated "$current$suffix"
109 if {[
catch {dict set _ctx {*}$keyPath $updated}]} {
110 error "ERR_TYPE_CONFLICT" "" ERR_TYPE_CONFLICT
115 proc Lappend {args} {
119 set item [
lindex $args end]
120 set keyPath [
lrange $args 0 end-1]
122 if {[dict exists $_ctx {*}$keyPath]} {
123 set current [dict get $_ctx {*}$keyPath]
128 set updated [
concat $current [list $item]]
129 if {[
catch {dict set _ctx {*}$keyPath $updated}]} {
130 error "ERR_TYPE_CONFLICT" "" ERR_TYPE_CONFLICT
135 proc Merge {inputDict} {
136 if {![
_isDict $inputDict]} { error "ERR_INVALID_DICT" "" ERR_INVALID_DICT}
140 set _ctx [dict merge $_ctx $inputDict]
148 return [dict size $_ctx]
156 if {[
llength $args] == 0} {
return [dict keys $_ctx]}
158 if {![dict exists $_ctx {*}$args]} {
return [list]}
160 set value [dict get $_ctx {*}$args]
161 if {[
catch {dict keys $value} keys]} { error "ERR_NOT_A_DICT" "" ERR_NOT_A_DICT}
166 proc SaveToFile {filename {overwrite false}} {
171 if {![
file exists $filename]} {
172 set fileId [open $filename "w"]
173 }
elseif {$overwrite} {
174 set fileId [open $filename "w"]
176 error "ERR_FILE_EXISTS" "" ERR_FILE_EXISTS
183 proc LoadFromFile {filename} {
184 if {![
file exists $filename]} { error "ERR_FILE_NOT_FOUND" "" ERR_FILE_NOT_FOUND}
186 set fileId [open $filename "r"]
187 set fileContent [read $fileId]
190 if {![
_isDict $fileContent]} { error "ERR_INVALID_DICT" "" ERR_INVALID_DICT}
193 set _ctx $fileContent
198 proc _isDict {value} {
199 return [
expr {![catch {dict size $value}]}]
207 proc _validate {args {minArgs 0} {checkCtx 1}} {
208 if {[
llength $args] < $minArgs} { error "not enough arguments" "" ERR_INVALID_ARGS}
209 if {$checkCtx && ![
_ctxValid]} { error "invalid context" "" ERR_INVALID_CONTEXT}