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.

224 lines
6.0 KiB

  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. "github.com/unknwon/com"
  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. if com.IsFile(setting.CustomConf) {
  88. if err := cfg.Append(setting.CustomConf); err != nil {
  89. log.Fatal("Failed to load custom conf '%s': %v", setting.CustomConf, err)
  90. }
  91. } else {
  92. log.Warn("Custom config '%s' not found, ignore this if you're running first time", setting.CustomConf)
  93. }
  94. cfg.NameMapper = ini.SnackCase
  95. prefix := c.String("prefix") + "__"
  96. for _, kv := range os.Environ() {
  97. idx := strings.IndexByte(kv, '=')
  98. if idx < 0 {
  99. continue
  100. }
  101. eKey := kv[:idx]
  102. value := kv[idx+1:]
  103. if !strings.HasPrefix(eKey, prefix) {
  104. continue
  105. }
  106. eKey = eKey[len(prefix):]
  107. sectionName, keyName := DecodeSectionKey(eKey)
  108. if len(keyName) == 0 {
  109. continue
  110. }
  111. section, err := cfg.GetSection(sectionName)
  112. if err != nil {
  113. section, err = cfg.NewSection(sectionName)
  114. if err != nil {
  115. log.Error("Error creating section: %s : %v", sectionName, err)
  116. continue
  117. }
  118. }
  119. key := section.Key(keyName)
  120. if key == nil {
  121. key, err = section.NewKey(keyName, value)
  122. if err != nil {
  123. log.Error("Error creating key: %s in section: %s with value: %s : %v", keyName, sectionName, value, err)
  124. continue
  125. }
  126. }
  127. key.SetValue(value)
  128. }
  129. destination := c.String("out")
  130. if len(destination) == 0 {
  131. destination = setting.CustomConf
  132. }
  133. err := cfg.SaveTo(destination)
  134. if err != nil {
  135. return err
  136. }
  137. if c.Bool("clear") {
  138. for _, kv := range os.Environ() {
  139. idx := strings.IndexByte(kv, '=')
  140. if idx < 0 {
  141. continue
  142. }
  143. eKey := kv[:idx]
  144. if strings.HasPrefix(eKey, prefix) {
  145. _ = os.Unsetenv(eKey)
  146. }
  147. }
  148. }
  149. return nil
  150. }
  151. const escapeRegexpString = "_0[xX](([0-9a-fA-F][0-9a-fA-F])+)_"
  152. var escapeRegex = regexp.MustCompile(escapeRegexpString)
  153. // DecodeSectionKey will decode a portable string encoded Section__Key pair
  154. // Portable strings are considered to be of the form [A-Z0-9_]*
  155. // We will encode a disallowed value as the UTF8 byte string preceded by _0X and
  156. // followed by _. E.g. _0X2C_ for a '-' and _0X2E_ for '.'
  157. // Section and Key are separated by a plain '__'.
  158. // The entire section can be encoded as a UTF8 byte string
  159. func DecodeSectionKey(encoded string) (string, string) {
  160. section := ""
  161. key := ""
  162. inKey := false
  163. last := 0
  164. escapeStringIndices := escapeRegex.FindAllStringIndex(encoded, -1)
  165. for _, unescapeIdx := range escapeStringIndices {
  166. preceding := encoded[last:unescapeIdx[0]]
  167. if !inKey {
  168. if splitter := strings.Index(preceding, "__"); splitter > -1 {
  169. section += preceding[:splitter]
  170. inKey = true
  171. key += preceding[splitter+2:]
  172. } else {
  173. section += preceding
  174. }
  175. } else {
  176. key += preceding
  177. }
  178. toDecode := encoded[unescapeIdx[0]+3 : unescapeIdx[1]-1]
  179. decodedBytes := make([]byte, len(toDecode)/2)
  180. for i := 0; i < len(toDecode)/2; i++ {
  181. // Can ignore error here as we know these should be hexadecimal from the regexp
  182. byteInt, _ := strconv.ParseInt(toDecode[2*i:2*i+2], 16, 0)
  183. decodedBytes[i] = byte(byteInt)
  184. }
  185. if inKey {
  186. key += string(decodedBytes)
  187. } else {
  188. section += string(decodedBytes)
  189. }
  190. last = unescapeIdx[1]
  191. }
  192. remaining := encoded[last:]
  193. if !inKey {
  194. if splitter := strings.Index(remaining, "__"); splitter > -1 {
  195. section += remaining[:splitter]
  196. inKey = true
  197. key += remaining[splitter+2:]
  198. } else {
  199. section += remaining
  200. }
  201. } else {
  202. key += remaining
  203. }
  204. return section, key
  205. }