1 // Copyright 2014 Unknwon
3 // Licensed under the Apache License, Version 2.0 (the "License"): you may
4 // not use this file except in compliance with the License. You may obtain
5 // a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations
26 // Key represents a key under a section.
41 // newKey simply return a key object with given values.
42 func newKey(s *Section, name, val string) *Key {
50 func (k *Key) addShadow(val string) error {
52 return errors.New("cannot add shadow to another shadow key")
53 } else if k.isAutoIncrement || k.isBooleanType {
54 return errors.New("cannot add shadow to auto-increment or boolean key")
57 shadow := newKey(k.s, k.name, val)
58 shadow.isShadow = true
59 k.shadows = append(k.shadows, shadow)
63 // AddShadow adds a new shadow key to itself.
64 func (k *Key) AddShadow(val string) error {
65 if !k.s.f.options.AllowShadows {
66 return errors.New("shadow key is not allowed")
68 return k.addShadow(val)
71 func (k *Key) addNestedValue(val string) error {
72 if k.isAutoIncrement || k.isBooleanType {
73 return errors.New("cannot add nested value to auto-increment or boolean key")
76 k.nestedValues = append(k.nestedValues, val)
80 // AddNestedValue adds a nested value to the key.
81 func (k *Key) AddNestedValue(val string) error {
82 if !k.s.f.options.AllowNestedValues {
83 return errors.New("nested value is not allowed")
85 return k.addNestedValue(val)
88 // ValueMapper represents a mapping function for values, e.g. os.ExpandEnv
89 type ValueMapper func(string) string
91 // Name returns name of key.
92 func (k *Key) Name() string {
96 // Value returns raw value of key for performance purpose.
97 func (k *Key) Value() string {
101 // ValueWithShadows returns raw values of key and its shadows if any.
102 func (k *Key) ValueWithShadows() []string {
103 if len(k.shadows) == 0 {
104 return []string{k.value}
106 vals := make([]string, len(k.shadows)+1)
108 for i := range k.shadows {
109 vals[i+1] = k.shadows[i].value
114 // NestedValues returns nested values stored in the key.
115 // It is possible returned value is nil if no nested values stored in the key.
116 func (k *Key) NestedValues() []string {
117 return k.nestedValues
120 // transformValue takes a raw value and transforms to its final string.
121 func (k *Key) transformValue(val string) string {
122 if k.s.f.ValueMapper != nil {
123 val = k.s.f.ValueMapper(val)
126 // Fail-fast if no indicate char found for recursive value
127 if !strings.Contains(val, "%") {
130 for i := 0; i < depthValues; i++ {
131 vr := varPattern.FindString(val)
136 // Take off leading '%(' and trailing ')s'.
137 noption := vr[2 : len(vr)-2]
139 // Search in the same section.
140 nk, err := k.s.GetKey(noption)
141 if err != nil || k == nk {
142 // Search again in default section.
143 nk, _ = k.s.f.Section("").GetKey(noption)
146 // Substitute by new value and take off leading '%(' and trailing ')s'.
147 val = strings.Replace(val, vr, nk.value, -1)
152 // String returns string representation of value.
153 func (k *Key) String() string {
154 return k.transformValue(k.value)
157 // Validate accepts a validate function which can
158 // return modifed result as key value.
159 func (k *Key) Validate(fn func(string) string) string {
160 return fn(k.String())
163 // parseBool returns the boolean value represented by the string.
165 // It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On,
166 // 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off.
167 // Any other value returns an error.
168 func parseBool(str string) (value bool, err error) {
170 case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On":
172 case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off":
175 return false, fmt.Errorf("parsing \"%s\": invalid syntax", str)
178 // Bool returns bool type value.
179 func (k *Key) Bool() (bool, error) {
180 return parseBool(k.String())
183 // Float64 returns float64 type value.
184 func (k *Key) Float64() (float64, error) {
185 return strconv.ParseFloat(k.String(), 64)
188 // Int returns int type value.
189 func (k *Key) Int() (int, error) {
190 v, err := strconv.ParseInt(k.String(), 0, 64)
194 // Int64 returns int64 type value.
195 func (k *Key) Int64() (int64, error) {
196 return strconv.ParseInt(k.String(), 0, 64)
199 // Uint returns uint type valued.
200 func (k *Key) Uint() (uint, error) {
201 u, e := strconv.ParseUint(k.String(), 0, 64)
205 // Uint64 returns uint64 type value.
206 func (k *Key) Uint64() (uint64, error) {
207 return strconv.ParseUint(k.String(), 0, 64)
210 // Duration returns time.Duration type value.
211 func (k *Key) Duration() (time.Duration, error) {
212 return time.ParseDuration(k.String())
215 // TimeFormat parses with given format and returns time.Time type value.
216 func (k *Key) TimeFormat(format string) (time.Time, error) {
217 return time.Parse(format, k.String())
220 // Time parses with RFC3339 format and returns time.Time type value.
221 func (k *Key) Time() (time.Time, error) {
222 return k.TimeFormat(time.RFC3339)
225 // MustString returns default value if key value is empty.
226 func (k *Key) MustString(defaultVal string) string {
235 // MustBool always returns value without error,
236 // it returns false if error occurs.
237 func (k *Key) MustBool(defaultVal ...bool) bool {
239 if len(defaultVal) > 0 && err != nil {
240 k.value = strconv.FormatBool(defaultVal[0])
246 // MustFloat64 always returns value without error,
247 // it returns 0.0 if error occurs.
248 func (k *Key) MustFloat64(defaultVal ...float64) float64 {
249 val, err := k.Float64()
250 if len(defaultVal) > 0 && err != nil {
251 k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64)
257 // MustInt always returns value without error,
258 // it returns 0 if error occurs.
259 func (k *Key) MustInt(defaultVal ...int) int {
261 if len(defaultVal) > 0 && err != nil {
262 k.value = strconv.FormatInt(int64(defaultVal[0]), 10)
268 // MustInt64 always returns value without error,
269 // it returns 0 if error occurs.
270 func (k *Key) MustInt64(defaultVal ...int64) int64 {
271 val, err := k.Int64()
272 if len(defaultVal) > 0 && err != nil {
273 k.value = strconv.FormatInt(defaultVal[0], 10)
279 // MustUint always returns value without error,
280 // it returns 0 if error occurs.
281 func (k *Key) MustUint(defaultVal ...uint) uint {
283 if len(defaultVal) > 0 && err != nil {
284 k.value = strconv.FormatUint(uint64(defaultVal[0]), 10)
290 // MustUint64 always returns value without error,
291 // it returns 0 if error occurs.
292 func (k *Key) MustUint64(defaultVal ...uint64) uint64 {
293 val, err := k.Uint64()
294 if len(defaultVal) > 0 && err != nil {
295 k.value = strconv.FormatUint(defaultVal[0], 10)
301 // MustDuration always returns value without error,
302 // it returns zero value if error occurs.
303 func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration {
304 val, err := k.Duration()
305 if len(defaultVal) > 0 && err != nil {
306 k.value = defaultVal[0].String()
312 // MustTimeFormat always parses with given format and returns value without error,
313 // it returns zero value if error occurs.
314 func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time {
315 val, err := k.TimeFormat(format)
316 if len(defaultVal) > 0 && err != nil {
317 k.value = defaultVal[0].Format(format)
323 // MustTime always parses with RFC3339 format and returns value without error,
324 // it returns zero value if error occurs.
325 func (k *Key) MustTime(defaultVal ...time.Time) time.Time {
326 return k.MustTimeFormat(time.RFC3339, defaultVal...)
329 // In always returns value without error,
330 // it returns default value if error occurs or doesn't fit into candidates.
331 func (k *Key) In(defaultVal string, candidates []string) string {
333 for _, cand := range candidates {
341 // InFloat64 always returns value without error,
342 // it returns default value if error occurs or doesn't fit into candidates.
343 func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 {
344 val := k.MustFloat64()
345 for _, cand := range candidates {
353 // InInt always returns value without error,
354 // it returns default value if error occurs or doesn't fit into candidates.
355 func (k *Key) InInt(defaultVal int, candidates []int) int {
357 for _, cand := range candidates {
365 // InInt64 always returns value without error,
366 // it returns default value if error occurs or doesn't fit into candidates.
367 func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 {
369 for _, cand := range candidates {
377 // InUint always returns value without error,
378 // it returns default value if error occurs or doesn't fit into candidates.
379 func (k *Key) InUint(defaultVal uint, candidates []uint) uint {
381 for _, cand := range candidates {
389 // InUint64 always returns value without error,
390 // it returns default value if error occurs or doesn't fit into candidates.
391 func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 {
392 val := k.MustUint64()
393 for _, cand := range candidates {
401 // InTimeFormat always parses with given format and returns value without error,
402 // it returns default value if error occurs or doesn't fit into candidates.
403 func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time {
404 val := k.MustTimeFormat(format)
405 for _, cand := range candidates {
413 // InTime always parses with RFC3339 format and returns value without error,
414 // it returns default value if error occurs or doesn't fit into candidates.
415 func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time {
416 return k.InTimeFormat(time.RFC3339, defaultVal, candidates)
419 // RangeFloat64 checks if value is in given range inclusively,
420 // and returns default value if it's not.
421 func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 {
422 val := k.MustFloat64()
423 if val < min || val > max {
429 // RangeInt checks if value is in given range inclusively,
430 // and returns default value if it's not.
431 func (k *Key) RangeInt(defaultVal, min, max int) int {
433 if val < min || val > max {
439 // RangeInt64 checks if value is in given range inclusively,
440 // and returns default value if it's not.
441 func (k *Key) RangeInt64(defaultVal, min, max int64) int64 {
443 if val < min || val > max {
449 // RangeTimeFormat checks if value with given format is in given range inclusively,
450 // and returns default value if it's not.
451 func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time {
452 val := k.MustTimeFormat(format)
453 if val.Unix() < min.Unix() || val.Unix() > max.Unix() {
459 // RangeTime checks if value with RFC3339 format is in given range inclusively,
460 // and returns default value if it's not.
461 func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time {
462 return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max)
465 // Strings returns list of string divided by given delimiter.
466 func (k *Key) Strings(delim string) []string {
473 vals := make([]string, 0, 2)
480 if runes[idx] != '\\' && !strings.HasPrefix(string(runes[idx:]), delim) {
483 buf.WriteRune(runes[idx])
485 if runes[idx] == '\\' {
487 } else if strings.HasPrefix(string(runes[idx:]), delim) {
488 idx += len(delim) - 1
489 vals = append(vals, strings.TrimSpace(buf.String()))
492 buf.WriteRune(runes[idx])
496 if idx == len(runes) {
502 vals = append(vals, strings.TrimSpace(buf.String()))
508 // StringsWithShadows returns list of string divided by given delimiter.
509 // Shadows will also be appended if any.
510 func (k *Key) StringsWithShadows(delim string) []string {
511 vals := k.ValueWithShadows()
512 results := make([]string, 0, len(vals)*2)
513 for i := range vals {
518 results = append(results, strings.Split(vals[i], delim)...)
521 for i := range results {
522 results[i] = k.transformValue(strings.TrimSpace(results[i]))
527 // Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value.
528 func (k *Key) Float64s(delim string) []float64 {
529 vals, _ := k.parseFloat64s(k.Strings(delim), true, false)
533 // Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value.
534 func (k *Key) Ints(delim string) []int {
535 vals, _ := k.parseInts(k.Strings(delim), true, false)
539 // Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value.
540 func (k *Key) Int64s(delim string) []int64 {
541 vals, _ := k.parseInt64s(k.Strings(delim), true, false)
545 // Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value.
546 func (k *Key) Uints(delim string) []uint {
547 vals, _ := k.parseUints(k.Strings(delim), true, false)
551 // Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value.
552 func (k *Key) Uint64s(delim string) []uint64 {
553 vals, _ := k.parseUint64s(k.Strings(delim), true, false)
557 // TimesFormat parses with given format and returns list of time.Time divided by given delimiter.
558 // Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
559 func (k *Key) TimesFormat(format, delim string) []time.Time {
560 vals, _ := k.parseTimesFormat(format, k.Strings(delim), true, false)
564 // Times parses with RFC3339 format and returns list of time.Time divided by given delimiter.
565 // Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
566 func (k *Key) Times(delim string) []time.Time {
567 return k.TimesFormat(time.RFC3339, delim)
570 // ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then
571 // it will not be included to result list.
572 func (k *Key) ValidFloat64s(delim string) []float64 {
573 vals, _ := k.parseFloat64s(k.Strings(delim), false, false)
577 // ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will
578 // not be included to result list.
579 func (k *Key) ValidInts(delim string) []int {
580 vals, _ := k.parseInts(k.Strings(delim), false, false)
584 // ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer,
585 // then it will not be included to result list.
586 func (k *Key) ValidInt64s(delim string) []int64 {
587 vals, _ := k.parseInt64s(k.Strings(delim), false, false)
591 // ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer,
592 // then it will not be included to result list.
593 func (k *Key) ValidUints(delim string) []uint {
594 vals, _ := k.parseUints(k.Strings(delim), false, false)
598 // ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned
599 // integer, then it will not be included to result list.
600 func (k *Key) ValidUint64s(delim string) []uint64 {
601 vals, _ := k.parseUint64s(k.Strings(delim), false, false)
605 // ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter.
606 func (k *Key) ValidTimesFormat(format, delim string) []time.Time {
607 vals, _ := k.parseTimesFormat(format, k.Strings(delim), false, false)
611 // ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter.
612 func (k *Key) ValidTimes(delim string) []time.Time {
613 return k.ValidTimesFormat(time.RFC3339, delim)
616 // StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input.
617 func (k *Key) StrictFloat64s(delim string) ([]float64, error) {
618 return k.parseFloat64s(k.Strings(delim), false, true)
621 // StrictInts returns list of int divided by given delimiter or error on first invalid input.
622 func (k *Key) StrictInts(delim string) ([]int, error) {
623 return k.parseInts(k.Strings(delim), false, true)
626 // StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input.
627 func (k *Key) StrictInt64s(delim string) ([]int64, error) {
628 return k.parseInt64s(k.Strings(delim), false, true)
631 // StrictUints returns list of uint divided by given delimiter or error on first invalid input.
632 func (k *Key) StrictUints(delim string) ([]uint, error) {
633 return k.parseUints(k.Strings(delim), false, true)
636 // StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input.
637 func (k *Key) StrictUint64s(delim string) ([]uint64, error) {
638 return k.parseUint64s(k.Strings(delim), false, true)
641 // StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter
642 // or error on first invalid input.
643 func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) {
644 return k.parseTimesFormat(format, k.Strings(delim), false, true)
647 // StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter
648 // or error on first invalid input.
649 func (k *Key) StrictTimes(delim string) ([]time.Time, error) {
650 return k.StrictTimesFormat(time.RFC3339, delim)
653 // parseFloat64s transforms strings to float64s.
654 func (k *Key) parseFloat64s(strs []string, addInvalid, returnOnInvalid bool) ([]float64, error) {
655 vals := make([]float64, 0, len(strs))
656 for _, str := range strs {
657 val, err := strconv.ParseFloat(str, 64)
658 if err != nil && returnOnInvalid {
661 if err == nil || addInvalid {
662 vals = append(vals, val)
668 // parseInts transforms strings to ints.
669 func (k *Key) parseInts(strs []string, addInvalid, returnOnInvalid bool) ([]int, error) {
670 vals := make([]int, 0, len(strs))
671 for _, str := range strs {
672 valInt64, err := strconv.ParseInt(str, 0, 64)
674 if err != nil && returnOnInvalid {
677 if err == nil || addInvalid {
678 vals = append(vals, val)
684 // parseInt64s transforms strings to int64s.
685 func (k *Key) parseInt64s(strs []string, addInvalid, returnOnInvalid bool) ([]int64, error) {
686 vals := make([]int64, 0, len(strs))
687 for _, str := range strs {
688 val, err := strconv.ParseInt(str, 0, 64)
689 if err != nil && returnOnInvalid {
692 if err == nil || addInvalid {
693 vals = append(vals, val)
699 // parseUints transforms strings to uints.
700 func (k *Key) parseUints(strs []string, addInvalid, returnOnInvalid bool) ([]uint, error) {
701 vals := make([]uint, 0, len(strs))
702 for _, str := range strs {
703 val, err := strconv.ParseUint(str, 0, 0)
704 if err != nil && returnOnInvalid {
707 if err == nil || addInvalid {
708 vals = append(vals, uint(val))
714 // parseUint64s transforms strings to uint64s.
715 func (k *Key) parseUint64s(strs []string, addInvalid, returnOnInvalid bool) ([]uint64, error) {
716 vals := make([]uint64, 0, len(strs))
717 for _, str := range strs {
718 val, err := strconv.ParseUint(str, 0, 64)
719 if err != nil && returnOnInvalid {
722 if err == nil || addInvalid {
723 vals = append(vals, val)
729 // parseTimesFormat transforms strings to times in given format.
730 func (k *Key) parseTimesFormat(format string, strs []string, addInvalid, returnOnInvalid bool) ([]time.Time, error) {
731 vals := make([]time.Time, 0, len(strs))
732 for _, str := range strs {
733 val, err := time.Parse(format, str)
734 if err != nil && returnOnInvalid {
737 if err == nil || addInvalid {
738 vals = append(vals, val)
744 // SetValue changes key value.
745 func (k *Key) SetValue(v string) {
748 defer k.s.f.lock.Unlock()
752 k.s.keysHash[k.name] = v