You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

environment-to-ini.go 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "os"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/util"
  13. "github.com/urfave/cli"
  14. ini "gopkg.in/ini.v1"
  15. )
  16. // EnvironmentPrefix environment variables prefixed with this represent ini values to write
  17. const EnvironmentPrefix = "GITEA"
  18. func main() {
  19. app := cli.NewApp()
  20. app.Name = "environment-to-ini"
  21. app.Usage = "Use provided environment to update configuration ini"
  22. app.Description = `As a helper to allow docker users to update the gitea configuration
  23. through the environment, this command allows environment variables to
  24. be mapped to values in the ini.
  25. Environment variables of the form "GITEA__SECTION_NAME__KEY_NAME"
  26. will be mapped to the ini section "[section_name]" and the key
  27. "KEY_NAME" with the value as provided.
  28. Environment variables are usually restricted to a reduced character
  29. set "0-9A-Z_" - in order to allow the setting of sections with
  30. characters outside of that set, they should be escaped as following:
  31. "_0X2E_" for ".". The entire section and key names can be escaped as
  32. a UTF8 byte string if necessary. E.g. to configure:
  33. """
  34. ...
  35. [log.console]
  36. COLORIZE=false
  37. STDERR=true
  38. ...
  39. """
  40. You would set the environment variables: "GITEA__LOG_0x2E_CONSOLE__COLORIZE=false"
  41. and "GITEA__LOG_0x2E_CONSOLE__STDERR=false". Other examples can be found
  42. on the configuration cheat sheet.`
  43. app.Flags = []cli.Flag{
  44. cli.StringFlag{
  45. Name: "custom-path, C",
  46. Value: setting.CustomPath,
  47. Usage: "Custom path file path",
  48. },
  49. cli.StringFlag{
  50. Name: "config, c",
  51. Value: setting.CustomConf,
  52. Usage: "Custom configuration file path",
  53. },
  54. cli.StringFlag{
  55. Name: "work-path, w",
  56. Value: setting.AppWorkPath,
  57. Usage: "Set the gitea working path",
  58. },
  59. cli.StringFlag{
  60. Name: "out, o",
  61. Value: "",
  62. Usage: "Destination file to write to",
  63. },
  64. cli.BoolFlag{
  65. Name: "clear",
  66. Usage: "Clears the matched variables from the environment",
  67. },
  68. cli.StringFlag{
  69. Name: "prefix, p",
  70. Value: EnvironmentPrefix,
  71. Usage: "Environment prefix to look for - will be suffixed by __ (2 underscores)",
  72. },
  73. }
  74. app.Action = runEnvironmentToIni
  75. setting.SetCustomPathAndConf("", "", "")
  76. err := app.Run(os.Args)
  77. if err != nil {
  78. log.Fatal("Failed to run app with %s: %v", os.Args, err)
  79. }
  80. }
  81. func runEnvironmentToIni(c *cli.Context) error {
  82. providedCustom := c.String("custom-path")
  83. providedConf := c.String("config")
  84. providedWorkPath := c.String("work-path")
  85. setting.SetCustomPathAndConf(providedCustom, providedConf, providedWorkPath)
  86. cfg := ini.Empty()
  87. isFile, err := util.IsFile(setting.CustomConf)
  88. if err != nil {
  89. log.Fatal("Unable to check if %s is a file. Error: %v", setting.CustomConf, err)
  90. }
  91. if isFile {
  92. if err := cfg.Append(setting.CustomConf); err != nil {
  93. log.Fatal("Failed to load custom conf '%s': %v", setting.CustomConf, err)
  94. }
  95. } else {
  96. log.Warn("Custom config '%s' not found, ignore this if you're running first time", setting.CustomConf)
  97. }
  98. cfg.NameMapper = ini.SnackCase
  99. changed := false
  100. prefix := c.String("prefix") + "__"
  101. for _, kv := range os.Environ() {
  102. idx := strings.IndexByte(kv, '=')
  103. if idx < 0 {
  104. continue
  105. }
  106. eKey := kv[:idx]
  107. value := kv[idx+1:]
  108. if !strings.HasPrefix(eKey, prefix) {
  109. continue
  110. }
  111. eKey = eKey[len(prefix):]
  112. sectionName, keyName := DecodeSectionKey(eKey)
  113. if len(keyName) == 0 {
  114. continue
  115. }
  116. section, err := cfg.GetSection(sectionName)
  117. if err != nil {
  118. section, err = cfg.NewSection(sectionName)
  119. if err != nil {
  120. log.Error("Error creating section: %s : %v", sectionName, err)
  121. continue
  122. }
  123. }
  124. key := section.Key(keyName)
  125. if key == nil {
  126. key, err = section.NewKey(keyName, value)
  127. if err != nil {
  128. log.Error("Error creating key: %s in section: %s with value: %s : %v", keyName, sectionName, value, err)
  129. continue
  130. }
  131. }
  132. oldValue := key.Value()
  133. if !changed && oldValue != value {
  134. changed = true
  135. }
  136. key.SetValue(value)
  137. }
  138. destination := c.String("out")
  139. if len(destination) == 0 {
  140. destination = setting.CustomConf
  141. }
  142. if destination != setting.CustomConf || changed {
  143. log.Info("Settings saved to: %q", destination)
  144. err = cfg.SaveTo(destination)
  145. if err != nil {
  146. return err
  147. }
  148. }
  149. if c.Bool("clear") {
  150. for _, kv := range os.Environ() {
  151. idx := strings.IndexByte(kv, '=')
  152. if idx < 0 {
  153. continue
  154. }
  155. eKey := kv[:idx]
  156. if strings.HasPrefix(eKey, prefix) {
  157. _ = os.Unsetenv(eKey)
  158. }
  159. }
  160. }
  161. return nil
  162. }
  163. const escapeRegexpString = "_0[xX](([0-9a-fA-F][0-9a-fA-F])+)_"
  164. var escapeRegex = regexp.MustCompile(escapeRegexpString)
  165. // DecodeSectionKey will decode a portable string encoded Section__Key pair
  166. // Portable strings are considered to be of the form [A-Z0-9_]*
  167. // We will encode a disallowed value as the UTF8 byte string preceded by _0X and
  168. // followed by _. E.g. _0X2C_ for a '-' and _0X2E_ for '.'
  169. // Section and Key are separated by a plain '__'.
  170. // The entire section can be encoded as a UTF8 byte string
  171. func DecodeSectionKey(encoded string) (string, string) {
  172. section := ""
  173. key := ""
  174. inKey := false
  175. last := 0
  176. escapeStringIndices := escapeRegex.FindAllStringIndex(encoded, -1)
  177. for _, unescapeIdx := range escapeStringIndices {
  178. preceding := encoded[last:unescapeIdx[0]]
  179. if !inKey {
  180. if splitter := strings.Index(preceding, "__"); splitter > -1 {
  181. section += preceding[:splitter]
  182. inKey = true
  183. key += preceding[splitter+2:]
  184. } else {
  185. section += preceding
  186. }
  187. } else {
  188. key += preceding
  189. }
  190. toDecode := encoded[unescapeIdx[0]+3 : unescapeIdx[1]-1]
  191. decodedBytes := make([]byte, len(toDecode)/2)
  192. for i := 0; i < len(toDecode)/2; i++ {
  193. // Can ignore error here as we know these should be hexadecimal from the regexp
  194. byteInt, _ := strconv.ParseInt(toDecode[2*i:2*i+2], 16, 0)
  195. decodedBytes[i] = byte(byteInt)
  196. }
  197. if inKey {
  198. key += string(decodedBytes)
  199. } else {
  200. section += string(decodedBytes)
  201. }
  202. last = unescapeIdx[1]
  203. }
  204. remaining := encoded[last:]
  205. if !inKey {
  206. if splitter := strings.Index(remaining, "__"); splitter > -1 {
  207. section += remaining[:splitter]
  208. key += remaining[splitter+2:]
  209. } else {
  210. section += remaining
  211. }
  212. } else {
  213. key += remaining
  214. }
  215. section = strings.ToLower(section)
  216. return section, key
  217. }