Debian Codegraph @

plumbing/format/config/option.go

raw
1 package config
2
3 import (
4 "fmt"
5 "strings"
6 )
7
8 // Option defines a key/value entity in a config file.
9 type Option struct {
10 // Key preserving original caseness.
11 // Use IsKey instead to compare key regardless of caseness.
12 Key string
13 // Original value as string, could be not normalized.
14 Value string
15 }
16
17 type Options []*Option
18
19 // IsKey returns true if the given key matches
20 // this option's key in a case-insensitive comparison.
21 func (o *Option) IsKey(key string) bool {
22 return strings.EqualFold(o.Key, key)
23 }
24
25 func (opts Options) GoString() string {
26 var strs []string
27 for _, opt := range opts {
28 strs = append(strs, fmt.Sprintf("%#v", opt))
29 }
30
31 return strings.Join(strs, ", ")
32 }
33
34 // Get gets the value for the given key if set,
35 // otherwise it returns the empty string.
36 //
37 // Note that there is no difference
38 //
39 // This matches git behaviour since git v1.8.1-rc1,
40 // if there are multiple definitions of a key, the
41 // last one wins.
42 //
43 // See: http://article.gmane.org/gmane.linux.kernel/1407184
44 //
45 // In order to get all possible values for the same key,
46 // use GetAll.
47 func (opts Options) Get(key string) string {
48 for i := len(opts) - 1; i >= 0; i-- {
49 o := opts[i]
50 if o.IsKey(key) {
51 return o.Value
52 }
53 }
54 return ""
55 }
56
57 // Has checks if an Option exist with the given key.
58 func (opts Options) Has(key string) bool {
59 for _, o := range opts {
60 if o.IsKey(key) {
61 return true
62 }
63 }
64 return false
65 }
66
67 // GetAll returns all possible values for the same key.
68 func (opts Options) GetAll(key string) []string {
69 result := []string{}
70 for _, o := range opts {
71 if o.IsKey(key) {
72 result = append(result, o.Value)
73 }
74 }
75 return result
76 }
77
78 func (opts Options) withoutOption(key string) Options {
79 result := Options{}
80 for _, o := range opts {
81 if !o.IsKey(key) {
82 result = append(result, o)
83 }
84 }
85 return result
86 }
87
88 func (opts Options) withAddedOption(key string, value string) Options {
89 return append(opts, &Option{key, value})
90 }
91
92 func (opts Options) withSettedOption(key string, values ...string) Options {
93 var result Options
94 var added []string
95 for _, o := range opts {
96 if !o.IsKey(key) {
97 result = append(result, o)
98 continue
99 }
100
101 if contains(values, o.Value) {
102 added = append(added, o.Value)
103 result = append(result, o)
104 continue
105 }
106 }
107
108 for _, value := range values {
109 if contains(added, value) {
110 continue
111 }
112
113 result = result.withAddedOption(key, value)
114 }
115
116 return result
117 }
118
119 func contains(haystack []string, needle string) bool {
120 for _, s := range haystack {
121 if s == needle {
122 return true
123 }
124 }
125
126 return false
127 }