Debian Codegraph @

examples/config_file/config_file.go

raw symbols SCIP
1 package main
2
3 import (
4 "encoding/json"
5 "fmt"
6 "github.com/docopt/docopt-go"
7 "strings"
8 )
9
10 func loadJSONConfig() map[string]interface{} {
11 var result map[string]interface{}
12 jsonData := []byte(`{"--force": true, "--timeout": "10", "--baud": "9600"}`)
13 json.Unmarshal(jsonData, &result)
14 return result
15 }
16
17 func loadIniConfig() map[string]interface{} {
18 iniData := `
19 [default-arguments]
20 --force
21 --baud=19200
22 <host>=localhost`
23 // trivial ini parser
24 // default value for an item is bool: true (for --force)
25 // otherwise the value is a string
26 iniParsed := make(map[string]map[string]interface{})
27 var section string
28 for _, line := range strings.Split(iniData, "\n") {
29 if strings.HasPrefix(line, "[") {
30 section = line
31 iniParsed[section] = make(map[string]interface{})
32 } else if section != "" {
33 kv := strings.SplitN(line, "=", 2)
34 if len(kv) == 1 {
35 iniParsed[section][kv[0]] = true
36 } else if len(kv) == 2 {
37 iniParsed[section][kv[0]] = kv[1]
38 }
39 }
40 }
41 return iniParsed["[default-arguments]"]
42 }
43
44 // merge combines two maps.
45 // truthiness takes priority over falsiness
46 // mapA takes priority over mapB
47 func merge(mapA, mapB map[string]interface{}) map[string]interface{} {
48 result := make(map[string]interface{})
49 for k, v := range mapA {
50 result[k] = v
51 }
52 for k, v := range mapB {
53 if _, ok := result[k]; !ok || result[k] == nil || result[k] == false {
54 result[k] = v
55 }
56 }
57 return result
58 }
59
60 func main() {
61 usage := `Usage:
62 config_file tcp [<host>] [--force] [--timeout=<seconds>]
63 config_file serial <port> [--baud=<rate>] [--timeout=<seconds>]
64 config_file -h | --help | --version`
65
66 jsonConfig := loadJSONConfig()
67 iniConfig := loadIniConfig()
68 arguments, _ := docopt.ParseArgs(usage, nil, "0.1.1rc")
69
70 // Arguments take priority over INI, INI takes priority over JSON
71 result := merge(arguments, merge(iniConfig, jsonConfig))
72
73 fmt.Println("JSON config: ", jsonConfig)
74 fmt.Println("INI config: ", iniConfig)
75 fmt.Println("Result: ", result)
76 }