Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions config/all_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"bufio"
"os"
"strings"
"reflect"
"testing"
)

Expand Down Expand Up @@ -270,3 +271,75 @@ func TestWriteReadFile(t *testing.T) {

defer os.Remove(tmp)
}

// Tests read options in a section without default options.
func TestSectionOptions(t *testing.T) {
cw := NewDefault()

// write file; will test only read later on
cw.AddSection("First-Section")
cw.AddOption("First-Section", "option1", "value option1")
cw.AddOption("First-Section", "option2", "2")

cw.AddOption("", "host", "www.example.com")
cw.AddOption(_DEFAULT_SECTION, "protocol", "https://")
cw.AddOption(_DEFAULT_SECTION, "base-url", "%(protocol)s%(host)s")

cw.AddOption("Another-Section", "useHTTPS", "y")
cw.AddOption("Another-Section", "url", "%(base-url)s/some/path")

cw.WriteFile(tmp, 0644, "Test file for test-case")

// read back file and test
cr, err := ReadDefault(tmp)
if err != nil {
t.Fatalf("ReadDefault failure: %s", err)
}

options, err := cr.SectionOptions("First-Section")

if err != nil {
t.Fatalf("SectionOptions failure: %s", err)
}

if len(options) != 2 {
t.Fatalf("SectionOptions reads wrong data: %v", options)
}

expected := map[string]bool{
"option1": true,
"option2": true,
}
actual := map[string]bool{}

for _, v := range options {
actual[v] = true
}

if !reflect.DeepEqual(expected, actual) {
t.Fatalf("SectionOptions reads wrong data: %v", options)
}

options, err = cr.SectionOptions(_DEFAULT_SECTION)

if err != nil {
t.Fatalf("SectionOptions failure: %s", err)
}

expected = map[string]bool{
"host": true,
"protocol": true,
"base-url": true,
}
actual = map[string]bool{}

for _, v := range options {
actual[v] = true
}

if !reflect.DeepEqual(expected, actual) {
t.Fatalf("SectionOptions reads wrong data: %v", options)
}

defer os.Remove(tmp)
}
18 changes: 18 additions & 0 deletions config/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,21 @@ func (self *Config) Options(section string) (options []string, err error) {

return options, nil
}

// SectionOptions returns only the list of options available in the given section.
// Unlike Options, SectionOptions doesn't return options in default section.
// It returns an error if the section doesn't exist.
func (self *Config) SectionOptions(section string) (options []string, err error) {
if _, ok := self.data[section]; !ok {
return nil, errors.New(sectionError(section).Error())
}

options = make([]string, len(self.data[section]))
i := 0
for s, _ := range self.data[section] {
options[i] = s
i++
}

return options, nil
}