package main import ( "encoding/json" "reflect" "strings" klog "k8s.io/klog/v2" ) // wkData can be either JSON data (map[string]interface{}) or plaintext data ([]string or string). type wkData interface{} // wkRegistry maps IDs to wkData. type wkRegistry map[string]wkData func (reg wkRegistry) encode() map[string]string { encoded := make(map[string]string) for key, data := range reg { var result string cmKey := strings.ReplaceAll(key, "/", "__") switch v := data.(type) { case []string: // For text files, join the array into a single string result = strings.Join(v, "\n") encoded[cmKey+".txt"] = result // store as .txt file case string: // For single string data result = v encoded[cmKey+".txt"] = result // store as .txt file case map[string]interface{}: // For JSON-like data, marshal into JSON jsonData, err := json.MarshalIndent(v, "", " ") if err != nil { klog.Error(err) continue } result = string(jsonData) encoded[cmKey+".json"] = result // store as .json file encoded[cmKey] = result // store without .json extension for compatibility default: klog.Warningf("Unsupported data type: %T", data) continue } } return encoded } // mergeData merges two wkData instances. func mergeData(d1, d2 wkData) wkData { switch v1 := d1.(type) { case map[string]interface{}: if v2, ok := d2.(map[string]interface{}); ok { return mergeMaps(v1, v2) } case []string: if v2, ok := d2.([]string); ok { return append(v1, v2...) } case string: if v2, ok := d2.(string); ok { return v2 } } return d1 } // mergeMaps recursively merges two maps. func mergeMaps(m1, m2 map[string]interface{}) map[string]interface{} { for k, v2 := range m2 { if v1, ok := m1[k]; ok { m1[k] = mergeStructs(v1, v2) } else { m1[k] = v2 } } return m1 } // mergeStructs recursively merges two data structures. func mergeStructs(x1, x2 interface{}) interface{} { if reflect.TypeOf(x1) != reflect.TypeOf(x2) { // Overwrite x1 with x2 when types differ return x2 } switch x1 := x1.(type) { case []interface{}: return append(x1, x2.([]interface{})...) case string: return x2.(string) case map[string]interface{}: return mergeMaps(x1, x2.(map[string]interface{})) default: klog.Warningf("unknown type: %T", x1) return x2 } }