hugolib: Extend the sections API

This commit adds some section related methods that have been asked for:

* .CurrentSection
* .IsDescendant
* .IsAncestor

Fixes #3591
This commit is contained in:
Bjørn Erik Pedersen
2017-07-02 20:14:06 +02:00
parent dd9b1baab0
commit a1d260b41a
5 changed files with 156 additions and 15 deletions

View File

@@ -194,6 +194,38 @@ func ReaderContains(r io.Reader, subslice []byte) bool {
return false
}
// HasStringsPrefix tests whether the string slice s begins with prefix slice s.
func HasStringsPrefix(s, prefix []string) bool {
return len(s) >= len(prefix) && compareStringSlices(s[0:len(prefix)], prefix)
}
// HasStringsSuffix tests whether the string slice s ends with suffix slice s.
func HasStringsSuffix(s, suffix []string) bool {
return len(s) >= len(suffix) && compareStringSlices(s[len(s)-len(suffix):], suffix)
}
func compareStringSlices(a, b []string) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// ThemeSet checks whether a theme is in use or not.
func (p *PathSpec) ThemeSet() bool {
return p.theme != ""

View File

@@ -64,6 +64,45 @@ func TestFirstUpper(t *testing.T) {
}
}
func TestHasStringsPrefix(t *testing.T) {
for i, this := range []struct {
s []string
prefix []string
expect bool
}{
{[]string{"a"}, []string{"a"}, true},
{[]string{}, []string{}, true},
{[]string{"a", "b", "c"}, []string{"a", "b"}, true},
{[]string{"d", "a", "b", "c"}, []string{"a", "b"}, false},
{[]string{"abra", "ca", "dabra"}, []string{"abra", "ca"}, true},
{[]string{"abra", "ca"}, []string{"abra", "ca", "dabra"}, false},
} {
result := HasStringsPrefix(this.s, this.prefix)
if result != this.expect {
t.Fatalf("[%d] got %t but expected %t", i, result, this.expect)
}
}
}
func TestHasStringsSuffix(t *testing.T) {
for i, this := range []struct {
s []string
suffix []string
expect bool
}{
{[]string{"a"}, []string{"a"}, true},
{[]string{}, []string{}, true},
{[]string{"a", "b", "c"}, []string{"b", "c"}, true},
{[]string{"abra", "ca", "dabra"}, []string{"abra", "ca"}, false},
{[]string{"abra", "ca", "dabra"}, []string{"ca", "dabra"}, true},
} {
result := HasStringsSuffix(this.s, this.suffix)
if result != this.expect {
t.Fatalf("[%d] got %t but expected %t", i, result, this.expect)
}
}
}
var containsTestText = (`На берегу пустынных волн
Стоял он, дум великих полн,
И вдаль глядел. Пред ним широко