Debian Codegraph @

plumbing/format/config/common.go

raw
1 package config
2
3 // New creates a new config instance.
4 func New() *Config {
5 return &Config{}
6 }
7
8 // Config contains all the sections, comments and includes from a config file.
9 type Config struct {
10 Comment *Comment
11 Sections Sections
12 Includes Includes
13 }
14
15 // Includes is a list of Includes in a config file.
16 type Includes []*Include
17
18 // Include is a reference to an included config file.
19 type Include struct {
20 Path string
21 Config *Config
22 }
23
24 // Comment string without the prefix '#' or ';'.
25 type Comment string
26
27 const (
28 // NoSubsection token is passed to Config.Section and Config.SetSection to
29 // represent the absence of a section.
30 NoSubsection = ""
31 )
32
33 // Section returns a existing section with the given name or creates a new one.
34 func (c *Config) Section(name string) *Section {
35 for i := len(c.Sections) - 1; i >= 0; i-- {
36 s := c.Sections[i]
37 if s.IsName(name) {
38 return s
39 }
40 }
41
42 s := &Section{Name: name}
43 c.Sections = append(c.Sections, s)
44 return s
45 }
46
47 // HasSection checks if the Config has a section with the specified name.
48 func (c *Config) HasSection(name string) bool {
49 for _, s := range c.Sections {
50 if s.IsName(name) {
51 return true
52 }
53 }
54 return false
55 }
56
57 // RemoveSection removes a section from a config file.
58 func (c *Config) RemoveSection(name string) *Config {
59 result := Sections{}
60 for _, s := range c.Sections {
61 if !s.IsName(name) {
62 result = append(result, s)
63 }
64 }
65
66 c.Sections = result
67 return c
68 }
69
70 // RemoveSubsection remove a subsection from a config file.
71 func (c *Config) RemoveSubsection(section string, subsection string) *Config {
72 for _, s := range c.Sections {
73 if s.IsName(section) {
74 result := Subsections{}
75 for _, ss := range s.Subsections {
76 if !ss.IsName(subsection) {
77 result = append(result, ss)
78 }
79 }
80 s.Subsections = result
81 }
82 }
83
84 return c
85 }
86
87 // AddOption adds an option to a given section and subsection. Use the
88 // NoSubsection constant for the subsection argument if no subsection is wanted.
89 func (c *Config) AddOption(section string, subsection string, key string, value string) *Config {
90 if subsection == "" {
91 c.Section(section).AddOption(key, value)
92 } else {
93 c.Section(section).Subsection(subsection).AddOption(key, value)
94 }
95
96 return c
97 }
98
99 // SetOption sets an option to a given section and subsection. Use the
100 // NoSubsection constant for the subsection argument if no subsection is wanted.
101 func (c *Config) SetOption(section string, subsection string, key string, value string) *Config {
102 if subsection == "" {
103 c.Section(section).SetOption(key, value)
104 } else {
105 c.Section(section).Subsection(subsection).SetOption(key, value)
106 }
107
108 return c
109 }