config.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. // Copyright 2013, Cong Ding. 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. //
  15. // author: Cong Ding <dinggnu@gmail.com>
  16. package config
  17. import (
  18. "bufio"
  19. "errors"
  20. "fmt"
  21. "io/ioutil"
  22. "os"
  23. "strings"
  24. )
  25. var commentPrefix = []string{"//", "#", ";"}
  26. // Config struct constructs a new configuration handler.
  27. type Config struct {
  28. filename string
  29. config map[string]map[string]string
  30. }
  31. // NewConfig function cnstructs a new Config struct with filename. You have to
  32. // call Read() function to let it read from the file. Otherwise you will get
  33. // empty string (i.e., "") when you are calling Get() function. Another usage
  34. // is that you call NewConfig() function and then call Add()/Set() function to
  35. // add new key-values to the configuration. Finally you can call Write()
  36. // function to write the new configuration to the file.
  37. func NewConfig(filename string) *Config {
  38. c := new(Config)
  39. c.filename = filename
  40. c.config = make(map[string]map[string]string)
  41. return c
  42. }
  43. // Filename function returns the filename of the configuration.
  44. func (c *Config) Filename() string {
  45. return c.filename
  46. }
  47. // SetFilename function sets the filename of the configuration.
  48. func (c *Config) SetFilename(filename string) {
  49. c.filename = filename
  50. }
  51. // Reset function reset the map in the configuration.
  52. func (c *Config) Reset() {
  53. c.config = make(map[string]map[string]string)
  54. }
  55. // Read function reads configurations from the file defined in
  56. // Config.filename.
  57. func (c *Config) Read() error {
  58. in, err := os.Open(c.filename)
  59. if err != nil {
  60. return err
  61. }
  62. defer in.Close()
  63. scanner := bufio.NewScanner(in)
  64. line := ""
  65. section := ""
  66. for scanner.Scan() {
  67. if scanner.Text() == "" {
  68. continue
  69. }
  70. if line == "" {
  71. sec, ok := checkSection(scanner.Text())
  72. if ok {
  73. section = sec
  74. continue
  75. }
  76. }
  77. if checkComment(scanner.Text()) {
  78. continue
  79. }
  80. line += scanner.Text()
  81. if strings.HasSuffix(line, "\\") {
  82. line = line[:len(line)-1]
  83. continue
  84. }
  85. key, value, ok := checkLine(line)
  86. if !ok {
  87. return errors.New("WRONG: " + line)
  88. }
  89. c.Set(section, key, value)
  90. line = ""
  91. }
  92. return nil
  93. }
  94. // Get function returns the value of a key in the configuration. If the key
  95. // does not exist, it returns empty string (i.e., "").
  96. func (c *Config) Get(section string, key string) string {
  97. value, ok := c.config[section][key]
  98. if !ok {
  99. return ""
  100. }
  101. return value
  102. }
  103. // Set function updates the value of a key in the configuration. Function
  104. // Set() is exactly the same as function Add().
  105. func (c *Config) Set(section string, key string, value string) {
  106. _, ok := c.config[section]
  107. if !ok {
  108. c.config[section] = make(map[string]string)
  109. }
  110. c.config[section][key] = value
  111. }
  112. // Add function adds a new key to the configuration. Function Add() is exactly
  113. // the same as function Set().
  114. func (c *Config) Add(section string, key string, value string) {
  115. c.Set(section, key, value)
  116. }
  117. // Del function deletes a key from the configuration.
  118. func (c *Config) Del(section string, key string) {
  119. _, ok := c.config[section]
  120. if ok {
  121. delete(c.config[section], key)
  122. if len(c.config[section]) == 0 {
  123. delete(c.config, section)
  124. }
  125. }
  126. }
  127. // Write function writes the updated configuration back.
  128. func (c *Config) Write() error {
  129. return nil
  130. }
  131. // WriteTo function writes the configuration to a new file. This function
  132. // re-organizes the configuration and deletes all the comments.
  133. func (c *Config) WriteTo(filename string) error {
  134. content := ""
  135. for k, v := range c.config {
  136. format := "%v = %v\n"
  137. if k != "" {
  138. content += fmt.Sprintf("[%v]\n", k)
  139. format = "\t" + format
  140. }
  141. for key, value := range v {
  142. content += fmt.Sprintf(format, key, value)
  143. }
  144. }
  145. return ioutil.WriteFile(filename, []byte(content), 0644)
  146. }
  147. // To check this line is a section or not. If it is not a section, it returns
  148. // "".
  149. func checkSection(line string) (string, bool) {
  150. line = strings.TrimSpace(line)
  151. lineLen := len(line)
  152. if lineLen < 2 {
  153. return "", false
  154. }
  155. if line[0] == '[' && line[lineLen-1] == ']' {
  156. return line[1 : lineLen-1], true
  157. }
  158. return "", false
  159. }
  160. // To check this line is a valid key-value pair or not.
  161. func checkLine(line string) (string, string, bool) {
  162. key := ""
  163. value := ""
  164. sp := strings.SplitN(line, "=", 2)
  165. if len(sp) != 2 {
  166. return key, value, false
  167. }
  168. key = strings.TrimSpace(sp[0])
  169. value = strings.TrimSpace(sp[1])
  170. return key, value, true
  171. }
  172. // To check this line is a whole line comment or not.
  173. func checkComment(line string) bool {
  174. line = strings.TrimSpace(line)
  175. for p := range commentPrefix {
  176. if strings.HasPrefix(line, commentPrefix[p]) {
  177. return true
  178. }
  179. }
  180. return false
  181. }