Skip to content

Commit b505416

Browse files
bryanpediniunknwon
andauthored
file: add HasSection method (#308)
Co-authored-by: Joe Chen <jc@unknwon.io>
1 parent e641746 commit b505416

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

file.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,12 @@ func (f *File) GetSection(name string) (*Section, error) {
142142
return secs[0], err
143143
}
144144

145+
// HasSection returns true if the file contains a section with given name.
146+
func (f *File) HasSection(name string) bool {
147+
section, _ := f.GetSection(name)
148+
return section != nil
149+
}
150+
145151
// SectionsByName returns all sections with given name.
146152
func (f *File) SectionsByName(name string) ([]*Section, error) {
147153
if len(name) == 0 {

file_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,20 @@ func TestFile_GetSection(t *testing.T) {
237237
})
238238
}
239239

240+
func TestFile_HasSection(t *testing.T) {
241+
f, err := Load(fullConf)
242+
require.NoError(t, err)
243+
require.NotNil(t, f)
244+
245+
sec := f.HasSection("author")
246+
assert.True(t, sec)
247+
248+
t.Run("section not exists", func(t *testing.T) {
249+
nonexistent := f.HasSection("404")
250+
assert.False(t, nonexistent)
251+
})
252+
}
253+
240254
func TestFile_Section(t *testing.T) {
241255
t.Run("get a section", func(t *testing.T) {
242256
f, err := Load(fullConf)

0 commit comments

Comments
 (0)