Files
opencloud/services/web/pkg/theme/kv.go
T
Ralf Haferkamp d8d7c1082b [full-ci] [stable-7.2] preparing 7.2.5 (#3953)
* Merge pull request #45 from opencloud-eu/backports/stable-7.2-42

[stable-7.2] fix(web): merge copies of the theme sources so themeDefaults is never…

* Merge pull request #47 from opencloud-eu/backports/stable-7.2-43

[stable-7.2] fix(search): handle missing operands in the bleve compiler

* Merge pull request #49 from opencloud-eu/fix/stable-7.2/search-highlight-escaping

[stable-7.2] fix(search): escape file content in OpenSearch highlights

* Bump version
2026-11-11 12:45:41 +01:00

103 lines
2.0 KiB
Go

package theme
import (
"bytes"
"encoding/json"
"strings"
"dario.cat/mergo"
"github.com/mohae/deepcopy"
"github.com/spf13/afero"
)
// KV is a generic key-value map.
type KV map[string]any
// MergeKV merges the given key-value maps into a new one, the given maps are not modified.
func MergeKV(values ...KV) (KV, error) {
var kv KV
for _, v := range values {
// mergo reuses the nested maps of a source in the destination and merges later sources into them,
// so it must only see a copy; otherwise shared inputs like themeDefaults get modified,
// concurrently when requests run in parallel.
err := mergo.Merge(&kv, deepcopy.Copy(v).(KV), mergo.WithOverride)
if err != nil {
return nil, err
}
}
return kv, nil
}
// PatchKV injects the given values into to v.
func PatchKV(v map[string]any, values KV) KV {
if v == nil {
v = KV{}
}
for k, val := range values {
t := v
path := strings.Split(k, ".")
for i, p := range path {
if i == len(path)-1 {
switch val {
// if the value is nil, we delete the key
case nil:
delete(t, p)
default:
t[p] = val
}
break
}
if _, ok := t[p]; !ok {
t[p] = map[string]any{}
}
t = t[p].(map[string]any)
}
}
return v
}
// LoadKV loads a key-value map from the given file system.
func LoadKV(fsys afero.Fs, p string) (KV, error) {
f, err := fsys.Open(p)
if err != nil {
return nil, err
}
defer f.Close()
var kv KV
err = json.NewDecoder(f).Decode(&kv)
if err != nil {
return nil, err
}
return kv, nil
}
// WriteKV writes the given key-value map to the file system.
func WriteKV(fsys afero.Fs, p string, kv KV) error {
data, err := json.Marshal(kv)
if err != nil {
return err
}
return afero.WriteReader(fsys, p, bytes.NewReader(data))
}
// UpdateKV updates the key-value map at the given path with the given values.
func UpdateKV(fsys afero.Fs, p string, values KV) error {
var kv KV
existing, err := LoadKV(fsys, p)
if err == nil {
kv = existing
}
kv = PatchKV(kv, values)
return WriteKV(fsys, p, kv)
}