Files
2435420f69 [full-ci] chore: bump reva to 2.52.2 (#3955)
* chore: bump reva to 2.52.2

* Merge pull request #42 from opencloud-eu/fix-web-theme-merge

fix(web): merge copies of the theme sources so themeDefaults is never mutated

* Merge pull request #43 from opencloud-eu/fix-search-trailing-not

fix(search): handle missing operands in the bleve compiler

* Merge pull request #44 from opencloud-eu/fix-search-highlight-escaping

fix(search): escape file content in OpenSearch highlights

---------

Co-authored-by: Ralf Haferkamp <r.haferkamp@opencloud.eu>
Co-authored-by: Florian Schade <f.schade@icloud.com>
2026-11-11 14:14:34 +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)
}