1package config
2
3// New creates a new config instance.
4func New() *Config {
5	return &Config{}
6}
7
8// Config contains all the sections, comments and includes from a config file.
9type Config struct {
10	Comment  *Comment
11	Sections Sections
12	Includes Includes
13}
14
15// Includes is a list of Includes in a config file.
16type Includes []*Include
17
18// Include is a reference to an included config file.
19type Include struct {
20	Path   string
21	Config *Config
22}
23
24// Comment string without the prefix '#' or ';'.
25type Comment string
26
27const (
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.
34func (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// AddOption adds an option to a given section and subsection. Use the
48// NoSubsection constant for the subsection argument if no subsection is wanted.
49func (c *Config) AddOption(section string, subsection string, key string, value string) *Config {
50	if subsection == "" {
51		c.Section(section).AddOption(key, value)
52	} else {
53		c.Section(section).Subsection(subsection).AddOption(key, value)
54	}
55
56	return c
57}
58
59// SetOption sets an option to a given section and subsection. Use the
60// NoSubsection constant for the subsection argument if no subsection is wanted.
61func (c *Config) SetOption(section string, subsection string, key string, value string) *Config {
62	if subsection == "" {
63		c.Section(section).SetOption(key, value)
64	} else {
65		c.Section(section).Subsection(subsection).SetOption(key, value)
66	}
67
68	return c
69}
70
71// RemoveSection removes a section from a config file.
72func (c *Config) RemoveSection(name string) *Config {
73	result := Sections{}
74	for _, s := range c.Sections {
75		if !s.IsName(name) {
76			result = append(result, s)
77		}
78	}
79
80	c.Sections = result
81	return c
82}
83
84// RemoveSubsection remove	s a subsection from a config file.
85func (c *Config) RemoveSubsection(section string, subsection string) *Config {
86	for _, s := range c.Sections {
87		if s.IsName(section) {
88			result := Subsections{}
89			for _, ss := range s.Subsections {
90				if !ss.IsName(subsection) {
91					result = append(result, ss)
92				}
93			}
94			s.Subsections = result
95		}
96	}
97
98	return c
99}
100