1// Copyright 2014 Unknwon 2// 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 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 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 13// under the License. 14 15package ini 16 17import ( 18 "fmt" 19 "strconv" 20 "strings" 21 "time" 22) 23 24// Key represents a key under a section. 25type Key struct { 26 s *Section 27 name string 28 value string 29 isAutoIncrement bool 30 isBooleanType bool 31 32 Comment string 33} 34 35// ValueMapper represents a mapping function for values, e.g. os.ExpandEnv 36type ValueMapper func(string) string 37 38// Name returns name of key. 39func (k *Key) Name() string { 40 return k.name 41} 42 43// Value returns raw value of key for performance purpose. 44func (k *Key) Value() string { 45 return k.value 46} 47 48// String returns string representation of value. 49func (k *Key) String() string { 50 val := k.value 51 if k.s.f.ValueMapper != nil { 52 val = k.s.f.ValueMapper(val) 53 } 54 if strings.Index(val, "%") == -1 { 55 return val 56 } 57 58 for i := 0; i < _DEPTH_VALUES; i++ { 59 vr := varPattern.FindString(val) 60 if len(vr) == 0 { 61 break 62 } 63 64 // Take off leading '%(' and trailing ')s'. 65 noption := strings.TrimLeft(vr, "%(") 66 noption = strings.TrimRight(noption, ")s") 67 68 // Search in the same section. 69 nk, err := k.s.GetKey(noption) 70 if err != nil { 71 // Search again in default section. 72 nk, _ = k.s.f.Section("").GetKey(noption) 73 } 74 75 // Substitute by new value and take off leading '%(' and trailing ')s'. 76 val = strings.Replace(val, vr, nk.value, -1) 77 } 78 return val 79} 80 81// Validate accepts a validate function which can 82// return modifed result as key value. 83func (k *Key) Validate(fn func(string) string) string { 84 return fn(k.String()) 85} 86 87// parseBool returns the boolean value represented by the string. 88// 89// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On, 90// 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off. 91// Any other value returns an error. 92func parseBool(str string) (value bool, err error) { 93 switch str { 94 case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On": 95 return true, nil 96 case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off": 97 return false, nil 98 } 99 return false, fmt.Errorf("parsing \"%s\": invalid syntax", str) 100} 101 102// Bool returns bool type value. 103func (k *Key) Bool() (bool, error) { 104 return parseBool(k.String()) 105} 106 107// Float64 returns float64 type value. 108func (k *Key) Float64() (float64, error) { 109 return strconv.ParseFloat(k.String(), 64) 110} 111 112// Int returns int type value. 113func (k *Key) Int() (int, error) { 114 return strconv.Atoi(k.String()) 115} 116 117// Int64 returns int64 type value. 118func (k *Key) Int64() (int64, error) { 119 return strconv.ParseInt(k.String(), 10, 64) 120} 121 122// Uint returns uint type valued. 123func (k *Key) Uint() (uint, error) { 124 u, e := strconv.ParseUint(k.String(), 10, 64) 125 return uint(u), e 126} 127 128// Uint64 returns uint64 type value. 129func (k *Key) Uint64() (uint64, error) { 130 return strconv.ParseUint(k.String(), 10, 64) 131} 132 133// Duration returns time.Duration type value. 134func (k *Key) Duration() (time.Duration, error) { 135 return time.ParseDuration(k.String()) 136} 137 138// TimeFormat parses with given format and returns time.Time type value. 139func (k *Key) TimeFormat(format string) (time.Time, error) { 140 return time.Parse(format, k.String()) 141} 142 143// Time parses with RFC3339 format and returns time.Time type value. 144func (k *Key) Time() (time.Time, error) { 145 return k.TimeFormat(time.RFC3339) 146} 147 148// MustString returns default value if key value is empty. 149func (k *Key) MustString(defaultVal string) string { 150 val := k.String() 151 if len(val) == 0 { 152 k.value = defaultVal 153 return defaultVal 154 } 155 return val 156} 157 158// MustBool always returns value without error, 159// it returns false if error occurs. 160func (k *Key) MustBool(defaultVal ...bool) bool { 161 val, err := k.Bool() 162 if len(defaultVal) > 0 && err != nil { 163 k.value = strconv.FormatBool(defaultVal[0]) 164 return defaultVal[0] 165 } 166 return val 167} 168 169// MustFloat64 always returns value without error, 170// it returns 0.0 if error occurs. 171func (k *Key) MustFloat64(defaultVal ...float64) float64 { 172 val, err := k.Float64() 173 if len(defaultVal) > 0 && err != nil { 174 k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64) 175 return defaultVal[0] 176 } 177 return val 178} 179 180// MustInt always returns value without error, 181// it returns 0 if error occurs. 182func (k *Key) MustInt(defaultVal ...int) int { 183 val, err := k.Int() 184 if len(defaultVal) > 0 && err != nil { 185 k.value = strconv.FormatInt(int64(defaultVal[0]), 10) 186 return defaultVal[0] 187 } 188 return val 189} 190 191// MustInt64 always returns value without error, 192// it returns 0 if error occurs. 193func (k *Key) MustInt64(defaultVal ...int64) int64 { 194 val, err := k.Int64() 195 if len(defaultVal) > 0 && err != nil { 196 k.value = strconv.FormatInt(defaultVal[0], 10) 197 return defaultVal[0] 198 } 199 return val 200} 201 202// MustUint always returns value without error, 203// it returns 0 if error occurs. 204func (k *Key) MustUint(defaultVal ...uint) uint { 205 val, err := k.Uint() 206 if len(defaultVal) > 0 && err != nil { 207 k.value = strconv.FormatUint(uint64(defaultVal[0]), 10) 208 return defaultVal[0] 209 } 210 return val 211} 212 213// MustUint64 always returns value without error, 214// it returns 0 if error occurs. 215func (k *Key) MustUint64(defaultVal ...uint64) uint64 { 216 val, err := k.Uint64() 217 if len(defaultVal) > 0 && err != nil { 218 k.value = strconv.FormatUint(defaultVal[0], 10) 219 return defaultVal[0] 220 } 221 return val 222} 223 224// MustDuration always returns value without error, 225// it returns zero value if error occurs. 226func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration { 227 val, err := k.Duration() 228 if len(defaultVal) > 0 && err != nil { 229 k.value = defaultVal[0].String() 230 return defaultVal[0] 231 } 232 return val 233} 234 235// MustTimeFormat always parses with given format and returns value without error, 236// it returns zero value if error occurs. 237func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time { 238 val, err := k.TimeFormat(format) 239 if len(defaultVal) > 0 && err != nil { 240 k.value = defaultVal[0].Format(format) 241 return defaultVal[0] 242 } 243 return val 244} 245 246// MustTime always parses with RFC3339 format and returns value without error, 247// it returns zero value if error occurs. 248func (k *Key) MustTime(defaultVal ...time.Time) time.Time { 249 return k.MustTimeFormat(time.RFC3339, defaultVal...) 250} 251 252// In always returns value without error, 253// it returns default value if error occurs or doesn't fit into candidates. 254func (k *Key) In(defaultVal string, candidates []string) string { 255 val := k.String() 256 for _, cand := range candidates { 257 if val == cand { 258 return val 259 } 260 } 261 return defaultVal 262} 263 264// InFloat64 always returns value without error, 265// it returns default value if error occurs or doesn't fit into candidates. 266func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 { 267 val := k.MustFloat64() 268 for _, cand := range candidates { 269 if val == cand { 270 return val 271 } 272 } 273 return defaultVal 274} 275 276// InInt always returns value without error, 277// it returns default value if error occurs or doesn't fit into candidates. 278func (k *Key) InInt(defaultVal int, candidates []int) int { 279 val := k.MustInt() 280 for _, cand := range candidates { 281 if val == cand { 282 return val 283 } 284 } 285 return defaultVal 286} 287 288// InInt64 always returns value without error, 289// it returns default value if error occurs or doesn't fit into candidates. 290func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 { 291 val := k.MustInt64() 292 for _, cand := range candidates { 293 if val == cand { 294 return val 295 } 296 } 297 return defaultVal 298} 299 300// InUint always returns value without error, 301// it returns default value if error occurs or doesn't fit into candidates. 302func (k *Key) InUint(defaultVal uint, candidates []uint) uint { 303 val := k.MustUint() 304 for _, cand := range candidates { 305 if val == cand { 306 return val 307 } 308 } 309 return defaultVal 310} 311 312// InUint64 always returns value without error, 313// it returns default value if error occurs or doesn't fit into candidates. 314func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 { 315 val := k.MustUint64() 316 for _, cand := range candidates { 317 if val == cand { 318 return val 319 } 320 } 321 return defaultVal 322} 323 324// InTimeFormat always parses with given format and returns value without error, 325// it returns default value if error occurs or doesn't fit into candidates. 326func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time { 327 val := k.MustTimeFormat(format) 328 for _, cand := range candidates { 329 if val == cand { 330 return val 331 } 332 } 333 return defaultVal 334} 335 336// InTime always parses with RFC3339 format and returns value without error, 337// it returns default value if error occurs or doesn't fit into candidates. 338func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time { 339 return k.InTimeFormat(time.RFC3339, defaultVal, candidates) 340} 341 342// RangeFloat64 checks if value is in given range inclusively, 343// and returns default value if it's not. 344func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 { 345 val := k.MustFloat64() 346 if val < min || val > max { 347 return defaultVal 348 } 349 return val 350} 351 352// RangeInt checks if value is in given range inclusively, 353// and returns default value if it's not. 354func (k *Key) RangeInt(defaultVal, min, max int) int { 355 val := k.MustInt() 356 if val < min || val > max { 357 return defaultVal 358 } 359 return val 360} 361 362// RangeInt64 checks if value is in given range inclusively, 363// and returns default value if it's not. 364func (k *Key) RangeInt64(defaultVal, min, max int64) int64 { 365 val := k.MustInt64() 366 if val < min || val > max { 367 return defaultVal 368 } 369 return val 370} 371 372// RangeTimeFormat checks if value with given format is in given range inclusively, 373// and returns default value if it's not. 374func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time { 375 val := k.MustTimeFormat(format) 376 if val.Unix() < min.Unix() || val.Unix() > max.Unix() { 377 return defaultVal 378 } 379 return val 380} 381 382// RangeTime checks if value with RFC3339 format is in given range inclusively, 383// and returns default value if it's not. 384func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time { 385 return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max) 386} 387 388// Strings returns list of string divided by given delimiter. 389func (k *Key) Strings(delim string) []string { 390 str := k.String() 391 if len(str) == 0 { 392 return []string{} 393 } 394 395 vals := strings.Split(str, delim) 396 for i := range vals { 397 vals[i] = strings.TrimSpace(vals[i]) 398 } 399 return vals 400} 401 402// Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value. 403func (k *Key) Float64s(delim string) []float64 { 404 vals, _ := k.getFloat64s(delim, true, false) 405 return vals 406} 407 408// Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value. 409func (k *Key) Ints(delim string) []int { 410 vals, _ := k.getInts(delim, true, false) 411 return vals 412} 413 414// Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value. 415func (k *Key) Int64s(delim string) []int64 { 416 vals, _ := k.getInt64s(delim, true, false) 417 return vals 418} 419 420// Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value. 421func (k *Key) Uints(delim string) []uint { 422 vals, _ := k.getUints(delim, true, false) 423 return vals 424} 425 426// Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value. 427func (k *Key) Uint64s(delim string) []uint64 { 428 vals, _ := k.getUint64s(delim, true, false) 429 return vals 430} 431 432// TimesFormat parses with given format and returns list of time.Time divided by given delimiter. 433// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). 434func (k *Key) TimesFormat(format, delim string) []time.Time { 435 vals, _ := k.getTimesFormat(format, delim, true, false) 436 return vals 437} 438 439// Times parses with RFC3339 format and returns list of time.Time divided by given delimiter. 440// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). 441func (k *Key) Times(delim string) []time.Time { 442 return k.TimesFormat(time.RFC3339, delim) 443} 444 445// ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then 446// it will not be included to result list. 447func (k *Key) ValidFloat64s(delim string) []float64 { 448 vals, _ := k.getFloat64s(delim, false, false) 449 return vals 450} 451 452// ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will 453// not be included to result list. 454func (k *Key) ValidInts(delim string) []int { 455 vals, _ := k.getInts(delim, false, false) 456 return vals 457} 458 459// ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer, 460// then it will not be included to result list. 461func (k *Key) ValidInt64s(delim string) []int64 { 462 vals, _ := k.getInt64s(delim, false, false) 463 return vals 464} 465 466// ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer, 467// then it will not be included to result list. 468func (k *Key) ValidUints(delim string) []uint { 469 vals, _ := k.getUints(delim, false, false) 470 return vals 471} 472 473// ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned 474// integer, then it will not be included to result list. 475func (k *Key) ValidUint64s(delim string) []uint64 { 476 vals, _ := k.getUint64s(delim, false, false) 477 return vals 478} 479 480// ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter. 481func (k *Key) ValidTimesFormat(format, delim string) []time.Time { 482 vals, _ := k.getTimesFormat(format, delim, false, false) 483 return vals 484} 485 486// ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter. 487func (k *Key) ValidTimes(delim string) []time.Time { 488 return k.ValidTimesFormat(time.RFC3339, delim) 489} 490 491// StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input. 492func (k *Key) StrictFloat64s(delim string) ([]float64, error) { 493 return k.getFloat64s(delim, false, true) 494} 495 496// StrictInts returns list of int divided by given delimiter or error on first invalid input. 497func (k *Key) StrictInts(delim string) ([]int, error) { 498 return k.getInts(delim, false, true) 499} 500 501// StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input. 502func (k *Key) StrictInt64s(delim string) ([]int64, error) { 503 return k.getInt64s(delim, false, true) 504} 505 506// StrictUints returns list of uint divided by given delimiter or error on first invalid input. 507func (k *Key) StrictUints(delim string) ([]uint, error) { 508 return k.getUints(delim, false, true) 509} 510 511// StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input. 512func (k *Key) StrictUint64s(delim string) ([]uint64, error) { 513 return k.getUint64s(delim, false, true) 514} 515 516// StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter 517// or error on first invalid input. 518func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) { 519 return k.getTimesFormat(format, delim, false, true) 520} 521 522// StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter 523// or error on first invalid input. 524func (k *Key) StrictTimes(delim string) ([]time.Time, error) { 525 return k.StrictTimesFormat(time.RFC3339, delim) 526} 527 528// getFloat64s returns list of float64 divided by given delimiter. 529func (k *Key) getFloat64s(delim string, addInvalid, returnOnInvalid bool) ([]float64, error) { 530 strs := k.Strings(delim) 531 vals := make([]float64, 0, len(strs)) 532 for _, str := range strs { 533 val, err := strconv.ParseFloat(str, 64) 534 if err != nil && returnOnInvalid { 535 return nil, err 536 } 537 if err == nil || addInvalid { 538 vals = append(vals, val) 539 } 540 } 541 return vals, nil 542} 543 544// getInts returns list of int divided by given delimiter. 545func (k *Key) getInts(delim string, addInvalid, returnOnInvalid bool) ([]int, error) { 546 strs := k.Strings(delim) 547 vals := make([]int, 0, len(strs)) 548 for _, str := range strs { 549 val, err := strconv.Atoi(str) 550 if err != nil && returnOnInvalid { 551 return nil, err 552 } 553 if err == nil || addInvalid { 554 vals = append(vals, val) 555 } 556 } 557 return vals, nil 558} 559 560// getInt64s returns list of int64 divided by given delimiter. 561func (k *Key) getInt64s(delim string, addInvalid, returnOnInvalid bool) ([]int64, error) { 562 strs := k.Strings(delim) 563 vals := make([]int64, 0, len(strs)) 564 for _, str := range strs { 565 val, err := strconv.ParseInt(str, 10, 64) 566 if err != nil && returnOnInvalid { 567 return nil, err 568 } 569 if err == nil || addInvalid { 570 vals = append(vals, val) 571 } 572 } 573 return vals, nil 574} 575 576// getUints returns list of uint divided by given delimiter. 577func (k *Key) getUints(delim string, addInvalid, returnOnInvalid bool) ([]uint, error) { 578 strs := k.Strings(delim) 579 vals := make([]uint, 0, len(strs)) 580 for _, str := range strs { 581 val, err := strconv.ParseUint(str, 10, 0) 582 if err != nil && returnOnInvalid { 583 return nil, err 584 } 585 if err == nil || addInvalid { 586 vals = append(vals, uint(val)) 587 } 588 } 589 return vals, nil 590} 591 592// getUint64s returns list of uint64 divided by given delimiter. 593func (k *Key) getUint64s(delim string, addInvalid, returnOnInvalid bool) ([]uint64, error) { 594 strs := k.Strings(delim) 595 vals := make([]uint64, 0, len(strs)) 596 for _, str := range strs { 597 val, err := strconv.ParseUint(str, 10, 64) 598 if err != nil && returnOnInvalid { 599 return nil, err 600 } 601 if err == nil || addInvalid { 602 vals = append(vals, val) 603 } 604 } 605 return vals, nil 606} 607 608// getTimesFormat parses with given format and returns list of time.Time divided by given delimiter. 609func (k *Key) getTimesFormat(format, delim string, addInvalid, returnOnInvalid bool) ([]time.Time, error) { 610 strs := k.Strings(delim) 611 vals := make([]time.Time, 0, len(strs)) 612 for _, str := range strs { 613 val, err := time.Parse(format, str) 614 if err != nil && returnOnInvalid { 615 return nil, err 616 } 617 if err == nil || addInvalid { 618 vals = append(vals, val) 619 } 620 } 621 return vals, nil 622} 623 624// SetValue changes key value. 625func (k *Key) SetValue(v string) { 626 if k.s.f.BlockMode { 627 k.s.f.lock.Lock() 628 defer k.s.f.lock.Unlock() 629 } 630 631 k.value = v 632 k.s.keysHash[k.name] = v 633} 634