go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/resources/parsers/ini.go (about) 1 // Copyright (c) Mondoo, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package parsers 5 6 import "strings" 7 8 // Ini contains the parsed contents of an ini-style file 9 type Ini struct { 10 Fields map[string]interface{} 11 } 12 13 // ParseIni parses the raw text contents of an ini-style file 14 func ParseIni(raw string, delimiter string) *Ini { 15 res := Ini{ 16 Fields: map[string]interface{}{}, 17 } 18 19 curGroup := "" 20 res.Fields[curGroup] = map[string]interface{}{} 21 22 lines := strings.Split(raw, "\n") 23 for i := range lines { 24 line := lines[i] 25 line = strings.TrimSpace(line) 26 if idx := strings.Index(line, "#"); idx >= 0 { 27 line = line[0:idx] 28 } 29 30 if len(line) == 0 { 31 continue 32 } 33 34 if line[0] == '[' { 35 gEnd := strings.Index(line, "]") 36 if gEnd > 0 { 37 curGroup = line[1:gEnd] 38 res.Fields[curGroup] = map[string]interface{}{} 39 } 40 continue 41 } 42 43 // this is a common occurrence on space-separated files 44 // we pre-process tabs to make things easier on the tester and allow for 45 // space-split mechanisms to still work 46 if delimiter != "\t" { 47 line = strings.ReplaceAll(line, "\t", " ") 48 } 49 50 kv := strings.SplitN(line, delimiter, 2) 51 k := strings.Trim(kv[0], " \t\r") 52 if k == "" { 53 continue 54 } 55 56 var v string 57 if len(kv) == 2 { 58 v = strings.Trim(kv[1], " \t\r") 59 } 60 61 res.Fields[curGroup].(map[string]interface{})[k] = v 62 } 63 64 // check if group "" really contains entries 65 defaultGroup := res.Fields[""].(map[string]interface{}) 66 if len(defaultGroup) == 0 { 67 delete(res.Fields, "") 68 } 69 70 return &res 71 }