Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package setting
  4. import (
  5. "errors"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/util"
  14. "gopkg.in/ini.v1" //nolint:depguard
  15. )
  16. type ConfigKey interface {
  17. Name() string
  18. Value() string
  19. SetValue(v string)
  20. In(defaultVal string, candidates []string) string
  21. String() string
  22. Strings(delim string) []string
  23. MustString(defaultVal string) string
  24. MustBool(defaultVal ...bool) bool
  25. MustInt(defaultVal ...int) int
  26. MustInt64(defaultVal ...int64) int64
  27. MustDuration(defaultVal ...time.Duration) time.Duration
  28. }
  29. type ConfigSection interface {
  30. Name() string
  31. MapTo(any) error
  32. HasKey(key string) bool
  33. NewKey(name, value string) (ConfigKey, error)
  34. Key(key string) ConfigKey
  35. Keys() []ConfigKey
  36. ChildSections() []ConfigSection
  37. }
  38. // ConfigProvider represents a config provider
  39. type ConfigProvider interface {
  40. Section(section string) ConfigSection
  41. Sections() []ConfigSection
  42. NewSection(name string) (ConfigSection, error)
  43. GetSection(name string) (ConfigSection, error)
  44. Save() error
  45. SaveTo(filename string) error
  46. DisableSaving()
  47. PrepareSaving() (ConfigProvider, error)
  48. IsLoadedFromEmpty() bool
  49. }
  50. type iniConfigProvider struct {
  51. file string
  52. ini *ini.File
  53. disableSaving bool // disable the "Save" method because the config options could be polluted
  54. loadedFromEmpty bool // whether the file has not existed previously
  55. }
  56. type iniConfigSection struct {
  57. sec *ini.Section
  58. }
  59. var (
  60. _ ConfigProvider = (*iniConfigProvider)(nil)
  61. _ ConfigSection = (*iniConfigSection)(nil)
  62. _ ConfigKey = (*ini.Key)(nil)
  63. )
  64. // ConfigSectionKey only searches the keys in the given section, but it is O(n).
  65. // ini package has a special behavior: with "[sec] a=1" and an empty "[sec.sub]",
  66. // then in "[sec.sub]", Key()/HasKey() can always see "a=1" because it always tries parent sections.
  67. // It returns nil if the key doesn't exist.
  68. func ConfigSectionKey(sec ConfigSection, key string) ConfigKey {
  69. if sec == nil {
  70. return nil
  71. }
  72. for _, k := range sec.Keys() {
  73. if k.Name() == key {
  74. return k
  75. }
  76. }
  77. return nil
  78. }
  79. func ConfigSectionKeyString(sec ConfigSection, key string, def ...string) string {
  80. k := ConfigSectionKey(sec, key)
  81. if k != nil && k.String() != "" {
  82. return k.String()
  83. }
  84. if len(def) > 0 {
  85. return def[0]
  86. }
  87. return ""
  88. }
  89. func ConfigSectionKeyBool(sec ConfigSection, key string, def ...bool) bool {
  90. k := ConfigSectionKey(sec, key)
  91. if k != nil && k.String() != "" {
  92. b, _ := strconv.ParseBool(k.String())
  93. return b
  94. }
  95. if len(def) > 0 {
  96. return def[0]
  97. }
  98. return false
  99. }
  100. // ConfigInheritedKey works like ini.Section.Key(), but it always returns a new key instance, it is O(n) because NewKey is O(n)
  101. // and the returned key is safe to be used with "MustXxx", it doesn't change the parent's values.
  102. // Otherwise, ini.Section.Key().MustXxx would pollute the parent section's keys.
  103. // It never returns nil.
  104. func ConfigInheritedKey(sec ConfigSection, key string) ConfigKey {
  105. k := sec.Key(key)
  106. if k != nil && k.String() != "" {
  107. newKey, _ := sec.NewKey(k.Name(), k.String())
  108. return newKey
  109. }
  110. newKey, _ := sec.NewKey(key, "")
  111. return newKey
  112. }
  113. func ConfigInheritedKeyString(sec ConfigSection, key string, def ...string) string {
  114. k := sec.Key(key)
  115. if k != nil && k.String() != "" {
  116. return k.String()
  117. }
  118. if len(def) > 0 {
  119. return def[0]
  120. }
  121. return ""
  122. }
  123. func (s *iniConfigSection) Name() string {
  124. return s.sec.Name()
  125. }
  126. func (s *iniConfigSection) MapTo(v any) error {
  127. return s.sec.MapTo(v)
  128. }
  129. func (s *iniConfigSection) HasKey(key string) bool {
  130. return s.sec.HasKey(key)
  131. }
  132. func (s *iniConfigSection) NewKey(name, value string) (ConfigKey, error) {
  133. return s.sec.NewKey(name, value)
  134. }
  135. func (s *iniConfigSection) Key(key string) ConfigKey {
  136. return s.sec.Key(key)
  137. }
  138. func (s *iniConfigSection) Keys() (keys []ConfigKey) {
  139. for _, k := range s.sec.Keys() {
  140. keys = append(keys, k)
  141. }
  142. return keys
  143. }
  144. func (s *iniConfigSection) ChildSections() (sections []ConfigSection) {
  145. for _, s := range s.sec.ChildSections() {
  146. sections = append(sections, &iniConfigSection{s})
  147. }
  148. return sections
  149. }
  150. // NewConfigProviderFromData this function is mainly for testing purpose
  151. func NewConfigProviderFromData(configContent string) (ConfigProvider, error) {
  152. cfg, err := ini.Load(strings.NewReader(configContent))
  153. if err != nil {
  154. return nil, err
  155. }
  156. cfg.NameMapper = ini.SnackCase
  157. return &iniConfigProvider{
  158. ini: cfg,
  159. loadedFromEmpty: true,
  160. }, nil
  161. }
  162. // NewConfigProviderFromFile load configuration from file.
  163. // NOTE: do not print any log except error.
  164. func NewConfigProviderFromFile(file string, extraConfigs ...string) (ConfigProvider, error) {
  165. cfg := ini.Empty(ini.LoadOptions{KeyValueDelimiterOnWrite: " = "})
  166. loadedFromEmpty := true
  167. if file != "" {
  168. isFile, err := util.IsFile(file)
  169. if err != nil {
  170. return nil, fmt.Errorf("unable to check if %q is a file. Error: %v", file, err)
  171. }
  172. if isFile {
  173. if err = cfg.Append(file); err != nil {
  174. return nil, fmt.Errorf("failed to load config file %q: %v", file, err)
  175. }
  176. loadedFromEmpty = false
  177. }
  178. }
  179. if len(extraConfigs) > 0 {
  180. for _, s := range extraConfigs {
  181. if err := cfg.Append([]byte(s)); err != nil {
  182. return nil, fmt.Errorf("unable to append more config: %v", err)
  183. }
  184. }
  185. }
  186. cfg.NameMapper = ini.SnackCase
  187. return &iniConfigProvider{
  188. file: file,
  189. ini: cfg,
  190. loadedFromEmpty: loadedFromEmpty,
  191. }, nil
  192. }
  193. func (p *iniConfigProvider) Section(section string) ConfigSection {
  194. return &iniConfigSection{sec: p.ini.Section(section)}
  195. }
  196. func (p *iniConfigProvider) Sections() (sections []ConfigSection) {
  197. for _, s := range p.ini.Sections() {
  198. sections = append(sections, &iniConfigSection{s})
  199. }
  200. return sections
  201. }
  202. func (p *iniConfigProvider) NewSection(name string) (ConfigSection, error) {
  203. sec, err := p.ini.NewSection(name)
  204. if err != nil {
  205. return nil, err
  206. }
  207. return &iniConfigSection{sec: sec}, nil
  208. }
  209. func (p *iniConfigProvider) GetSection(name string) (ConfigSection, error) {
  210. sec, err := p.ini.GetSection(name)
  211. if err != nil {
  212. return nil, err
  213. }
  214. return &iniConfigSection{sec: sec}, nil
  215. }
  216. var errDisableSaving = errors.New("this config can't be saved, developers should prepare a new config to save")
  217. // Save saves the content into file
  218. func (p *iniConfigProvider) Save() error {
  219. if p.disableSaving {
  220. return errDisableSaving
  221. }
  222. filename := p.file
  223. if filename == "" {
  224. return fmt.Errorf("config file path must not be empty")
  225. }
  226. if p.loadedFromEmpty {
  227. if err := os.MkdirAll(filepath.Dir(filename), os.ModePerm); err != nil {
  228. return fmt.Errorf("failed to create %q: %v", filename, err)
  229. }
  230. }
  231. if err := p.ini.SaveTo(filename); err != nil {
  232. return fmt.Errorf("failed to save %q: %v", filename, err)
  233. }
  234. // Change permissions to be more restrictive
  235. fi, err := os.Stat(filename)
  236. if err != nil {
  237. return fmt.Errorf("failed to determine current conf file permissions: %v", err)
  238. }
  239. if fi.Mode().Perm() > 0o600 {
  240. if err = os.Chmod(filename, 0o600); err != nil {
  241. log.Warn("Failed changing conf file permissions to -rw-------. Consider changing them manually.")
  242. }
  243. }
  244. return nil
  245. }
  246. func (p *iniConfigProvider) SaveTo(filename string) error {
  247. if p.disableSaving {
  248. return errDisableSaving
  249. }
  250. return p.ini.SaveTo(filename)
  251. }
  252. // DisableSaving disables the saving function, use PrepareSaving to get clear config options.
  253. func (p *iniConfigProvider) DisableSaving() {
  254. p.disableSaving = true
  255. }
  256. // PrepareSaving loads the ini from file again to get clear config options.
  257. // Otherwise, the "MustXxx" calls would have polluted the current config provider,
  258. // it makes the "Save" outputs a lot of garbage options
  259. // After the INI package gets refactored, no "MustXxx" pollution, this workaround can be dropped.
  260. func (p *iniConfigProvider) PrepareSaving() (ConfigProvider, error) {
  261. if p.file == "" {
  262. return nil, errors.New("no config file to save")
  263. }
  264. return NewConfigProviderFromFile(p.file)
  265. }
  266. func (p *iniConfigProvider) IsLoadedFromEmpty() bool {
  267. return p.loadedFromEmpty
  268. }
  269. func mustMapSetting(rootCfg ConfigProvider, sectionName string, setting any) {
  270. if err := rootCfg.Section(sectionName).MapTo(setting); err != nil {
  271. log.Fatal("Failed to map %s settings: %v", sectionName, err)
  272. }
  273. }
  274. // DeprecatedWarnings contains the warning message for various deprecations, including: setting option, file/folder, etc
  275. var DeprecatedWarnings []string
  276. func deprecatedSetting(rootCfg ConfigProvider, oldSection, oldKey, newSection, newKey, version string) {
  277. if rootCfg.Section(oldSection).HasKey(oldKey) {
  278. msg := fmt.Sprintf("Deprecated config option `[%s]` `%s` present. Use `[%s]` `%s` instead. This fallback will be/has been removed in %s", oldSection, oldKey, newSection, newKey, version)
  279. log.Error("%v", msg)
  280. DeprecatedWarnings = append(DeprecatedWarnings, msg)
  281. }
  282. }
  283. // deprecatedSettingDB add a hint that the configuration has been moved to database but still kept in app.ini
  284. func deprecatedSettingDB(rootCfg ConfigProvider, oldSection, oldKey string) {
  285. if rootCfg.Section(oldSection).HasKey(oldKey) {
  286. log.Error("Deprecated `[%s]` `%s` present which has been copied to database table sys_setting", oldSection, oldKey)
  287. }
  288. }
  289. // NewConfigProviderForLocale loads locale configuration from source and others. "string" if for a local file path, "[]byte" is for INI content
  290. func NewConfigProviderForLocale(source any, others ...any) (ConfigProvider, error) {
  291. iniFile, err := ini.LoadSources(ini.LoadOptions{
  292. IgnoreInlineComment: true,
  293. UnescapeValueCommentSymbols: true,
  294. }, source, others...)
  295. if err != nil {
  296. return nil, fmt.Errorf("unable to load locale ini: %w", err)
  297. }
  298. iniFile.BlockMode = false
  299. return &iniConfigProvider{
  300. ini: iniFile,
  301. loadedFromEmpty: true,
  302. }, nil
  303. }
  304. func init() {
  305. ini.PrettyFormat = false
  306. }