config.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package ini
  2. import (
  3. "fmt"
  4. "io"
  5. "git.ali33.ru/fcg-xvii/go-tools/text/config"
  6. "git.ali33.ru/fcg-xvii/go-tools/value"
  7. )
  8. func newConfig() *Config {
  9. mainSection := []config.Section{
  10. newSection(),
  11. }
  12. return &Config{
  13. sections: map[string][]config.Section{
  14. "main": mainSection,
  15. },
  16. }
  17. }
  18. type Config struct {
  19. sections map[string][]config.Section
  20. }
  21. func (s *Config) Sections(name string) ([]config.Section, bool) {
  22. sections, check := s.sections[name]
  23. return sections, check
  24. }
  25. func (s *Config) Section(name string) (config.Section, bool) {
  26. if sections, check := s.Sections(name); check {
  27. return sections[0], true
  28. }
  29. return nil, false
  30. }
  31. func (s *Config) AppendSection(name string) config.Section {
  32. section := newSection()
  33. if sections, check := s.Sections(name); check {
  34. sections = append(sections, section)
  35. s.sections[name] = sections
  36. } else {
  37. s.sections[name] = []config.Section{section}
  38. }
  39. return section
  40. }
  41. func (s *Config) ValueSetup(name string, ptr interface{}) bool {
  42. if main, check := s.Section("main"); check {
  43. return main.ValueSetup(name, ptr)
  44. }
  45. return false
  46. }
  47. func (s *Config) Value(name string) (value.Value, bool) {
  48. if main, check := s.Section("main"); check {
  49. return main.Value(name)
  50. }
  51. return value.Value{}, false
  52. }
  53. func (s *Config) ValueDefault(name string, defaultVal interface{}) interface{} {
  54. s.ValueSetup(name, &defaultVal)
  55. return defaultVal
  56. }
  57. func (s *Config) Save(w io.Writer) (err error) {
  58. for name, sections := range s.sections {
  59. for _, section := range sections {
  60. if _, err = w.Write([]byte(fmt.Sprintf("[%v]\n", name))); err != nil {
  61. return
  62. }
  63. if err = section.Save(w); err != nil {
  64. return
  65. }
  66. }
  67. }
  68. return
  69. }