config.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. // Copyright 2013 Google, Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain 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,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package yaml
  15. import (
  16. "bytes"
  17. "fmt"
  18. "os"
  19. "strconv"
  20. "strings"
  21. )
  22. // A File represents the top-level YAML node found in a file. It is intended
  23. // for use as a configuration file.
  24. type File struct {
  25. Root Node
  26. // TODO(kevlar): Add a cache?
  27. }
  28. // ReadFile reads a YAML configuration file from the given filename.
  29. func ReadFile(filename string) (*File, error) {
  30. fin, err := os.Open(filename)
  31. if err != nil {
  32. return nil, err
  33. }
  34. defer fin.Close()
  35. f := new(File)
  36. f.Root, err = Parse(fin)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return f, nil
  41. }
  42. // Config reads a YAML configuration from a static string. If an error is
  43. // found, it will panic. This is a utility function and is intended for use in
  44. // initializers.
  45. func Config(yamlconf string) *File {
  46. var err error
  47. buf := bytes.NewBufferString(yamlconf)
  48. f := new(File)
  49. f.Root, err = Parse(buf)
  50. if err != nil {
  51. panic(err)
  52. }
  53. return f
  54. }
  55. // ConfigFile reads a YAML configuration file from the given filename and
  56. // panics if an error is found. This is a utility function and is intended for
  57. // use in initializers.
  58. func ConfigFile(filename string) *File {
  59. f, err := ReadFile(filename)
  60. if err != nil {
  61. panic(err)
  62. }
  63. return f
  64. }
  65. // Get retrieves a scalar from the file specified by a string of the same
  66. // format as that expected by Child. If the final node is not a Scalar, Get
  67. // will return an error.
  68. func (f *File) Get(spec string) (string, error) {
  69. node, err := Child(f.Root, spec)
  70. if err != nil {
  71. return "", err
  72. }
  73. if node == nil {
  74. return "", &NodeNotFound{
  75. Full: spec,
  76. Spec: spec,
  77. }
  78. }
  79. scalar, ok := node.(Scalar)
  80. if !ok {
  81. return "", &NodeTypeMismatch{
  82. Full: spec,
  83. Spec: spec,
  84. Token: "$",
  85. Expected: "yaml.Scalar",
  86. Node: node,
  87. }
  88. }
  89. return scalar.String(), nil
  90. }
  91. func (f *File) GetInt(spec string) (int64, error) {
  92. s, err := f.Get(spec)
  93. if err != nil {
  94. return 0, err
  95. }
  96. i, err := strconv.ParseInt(s, 10, 64)
  97. if err != nil {
  98. return 0, err
  99. }
  100. return i, nil
  101. }
  102. func (f *File) GetBool(spec string) (bool, error) {
  103. s, err := f.Get(spec)
  104. if err != nil {
  105. return false, err
  106. }
  107. b, err := strconv.ParseBool(s)
  108. if err != nil {
  109. return false, err
  110. }
  111. return b, nil
  112. }
  113. // Count retrieves a the number of elements in the specified list from the file
  114. // using the same format as that expected by Child. If the final node is not a
  115. // List, Count will return an error.
  116. func (f *File) Count(spec string) (int, error) {
  117. node, err := Child(f.Root, spec)
  118. if err != nil {
  119. return -1, err
  120. }
  121. if node == nil {
  122. return -1, &NodeNotFound{
  123. Full: spec,
  124. Spec: spec,
  125. }
  126. }
  127. lst, ok := node.(List)
  128. if !ok {
  129. return -1, &NodeTypeMismatch{
  130. Full: spec,
  131. Spec: spec,
  132. Token: "$",
  133. Expected: "yaml.List",
  134. Node: node,
  135. }
  136. }
  137. return lst.Len(), nil
  138. }
  139. // Require retrieves a scalar from the file specified by a string of the same
  140. // format as that expected by Child. If the final node is not a Scalar, String
  141. // will panic. This is a convenience function for use in initializers.
  142. func (f *File) Require(spec string) string {
  143. str, err := f.Get(spec)
  144. if err != nil {
  145. panic(err)
  146. }
  147. return str
  148. }
  149. // Child retrieves a child node from the specified node as follows:
  150. // .mapkey - Get the key 'mapkey' of the Node, which must be a Map
  151. // [idx] - Choose the index from the current Node, which must be a List
  152. //
  153. // The above selectors may be applied recursively, and each successive selector
  154. // applies to the result of the previous selector. For convenience, a "." is
  155. // implied as the first character if the first character is not a "." or "[".
  156. // The node tree is walked from the given node, considering each token of the
  157. // above format. If a node along the evaluation path is not found, an error is
  158. // returned. If a node is not the proper type, an error is returned. If the
  159. // final node is not a Scalar, an error is returned.
  160. func Child(root Node, spec string) (Node, error) {
  161. if len(spec) == 0 {
  162. return root, nil
  163. }
  164. if first := spec[0]; first != '.' && first != '[' {
  165. spec = "." + spec
  166. }
  167. var recur func(Node, string, string) (Node, error)
  168. recur = func(n Node, last, s string) (Node, error) {
  169. if len(s) == 0 {
  170. return n, nil
  171. }
  172. if n == nil {
  173. return nil, &NodeNotFound{
  174. Full: spec,
  175. Spec: last,
  176. }
  177. }
  178. // Extract the next token
  179. delim := 1 + strings.IndexAny(s[1:], ".[")
  180. if delim <= 0 {
  181. delim = len(s)
  182. }
  183. tok := s[:delim]
  184. remain := s[delim:]
  185. switch s[0] {
  186. case '[':
  187. s, ok := n.(List)
  188. if !ok {
  189. return nil, &NodeTypeMismatch{
  190. Node: n,
  191. Expected: "yaml.List",
  192. Full: spec,
  193. Spec: last,
  194. Token: tok,
  195. }
  196. }
  197. if tok[0] == '[' && tok[len(tok)-1] == ']' {
  198. if num, err := strconv.Atoi(tok[1 : len(tok)-1]); err == nil {
  199. if num >= 0 && num < len(s) {
  200. return recur(s[num], last+tok, remain)
  201. }
  202. }
  203. }
  204. return nil, &NodeNotFound{
  205. Full: spec,
  206. Spec: last + tok,
  207. }
  208. default:
  209. m, ok := n.(Map)
  210. if !ok {
  211. return nil, &NodeTypeMismatch{
  212. Node: n,
  213. Expected: "yaml.Map",
  214. Full: spec,
  215. Spec: last,
  216. Token: tok,
  217. }
  218. }
  219. n, ok = m[tok[1:]]
  220. if !ok {
  221. return nil, &NodeNotFound{
  222. Full: spec,
  223. Spec: last + tok,
  224. }
  225. }
  226. return recur(n, last+tok, remain)
  227. }
  228. }
  229. return recur(root, "", spec)
  230. }
  231. type NodeNotFound struct {
  232. Full string
  233. Spec string
  234. }
  235. func (e *NodeNotFound) Error() string {
  236. return fmt.Sprintf("yaml: %s: %q not found", e.Full, e.Spec)
  237. }
  238. type NodeTypeMismatch struct {
  239. Full string
  240. Spec string
  241. Token string
  242. Node Node
  243. Expected string
  244. }
  245. func (e *NodeTypeMismatch) Error() string {
  246. return fmt.Sprintf("yaml: %s: type mismatch: %q is %T, want %s (at %q)",
  247. e.Full, e.Spec, e.Node, e.Expected, e.Token)
  248. }