key.go 18 KB

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