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
25 // Key represents a key under a section.
39 // newKey simply return a key object with given values.
40 func newKey(s *Section, name, val string) *Key {
48 func (k *Key) addShadow(val string) error {
50 return errors.New("cannot add shadow to another shadow key")
51 } else if k.isAutoIncrement || k.isBooleanType {
52 return errors.New("cannot add shadow to auto-increment or boolean key")
55 shadow := newKey(k.s, k.name, val)
56 shadow.isShadow = true
57 k.shadows = append(k.shadows, shadow)
61 // AddShadow adds a new shadow key to itself.
62 func (k *Key) AddShadow(val string) error {
63 if !k.s.f.options.AllowShadows {
64 return errors.New("shadow key is not allowed")
66 return k.addShadow(val)
69 // ValueMapper represents a mapping function for values, e.g. os.ExpandEnv
70 type ValueMapper func(string) string
72 // Name returns name of key.
73 func (k *Key) Name() string {
77 // Value returns raw value of key for performance purpose.
78 func (k *Key) Value() string {
82 // ValueWithShadows returns raw values of key and its shadows if any.
83 func (k *Key) ValueWithShadows() []string {
84 if len(k.shadows) == 0 {
85 return []string{k.value}
87 vals := make([]string, len(k.shadows)+1)
89 for i := range k.shadows {
90 vals[i+1] = k.shadows[i].value
95 // transformValue takes a raw value and transforms to its final string.
96 func (k *Key) transformValue(val string) string {
97 if k.s.f.ValueMapper != nil {
98 val = k.s.f.ValueMapper(val)
101 // Fail-fast if no indicate char found for recursive value
102 if !strings.Contains(val, "%") {
105 for i := 0; i < _DEPTH_VALUES; i++ {
106 vr := varPattern.FindString(val)
111 // Take off leading '%(' and trailing ')s'.
112 noption := strings.TrimLeft(vr, "%(")
113 noption = strings.TrimRight(noption, ")s")
115 // Search in the same section.
116 nk, err := k.s.GetKey(noption)
118 // Search again in default section.
119 nk, _ = k.s.f.Section("").GetKey(noption)
122 // Substitute by new value and take off leading '%(' and trailing ')s'.
123 val = strings.Replace(val, vr, nk.value, -1)
128 // String returns string representation of value.
129 func (k *Key) String() string {
130 return k.transformValue(k.value)
133 // Validate accepts a validate function which can
134 // return modifed result as key value.
135 func (k *Key) Validate(fn func(string) string) string {
136 return fn(k.String())
139 // parseBool returns the boolean value represented by the string.
141 // It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On,
142 // 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off.
143 // Any other value returns an error.
144 func parseBool(str string) (value bool, err error) {
146 case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On":
148 case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off":
151 return false, fmt.Errorf("parsing \"%s\": invalid syntax", str)
154 // Bool returns bool type value.
155 func (k *Key) Bool() (bool, error) {
156 return parseBool(k.String())
159 // Float64 returns float64 type value.
160 func (k *Key) Float64() (float64, error) {
161 return strconv.ParseFloat(k.String(), 64)
164 // Int returns int type value.
165 func (k *Key) Int() (int, error) {
166 return strconv.Atoi(k.String())
169 // Int64 returns int64 type value.
170 func (k *Key) Int64() (int64, error) {
171 return strconv.ParseInt(k.String(), 10, 64)
174 // Uint returns uint type valued.
175 func (k *Key) Uint() (uint, error) {
176 u, e := strconv.ParseUint(k.String(), 10, 64)
180 // Uint64 returns uint64 type value.
181 func (k *Key) Uint64() (uint64, error) {
182 return strconv.ParseUint(k.String(), 10, 64)
185 // Duration returns time.Duration type value.
186 func (k *Key) Duration() (time.Duration, error) {
187 return time.ParseDuration(k.String())
190 // TimeFormat parses with given format and returns time.Time type value.
191 func (k *Key) TimeFormat(format string) (time.Time, error) {
192 return time.Parse(format, k.String())
195 // Time parses with RFC3339 format and returns time.Time type value.
196 func (k *Key) Time() (time.Time, error) {
197 return k.TimeFormat(time.RFC3339)
200 // MustString returns default value if key value is empty.
201 func (k *Key) MustString(defaultVal string) string {
210 // MustBool always returns value without error,
211 // it returns false if error occurs.
212 func (k *Key) MustBool(defaultVal ...bool) bool {
214 if len(defaultVal) > 0 && err != nil {
215 k.value = strconv.FormatBool(defaultVal[0])
221 // MustFloat64 always returns value without error,
222 // it returns 0.0 if error occurs.
223 func (k *Key) MustFloat64(defaultVal ...float64) float64 {
224 val, err := k.Float64()
225 if len(defaultVal) > 0 && err != nil {
226 k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64)
232 // MustInt always returns value without error,
233 // it returns 0 if error occurs.
234 func (k *Key) MustInt(defaultVal ...int) int {
236 if len(defaultVal) > 0 && err != nil {
237 k.value = strconv.FormatInt(int64(defaultVal[0]), 10)
243 // MustInt64 always returns value without error,
244 // it returns 0 if error occurs.
245 func (k *Key) MustInt64(defaultVal ...int64) int64 {
246 val, err := k.Int64()
247 if len(defaultVal) > 0 && err != nil {
248 k.value = strconv.FormatInt(defaultVal[0], 10)
254 // MustUint always returns value without error,
255 // it returns 0 if error occurs.
256 func (k *Key) MustUint(defaultVal ...uint) uint {
258 if len(defaultVal) > 0 && err != nil {
259 k.value = strconv.FormatUint(uint64(defaultVal[0]), 10)
265 // MustUint64 always returns value without error,
266 // it returns 0 if error occurs.
267 func (k *Key) MustUint64(defaultVal ...uint64) uint64 {
268 val, err := k.Uint64()
269 if len(defaultVal) > 0 && err != nil {
270 k.value = strconv.FormatUint(defaultVal[0], 10)
276 // MustDuration always returns value without error,
277 // it returns zero value if error occurs.
278 func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration {
279 val, err := k.Duration()
280 if len(defaultVal) > 0 && err != nil {
281 k.value = defaultVal[0].String()
287 // MustTimeFormat always parses with given format and returns value without error,
288 // it returns zero value if error occurs.
289 func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time {
290 val, err := k.TimeFormat(format)
291 if len(defaultVal) > 0 && err != nil {
292 k.value = defaultVal[0].Format(format)
298 // MustTime always parses with RFC3339 format and returns value without error,
299 // it returns zero value if error occurs.
300 func (k *Key) MustTime(defaultVal ...time.Time) time.Time {
301 return k.MustTimeFormat(time.RFC3339, defaultVal...)
304 // In always returns value without error,
305 // it returns default value if error occurs or doesn't fit into candidates.
306 func (k *Key) In(defaultVal string, candidates []string) string {
308 for _, cand := range candidates {
316 // InFloat64 always returns value without error,
317 // it returns default value if error occurs or doesn't fit into candidates.
318 func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 {
319 val := k.MustFloat64()
320 for _, cand := range candidates {
328 // InInt always returns value without error,
329 // it returns default value if error occurs or doesn't fit into candidates.
330 func (k *Key) InInt(defaultVal int, candidates []int) int {
332 for _, cand := range candidates {
340 // InInt64 always returns value without error,
341 // it returns default value if error occurs or doesn't fit into candidates.
342 func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 {
344 for _, cand := range candidates {
352 // InUint always returns value without error,
353 // it returns default value if error occurs or doesn't fit into candidates.
354 func (k *Key) InUint(defaultVal uint, candidates []uint) uint {
356 for _, cand := range candidates {
364 // InUint64 always returns value without error,
365 // it returns default value if error occurs or doesn't fit into candidates.
366 func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 {
367 val := k.MustUint64()
368 for _, cand := range candidates {
376 // InTimeFormat always parses with given format and returns value without error,
377 // it returns default value if error occurs or doesn't fit into candidates.
378 func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time {
379 val := k.MustTimeFormat(format)
380 for _, cand := range candidates {
388 // InTime always parses with RFC3339 format and returns value without error,
389 // it returns default value if error occurs or doesn't fit into candidates.
390 func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time {
391 return k.InTimeFormat(time.RFC3339, defaultVal, candidates)
394 // RangeFloat64 checks if value is in given range inclusively,
395 // and returns default value if it's not.
396 func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 {
397 val := k.MustFloat64()
398 if val < min || val > max {
404 // RangeInt checks if value is in given range inclusively,
405 // and returns default value if it's not.
406 func (k *Key) RangeInt(defaultVal, min, max int) int {
408 if val < min || val > max {
414 // RangeInt64 checks if value is in given range inclusively,
415 // and returns default value if it's not.
416 func (k *Key) RangeInt64(defaultVal, min, max int64) int64 {
418 if val < min || val > max {
424 // RangeTimeFormat checks if value with given format is in given range inclusively,
425 // and returns default value if it's not.
426 func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time {
427 val := k.MustTimeFormat(format)
428 if val.Unix() < min.Unix() || val.Unix() > max.Unix() {
434 // RangeTime checks if value with RFC3339 format is in given range inclusively,
435 // and returns default value if it's not.
436 func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time {
437 return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max)
440 // Strings returns list of string divided by given delimiter.
441 func (k *Key) Strings(delim string) []string {
447 vals := strings.Split(str, delim)
448 for i := range vals {
449 // vals[i] = k.transformValue(strings.TrimSpace(vals[i]))
450 vals[i] = strings.TrimSpace(vals[i])
455 // StringsWithShadows returns list of string divided by given delimiter.
456 // Shadows will also be appended if any.
457 func (k *Key) StringsWithShadows(delim string) []string {
458 vals := k.ValueWithShadows()
459 results := make([]string, 0, len(vals)*2)
460 for i := range vals {
465 results = append(results, strings.Split(vals[i], delim)...)
468 for i := range results {
469 results[i] = k.transformValue(strings.TrimSpace(results[i]))
474 // Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value.
475 func (k *Key) Float64s(delim string) []float64 {
476 vals, _ := k.getFloat64s(delim, true, false)
480 // Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value.
481 func (k *Key) Ints(delim string) []int {
482 vals, _ := k.parseInts(k.Strings(delim), true, false)
486 // Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value.
487 func (k *Key) Int64s(delim string) []int64 {
488 vals, _ := k.parseInt64s(k.Strings(delim), true, false)
492 // Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value.
493 func (k *Key) Uints(delim string) []uint {
494 vals, _ := k.getUints(delim, true, false)
498 // Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value.
499 func (k *Key) Uint64s(delim string) []uint64 {
500 vals, _ := k.getUint64s(delim, true, false)
504 // TimesFormat parses with given format and returns list of time.Time divided by given delimiter.
505 // Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
506 func (k *Key) TimesFormat(format, delim string) []time.Time {
507 vals, _ := k.getTimesFormat(format, delim, true, false)
511 // Times parses with RFC3339 format and returns list of time.Time divided by given delimiter.
512 // Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
513 func (k *Key) Times(delim string) []time.Time {
514 return k.TimesFormat(time.RFC3339, delim)
517 // ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then
518 // it will not be included to result list.
519 func (k *Key) ValidFloat64s(delim string) []float64 {
520 vals, _ := k.getFloat64s(delim, false, false)
524 // ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will
525 // not be included to result list.
526 func (k *Key) ValidInts(delim string) []int {
527 vals, _ := k.parseInts(k.Strings(delim), false, false)
531 // ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer,
532 // then it will not be included to result list.
533 func (k *Key) ValidInt64s(delim string) []int64 {
534 vals, _ := k.parseInt64s(k.Strings(delim), false, false)
538 // ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer,
539 // then it will not be included to result list.
540 func (k *Key) ValidUints(delim string) []uint {
541 vals, _ := k.getUints(delim, false, false)
545 // ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned
546 // integer, then it will not be included to result list.
547 func (k *Key) ValidUint64s(delim string) []uint64 {
548 vals, _ := k.getUint64s(delim, false, false)
552 // ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter.
553 func (k *Key) ValidTimesFormat(format, delim string) []time.Time {
554 vals, _ := k.getTimesFormat(format, delim, false, false)
558 // ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter.
559 func (k *Key) ValidTimes(delim string) []time.Time {
560 return k.ValidTimesFormat(time.RFC3339, delim)
563 // StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input.
564 func (k *Key) StrictFloat64s(delim string) ([]float64, error) {
565 return k.getFloat64s(delim, false, true)
568 // StrictInts returns list of int divided by given delimiter or error on first invalid input.
569 func (k *Key) StrictInts(delim string) ([]int, error) {
570 return k.parseInts(k.Strings(delim), false, true)
573 // StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input.
574 func (k *Key) StrictInt64s(delim string) ([]int64, error) {
575 return k.parseInt64s(k.Strings(delim), false, true)
578 // StrictUints returns list of uint divided by given delimiter or error on first invalid input.
579 func (k *Key) StrictUints(delim string) ([]uint, error) {
580 return k.getUints(delim, false, true)
583 // StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input.
584 func (k *Key) StrictUint64s(delim string) ([]uint64, error) {
585 return k.getUint64s(delim, false, true)
588 // StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter
589 // or error on first invalid input.
590 func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) {
591 return k.getTimesFormat(format, delim, false, true)
594 // StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter
595 // or error on first invalid input.
596 func (k *Key) StrictTimes(delim string) ([]time.Time, error) {
597 return k.StrictTimesFormat(time.RFC3339, delim)
600 // getFloat64s returns list of float64 divided by given delimiter.
601 func (k *Key) getFloat64s(delim string, addInvalid, returnOnInvalid bool) ([]float64, error) {
602 strs := k.Strings(delim)
603 vals := make([]float64, 0, len(strs))
604 for _, str := range strs {
605 val, err := strconv.ParseFloat(str, 64)
606 if err != nil && returnOnInvalid {
609 if err == nil || addInvalid {
610 vals = append(vals, val)
616 // parseInts transforms strings to ints.
617 func (k *Key) parseInts(strs []string, addInvalid, returnOnInvalid bool) ([]int, error) {
618 vals := make([]int, 0, len(strs))
619 for _, str := range strs {
620 val, err := strconv.Atoi(str)
621 if err != nil && returnOnInvalid {
624 if err == nil || addInvalid {
625 vals = append(vals, val)
631 // parseInt64s transforms strings to int64s.
632 func (k *Key) parseInt64s(strs []string, addInvalid, returnOnInvalid bool) ([]int64, error) {
633 vals := make([]int64, 0, len(strs))
634 for _, str := range strs {
635 val, err := strconv.ParseInt(str, 10, 64)
636 if err != nil && returnOnInvalid {
639 if err == nil || addInvalid {
640 vals = append(vals, val)
646 // getUints returns list of uint divided by given delimiter.
647 func (k *Key) getUints(delim string, addInvalid, returnOnInvalid bool) ([]uint, error) {
648 strs := k.Strings(delim)
649 vals := make([]uint, 0, len(strs))
650 for _, str := range strs {
651 val, err := strconv.ParseUint(str, 10, 0)
652 if err != nil && returnOnInvalid {
655 if err == nil || addInvalid {
656 vals = append(vals, uint(val))
662 // getUint64s returns list of uint64 divided by given delimiter.
663 func (k *Key) getUint64s(delim string, addInvalid, returnOnInvalid bool) ([]uint64, error) {
664 strs := k.Strings(delim)
665 vals := make([]uint64, 0, len(strs))
666 for _, str := range strs {
667 val, err := strconv.ParseUint(str, 10, 64)
668 if err != nil && returnOnInvalid {
671 if err == nil || addInvalid {
672 vals = append(vals, val)
678 // getTimesFormat parses with given format and returns list of time.Time divided by given delimiter.
679 func (k *Key) getTimesFormat(format, delim string, addInvalid, returnOnInvalid bool) ([]time.Time, error) {
680 strs := k.Strings(delim)
681 vals := make([]time.Time, 0, len(strs))
682 for _, str := range strs {
683 val, err := time.Parse(format, str)
684 if err != nil && returnOnInvalid {
687 if err == nil || addInvalid {
688 vals = append(vals, val)
694 // SetValue changes key value.
695 func (k *Key) SetValue(v string) {
698 defer k.s.f.lock.Unlock()
702 k.s.keysHash[k.name] = v