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.3KB

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