nameAndPackage := func(t reflect.Type) (string, string) {
var name, pkg string
- isPointer := t.Kind() == reflect.Ptr
+ isPointer := t.Kind() == reflect.Pointer
if isPointer {
t = t.Elem()
func TestMethods(t *testing.T) {
var (
- zeroIE = reflect.TypeOf((*IEmbed)(nil)).Elem()
- zeroIEOnly = reflect.TypeOf((*IEOnly)(nil)).Elem()
- zeroI = reflect.TypeOf((*I)(nil)).Elem()
+ zeroIE = reflect.TypeFor[IEmbed]()
+ zeroIEOnly = reflect.TypeFor[IEOnly]()
+ zeroI = reflect.TypeFor[I]()
)
dir, _ := os.Getwd()
var wg sync.WaitGroup
for i := range 10 {
- wg.Add(1)
- go func() {
- defer wg.Done()
+ wg.Go(func() {
for j := range 100 {
s := strings.Repeat("Hello ", i+j+1*42)
r := strings.NewReader(s)
expect, _ := XXHashFromString(s)
c.Assert(got, qt.Equals, expect)
}
- }()
+ })
}
wg.Wait()
fe := NewFileErrorFromName(errors.New("bar"), "foo.html")
c.Assert(fe.Error(), qt.Equals, `"foo.html:1:1": bar`)
- lines := ""
+ var lines strings.Builder
for i := 1; i <= 100; i++ {
- lines += fmt.Sprintf("line %d\n", i)
+ lines.WriteString(fmt.Sprintf("line %d\n", i))
}
fe.UpdatePosition(text.Position{LineNumber: 32, ColumnNumber: 2})
c.Assert(fe.Error(), qt.Equals, `"foo.html:32:2": bar`)
fe.UpdatePosition(text.Position{LineNumber: 0, ColumnNumber: 0, Offset: 212})
- fe.UpdateContent(strings.NewReader(lines), nil)
+ fe.UpdateContent(strings.NewReader(lines.String()), nil)
c.Assert(fe.Error(), qt.Equals, `"foo.html:32:0": bar`)
errorContext := fe.ErrorContext()
c.Assert(errorContext, qt.IsNotNil)
// See Issue 14079.
func ConvertIfPossible(val reflect.Value, typ reflect.Type) (reflect.Value, bool) {
switch val.Kind() {
- case reflect.Ptr, reflect.Interface:
+ case reflect.Pointer, reflect.Interface:
if val.IsNil() {
// Return typ's zero value.
return reflect.Zero(typ), true
// IsInterfaceOrPointer returns whether the given kind is an interface or a pointer.
func IsInterfaceOrPointer(kind reflect.Kind) bool {
- return kind == reflect.Interface || kind == reflect.Ptr
+ return kind == reflect.Interface || kind == reflect.Pointer
}
// TODO(bep) replace the private versions in /tpl with these.
return reflect.ValueOf(v).Kind() == reflect.Slice
}
-var zeroType = reflect.TypeOf((*types.Zeroer)(nil)).Elem()
+var zeroType = reflect.TypeFor[types.Zeroer]()
var isZeroCache sync.Map
truth = val.Bool()
case reflect.Complex64, reflect.Complex128:
truth = val.Complex() != 0
- case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
+ case reflect.Chan, reflect.Func, reflect.Pointer, reflect.Interface:
truth = !val.IsNil()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
truth = val.Int() != 0
}
var (
- timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
- asTimeProviderType = reflect.TypeOf((*htime.AsTimeProvider)(nil)).Elem()
+ timeType = reflect.TypeFor[time.Time]()
+ asTimeProviderType = reflect.TypeFor[htime.AsTimeProvider]()
)
// IsTime returns whether tp is a time.Time type or if it can be converted into one
}
switch v.Kind() {
- case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
return !v.IsNil()
}
return true
}
switch v.Kind() {
- case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
return v.IsNil()
}
return false
}
-var contextInterface = reflect.TypeOf((*context.Context)(nil)).Elem()
+var contextInterface = reflect.TypeFor[context.Context]()
var isContextCache = hmaps.NewCache[reflect.Type, bool]()
queue := NewEvictingQueue[string](3)
for range 100 {
- wg.Add(1)
- go func() {
- defer wg.Done()
+ wg.Go(func() {
queue.Add(val)
v := queue.Peek()
if v != val {
if len(vals) != 1 || vals[0] != val {
t.Error("wrong val")
}
- }()
+ })
}
wg.Wait()
}
value := reflect.ValueOf(v)
switch value.Kind() {
- case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
return value.IsNil()
}
t reflect.Type,
data any,
) (any, error) {
- if t != reflect.TypeOf(Whitelist{}) {
+ if t != reflect.TypeFor[Whitelist]() {
return data, nil
}
return "./"
}
- var dottedPath string
+ var dottedPath strings.Builder
for i := 1; i < sectionCount; i++ {
- dottedPath += "../"
+ dottedPath.WriteString("../")
}
- return dottedPath
+ return dottedPath.String()
}
type NamedSlice struct {
t.Run("Limits number of root groups", func(t *testing.T) {
in := []string{}
// Create 15 different root paths to exceed maxRootGroups (10)
- for i := 0; i < 15; i++ {
+ for i := range 15 {
in = append(in, filepath.FromSlash(fmt.Sprintf("/path%d/subdir", i)))
}
func BenchmarkExtractAndGroupRootPaths(b *testing.B) {
in := []string{}
- for i := 0; i < 10; i++ {
- for j := 0; j < 1000; j++ {
+ for i := range 10 {
+ for j := range 1000 {
in = append(in, fmt.Sprintf("/a/b/c/s%d/p%d", i, j))
}
}
return
}
switch v.Kind() {
- case reflect.Ptr:
+ case reflect.Pointer:
if !v.IsNil() {
structTypes(v.Elem(), m)
}
import (
"fmt"
+ "strings"
"testing"
"github.com/gohugoio/hugo/hugolib/sitesmatrix"
)
func BenchmarkCascadeTarget(b *testing.B) {
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- content/_index.md --
background = 'yosemite.jpg'
[cascade._target]
kind = '{section,term}'
-- content/posts/_index.md --
-- content/posts/funny/_index.md --
-`
+`)
for i := 1; i < 100; i++ {
- files += fmt.Sprintf("\n-- content/posts/p%d.md --\n", i+1)
+ files.WriteString(fmt.Sprintf("\n-- content/posts/p%d.md --\n", i+1))
}
for i := 1; i < 100; i++ {
- files += fmt.Sprintf("\n-- content/posts/funny/pf%d.md --\n", i+1)
+ files.WriteString(fmt.Sprintf("\n-- content/posts/funny/pf%d.md --\n", i+1))
}
b.Run("Kind", func(b *testing.B) {
cfg := IntegrationTestConfig{
T: b,
- TxtarString: files,
+ TxtarString: files.String(),
}
b.ResetTimer()
func BenchmarkSimpleThreadSafeTree(b *testing.B) {
newTestTree := func() TreeThreadSafe[int] {
t := NewSimpleThreadSafeTree[int]()
- for i := 0; i < 1000; i++ {
+ for i := range 1000 {
t.Insert(fmt.Sprintf("key%d", i), i)
}
return t
}
for _, test := range tests {
- test := test
if test.name != "Base template parse failed" {
continue
}
return
}
- for i := 0; i < sectionsPerLevel; i++ {
+ for i := range sectionsPerLevel {
sectionCount++
sectionName := fmt.Sprintf("s%d", i)
sectionPath := sectionName
sb.WriteString(section(currentSection, i))
// Pages in this section
- for j := 0; j < pagesPerSection; j++ {
+ for j := range pagesPerSection {
pageCount++
sb.WriteString(page(sectionPath, j))
}
func benchmarkBaselineFiles(leafBundles bool) string {
rnd := rand.New(rand.NewSource(32))
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = "https://example.com"
defaultContentLanguage = 'en'
{{ .Content }}
-- layouts/_shortcodes/myshort.html --
{{ .Inner }}
-`
+`)
contentTemplate := `
---
`
for _, lang := range []string{"en", "nn", "no", "sv"} {
- files += fmt.Sprintf("\n-- content/%s/_index.md --\n"+contentTemplate, lang, 1, 1, 1)
+ files.WriteString(fmt.Sprintf("\n-- content/%s/_index.md --\n"+contentTemplate, lang, 1, 1, 1))
for i, root := range []string{"", "foo", "bar", "baz"} {
for j, section := range []string{"posts", "posts/funny", "posts/science", "posts/politics", "posts/world", "posts/technology", "posts/world/news", "posts/world/news/europe"} {
n := i + j + 1
- files += fmt.Sprintf("\n-- content/%s/%s/%s/_index.md --\n"+contentTemplate, lang, root, section, n, n, n)
+ files.WriteString(fmt.Sprintf("\n-- content/%s/%s/%s/_index.md --\n"+contentTemplate, lang, root, section, n, n, n))
for k := 1; k < rnd.Intn(30)+1; k++ {
n := n + k
ns := fmt.Sprintf("%d", n)
ns = fmt.Sprintf("%d/index", n)
}
file := fmt.Sprintf("\n-- content/%s/%s/%s/p%s.md --\n"+contentTemplate, lang, root, section, ns, n, n)
- files += file
+ files.WriteString(file)
}
}
}
}
- return files
+ return files.String()
}
}
for _, tc := range testCases {
- tc := tc
c.Run(tc.name, func(c *qt.C) {
files := fmt.Sprintf(`
-- hugo.toml --
return strings.Trim(tpl.StripHTML(str), " ")
case "ad":
paragraphs := strings.Split(str, "</p>")
- expected := ""
+ var expected strings.Builder
for _, para := range paragraphs {
if para == "" {
continue
}
- expected += fmt.Sprintf("<div class=\"paragraph\">\n%s</p></div>\n", para)
+ expected.WriteString(fmt.Sprintf("<div class=\"paragraph\">\n%s</p></div>\n", para))
}
- return expected
+ return expected.String()
case "rst":
if str == "" {
return "<div class=\"document\"></div>"
panic("contentDir must be set to 'content' for this test")
}
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
[security]
[security.exec]
allow = ['^python$', '^rst2html.*', '^asciidoctor$']
-`
+`)
for i, source := range pageSources {
- files += fmt.Sprintf("-- content/p%d.%s --\n%s\n", i, e.ext, source)
+ files.WriteString(fmt.Sprintf("-- content/p%d.%s --\n%s\n", i, e.ext, source))
}
homePath := fmt.Sprintf("_index.%s", e.ext)
- files += fmt.Sprintf("-- content/%s --\n%s\n", homePath, homePage)
+ files.WriteString(fmt.Sprintf("-- content/%s --\n%s\n", homePath, homePage))
b := NewIntegrationTestBuilder(
IntegrationTestConfig{
T: t,
- TxtarString: files,
+ TxtarString: files.String(),
NeedsOsFS: true,
BaseCfg: cfg,
},
func TestPageDatesSections(t *testing.T) {
t.Parallel()
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = "http://example.com/"
-- content/no-index/page.md --
title: Date
date: 2018-01-15
---
-`
+`)
for i := 1; i <= 20; i++ {
- files += fmt.Sprintf(`
+ files.WriteString(fmt.Sprintf(`
-- content/main-section/p%d.md --
---
title: Date
date: 2012-01-12
---
-`, i)
+`, i))
}
- b := Test(t, files)
+ b := Test(t, files.String())
b.Assert(len(b.H.Sites), qt.Equals, 1)
s := b.H.Sites[0]
}
for i, test := range tests {
- test := test
t.Run(fmt.Sprintf("Test%d", i), func(t *testing.T) {
t.Parallel()
import (
"fmt"
"math/rand"
+ "strings"
"testing"
"github.com/gohugoio/hugo/resources/page"
---
`
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = "http://example.com/"
-`
+`)
for i := 1; i <= numPages; i++ {
- files += fmt.Sprintf("-- content/page%d.md --%s\n", i, fmt.Sprintf(pageTemplate, i, rand.Intn(numPages), categoriesSlice))
+ files.WriteString(fmt.Sprintf("-- content/page%d.md --%s\n", i, fmt.Sprintf(pageTemplate, i, rand.Intn(numPages), categoriesSlice)))
}
- return Test(t, files, TestOptSkipRender())
+ return Test(t, files.String(), TestOptSkipRender())
}
func TestPagesPrevNext(t *testing.T) {
import (
"fmt"
+ "strings"
"testing"
qt "github.com/frankban/quicktest"
)
func TestPaginator(t *testing.T) {
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = "https://example.com/foo/"
[languages.nn]
weight = 2
contentDir = "content/nn"
-`
+`)
// Manually generate content files for the txtar string
- for i := 0; i < 9; i++ {
- files += fmt.Sprintf(`
+ for i := range 9 {
+ files.WriteString(fmt.Sprintf(`
-- content/en/blog/page%d.md --
---
title: Page %d
---
Content.
-`, i, i)
- files += fmt.Sprintf(`
+`, i, i))
+ files.WriteString(fmt.Sprintf(`
-- content/nn/blog/page%d.md --
---
title: Page %d
---
Content.
-`, i, i)
+`, i, i))
}
- files += `
+ files.WriteString(`
-- layouts/home.html --
{{ $pag := $.Paginator }}
Total: {{ $pag.TotalPages }}
{{ range $i, $e := $pag.Pagers }}
{{ printf "%d: %d/%d %t" $i $pag.PageNumber .PageNumber (eq . $pag) -}}
{{ end }}
-`
+`)
- b := Test(t, files)
+ b := Test(t, files.String())
b.AssertFileContent("public/index.html",
"Page Number: 1",
// https://github.com/gohugoio/hugo/issues/6797
func TestPaginateOutputFormat(t *testing.T) {
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = "http://example.com/"
-- content/_index.md --
outputs:
- JSON
---
-`
- for i := 0; i < 22; i++ {
- files += fmt.Sprintf(`
+`)
+ for i := range 22 {
+ files.WriteString(fmt.Sprintf(`
-- content/p%d.md --
---
title: "Page"
weight: %d
---
-`, i+1, i+1)
+`, i+1, i+1))
}
- files += `
+ files.WriteString(`
-- layouts/index.json --
JSON: {{ .Paginator.TotalNumberOfElements }}: {{ range .Paginator.Pages }}|{{ .RelPermalink }}{{ end }}:DONE
-`
+`)
- b := Test(t, files)
+ b := Test(t, files.String())
b.AssertFileContent("public/index.json",
`JSON: 22
}
func benchmarkFilesEdit(count int) string {
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = "https://example.com"
disableKinds = ["term", "taxonomy"]
---
title: "My Sect"
---
- `
+ `)
contentTemplate := `
---
`
for i := range count {
- files += fmt.Sprintf("-- content/mysect/p%d/index.md --\n%s", i, fmt.Sprintf(contentTemplate, i, i))
+ files.WriteString(fmt.Sprintf("-- content/mysect/p%d/index.md --\n%s", i, fmt.Sprintf(contentTemplate, i, i)))
}
- return files
+ return files.String()
}
func BenchmarkRebuildContentFileChange(b *testing.B) {
}
for _, test := range tests {
- test := test
t.Run(test.name, func(t *testing.T) {
if !test.shouldRun() {
t.Skip()
}
if len(sc.inner) > 0 {
- var inner string
+ var inner strings.Builder
for _, innerData := range sc.inner {
switch innerData := innerData.(type) {
case string:
- inner += innerData
+ inner.WriteString(innerData)
case *shortcode:
s, err := prepareShortcode(level+1, innerData, data, po, isRenderString)
if err != nil {
if err != nil {
return zeroShortcode, err
}
- inner += ss
+ inner.WriteString(ss)
default:
po.p.s.Log.Errorf("Illegal state on shortcode rendering of %q in page %q. Illegal type in inner data: %s ",
sc.name, p.File().Path(), reflect.TypeOf(innerData))
// shortcode.
if sc.doMarkup && (level > 0 || sc.configVersion() == 1) {
var err error
- b, err := p.pageOutput.contentRenderer.ParseAndRenderContent(ctx, []byte(inner), false)
+ b, err := p.pageOutput.contentRenderer.ParseAndRenderContent(ctx, []byte(inner.String()), false)
if err != nil {
return zeroShortcode, err
}
// the newline.
switch p.m.pageConfigSource.Content.Markup {
case "", "markdown":
- if match, _ := regexp.MatchString(innerNewlineRegexp, inner); !match {
+ if match, _ := regexp.MatchString(innerNewlineRegexp, inner.String()); !match {
cleaner, err := regexp.Compile(innerCleanupRegexp)
if err == nil {
// TODO(bep) we may have plain text inner templates.
data.Inner = template.HTML(newInner)
} else {
- data.Inner = template.HTML(inner)
+ data.Inner = template.HTML(inner.String())
}
}
import (
"bytes"
"fmt"
+ "strings"
"testing"
"github.com/gohugoio/hugo/helpers"
c := qt.New(t)
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = "http://example.com/blog"
-- layouts/terms.html --
Terms List|{{ .Title }}|{{ .Content }}
-`
+`)
pageTemplate := `---
title: "T%d"
for i := range 2 {
for j := range 2 {
pageID := i + j + 1
- files += fmt.Sprintf("\n-- content/p%d.md --\n", pageID)
- files += fmt.Sprintf(pageTemplate, pageID, fmt.Sprintf("- tag%d", j), fmt.Sprintf("- category%d", j), pageID)
+ files.WriteString(fmt.Sprintf("\n-- content/p%d.md --\n", pageID))
+ files.WriteString(fmt.Sprintf(pageTemplate, pageID, fmt.Sprintf("- tag%d", j), fmt.Sprintf("- category%d", j), pageID))
}
}
for i := range 5 {
- files += fmt.Sprintf("\n-- assets/myimage%d.png --\niVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", i+1)
+ files.WriteString(fmt.Sprintf("\n-- assets/myimage%d.png --\niVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", i+1))
}
- b := Test(t, files)
+ b := Test(t, files.String())
h := b.H
stats := []*helpers.ProcessingStats{
}
func newSitesMatrixContentBenchmarkBuilder(t testing.TB, numPages int, skipRender, multipleDimensions bool) *hugolib.IntegrationTestBuilder {
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
disableKinds = ["rss", "sitemap", "section", "taxonomy", "term"]
defaultContentLanguage = "en"
weight = 1
-`
+`)
if multipleDimensions {
- files += `
+ files.WriteString(`
[languages.nn]
weight = 2
[languages.sv]
weight = 300
[roles.member]
weight = 200
-`
+`)
}
- files += `
+ files.WriteString(`
[[module.mounts]]
source = 'content'
roles = ["**"]
-- layouts/all.html --
All. {{ .Title }}|
-`
+`)
if multipleDimensions {
- files += `
+ files.WriteString(`
Rotate(language): {{ with .Rotate "language" }}{{ range . }}{{ template "printp" . }}|{{ end }}{{ end }}$
Rotate(version): {{ with .Rotate "version" }}{{ range . }}{{ template "printp" . }}|{{ end }}{{ end }}$
Rotate(role): {{ with .Rotate "role" }}{{ range . }}{{ template "printp" . }}|{{ end }}{{ end }}$
{{ define "printp" }}{{ .RelPermalink }}:{{ with .Site }}{{ template "prints" . }}{{ end }}{{ end }}
{{ define "prints" }}/l:{{ .Language.Name }}/v:{{ .Version.Name }}/r:{{ .Role.Name }}{{ end }}
-`
+`)
}
for i := range numPages {
- files += fmt.Sprintf(`
+ files.WriteString(fmt.Sprintf(`
-- content/p%d/index.md --
---
title: "P%d"
---
-`, i+1, i+1)
+`, i+1, i+1))
}
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
- TxtarString: files,
+ TxtarString: files.String(),
BuildCfg: hugolib.BuildCfg{
SkipRender: skipRender,
},
import (
"fmt"
+ "strings"
"testing"
"github.com/gohugoio/hugo/resources/kinds"
Content.
`
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = "http://example.com"
-- layouts/home.html --
<li><a href="{{ .Page.Permalink }}">{{ .Page.Title }}</a> {{ .Count }}</li>
{{ end }}
</ul>
-`
+`)
for i := range 10 {
- files += fmt.Sprintf("\n-- content/page%d.md --\n%s", i+1, pageContent)
+ files.WriteString(fmt.Sprintf("\n-- content/page%d.md --\n%s", i+1, pageContent))
}
- b := Test(t, files)
+ b := Test(t, files.String())
b.AssertFileContent("public/index.html", `<li><a href="http://example.com/tags/hugo-rocks/">Hugo Rocks!</a> 10</li>`)
b.AssertFileContent("public/categories/index.html", `<li><a href="http://example.com/categories/this-is-cool/">This Is Cool</a> 10</li>`)
createBuilder := func(b *testing.B, numPages int) *IntegrationTestBuilder {
b.StopTimer()
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = "https://example.com"
disableKinds = ["RSS", "sitemap", "section"]
-- layouts/single.html --
GetTerms.tags: {{ range .GetTerms "tags" }}{{ .Title }}|{{ end }}
-- content/_index.md --
-`
+`)
tagsVariants := []string{
"tags: ['a']",
for i := 1; i < numPages; i++ {
tags := tagsVariants[i%len(tagsVariants)]
- files += fmt.Sprintf("\n-- content/posts/p%d.md --\n---\n%s\n---", i+1, tags)
+ files.WriteString(fmt.Sprintf("\n-- content/posts/p%d.md --\n---\n%s\n---", i+1, tags))
}
cfg := IntegrationTestConfig{
T: b,
- TxtarString: files,
+ TxtarString: files.String(),
}
bb := NewIntegrationTestBuilder(cfg)
frameSize := stride * h
frames := make([]image.Image, len(destination.Bytes())/frameSize)
- for i := 0; i < len(frames); i++ {
+ for i := range frames {
frameBytes := destination.Bytes()[i*frameSize : (i+1)*frameSize]
frameImg := &image.NRGBA{
Pix: frameBytes,
rgbData := destination.Bytes()
nrgbaStride = w * 4
pix = make([]byte, nrgbaStride*h)
- for y := 0; y < h; y++ {
+ for y := range h {
srcIdx := y * stride
dstIdx := y * nrgbaStride
- for x := 0; x < w; x++ {
+ for range w {
pix[dstIdx+0] = rgbData[srcIdx+0] // R
pix[dstIdx+1] = rgbData[srcIdx+1] // G
pix[dstIdx+2] = rgbData[srcIdx+2] // B
}
func BenchmarkRenderHooks(b *testing.B) {
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
-- layouts/_markup/render-heading.html --
<h{{ .Level }} id="{{ .Anchor | safeURL }}">
<a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text }}</a>
-- layouts/single.html --
{{ .Content }}
-`
+`)
content := `
`
for i := 1; i < 100; i++ {
- files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1)
+ files.WriteString(fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1))
}
cfg := hugolib.IntegrationTestConfig{
T: b,
- TxtarString: files,
+ TxtarString: files.String(),
}
for b.Loop() {
}
func BenchmarkCodeblocks(b *testing.B) {
- filesTemplate := `
+ var filesTemplate strings.Builder
+ filesTemplate.WriteString(`
-- hugo.toml --
[markup]
[markup.highlight]
tabWidth = 4
-- layouts/single.html --
{{ .Content }}
-`
+`)
content := `
content = strings.ReplaceAll(content, "FENCE", "```")
for i := 1; i < 100; i++ {
- filesTemplate += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1)
+ filesTemplate.WriteString(fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1))
}
runBenchmark := func(files string, b *testing.B) {
}
b.Run("Default", func(b *testing.B) {
- runBenchmark(filesTemplate, b)
+ runBenchmark(filesTemplate.String(), b)
})
b.Run("Hook no higlight", func(b *testing.B) {
- files := filesTemplate + `
+ files := filesTemplate.String() + `
-- layouts/_markup/render-codeblock.html --
{{ .Inner }}
`
}
for range 100 {
- wg.Add(1)
- go func() {
- defer wg.Done()
+ wg.Go(func() {
for k, menu := range testMenuSets {
l1.Lock()
m, ca := c1.get("k1", nil, menu)
c.Assert(m3, qt.Not(qt.IsNil))
c.Assert("changed", qt.Equals, m3[0].Title)
}
- }()
+ })
}
wg.Wait()
}
"context"
"fmt"
"math/rand"
+ "strings"
"testing"
"time"
}
func (d *testDoc) String() string {
- s := "\n"
+ var s strings.Builder
+ s.WriteString("\n")
for k, v := range d.keywords {
- s += k + ":\t\t"
+ s.WriteString(k + ":\t\t")
for _, vv := range v {
- s += " " + vv.String()
+ s.WriteString(" " + vv.String())
}
- s += "\n"
+ s.WriteString("\n")
}
- return s
+ return s.String()
}
func (d *testDoc) Name() string {
import (
"fmt"
"math/rand"
+ "strings"
"testing"
"github.com/gohugoio/hugo/hugolib"
}
func BenchmarkRelatedSite(b *testing.B) {
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = "http://example.com/"
disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT"]
weight = 30
-- layouts/single.html --
Len related: {{ site.RegularPages.Related . | len }}
-`
+`)
createContent := func(n int) string {
base := `---
}
for i := 1; i < 100; i++ {
- files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+createContent(i+1), i+1)
+ files.WriteString(fmt.Sprintf("\n-- content/posts/p%d.md --\n"+createContent(i+1), i+1))
}
cfg := hugolib.IntegrationTestConfig{
T: b,
- TxtarString: files,
+ TxtarString: files.String(),
}
for b.Loop() {
s = strings.ToLower(s)
if len(s) == 3 || len(s) == 4 {
- var v string
+ var v strings.Builder
for _, r := range s {
- v += string(r) + string(r)
+ v.WriteString(string(r) + string(r))
}
- s = v
+ s = v.String()
}
// Standard colors.
"os"
"path/filepath"
"reflect"
+ "strings"
"github.com/gohugoio/hugo/codegen"
"github.com/gohugoio/hugo/resources/page"
`
var (
- pageInterface = reflect.TypeOf((*page.PageMetaProvider)(nil)).Elem()
+ pageInterface = reflect.TypeFor[page.PageMetaProvider]()
packageDir = filepath.FromSlash("resources/page")
)
return fmt.Sprintf("import %q", imps[0])
}
- impsStr := "import (\n"
+ var impsStr strings.Builder
+ impsStr.WriteString("import (\n")
for _, imp := range imps {
- impsStr += fmt.Sprintf("%q\n", imp)
+ impsStr.WriteString(fmt.Sprintf("%q\n", imp))
}
- return impsStr + ")"
+ return impsStr.String() + ")"
}
}
for range 100 {
- wg.Add(1)
- go func() {
- defer wg.Done()
+ wg.Go(func() {
for k, pages := range testPageSets {
l1.Lock()
p, ca := c1.get("k1", nil, pages)
c.Assert(p3, qt.Not(qt.IsNil))
c.Assert("changed", qt.Equals, p3[0].(*testPage).description)
}
- }()
+ })
}
wg.Wait()
}
func TestMiscPathIssues(t *testing.T) {
t.Parallel()
- filesTemplate := `
+ var filesTemplate strings.Builder
+ filesTemplate.WriteString(`
-- hugo.toml --
uglyURLs = false
---
title: red
---
-`
+`)
templates := []string{
"layouts/home.html",
const code string = "TITLE: {{ .Title }} | AOFRP: {{ range .AlternativeOutputFormats }}{{ .RelPermalink }}{{ end }} | TEMPLATE: {{ templates.Current.Name }}"
for _, template := range templates {
- filesTemplate += "-- " + template + " --\n" + code + "\n"
+ filesTemplate.WriteString("-- " + template + " --\n" + code + "\n")
}
- files := filesTemplate
+ files := filesTemplate.String()
b := hugolib.Test(t, files)
b.AssertFileContent("public/print/tags/index.txt", "TITLE: tags | AOFRP: /tags/ | TEMPLATE: taxonomy.print.txt")
b.AssertFileContent("public/print/tags/red/index.txt", "TITLE: red | AOFRP: /tags/red/ | TEMPLATE: term.print.txt")
- files = strings.ReplaceAll(filesTemplate, "uglyURLs = false", "uglyURLs = true")
+ files = strings.ReplaceAll(filesTemplate.String(), "uglyURLs = false", "uglyURLs = true")
b = hugolib.Test(t, files)
// uglyURLs: true, outputFormat: html
}
}
-var typeOfReflectValue = reflect.TypeOf(reflect.Value{})
+var typeOfReflectValue = reflect.TypeFor[reflect.Value]()
func applyFnToThis(ctx context.Context, fn, this reflect.Value, args ...any) (reflect.Value, error) {
num := fn.Type().NumIn()
return "", errors.New("can't iterate over a nil value")
}
- var str string
+ var str strings.Builder
switch lv.Kind() {
case reflect.Map:
sortSeq, err := ns.Sort(ctx, l)
}
switch {
case i == lv.Len()-2 && dLast != nil:
- str += valStr + *dLast
+ str.WriteString(valStr + *dLast)
case i == lv.Len()-1:
- str += valStr
+ str.WriteString(valStr)
default:
- str += valStr + d
+ str.WriteString(valStr + d)
}
}
return "", fmt.Errorf("can't iterate over %T", l)
}
- return str, nil
+ return str.String(), nil
}
// Dictionary creates a new map from the given parameters by
if err1 == nil && err2 == nil && f1 == f2 {
i.appendIfNotSeen(l1vv)
}
- case kind == reflect.Ptr, kind == reflect.Struct:
+ case kind == reflect.Pointer, kind == reflect.Struct:
if types.Unwrapv(l1vv.Interface()) == types.Unwrapv(l2vv.Interface()) {
i.appendIfNotSeen(l1vv)
}
if err == nil {
ins.appendIfNotSeen(l2vv)
}
- case kind == reflect.Interface, kind == reflect.Struct, kind == reflect.Ptr:
+ case kind == reflect.Interface, kind == reflect.Struct, kind == reflect.Pointer:
ins.appendIfNotSeen(l2vv)
}
import (
"context"
"fmt"
+ "strings"
"testing"
"github.com/gohugoio/hugo/hugolib"
---
`
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
-- layouts/all.html --
All.
-`
+`)
- for i := 0; i < 500; i++ {
- files += fmt.Sprintf(pageTemplate, i, i)
+ for i := range 500 {
+ files.WriteString(fmt.Sprintf(pageTemplate, i, i))
}
- bb := hugolib.Test(b, files, hugolib.TestOptWithConfig(func(conf *hugolib.IntegrationTestConfig) {
+ bb := hugolib.Test(b, files.String(), hugolib.TestOptWithConfig(func(conf *hugolib.IntegrationTestConfig) {
conf.BuildCfg = hugolib.BuildCfg{
SkipRender: true,
}
// Copied from Go stdlib src/text/template/exec.go.
func canBeNil(typ reflect.Type) bool {
switch typ.Kind() {
- case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
return true
}
return false
switch tp.Kind() {
case reflect.Array, reflect.Slice:
tp = tp.Elem()
- if tp.Kind() == reflect.Ptr {
+ if tp.Kind() == reflect.Pointer {
tp = tp.Elem()
}
// gobench --package ./tpl/partials
func BenchmarkIncludeCached(b *testing.B) {
- files := `
+ var files strings.Builder
+ files.WriteString(`
-- hugo.toml --
baseURL = 'http://example.com/'
-- layouts/home.html --
{{ end }}
-`
+`)
for i := 1; i < 100; i++ {
- files += fmt.Sprintf("\n-- content/p%d.md --\n---\ntitle: page\n---\n"+strings.Repeat("FOO ", i), i)
+ files.WriteString(fmt.Sprintf("\n-- content/p%d.md --\n---\ntitle: page\n---\n"+strings.Repeat("FOO ", i), i))
}
cfg := hugolib.IntegrationTestConfig{
T: b,
- TxtarString: files,
+ TxtarString: files.String(),
}
for b.Loop() {
} else {
endTextPos = lastWordIndex
}
- out := text[0:endTextPos]
+ var out strings.Builder
+ out.WriteString(text[0:endTextPos])
if isHTML {
- out += ellipsis
+ out.WriteString(ellipsis)
// Close out any open HTML tags
var currentTag *htmlTag
for i := len(tags) - 1; i >= 0; i-- {
}
if tag.openTag {
- out += ("</" + tag.name + ">")
+ out.WriteString(("</" + tag.name + ">"))
} else {
currentTag = &tag
}
}
- return template.HTML(out), nil
+ return template.HTML(out.String()), nil
}
- return template.HTML(html.EscapeString(out) + ellipsis), nil
+ return template.HTML(html.EscapeString(out.String()) + ellipsis), nil
}
}
return v, v.IsValid()
}
-var typeParams = reflect.TypeOf(hmaps.Params{})
+var typeParams = reflect.TypeFor[hmaps.Params]()
func (t *templateExecHelper) GetMethod(ctx context.Context, tmpl texttemplate.Preparer, receiver reflect.Value, name string) (method reflect.Value, firstArg reflect.Value) {
if strings.EqualFold(name, "mainsections") && receiver.Type() == typeParams && receiver.Pointer() == t.siteParams.Pointer() {