From 7b5199fdeff7d7682e9f979f468d55bc7b67b934 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Thu, 20 Aug 2026 20:39:57 +0200 Subject: [PATCH] all: Run modernize -fix ./... --- common/collections/stack.go | 6 +- config/allconfig/allconfig.go | 50 +++---- create/content_test.go | 2 +- deps/deps.go | 4 +- hugolib/doctree/support.go | 5 +- hugolib/page.go | 32 ++-- hugolib/page__content.go | 6 +- hugolib/site.go | 38 ++--- identity/identity.go | 4 +- internal/js/esbuild/batch.go | 166 ++++++++++----------- internal/js/esbuild/options_test.go | 88 ++++------- markup/goldmark/hugocontext/hugocontext.go | 4 +- markup/goldmark/render_hooks.go | 20 +-- media/mediaType.go | 4 +- modules/client.go | 2 +- navigation/menu_cache_test.go | 8 +- parser/pageparser/pagelexer.go | 18 +-- resources/page/hugoinfo.go | 2 +- resources/page/pages_cache_test.go | 8 +- tpl/collections/sort.go | 4 +- tpl/strings/truncate.go | 5 +- 21 files changed, 206 insertions(+), 270 deletions(-) diff --git a/common/collections/stack.go b/common/collections/stack.go index 3eb6ab515..bcac2e4e0 100644 --- a/common/collections/stack.go +++ b/common/collections/stack.go @@ -81,9 +81,9 @@ func (s *StackThreadSafe[T]) DrainMatching(predicate func(T) bool) []T { s.mu.Lock() defer s.mu.Unlock() var items []T - for i := len(s.items) - 1; i >= 0; i-- { - if predicate(s.items[i]) { - items = append(items, s.items[i]) + for i, v := range slices.Backward(s.items) { + if predicate(v) { + items = append(items, v) s.items = slices.Delete(s.items, i, i+1) } } diff --git a/config/allconfig/allconfig.go b/config/allconfig/allconfig.go index 1a941ba1b..37a6611aa 100644 --- a/config/allconfig/allconfig.go +++ b/config/allconfig/allconfig.go @@ -1005,34 +1005,30 @@ func (c Configs) GetByLang(lang string) config.AllProvider { func newDefaultConfig() *Config { return &Config{ - Taxonomies: map[string]string{"tag": "tags", "category": "categories"}, - Sitemap: config.SitemapConfig{Priority: -1, Filename: "sitemap.xml"}, - RootConfig: RootConfig{ - Environment: hugo.EnvironmentProduction, - TitleCaseStyle: "AP", - PluralizeListTitles: true, - CapitalizeListTitles: true, - StaticDir: []string{"static"}, - SummaryLength: 70, - Timeout: "60s", + Taxonomies: map[string]string{"tag": "tags", "category": "categories"}, + Sitemap: config.SitemapConfig{Priority: -1, Filename: "sitemap.xml"}, + Environment: hugo.EnvironmentProduction, + TitleCaseStyle: "AP", + PluralizeListTitles: true, + CapitalizeListTitles: true, + StaticDir: []string{"static"}, + SummaryLength: 70, + Timeout: "60s", - CommonDirs: config.CommonDirs{ - //lint:ignore SA1019 Keep as adapter for now. - ArcheTypeDir: "archetypes", - ContentDir: "content", - ResourceDir: "resources", - PublishDir: "public", - ThemesDir: "themes", - //lint:ignore SA1019 Keep as adapter for now. - AssetDir: "assets", - //lint:ignore SA1019 Keep as adapter for now. - LayoutDir: "layouts", - //lint:ignore SA1019 Keep as adapter for now. - I18nDir: "i18n", - //lint:ignore SA1019 Keep as adapter for now. - DataDir: "data", - }, - }, + //lint:ignore SA1019 Keep as adapter for now. + ArcheTypeDir: "archetypes", + ContentDir: "content", + ResourceDir: "resources", + PublishDir: "public", + ThemesDir: "themes", + //lint:ignore SA1019 Keep as adapter for now. + AssetDir: "assets", + //lint:ignore SA1019 Keep as adapter for now. + LayoutDir: "layouts", + //lint:ignore SA1019 Keep as adapter for now. + I18nDir: "i18n", + //lint:ignore SA1019 Keep as adapter for now. + DataDir: "data", } } diff --git a/create/content_test.go b/create/content_test.go index 14320d3b4..905b9ca8f 100644 --- a/create/content_test.go +++ b/create/content_test.go @@ -317,7 +317,7 @@ func readFileFromFs(t testing.TB, fs afero.Fs, filename string) string { b, err := afero.ReadFile(fs, filename) if err != nil { // Print some debug info - root := strings.Split(filename, helpers.FilePathSeparator)[0] + root, _, _ := strings.Cut(filename, helpers.FilePathSeparator) afero.Walk(fs, root, func(path string, info os.FileInfo, err error) error { if info != nil && !info.IsDir() { fmt.Println(" ", path) diff --git a/deps/deps.go b/deps/deps.go index 8e7780cb2..3899024d6 100644 --- a/deps/deps.go +++ b/deps/deps.go @@ -459,7 +459,7 @@ func (c TestConfig) IsZero() bool { // BuildState are state used during a build. type BuildState struct { - counter uint64 + counter atomic.Uint64 // Tracks invocations of the Build method. BuildCounter atomic.Uint64 @@ -538,5 +538,5 @@ func (b *BuildState) GetFilenamesWithPostPrefix() []string { } func (b *BuildState) Incr() int { - return int(atomic.AddUint64(&b.counter, uint64(1))) + return int(b.counter.Add(uint64(1))) } diff --git a/hugolib/doctree/support.go b/hugolib/doctree/support.go index b64221e08..dcf560492 100644 --- a/hugolib/doctree/support.go +++ b/hugolib/doctree/support.go @@ -16,6 +16,7 @@ package doctree import ( "fmt" "iter" + "slices" "strings" "sync" @@ -251,8 +252,8 @@ func (ctx *WalkContext[T]) HandleEvents() error { // Loop the event handlers in reverse order so // that events created by the handlers themselves will // be picked up further up the tree. - for i := len(ctx.eventHandlers[event.Name]) - 1; i >= 0; i-- { - ctx.eventHandlers[event.Name][i](event) + for _, v := range slices.Backward(ctx.eventHandlers[event.Name]) { + v(event) if event.stopPropagation { break } diff --git a/hugolib/page.go b/hugolib/page.go index af1d65f1f..0cfb9c741 100644 --- a/hugolib/page.go +++ b/hugolib/page.go @@ -332,10 +332,8 @@ func (ps *pageState) RegularPagesRecursive() page.Pages { case kinds.KindSection, kinds.KindHome: return ps.s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ - pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ - Path: ps.Path(), - Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindPage).BoolFunc(), - }, + Path: ps.Path(), + Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindPage).BoolFunc(), Recursive: true, }, ) @@ -354,10 +352,8 @@ func (ps *pageState) RegularPages() page.Pages { case kinds.KindSection, kinds.KindHome, kinds.KindTaxonomy: return ps.s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ - pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ - Path: ps.Path(), - Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindPage).BoolFunc(), - }, + Path: ps.Path(), + Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindPage).BoolFunc(), }, ) case kinds.KindTerm: @@ -379,13 +375,11 @@ func (ps *pageState) Pages() page.Pages { case kinds.KindSection, kinds.KindHome: return ps.s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ - pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ - Path: ps.Path(), - KeyPart: "page-section", - Include: pagePredicates.ShouldListLocal.And( - pagePredicates.KindPage.Or(pagePredicates.KindSection), - ).BoolFunc(), - }, + Path: ps.Path(), + KeyPart: "page-section", + Include: pagePredicates.ShouldListLocal.And( + pagePredicates.KindPage.Or(pagePredicates.KindSection), + ).BoolFunc(), }, ) case kinds.KindTerm: @@ -397,11 +391,9 @@ func (ps *pageState) Pages() page.Pages { case kinds.KindTaxonomy: return ps.s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ - pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ - Path: ps.Path(), - KeyPart: "term", - Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindTerm).BoolFunc(), - }, + Path: ps.Path(), + KeyPart: "term", + Include: pagePredicates.ShouldListLocal.And(pagePredicates.KindTerm).BoolFunc(), Recursive: true, }, ) diff --git a/hugolib/page__content.go b/hugolib/page__content.go index 725576f38..8b23e2a46 100644 --- a/hugolib/page__content.go +++ b/hugolib/page__content.go @@ -941,10 +941,8 @@ func (c *cachedContentScope) RenderString(ctx context.Context, args ...any) (tem if pageparser.HasShortcode(contentToRender) { ct := contentTableOfContents{ - sourceInfo: sourceInfo{ - filename: pco.po.p.pathOrTitle() + " (rendered from string)", - source: []byte(contentToRender), - }, + filename: pco.po.p.pathOrTitle() + " (rendered from string)", + source: []byte(contentToRender), } ct.contentToRender = ct.source // String contains a shortcode. diff --git a/hugolib/site.go b/hugolib/site.go index c23b756d8..42562cf3e 100644 --- a/hugolib/site.go +++ b/hugolib/site.go @@ -759,11 +759,9 @@ func (s *Site) Pages() page.Pages { s.CheckReady() return s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ - pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ - Path: "", - KeyPart: "global", - Include: pagePredicates.ShouldListGlobal.BoolFunc(), - }, + Path: "", + KeyPart: "global", + Include: pagePredicates.ShouldListGlobal.BoolFunc(), Recursive: true, IncludeSelf: true, }, @@ -776,11 +774,9 @@ func (s *Site) RegularPages() page.Pages { s.CheckReady() return s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ - pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ - Path: "", - KeyPart: "global", - Include: pagePredicates.ShouldListGlobal.And(pagePredicates.KindPage).BoolFunc(), - }, + Path: "", + KeyPart: "global", + Include: pagePredicates.ShouldListGlobal.And(pagePredicates.KindPage).BoolFunc(), Recursive: true, }, ) @@ -922,11 +918,9 @@ func (s *Site) prepareInits() { sections := s.pageMap.getPagesInSection( pageMapQueryPagesInSection{ - pageMapQueryPagesBelowPath: pageMapQueryPagesBelowPath{ - Path: "", - KeyPart: "sectionorhome", - Include: pagePredicates.KindSection.Or(pagePredicates.KindHome).BoolFunc(), - }, + Path: "", + KeyPart: "sectionorhome", + Include: pagePredicates.KindSection.Or(pagePredicates.KindHome).BoolFunc(), IncludeSelf: true, Recursive: true, }, @@ -1464,12 +1458,10 @@ func (s *Site) assembleMenus() (navigation.Menus, error) { return false, nil } me := navigation.MenuEntry{ - MenuConfig: navigation.MenuConfig{ - Identifier: id, - Name: p.LinkTitle(), - Weight: p.Weight(), - }, - Page: p, + Identifier: id, + Name: p.LinkTitle(), + Weight: p.Weight(), + Page: p, } navigation.SetPageValues(&me, p) @@ -1508,9 +1500,7 @@ func (s *Site) assembleMenus() (navigation.Menus, error) { if !ok { // if parent does not exist, create one without a URL flat[twoD{p.MenuName, p.EntryName}] = &navigation.MenuEntry{ - MenuConfig: navigation.MenuConfig{ - Name: p.EntryName, - }, + Name: p.EntryName, } } flat[twoD{p.MenuName, p.EntryName}].Children = childmenu diff --git a/identity/identity.go b/identity/identity.go index d0823c57f..3dfae1107 100644 --- a/identity/identity.go +++ b/identity/identity.go @@ -252,11 +252,11 @@ type IsRebuildProvider interface { // IncrementByOne implements Incrementer adding 1 every time Incr is called. type IncrementByOne struct { - counter uint64 + counter atomic.Uint64 } func (c *IncrementByOne) Incr() int { - return int(atomic.AddUint64(&c.counter, uint64(1))) + return int(c.counter.Add(uint64(1))) } // Incrementer increments and returns the value. diff --git a/internal/js/esbuild/batch.go b/internal/js/esbuild/batch.go index 61c6b6d5c..30eb3a236 100644 --- a/internal/js/esbuild/batch.go +++ b/internal/js/esbuild/batch.go @@ -528,96 +528,94 @@ func (b *batcher) doBuild(ctx context.Context) (*Package, error) { } jsOpts := Options{ - ExternalOptions: externalOptions, - InternalOptions: InternalOptions{ - DependencyManager: b.dependencyManager, - Splitting: true, - ImportOnResolveFunc: func(imp string, args api.OnResolveArgs) string { - var importContextPath string - if args.Kind == api.ResolveEntryPoint { - importContextPath = args.Path - } else { - importContextPath = args.Importer - } - importContext, importContextFound := state.importerImportContext.Get(importContextPath) + ExternalOptions: externalOptions, + DependencyManager: b.dependencyManager, + Splitting: true, + ImportOnResolveFunc: func(imp string, args api.OnResolveArgs) string { + var importContextPath string + if args.Kind == api.ResolveEntryPoint { + importContextPath = args.Path + } else { + importContextPath = args.Importer + } + importContext, importContextFound := state.importerImportContext.Get(importContextPath) - // We want to track the dependencies closest to where they're used. - dm := b.dependencyManager - if importContextFound { - dm = importContext.dm - } + // We want to track the dependencies closest to where they're used. + dm := b.dependencyManager + if importContextFound { + dm = importContext.dm + } - if r, found := state.importResource.Get(imp); found { - dm.AddIdentity(identity.FirstIdentity(r)) + if r, found := state.importResource.Get(imp); found { + dm.AddIdentity(identity.FirstIdentity(r)) + return imp + } + + if importContext.resourceGetter != nil { + resolved := ResolveResource(imp, importContext.resourceGetter) + if resolved != nil { + resolvePath := resources.InternalResourceTargetPath(resolved) + dm.AddIdentity(identity.FirstIdentity(resolved)) + imp := PrefixHugoVirtual + resolvePath + state.importResource.Set(imp, resolved) + state.importerImportContext.Set(imp, importContext) return imp - } - - if importContext.resourceGetter != nil { - resolved := ResolveResource(imp, importContext.resourceGetter) - if resolved != nil { - resolvePath := resources.InternalResourceTargetPath(resolved) - dm.AddIdentity(identity.FirstIdentity(resolved)) - imp := PrefixHugoVirtual + resolvePath - state.importResource.Set(imp, resolved) - state.importerImportContext.Set(imp, importContext) - return imp - - } - } - return "" - }, - ImportOnLoadFunc: func(args api.OnLoadArgs) (string, error) { - imp := args.Path - - if r, found := state.importResource.Get(imp); found { - content, err := resources.InternalResourceSourceContent(ctx, r) - if err != nil { - return "", fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err) - } - return content, nil - } - return "", nil - }, - ImportParamsOnLoadFunc: func(args api.OnLoadArgs) json.RawMessage { - if importContext, found := state.importerImportContext.Get(args.Path); found { - if !importContext.scriptOptions.IsZero() { - return importContext.scriptOptions.Params - } - } - return nil - }, - ErrorMessageResolveFunc: func(args api.Message) *ErrorMessageResolved { - if loc := args.Location; loc != nil { - path := strings.TrimPrefix(loc.File, NsHugoImportResolveFunc+":") - if r, found := state.importResource.Get(path); found { - sourcePath := resources.InternalResourceSourcePathBestEffort(r) - - var contentr hugio.ReadSeekCloser - if cp, ok := r.(hugio.ReadSeekCloserProvider); ok { - contentr, _ = cp.ReadSeekCloser() - } - return &ErrorMessageResolved{ - Content: contentr, - Path: sourcePath, - Message: args.Text, - } - - } } - return nil - }, - ResolveSourceMapSource: func(s string) string { - if r, found := state.importResource.Get(s); found { - if ss := resources.InternalResourceSourcePath(r); ss != "" { - return ss - } - return PrefixHugoMemory + s - } - return "" - }, - EntryPoints: entryPoints, + } + return "" }, + ImportOnLoadFunc: func(args api.OnLoadArgs) (string, error) { + imp := args.Path + + if r, found := state.importResource.Get(imp); found { + content, err := resources.InternalResourceSourceContent(ctx, r) + if err != nil { + return "", fmt.Errorf("failed to read import %q: %w", resources.InternalResourceSourcePathBestEffort(r), err) + } + return content, nil + } + return "", nil + }, + ImportParamsOnLoadFunc: func(args api.OnLoadArgs) json.RawMessage { + if importContext, found := state.importerImportContext.Get(args.Path); found { + if !importContext.scriptOptions.IsZero() { + return importContext.scriptOptions.Params + } + } + return nil + }, + ErrorMessageResolveFunc: func(args api.Message) *ErrorMessageResolved { + if loc := args.Location; loc != nil { + path := strings.TrimPrefix(loc.File, NsHugoImportResolveFunc+":") + if r, found := state.importResource.Get(path); found { + sourcePath := resources.InternalResourceSourcePathBestEffort(r) + + var contentr hugio.ReadSeekCloser + if cp, ok := r.(hugio.ReadSeekCloserProvider); ok { + contentr, _ = cp.ReadSeekCloser() + } + return &ErrorMessageResolved{ + Content: contentr, + Path: sourcePath, + Message: args.Text, + } + + } + + } + return nil + }, + ResolveSourceMapSource: func(s string) string { + if r, found := state.importResource.Get(s); found { + if ss := resources.InternalResourceSourcePath(r); ss != "" { + return ss + } + return PrefixHugoMemory + s + } + return "" + }, + EntryPoints: entryPoints, } result, err := b.client.buildClient.Build(jsOpts) diff --git a/internal/js/esbuild/options_test.go b/internal/js/esbuild/options_test.go index 6d430e9ab..b60dcbc4a 100644 --- a/internal/js/esbuild/options_test.go +++ b/internal/js/esbuild/options_test.go @@ -27,10 +27,8 @@ func TestToBuildOptions(t *testing.T) { c := qt.New(t) opts := Options{ - InternalOptions: InternalOptions{ - MediaType: media.Builtin.JavascriptType, - Stdin: true, - }, + MediaType: media.Builtin.JavascriptType, + Stdin: true, } c.Assert(opts.compile(), qt.IsNil) @@ -46,16 +44,12 @@ func TestToBuildOptions(t *testing.T) { }) opts = Options{ - ExternalOptions: ExternalOptions{ - Target: []string{"es2018"}, - Format: "cjs", - Minify: true, - AvoidTDZ: true, - }, - InternalOptions: InternalOptions{ - MediaType: media.Builtin.JavascriptType, - Stdin: true, - }, + Target: []string{"es2018"}, + Format: "cjs", + Minify: true, + AvoidTDZ: true, + MediaType: media.Builtin.JavascriptType, + Stdin: true, } c.Assert(opts.compile(), qt.IsNil) @@ -74,14 +68,10 @@ func TestToBuildOptions(t *testing.T) { }) opts = Options{ - ExternalOptions: ExternalOptions{ - Target: []string{"es2018"}, Format: "cjs", Minify: true, - SourceMap: "inline", - }, - InternalOptions: InternalOptions{ - MediaType: media.Builtin.JavascriptType, - Stdin: true, - }, + Target: []string{"es2018"}, Format: "cjs", Minify: true, + SourceMap: "inline", + MediaType: media.Builtin.JavascriptType, + Stdin: true, } c.Assert(opts.compile(), qt.IsNil) @@ -101,14 +91,10 @@ func TestToBuildOptions(t *testing.T) { }) opts = Options{ - ExternalOptions: ExternalOptions{ - Target: []string{"es2018"}, Format: "cjs", Minify: true, - SourceMap: "inline", - }, - InternalOptions: InternalOptions{ - MediaType: media.Builtin.JavascriptType, - Stdin: true, - }, + Target: []string{"es2018"}, Format: "cjs", Minify: true, + SourceMap: "inline", + MediaType: media.Builtin.JavascriptType, + Stdin: true, } c.Assert(opts.compile(), qt.IsNil) @@ -128,14 +114,10 @@ func TestToBuildOptions(t *testing.T) { }) opts = Options{ - ExternalOptions: ExternalOptions{ - Target: []string{"es2018"}, Format: "cjs", Minify: true, - SourceMap: "external", - }, - InternalOptions: InternalOptions{ - MediaType: media.Builtin.JavascriptType, - Stdin: true, - }, + Target: []string{"es2018"}, Format: "cjs", Minify: true, + SourceMap: "external", + MediaType: media.Builtin.JavascriptType, + Stdin: true, } c.Assert(opts.compile(), qt.IsNil) @@ -155,13 +137,9 @@ func TestToBuildOptions(t *testing.T) { }) opts = Options{ - ExternalOptions: ExternalOptions{ - JSX: "automatic", JSXImportSource: "preact", - }, - InternalOptions: InternalOptions{ - MediaType: media.Builtin.JavascriptType, - Stdin: true, - }, + JSX: "automatic", JSXImportSource: "preact", + MediaType: media.Builtin.JavascriptType, + Stdin: true, } c.Assert(opts.compile(), qt.IsNil) @@ -179,24 +157,18 @@ func TestToBuildOptions(t *testing.T) { }) opts = Options{ - ExternalOptions: ExternalOptions{ - Drop: "console", - }, + Drop: "console", } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled.Drop, qt.Equals, api.DropConsole) opts = Options{ - ExternalOptions: ExternalOptions{ - Drop: "debugger", - }, + Drop: "debugger", } c.Assert(opts.compile(), qt.IsNil) c.Assert(opts.compiled.Drop, qt.Equals, api.DropDebugger) opts = Options{ - ExternalOptions: ExternalOptions{ - Drop: "adsfadsf", - }, + Drop: "adsfadsf", } c.Assert(opts.compile(), qt.ErrorMatches, `unsupported drop type: "adsfadsf"`) } @@ -222,12 +194,8 @@ func TestToBuildOptionsTarget(t *testing.T) { } { c.Run(test.target, func(c *qt.C) { opts := Options{ - ExternalOptions: ExternalOptions{ - Target: []string{test.target}, - }, - InternalOptions: InternalOptions{ - MediaType: media.Builtin.JavascriptType, - }, + Target: []string{test.target}, + MediaType: media.Builtin.JavascriptType, } c.Assert(opts.compile(), qt.IsNil) diff --git a/markup/goldmark/hugocontext/hugocontext.go b/markup/goldmark/hugocontext/hugocontext.go index 1ec188647..c8e24975d 100644 --- a/markup/goldmark/hugocontext/hugocontext.go +++ b/markup/goldmark/hugocontext/hugocontext.go @@ -326,9 +326,7 @@ func (a *hugoContextExtension) Extend(m goldmark.Markdown) { renderer.WithNodeRenderers( util.Prioritized(&hugoContextRenderer{ logger: a.logger, - Config: html.Config{ - Writer: html.DefaultWriter, - }, + Writer: html.DefaultWriter, }, 50), ), ) diff --git a/markup/goldmark/render_hooks.go b/markup/goldmark/render_hooks.go index 29593c7dd..0aab5ed12 100644 --- a/markup/goldmark/render_hooks.go +++ b/markup/goldmark/render_hooks.go @@ -36,9 +36,7 @@ var _ renderer.SetOptioner = (*hookedRenderer)(nil) func newLinkRenderer(cfg goldmark_config.Config) renderer.NodeRenderer { r := &hookedRenderer{ linkifyProtocol: []byte(cfg.Extensions.LinkifyProtocol), - Config: html.Config{ - Writer: html.DefaultWriter, - }, + Writer: html.DefaultWriter, } return r } @@ -169,15 +167,13 @@ func (r *hookedRenderer) renderImage(w util.BufWriter, source []byte, node ast.N ctx.RenderContext().Ctx, w, imageLinkContext{ - linkContext: linkContext{ - BaseContext: render.NewBaseContext(ctx, lr, node, source, ordinal), - destination: string(n.Destination), - title: string(n.Title), - text: hstring.HTML(text), - plainText: render.TextPlain(n, source), - AttributesHolder: attributes.New(attrs, attributes.AttributesOwnerGeneral), - }, - isBlock: isBlock, + BaseContext: render.NewBaseContext(ctx, lr, node, source, ordinal), + destination: string(n.Destination), + title: string(n.Title), + text: hstring.HTML(text), + plainText: render.TextPlain(n, source), + AttributesHolder: attributes.New(attrs, attributes.AttributesOwnerGeneral), + isBlock: isBlock, }, ) diff --git a/media/mediaType.go b/media/mediaType.go index b3b615444..a3b7ccae2 100644 --- a/media/mediaType.go +++ b/media/mediaType.go @@ -70,7 +70,7 @@ type SuffixInfo struct { // If http.DetectContentType resolves to application/octet-stream, a zero Type is returned. // If http.DetectContentType resolves to text/plain or application/xml, we try to get more specific using types and ext. func FromContent(types Types, extensionHints []string, content []byte) Type { - t := strings.Split(http.DetectContentType(content), ";")[0] + t, _, _ := strings.Cut(http.DetectContentType(content), ";") if t == "application/octet-stream" { return zero } @@ -143,7 +143,7 @@ func FromString(t string) (Type, error) { mainType := parts[0] subParts := strings.Split(parts[1], "+") - subType := strings.Split(subParts[0], ";")[0] + subType, _, _ := strings.Cut(subParts[0], ";") var suffix string diff --git a/modules/client.go b/modules/client.go index 1fa3b6a3e..153b3b9c2 100644 --- a/modules/client.go +++ b/modules/client.go @@ -615,7 +615,7 @@ func (c *Client) writeHugoDirectSum(mods Modules) error { continue } if m.IsGoMod() && m.VersionQuery() != "" { - sums = append(sums, modSum{pathVersionKey: pathVersionKey{path: m.Path(), version: m.Version()}, sum: m.Sum()}) + sums = append(sums, modSum{path: m.Path(), version: m.Version(), sum: m.Sum()}) } } diff --git a/navigation/menu_cache_test.go b/navigation/menu_cache_test.go index 98e98c442..2dafe0568 100644 --- a/navigation/menu_cache_test.go +++ b/navigation/menu_cache_test.go @@ -40,8 +40,8 @@ func TestMenuCache(t *testing.T) { m[0].MenuConfig.Title = "changed" } - var o1 uint64 - var o2 uint64 + var o1 atomic.Uint64 + var o2 atomic.Uint64 var wg sync.WaitGroup @@ -59,7 +59,7 @@ func TestMenuCache(t *testing.T) { for k, menu := range testMenuSets { l1.Lock() m, ca := c1.get("k1", nil, menu) - c.Assert(ca, qt.Equals, !atomic.CompareAndSwapUint64(&o1, uint64(k), uint64(k+1))) + c.Assert(ca, qt.Equals, !o1.CompareAndSwap(uint64(k), uint64(k+1))) l1.Unlock() m2, c2 := c1.get("k1", nil, m) c.Assert(c2, qt.Equals, true) @@ -69,7 +69,7 @@ func TestMenuCache(t *testing.T) { l2.Lock() m3, c3 := c1.get("k2", changeFirst, menu) - c.Assert(c3, qt.Equals, !atomic.CompareAndSwapUint64(&o2, uint64(k), uint64(k+1))) + c.Assert(c3, qt.Equals, !o2.CompareAndSwap(uint64(k), uint64(k+1))) l2.Unlock() c.Assert(m3, qt.Not(qt.IsNil)) c.Assert("changed", qt.Equals, m3[0].Title) diff --git a/parser/pageparser/pagelexer.go b/parser/pageparser/pagelexer.go index a1a1b5de6..10d27073a 100644 --- a/parser/pageparser/pagelexer.go +++ b/parser/pageparser/pagelexer.go @@ -72,16 +72,14 @@ type Config struct { // can be set if position of first shortcode is known func newPageLexer(input []byte, stateStart stateFunc, cfg Config) *pageLexer { lexer := &pageLexer{ - input: input, - stateStart: stateStart, - summaryDivider: summaryDivider, - cfg: cfg, - lexerShortcodeState: lexerShortcodeState{ - currLeftDelimItem: tLeftDelimScNoMarkup, - currRightDelimItem: tRightDelimScNoMarkup, - openShortcodes: make(map[unique.Handle[string]]bool), - }, - items: make([]Item, 0, 5), + input: input, + stateStart: stateStart, + summaryDivider: summaryDivider, + cfg: cfg, + currLeftDelimItem: tLeftDelimScNoMarkup, + currRightDelimItem: tRightDelimScNoMarkup, + openShortcodes: make(map[unique.Handle[string]]bool), + items: make([]Item, 0, 5), } lexer.sectionHandlers = createSectionHandlers(lexer) diff --git a/resources/page/hugoinfo.go b/resources/page/hugoinfo.go index 64963885d..31774734a 100644 --- a/resources/page/hugoinfo.go +++ b/resources/page/hugoinfo.go @@ -162,7 +162,7 @@ func NewHugoInfo(opts HugoInfoOptions) HugoInfo { BuildDate: opts.BuildDate, GoVersion: opts.GoVersion, - hugoInfoProviders: hugoInfoProviders{HugoInfoHugoSitesProvider: opts.HugoInfoHugoSitesProvider}, + HugoInfoHugoSitesProvider: opts.HugoInfoHugoSitesProvider, opts: opts, store: hstore.NewScratch(), diff --git a/resources/page/pages_cache_test.go b/resources/page/pages_cache_test.go index 44e540bac..128dd6997 100644 --- a/resources/page/pages_cache_test.go +++ b/resources/page/pages_cache_test.go @@ -31,8 +31,8 @@ func TestPageCache(t *testing.T) { p[0].(*testPage).description = "changed" } - var o1 uint64 - var o2 uint64 + var o1 atomic.Uint64 + var o2 atomic.Uint64 var wg sync.WaitGroup @@ -50,7 +50,7 @@ func TestPageCache(t *testing.T) { for k, pages := range testPageSets { l1.Lock() p, ca := c1.get("k1", nil, pages) - c.Assert(ca, qt.Equals, !atomic.CompareAndSwapUint64(&o1, uint64(k), uint64(k+1))) + c.Assert(ca, qt.Equals, !o1.CompareAndSwap(uint64(k), uint64(k+1))) l1.Unlock() p2, c2 := c1.get("k1", nil, p) c.Assert(c2, qt.Equals, true) @@ -60,7 +60,7 @@ func TestPageCache(t *testing.T) { l2.Lock() p3, c3 := c1.get("k2", changeFirst, pages) - c.Assert(c3, qt.Equals, !atomic.CompareAndSwapUint64(&o2, uint64(k), uint64(k+1))) + c.Assert(c3, qt.Equals, !o2.CompareAndSwap(uint64(k), uint64(k+1))) l2.Unlock() c.Assert(p3, qt.Not(qt.IsNil)) c.Assert("changed", qt.Equals, p3[0].(*testPage).description) diff --git a/tpl/collections/sort.go b/tpl/collections/sort.go index 15f6eb34a..9d24c007b 100644 --- a/tpl/collections/sort.go +++ b/tpl/collections/sort.go @@ -53,8 +53,8 @@ func (ns *Namespace) Sort(ctx context.Context, l any, args ...any) (any, error) collator := langs.GetCollator1(ns.deps.Conf.Language().(*langs.Language)) // Create a list of pairs that will be used to do the sort - p := pairList{Collator: collator, sortComp: ns.sortComp, SortAsc: true, SliceType: sliceType} - p.Pairs = make([]pair, seqv.Len()) + p := pairList{Collator: collator, sortComp: ns.sortComp, SortAsc: true, SliceType: sliceType, + Pairs: make([]pair, seqv.Len())} var sortByField string for i, l := range args { diff --git a/tpl/strings/truncate.go b/tpl/strings/truncate.go index 66811c74e..557703079 100644 --- a/tpl/strings/truncate.go +++ b/tpl/strings/truncate.go @@ -18,6 +18,7 @@ import ( "html" "html/template" "regexp" + "slices" "strings" "unicode" "unicode/utf8" @@ -132,8 +133,8 @@ func (ns *Namespace) Truncate(s any, options ...any) (template.HTML, error) { out.WriteString(ellipsis) // Close out any open HTML tags var currentTag *htmlTag - for i := len(tags) - 1; i >= 0; i-- { - tag := tags[i] + for _, tag := range slices.Backward(tags) { + if tag.pos >= endTextPos || currentTag != nil { if currentTag != nil && currentTag.name == tag.name { currentTag = nil