repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/tableofcontents/tableofcontents_integration_test.go
markup/tableofcontents/tableofcontents_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tableofcontents_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue #10776 func TestHeadingsLevel(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ range .Fragments.HeadingsMap }} {{ printf "%s|%d|%s" .ID .Level .Title }} {{ end }} -- content/_index.md -- ## Heading L2 ### Heading L3 ##### Heading L5 ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "heading-l2|2|Heading L2", "heading-l3|3|Heading L3", "heading-l5|5|Heading L5", ) } // Issue #13107 func TestToHTMLArgTypes(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','section','rss','sitemap','taxonomy','term'] -- layouts/single.html -- {{ .Fragments.ToHTML .Params.toc.startLevel .Params.toc.endLevel false }} -- content/json.md -- { "title": "json", "params": { "toc": { "startLevel": 2, "endLevel": 4 } } } CONTENT -- content/toml.md -- +++ title = 'toml' [params.toc] startLevel = 2 endLevel = 4 +++ CONTENT -- content/yaml.md -- --- title: yaml params: toc: startLevel: 2 endLevel: 4 --- CONTENT ` content := ` # Level One ## Level Two ### Level Three #### Level Four ##### Level Five ###### Level Six ` want := ` <nav id="TableOfContents"> <ul> <li><a href="#level-two">Level Two</a> <ul> <li><a href="#level-three">Level Three</a> <ul> <li><a href="#level-four">Level Four</a></li> </ul> </li> </ul> </li> </ul> </nav> ` files = strings.ReplaceAll(files, "CONTENT", content) b := hugolib.Test(t, files) b.AssertFileContentEquals("public/json/index.html", strings.TrimSpace(want)) b.AssertFileContentEquals("public/toml/index.html", strings.TrimSpace(want)) b.AssertFileContentEquals("public/yaml/index.html", strings.TrimSpace(want)) files = strings.ReplaceAll(files, `2`, `"x"`) b, err := hugolib.TestE(t, files) b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, `error calling ToHTML: startLevel: unable to cast "x" of type string`) } func TestHeadingsNilpointerIssue11843(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- layouts/home.html -- {{ $h := index .Fragments.HeadingsMap "bad_id" }} {{ if not $h }}OK{{ end }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "OK") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/markup_config/config.go
markup/markup_config/config.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package markup_config import ( "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/markup/asciidocext/asciidocext_config" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/mitchellh/mapstructure" ) type Config struct { // Default markdown handler for md/markdown extensions. // Default is "goldmark". DefaultMarkdownHandler string // The configuration used by code highlighters. Highlight highlight.Config // Table of contents configuration TableOfContents tableofcontents.Config // Configuration for the Goldmark markdown engine. Goldmark goldmark_config.Config // Configuration for the AsciiDoc external markdown engine. AsciiDocExt asciidocext_config.Config } func (c *Config) Init() error { return c.Goldmark.Init() } func Decode(cfg config.Provider) (conf Config, err error) { conf = Default m := cfg.GetStringMap("markup") if m == nil { return } m = maps.CleanConfigStringMap(m) normalizeConfig(m) err = mapstructure.WeakDecode(m, &conf) if err != nil { return } if err = conf.Init(); err != nil { return } if err = highlight.ApplyLegacyConfig(cfg, &conf.Highlight); err != nil { return } return } func normalizeConfig(m map[string]any) { v, err := maps.GetNestedParam("goldmark.parser", ".", m) if err == nil { vm := maps.ToStringMap(v) // Changed from a bool in 0.81.0 if vv, found := vm["attribute"]; found { if vvb, ok := vv.(bool); ok { vm["attribute"] = goldmark_config.ParserAttribute{ Title: vvb, } } } } // Handle changes to the Goldmark configuration. v, err = maps.GetNestedParam("goldmark.extensions", ".", m) if err == nil { vm := maps.ToStringMap(v) // We changed the typographer extension config from a bool to a struct in 0.112.0. migrateGoldmarkConfig(vm, "typographer", goldmark_config.Typographer{Disable: true}) // We changed the footnote extension config from a bool to a struct in 0.151.0. migrateGoldmarkConfig(vm, "footnote", goldmark_config.Footnote{Enable: false}) } } func migrateGoldmarkConfig(vm map[string]any, key string, falseVal any) { if vv, found := vm[key]; found { if vvb, ok := vv.(bool); ok { if !vvb { vm[key] = falseVal } else { delete(vm, key) } } } } var Default = Config{ DefaultMarkdownHandler: "goldmark", TableOfContents: tableofcontents.DefaultConfig, Highlight: highlight.DefaultConfig, Goldmark: goldmark_config.Default, AsciiDocExt: asciidocext_config.Default, }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/markup_config/config_test.go
markup/markup_config/config_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package markup_config import ( "testing" "github.com/gohugoio/hugo/config" qt "github.com/frankban/quicktest" ) func TestConfig(t *testing.T) { c := qt.New(t) c.Run("Decode", func(c *qt.C) { c.Parallel() v := config.New() v.Set("markup", map[string]any{ "goldmark": map[string]any{ "renderer": map[string]any{ "unsafe": true, }, }, "asciidocext": map[string]any{ "workingFolderCurrent": true, "safeMode": "save", "extensions": []string{"asciidoctor-html5s"}, }, }) conf, err := Decode(v) c.Assert(err, qt.IsNil) c.Assert(conf.Goldmark.Renderer.Unsafe, qt.Equals, true) c.Assert(conf.Goldmark.Parser.Attribute.Title, qt.Equals, true) c.Assert(conf.Goldmark.Parser.Attribute.Block, qt.Equals, false) c.Assert(conf.AsciiDocExt.WorkingFolderCurrent, qt.Equals, true) c.Assert(conf.AsciiDocExt.Extensions[0], qt.Equals, "asciidoctor-html5s") }) // We changed the typographer extension config from a bool to a struct in 0.112.0. // We changed the footnote extension config from a bool to a struct in 0.151.0. c.Run("Decode legacy Goldmark configs", func(c *qt.C) { c.Parallel() v := config.New() v.Set("markup", map[string]any{ "goldmark": map[string]any{ "extensions": map[string]any{ "footnote": false, "typographer": false, }, }, }) conf, err := Decode(v) c.Assert(err, qt.IsNil) c.Assert(conf.Goldmark.Extensions.Footnote.Enable, qt.Equals, false) c.Assert(conf.Goldmark.Extensions.Typographer.Disable, qt.Equals, true) v.Set("markup", map[string]any{ "goldmark": map[string]any{ "extensions": map[string]any{ "footnote": true, "typographer": true, }, }, }) conf, err = Decode(v) c.Assert(err, qt.IsNil) c.Assert(conf.Goldmark.Extensions.Footnote.Enable, qt.Equals, true) c.Assert(conf.Goldmark.Extensions.Typographer.Disable, qt.Equals, false) c.Assert(conf.Goldmark.Extensions.Typographer.Ellipsis, qt.Equals, "&hellip;") }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/converter/converter.go
markup/converter/converter.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package converter import ( "bytes" "context" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/spf13/afero" ) // ProviderConfig configures a new Provider. type ProviderConfig struct { Conf config.AllProvider // Site config ContentFs afero.Fs Logger loggers.Logger Exec *hexec.Exec highlight.Highlighter } func (p ProviderConfig) MarkupConfig() markup_config.Config { return p.Conf.GetConfigSection("markup").(markup_config.Config) } // ProviderProvider creates converter providers. type ProviderProvider interface { New(cfg ProviderConfig) (Provider, error) } // Provider creates converters. type Provider interface { New(ctx DocumentContext) (Converter, error) Name() string } // NewProvider creates a new Provider with the given name. func NewProvider(name string, create func(ctx DocumentContext) (Converter, error)) Provider { return newConverter{ name: name, create: create, } } type newConverter struct { name string create func(ctx DocumentContext) (Converter, error) } func (n newConverter) New(ctx DocumentContext) (Converter, error) { return n.create(ctx) } func (n newConverter) Name() string { return n.name } var NopConverter = new(nopConverter) type nopConverter int func (nopConverter) Convert(ctx RenderContext) (ResultRender, error) { return &bytes.Buffer{}, nil } func (nopConverter) Supports(feature identity.Identity) bool { return false } // Converter wraps the Convert method that converts some markup into // another format, e.g. Markdown to HTML. type Converter interface { Convert(ctx RenderContext) (ResultRender, error) } // ParseRenderer is an optional interface. // The Goldmark converter implements this, and this allows us // to extract the ToC without having to render the content. type ParseRenderer interface { Parse(RenderContext) (ResultParse, error) Render(RenderContext, any) (ResultRender, error) } // ResultRender represents the minimum returned from Convert and Render. type ResultRender interface { Bytes() []byte } // ResultParse represents the minimum returned from Parse. type ResultParse interface { Doc() any TableOfContents() *tableofcontents.Fragments } // DocumentInfo holds additional information provided by some converters. type DocumentInfo interface { AnchorSuffix() string } // TableOfContentsProvider provides the content as a ToC structure. type TableOfContentsProvider interface { TableOfContents() *tableofcontents.Fragments } // AnchorNameSanitizer tells how a converter sanitizes anchor names. type AnchorNameSanitizer interface { SanitizeAnchorName(s string) string } // Bytes holds a byte slice and implements the Result interface. type Bytes []byte // Bytes returns itself func (b Bytes) Bytes() []byte { return b } // DocumentContext holds contextual information about the document to convert. type DocumentContext struct { Document any // May be nil. Usually a page.Page DocumentLookup func(uint64) any // May be nil. DocumentID string DocumentName string Filename string } // RenderContext holds contextual information about the content to render. type RenderContext struct { // Ctx is the context.Context for the current Page render. Ctx context.Context // Src is the content to render. Src []byte // Whether to render TableOfContents. RenderTOC bool // GerRenderer provides hook renderers on demand. GetRenderer hooks.GetRendererFunc }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/converter/hooks/hooks.go
markup/converter/hooks/hooks.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hooks import ( "context" "io" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/common/types/hstring" "github.com/gohugoio/hugo/markup/internal/attributes" ) var _ AttributesOptionsSliceProvider = (*attributes.AttributesHolder)(nil) type AttributesProvider interface { // Attributes passed in from Markdown (e.g. { attrName1=attrValue1 attrName2="attr Value 2" }). Attributes() map[string]any } // LinkContext is the context passed to a link render hook. type LinkContext interface { PageProvider // The link URL. Destination() string // The link title attribute. Title() string // The rendered (HTML) text. Text() hstring.HTML // The plain variant of Text. PlainText() string } // ImageLinkContext is the context passed to a image link render hook. type ImageLinkContext interface { LinkContext // Returns true if this is a standalone image and the config option // markup.goldmark.parser.wrapStandAloneImageWithinParagraph is disabled. IsBlock() bool // Zero-based ordinal for all the images in the current document. Ordinal() int } // CodeblockContext is the context passed to a code block render hook. type CodeblockContext interface { BaseContext AttributesProvider // Chroma highlighting processing options. This will only be filled if Type is a known Chroma Lexer. Options() map[string]any // The type of code block. This will be the programming language, e.g. bash, when doing code highlighting. Type() string // The text between the code fences. Inner() string } // TableContext is the context passed to a table render hook. type TableContext interface { BaseContext AttributesProvider THead() []TableRow TBody() []TableRow } // BaseContext is the base context used in most render hooks. type BaseContext interface { text.Positioner PageProvider // Zero-based ordinal for all elements of this kind in the current document. Ordinal() int } // BlockquoteContext is the context passed to a blockquote render hook. type BlockquoteContext interface { BaseContext AttributesProvider // The blockquote text. // If type is "alert", this will be the alert text. Text() hstring.HTML /// Returns the blockquote type, one of "regular" and "alert". // Type "alert" indicates that this is a GitHub type alert. Type() string // The GitHub alert type converted to lowercase, e.g. "note". // Only set if Type is "alert". AlertType() string // The alert title. // Currently only relevant for Obsidian alerts. // GitHub does not suport alert titles and will not render alerts with titles. AlertTitle() hstring.HTML // The alert sign, "+" or "-" or "" used to indicate folding. // Currently only relevant for Obsidian alerts. // GitHub does not suport alert signs and will not render alerts with signs. AlertSign() string } type PositionerSourceTargetProvider interface { // For internal use. PositionerSourceTarget() []byte } // PassThroughContext is the context passed to a passthrough render hook. type PassthroughContext interface { BaseContext AttributesProvider // Currently one of "inline" or "block". Type() string // The inner content of the passthrough element, excluding the delimiters. Inner() string } type AttributesOptionsSliceProvider interface { AttributesSlice() []attributes.Attribute OptionsSlice() []attributes.Attribute } type LinkRenderer interface { RenderLink(cctx context.Context, w io.Writer, ctx LinkContext) error } type CodeBlockRenderer interface { RenderCodeblock(cctx context.Context, w hugio.FlexiWriter, ctx CodeblockContext) error } type BlockquoteRenderer interface { RenderBlockquote(cctx context.Context, w hugio.FlexiWriter, ctx BlockquoteContext) error } type TableRenderer interface { RenderTable(cctx context.Context, w hugio.FlexiWriter, ctx TableContext) error } type PassthroughRenderer interface { RenderPassthrough(cctx context.Context, w io.Writer, ctx PassthroughContext) error } type IsDefaultCodeBlockRendererProvider interface { IsDefaultCodeBlockRenderer() bool } // HeadingContext contains accessors to all attributes that a HeadingRenderer // can use to render a heading. type HeadingContext interface { PageProvider // Level is the level of the header (i.e. 1 for top-level, 2 for sub-level, etc.). Level() int // Anchor is the HTML id assigned to the heading. Anchor() string // Text is the rendered (HTML) heading text, excluding the heading marker. Text() hstring.HTML // PlainText is the unrendered version of Text. PlainText() string // Attributes (e.g. CSS classes) AttributesProvider } type PageProvider interface { // Page is the page being rendered. Page() any // PageInner may be different than Page when .RenderShortcodes is in play. // The main use case for this is to include other pages' markdown into the current page // but resolve resources and pages relative to the original. PageInner() any } // HeadingRenderer describes a uniquely identifiable rendering hook. type HeadingRenderer interface { // RenderHeading writes the rendered content to w using the data in w. RenderHeading(cctx context.Context, w io.Writer, ctx HeadingContext) error } // ElementPositionResolver provides a way to resolve the start Position // of a markdown element in the original source document. // This may be both slow and approximate, so should only be // used for error logging. type ElementPositionResolver interface { ResolvePosition(ctx any) text.Position } type RendererType int const ( LinkRendererType RendererType = iota + 1 ImageRendererType HeadingRendererType CodeBlockRendererType PassthroughRendererType BlockquoteRendererType TableRendererType ) type GetRendererFunc func(t RendererType, id any) any type TableCell struct { Text hstring.HTML Alignment string // left, center, or right } type TableRow []TableCell type Table struct { THead []TableRow TBody []TableRow }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/internal/external.go
markup/internal/external.go
package internal import ( "bytes" "fmt" "strings" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/markup/converter" ) func ExternallyRenderContent( cfg converter.ProviderConfig, ctx converter.DocumentContext, content []byte, binaryName string, args []string, ) ([]byte, error) { logger := cfg.Logger if strings.Contains(binaryName, "/") { panic(fmt.Sprintf("should be no slash in %q", binaryName)) } argsv := collections.StringSliceToInterfaceSlice(args) var out, cmderr bytes.Buffer argsv = append(argsv, hexec.WithStdout(&out)) argsv = append(argsv, hexec.WithStderr(&cmderr)) argsv = append(argsv, hexec.WithStdin(bytes.NewReader(content))) cmd, err := cfg.Exec.New(binaryName, argsv...) if err != nil { return nil, err } err = cmd.Run() // Most external helpers exit w/ non-zero exit code only if severe, i.e. // halting errors occurred. -> log stderr output regardless of state of err for item := range strings.SplitSeq(cmderr.String(), "\n") { item := strings.TrimSpace(item) if item != "" { if err == nil { logger.Warnf("%s: %s", ctx.DocumentName, item) } else { logger.Errorf("%s: %s", ctx.DocumentName, item) } } } if err != nil { logger.Errorf("%s rendering %s: %v", binaryName, ctx.DocumentName, err) } return normalizeExternalHelperLineFeeds(out.Bytes()), nil } // Strips carriage returns from third-party / external processes (useful for Windows) func normalizeExternalHelperLineFeeds(content []byte) []byte { return bytes.Replace(content, []byte("\r"), []byte(""), -1) } var pythonBinaryCandidates = []string{"python", "python.exe"} func GetPythonBinaryAndExecPath() (string, string) { for _, p := range pythonBinaryCandidates { if pth := hexec.LookPath(p); pth != "" { return p, pth } } return "", "" }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/internal/attributes/attributes.go
markup/internal/attributes/attributes.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package attributes import ( "fmt" "strconv" "strings" "sync" "github.com/gohugoio/hugo/common/hugio" "github.com/spf13/cast" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/util" ) // Markdown attributes used as options by the Chroma highlighter. var chromaHighlightProcessingAttributes = map[string]bool{ "anchorLineNos": true, "guessSyntax": true, "hl_Lines": true, "hl_inline": true, "lineAnchors": true, "lineNos": true, "lineNoStart": true, "lineNumbersInTable": true, "noClasses": true, "style": true, "tabWidth": true, } func init() { for k, v := range chromaHighlightProcessingAttributes { chromaHighlightProcessingAttributes[strings.ToLower(k)] = v } } type AttributesOwnerType int const ( AttributesOwnerGeneral AttributesOwnerType = iota AttributesOwnerCodeBlockChroma AttributesOwnerCodeBlockCustom ) func New(astAttributes []ast.Attribute, ownerType AttributesOwnerType) *AttributesHolder { var ( attrs []Attribute opts []Attribute ) for _, v := range astAttributes { nameLower := strings.ToLower(string(v.Name)) if strings.HasPrefix(string(nameLower), "on") { continue } var vv any switch vvv := v.Value.(type) { case bool, float64: vv = vvv case []any: // Highlight line number hlRanges. var hlRanges [][2]int for _, l := range vvv { if ln, ok := l.(float64); ok { hlRanges = append(hlRanges, [2]int{int(ln) - 1, int(ln) - 1}) } else if rng, ok := l.([]uint8); ok { slices := strings.Split(string([]byte(rng)), "-") lhs, err := strconv.Atoi(slices[0]) if err != nil { continue } rhs := lhs if len(slices) > 1 { rhs, err = strconv.Atoi(slices[1]) if err != nil { continue } } hlRanges = append(hlRanges, [2]int{lhs - 1, rhs - 1}) } } vv = hlRanges case []byte: // Note that we don't do any HTML escaping here. // We used to do that, but that changed in #9558. // Now it's up to the templates to decide. vv = string(vvv) default: panic(fmt.Sprintf("not implemented: %T", vvv)) } if ownerType == AttributesOwnerCodeBlockChroma && chromaHighlightProcessingAttributes[nameLower] { attr := Attribute{Name: string(v.Name), Value: vv} opts = append(opts, attr) } else { attr := Attribute{Name: nameLower, Value: vv} attrs = append(attrs, attr) } } return &AttributesHolder{ attributes: attrs, options: opts, } } type Attribute struct { Name string Value any } func (a Attribute) ValueString() string { return cast.ToString(a.Value) } // Empty holds no attributes. var Empty = &AttributesHolder{} type AttributesHolder struct { // What we get from Goldmark. attributes []Attribute // Attributes considered to be an option (code blocks) options []Attribute // What we send to the render hooks. attributesMapInit sync.Once attributesMap map[string]any optionsMapInit sync.Once optionsMap map[string]any } type Attributes map[string]any func (a *AttributesHolder) Attributes() map[string]any { a.attributesMapInit.Do(func() { a.attributesMap = make(map[string]any) for _, v := range a.attributes { a.attributesMap[v.Name] = v.Value } }) return a.attributesMap } func (a *AttributesHolder) Options() map[string]any { a.optionsMapInit.Do(func() { a.optionsMap = make(map[string]any) for _, v := range a.options { a.optionsMap[v.Name] = v.Value } }) return a.optionsMap } func (a *AttributesHolder) AttributesSlice() []Attribute { return a.attributes } func (a *AttributesHolder) OptionsSlice() []Attribute { return a.options } // RenderASTAttributes writes the AST attributes to the given as attributes to an HTML element. // This is used by the default HTML renderers, e.g. for headings etc. where no hook template could be found. // This performs HTML escaping of string attributes. func RenderASTAttributes(w hugio.FlexiWriter, attributes ...ast.Attribute) { for _, attr := range attributes { a := strings.ToLower(string(attr.Name)) if strings.HasPrefix(a, "on") { continue } _, _ = w.WriteString(" ") _, _ = w.Write(attr.Name) _, _ = w.WriteString(`="`) switch v := attr.Value.(type) { case []byte: _, _ = w.Write(util.EscapeHTML(v)) default: w.WriteString(cast.ToString(v)) } _ = w.WriteByte('"') } } // RenderAttributes Render writes the attributes to the given as attributes to an HTML element. // This is used for the default codeblock rendering. // This performs HTML escaping of string attributes. func RenderAttributes(w hugio.FlexiWriter, skipClass bool, attributes ...Attribute) { for _, attr := range attributes { a := strings.ToLower(string(attr.Name)) if skipClass && a == "class" { continue } _, _ = w.WriteString(" ") _, _ = w.WriteString(attr.Name) _, _ = w.WriteString(`="`) switch v := attr.Value.(type) { case []byte: _, _ = w.Write(util.EscapeHTML(v)) default: w.WriteString(cast.ToString(v)) } _ = w.WriteByte('"') } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/asciidocext/convert_test.go
markup/asciidocext/convert_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package asciidocext converts AsciiDoc to HTML using the Asciidoctor // external binary. The `asciidoc` module is reserved for a future golang // implementation. package asciidocext_test import ( "encoding/json" "testing" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/markup/asciidocext" "github.com/gohugoio/hugo/markup/asciidocext/asciidocext_config" "github.com/gohugoio/hugo/markup/asciidocext/internal" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/markup/markup_config" "github.com/spf13/afero" qt "github.com/frankban/quicktest" ) var defaultAsciiDocExtConfigAsJSON []byte func init() { var err error defaultAsciiDocExtConfigAsJSON, err = json.Marshal(markup_config.Default.AsciiDocExt) if err != nil { panic(err) } } func resetDefaultAsciiDocExtConfig() { markup_config.Default.AsciiDocExt = asciidocext_config.Config{} err := json.Unmarshal(defaultAsciiDocExtConfigAsJSON, &markup_config.Default.AsciiDocExt) if err != nil { panic(err) } } func TestAsciidoctorDefaultArgs(t *testing.T) { c := qt.New(t) cfg := config.New() conf := testconfig.GetTestConfig(afero.NewMemMapFs(), cfg) p, err := asciidocext.Provider.New( converter.ProviderConfig{ Conf: conf, Logger: loggers.NewDefault(), }, ) c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) ac := conv.(*internal.AsciiDocConverter) c.Assert(ac, qt.Not(qt.IsNil)) args, err := ac.ParseArgs(converter.DocumentContext{}) c.Assert(err, qt.IsNil) expected := []string{"--no-header-footer"} c.Assert(args, qt.DeepEquals, expected) } func TestAsciidoctorNonDefaultArgs(t *testing.T) { c := qt.New(t) t.Cleanup(func() { resetDefaultAsciiDocExtConfig() }) mconf := markup_config.Default mconf.AsciiDocExt.Backend = "manpage" mconf.AsciiDocExt.NoHeaderOrFooter = false mconf.AsciiDocExt.SafeMode = "safe" mconf.AsciiDocExt.SectionNumbers = true mconf.AsciiDocExt.Verbose = true mconf.AsciiDocExt.Trace = false mconf.AsciiDocExt.FailureLevel = "warn" conf := testconfig.GetTestConfigSectionFromStruct("markup", mconf) p, err := asciidocext.Provider.New( converter.ProviderConfig{ Conf: conf, Logger: loggers.NewDefault(), }, ) c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) ac := conv.(*internal.AsciiDocConverter) c.Assert(ac, qt.Not(qt.IsNil)) args, err := ac.ParseArgs(converter.DocumentContext{}) c.Assert(err, qt.IsNil) expected := []string{"-b", "manpage", "--section-numbers", "--verbose", "--failure-level", "warn", "--safe-mode", "safe"} c.Assert(args, qt.DeepEquals, expected) } func TestAsciidoctorDisallowedArgs(t *testing.T) { c := qt.New(t) t.Cleanup(func() { resetDefaultAsciiDocExtConfig() }) mconf := markup_config.Default mconf.AsciiDocExt.Backend = "disallowed-backend" mconf.AsciiDocExt.Extensions = []string{"./disallowed-extension"} mconf.AsciiDocExt.Attributes = map[string]any{"outdir": "disallowed-attribute"} mconf.AsciiDocExt.SafeMode = "disallowed-safemode" mconf.AsciiDocExt.FailureLevel = "disallowed-failurelevel" conf := testconfig.GetTestConfigSectionFromStruct("markup", mconf) p, err := asciidocext.Provider.New( converter.ProviderConfig{ Conf: conf, Logger: loggers.NewDefault(), }, ) c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) ac := conv.(*internal.AsciiDocConverter) c.Assert(ac, qt.Not(qt.IsNil)) args, err := ac.ParseArgs(converter.DocumentContext{}) c.Assert(err, qt.IsNil) expected := []string{"--no-header-footer"} c.Assert(args, qt.DeepEquals, expected) } func TestAsciidoctorArbitraryExtension(t *testing.T) { c := qt.New(t) t.Cleanup(func() { resetDefaultAsciiDocExtConfig() }) mconf := markup_config.Default mconf.AsciiDocExt.Extensions = []string{"arbitrary-extension"} conf := testconfig.GetTestConfigSectionFromStruct("markup", mconf) p, err := asciidocext.Provider.New( converter.ProviderConfig{ Conf: conf, Logger: loggers.NewDefault(), }, ) c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) ac := conv.(*internal.AsciiDocConverter) c.Assert(ac, qt.Not(qt.IsNil)) args, err := ac.ParseArgs(converter.DocumentContext{}) c.Assert(err, qt.IsNil) expected := []string{"-r", "arbitrary-extension", "--no-header-footer"} c.Assert(args, qt.DeepEquals, expected) } func TestAsciidoctorDisallowedExtension(t *testing.T) { c := qt.New(t) t.Cleanup(func() { resetDefaultAsciiDocExtConfig() }) for _, disallowedExtension := range []string{ `foo-bar//`, `foo-bar\\ `, `../../foo-bar`, `/foo-bar`, `C:\foo-bar`, `foo-bar.rb`, `foo.bar`, } { mconf := markup_config.Default mconf.AsciiDocExt.Extensions = []string{disallowedExtension} conf := testconfig.GetTestConfigSectionFromStruct("markup", mconf) p, err := asciidocext.Provider.New( converter.ProviderConfig{ Conf: conf, Logger: loggers.NewDefault(), }, ) c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) ac := conv.(*internal.AsciiDocConverter) c.Assert(ac, qt.Not(qt.IsNil)) args, err := ac.ParseArgs(converter.DocumentContext{}) c.Assert(err, qt.IsNil) expected := []string{"--no-header-footer"} c.Assert(args, qt.DeepEquals, expected) } } func TestAsciidoctorAttributes(t *testing.T) { c := qt.New(t) t.Cleanup(func() { resetDefaultAsciiDocExtConfig() }) cfg := config.FromTOMLConfigString(` [markup] [markup.asciidocext] trace = false [markup.asciidocext.attributes] my-base-url = "https://gohugo.io/" my-attribute-name = "my value" my-attribute-true = true my-attribute-false = false `) conf := testconfig.GetTestConfig(nil, cfg) p, err := asciidocext.Provider.New( converter.ProviderConfig{ Conf: conf, Logger: loggers.NewDefault(), }, ) c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) ac := conv.(*internal.AsciiDocConverter) c.Assert(ac, qt.Not(qt.IsNil)) expectedValues := map[string]bool{ "my-base-url=https://gohugo.io/": true, "my-attribute-name=my value": true, "my-attribute-true": true, "'!my-attribute-false'": true, } args, err := ac.ParseArgs(converter.DocumentContext{}) c.Assert(err, qt.IsNil) c.Assert(len(args), qt.Equals, 9) c.Assert(args[0], qt.Equals, "-a") c.Assert(expectedValues[args[1]], qt.Equals, true) c.Assert(args[2], qt.Equals, "-a") c.Assert(expectedValues[args[3]], qt.Equals, true) c.Assert(args[4], qt.Equals, "-a") c.Assert(expectedValues[args[5]], qt.Equals, true) c.Assert(args[6], qt.Equals, "-a") c.Assert(expectedValues[args[7]], qt.Equals, true) c.Assert(args[8], qt.Equals, "--no-header-footer") } func getProvider(c *qt.C, mConfStr string) converter.Provider { confStr := ` [security] [security.exec] allow = ['asciidoctor'] ` confStr += mConfStr cfg := config.FromTOMLConfigString(confStr) conf := testconfig.GetTestConfig(nil, cfg) securityConfig := conf.GetConfigSection("security").(security.Config) p, err := asciidocext.Provider.New( converter.ProviderConfig{ Logger: loggers.NewDefault(), Conf: conf, Exec: hexec.New(securityConfig, "", loggers.NewDefault()), }, ) c.Assert(err, qt.IsNil) return p } func TestConvert(t *testing.T) { if ok, err := asciidocext.Supports(); !ok { t.Skip(err) } c := qt.New(t) p := getProvider(c, "") conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte("testContent")}) c.Assert(err, qt.IsNil) c.Assert(string(b.Bytes()), qt.Equals, "<div class=\"paragraph\">\n<p>testContent</p>\n</div>\n") } func TestTableOfContents(t *testing.T) { if ok, err := asciidocext.Supports(); !ok { t.Skip(err) } c := qt.New(t) p := getProvider(c, "") conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) r, err := conv.Convert(converter.RenderContext{Src: []byte(`:toc: macro :toclevels: 4 toc::[] === Introduction == Section 1 === Section 1.1 ==== Section 1.1.1 === Section 1.2 testContent == Section 2 `)}) c.Assert(err, qt.IsNil) toc, ok := r.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) c.Assert(toc.TableOfContents().Identifiers, qt.DeepEquals, collections.SortedStringSlice{"_introduction", "_section_1", "_section_1_1", "_section_1_1_1", "_section_1_2", "_section_2"}) // Although "Introduction" has a level 3 markup heading, AsciiDoc treats the first heading as level 2. c.Assert(toc.TableOfContents().HeadingsMap["_introduction"].Level, qt.Equals, 2) c.Assert(toc.TableOfContents().HeadingsMap["_section_1"].Level, qt.Equals, 2) c.Assert(toc.TableOfContents().HeadingsMap["_section_1_1"].Level, qt.Equals, 3) c.Assert(toc.TableOfContents().HeadingsMap["_section_1_1_1"].Level, qt.Equals, 4) c.Assert(toc.TableOfContents().HeadingsMap["_section_1_2"].Level, qt.Equals, 3) c.Assert(toc.TableOfContents().HeadingsMap["_section_2"].Level, qt.Equals, 2) c.Assert(string(r.Bytes()), qt.Not(qt.Contains), "<div id=\"toc\" class=\"toc\">") } func TestTableOfContentsWithCode(t *testing.T) { if ok, err := asciidocext.Supports(); !ok { t.Skip(err) } c := qt.New(t) p := getProvider(c, "") conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) r, err := conv.Convert(converter.RenderContext{Src: []byte(`:toc: auto == Some ` + "`code`" + ` in the title `)}) c.Assert(err, qt.IsNil) toc, ok := r.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) c.Assert(toc.TableOfContents().HeadingsMap["_some_code_in_the_title"].Title, qt.Equals, "Some <code>code</code> in the title") c.Assert(string(r.Bytes()), qt.Not(qt.Contains), "<div id=\"toc\" class=\"toc\">") } func TestTableOfContentsPreserveTOC(t *testing.T) { if ok, err := asciidocext.Supports(); !ok { t.Skip(err) } c := qt.New(t) confStr := ` [markup] [markup.asciidocExt] preserveTOC = true ` p := getProvider(c, confStr) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) r, err := conv.Convert(converter.RenderContext{Src: []byte(`:toc: :idprefix: :idseparator: - == Some title `)}) c.Assert(err, qt.IsNil) toc, ok := r.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) c.Assert(toc.TableOfContents().Identifiers, qt.DeepEquals, collections.SortedStringSlice{"some-title"}) c.Assert(string(r.Bytes()), qt.Contains, "<div id=\"toc\" class=\"toc\">") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/asciidocext/convert.go
markup/asciidocext/convert.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package asciidocext converts AsciiDoc to HTML using Asciidoctor // external binary. The `asciidoc` module is reserved for a future golang // implementation. package asciidocext import ( "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/markup/asciidocext/internal" "github.com/gohugoio/hugo/markup/converter" ) // Provider is the package entry point. var Provider converter.ProviderProvider = provider{} type provider struct{} func (p provider) New(cfg converter.ProviderConfig) (converter.Provider, error) { return converter.NewProvider("asciidocext", func(ctx converter.DocumentContext) (converter.Converter, error) { return &internal.AsciiDocConverter{ Ctx: ctx, Cfg: cfg, }, nil }), nil } // Supports reports whether the AsciiDoc converter is installed. Only used in // tests. func Supports() (bool, error) { hasAsciiDoc, err := internal.HasAsciiDoc() if htesting.SupportsAll() { if !hasAsciiDoc { panic(err) } return true, nil } return hasAsciiDoc, err } // SupportsGoATDiagrams reports whether the AsciiDoc converter can render GoAT // diagrams. Only used in tests. func SupportsGoATDiagrams() (bool, error) { supportsGoATDiagrams, err := internal.CanRenderGoATDiagrams() if htesting.SupportsAll() { if !supportsGoATDiagrams { panic(err) } return true, nil } return supportsGoATDiagrams, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/asciidocext/asciidoc_integration_test.go
markup/asciidocext/asciidoc_integration_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package asciidocext_test import ( "fmt" "os" "path/filepath" "runtime" "slices" "strings" "testing" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/markup/asciidocext" ) type contentFile struct { // The path to the content file, relative to the project directory. path string // The title of the content file. title string } type publishedContentFile struct { // The path to the published content file, relative to the project directory. path string // The expected string in the content file used for content test assertions. match string } type testCase struct { name string baseURL string defaultContentLanguageInSubdir bool langEnBaseURL string langDeBaseURL string langDeDisabled bool uglyURLsS1 bool validate func(b *hugolib.IntegrationTestBuilder) } // Issue 9202, Issue 10183, Issue 10473 func TestAsciiDocDiagrams(t *testing.T) { if !htesting.IsRealCI() { t.Skip() } if ok, err := asciidocext.Supports(); !ok { t.Skip(err) } if ok, err := asciidocext.SupportsGoATDiagrams(); !ok { t.Skip(err) } t.Cleanup(func() { resetDefaultAsciiDocExtConfig() }) diagramCacheDir := t.TempDir() // we want this to persist for all tests files := createContentFiles() + contentAdapter + layouts testCases := []testCase{ // Test 1 - Monolingual, uglyURLs = false for s1, without subdir in base URL, defaultContentLanguageInSubdir = false {"Test 1", "https://example.org/", false, "", "", true, false, validatePublishedSite_1}, // Test 2 - Monolingual, uglyURLs = false for s1, with subdir in base URL, defaultContentLanguageInSubdir = false {"Test 2", "https://example.org/subdir/", false, "", "", true, false, validatePublishedSite_2}, // // Test 3 - Monolingual, uglyURLs = true for s1, without subdir in base URL, defaultContentLanguageInSubdir = false {"Test 3", "https://example.org/", false, "", "", true, true, validatePublishedSite_3}, // // Test 4 - Monolingual, uglyURLs = true for s1, with subdir in base URL, defaultContentLanguageInSubdir = false {"Test 4", "https://example.org/subdir/", false, "", "", true, true, validatePublishedSite_4}, // // Test 5 - Multilingual, single-host, uglyURLs = false for s1, without subdir in base URL, defaultContentLanguageInSubdir = false {"Test 5", "https://example.org/", false, "", "", false, false, validatePublishedSite_5}, // Test 6 - Multilingual, single-host, uglyURLs = false for s1, with subdir in base URL, defaultContentLanguageInSubdir = false {"Test 6", "https://example.org/subdir/", false, "", "", false, false, validatePublishedSite_6}, // Test 7 - Multilingual, single-host, uglyURLs = true for s1, without subdir in base URL, defaultContentLanguageInSubdir = false {"Test 7", "https://example.org/", false, "", "", false, true, validatePublishedSite_7}, // Test 8 - Multilingual, single-host, uglyURLs = true for s1, with subdir in base URL, defaultContentLanguageInSubdir = false {"Test 8", "https://example.org/subdir/", false, "", "", false, true, validatePublishedSite_8}, // Test 9 - Multilingual, single-host, uglyURLs = false for s1, without subdir in base URL, defaultContentLanguageInSubdir = true {"Test 9", "https://example.org/", true, "", "", false, false, validatePublishedSite_9}, // Test 10 - Multilingual, single-host, uglyURLs = false for s1, with subdir in base URL, defaultContentLanguageInSubdir = true {"Test 10", "https://example.org/subdir/", true, "", "", false, false, validatePublishedSite_10}, // Test 11 - Multilingual, single-host, uglyURLs = true for s1, without subdir in base URL, defaultContentLanguageInSubdir = true {"Test 11", "https://example.org/", true, "", "", false, true, validatePublishedSite_11}, // Test 12 - Multilingual, single-host, uglyURLs = true for s1, with subdir in base URL, defaultContentLanguageInSubdir = true {"Test 12", "https://example.org/subdir/", true, "", "", false, true, validatePublishedSite_12}, // Test 13 - Multilingual, multi-host, uglyURLs = false, without subdir in base URL, defaultContentLanguageInSubdir = false {"Test 13", "", false, `baseURL = "https://.en.example.org/"`, `baseURL = "https://.de.example.org/"`, false, false, validatePublishedSite_13}, // Test 14 - Multilingual, multi-host, uglyURLs = false for s1, with subdir in base URL, defaultContentLanguageInSubdir = false {"Test 14", "", false, `baseURL = "https://.en.example.org/subdir/"`, `baseURL = "https://.de.example.org/subdir/"`, false, false, validatePublishedSite_14}, // Test 15 - Multilingual, multi-host, uglyURLs = true for s1, without subdir in base URL, defaultContentLanguageInSubdir = false {"Test 15", "", false, `baseURL = "https://.en.example.org/"`, `baseURL = "https://.de.example.org/"`, false, true, validatePublishedSite_15}, // Test 16 - Multilingual, multi-host, uglyURLs = true for s1, with subdir in base URL, defaultContentLanguageInSubdir = false {"Test 16", "", false, `baseURL = "https://.en.example.org/subdir/"`, `baseURL = "https://.de.example.org/subdir/"`, false, true, validatePublishedSite_16}, // Test 17 - Multilingual, multi-host, uglyURLs = false for s1, without subdir in base URL, defaultContentLanguageInSubdir = true {"Test 17", "", true, `baseURL = "https://.en.example.org/"`, `baseURL = "https://.de.example.org/"`, false, false, validatePublishedSite_17}, // Test 18 - Multilingual, multi-host, uglyURLs = false for s1, with subdir in base URL, defaultContentLanguageInSubdir = true {"Test 18", "", true, `baseURL = "https://.en.example.org/subdir/"`, `baseURL = "https://.de.example.org/subdir/"`, false, false, validatePublishedSite_18}, // Test 19 - Multilingual, multi-host, uglyURLs = true for s1, without subdir in base URL, defaultContentLanguageInSubdir = true {"Test 19", "", true, `baseURL = "https://.en.example.org/"`, `baseURL = "https://.de.example.org/"`, false, true, validatePublishedSite_19}, // Test 20 - Multilingual, multi-host, uglyURLs = true for s1, with subdir in base URL, defaultContentLanguageInSubdir = true {"Test 20", "", true, `baseURL = "https://.en.example.org/subdir/"`, `baseURL = "https://.de.example.org/subdir/"`, false, true, validatePublishedSite_20}, } for _, tc := range testCases { // Asciidoctor is really, really slow on Windows. Only run a few tests. isExcludedTest := htesting.IsRealCI() && runtime.GOOS == "windows" && !slices.Contains([]string{"Test 4", "Test 8", "Test 16"}, tc.name) if isExcludedTest { continue } t.Run(tc.name, func(t *testing.T) { baseURLKV := "" if tc.baseURL != "" { baseURLKV = fmt.Sprintf(`baseURL = %q`, tc.baseURL) } replacer := strings.NewReplacer( `BASE_URL_KEY_VALUE_PAIR`, baseURLKV, `DEFAULT_CONTENT_LANGUAGE_IN_SUBDIR`, fmt.Sprintf("%v", tc.defaultContentLanguageInSubdir), `LANGUAGES.EN.BASE_URL_KEY_VALUE_PAIR`, tc.langEnBaseURL, `LANGUAGES.DE.BASE_URL_KEY_VALUE_PAIR`, tc.langDeBaseURL, `LANGUAGES.DE.DISABLED`, fmt.Sprintf("%v", tc.langDeDisabled), `UGLYURLS_S1`, fmt.Sprintf("%v", tc.uglyURLsS1), `DIAGRAM_CACHEDIR`, diagramCacheDir, ) f := files + replacer.Replace(configFileWithPlaceholders) tempDir := t.TempDir() t.Chdir(tempDir) b := hugolib.Test(t, f, hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) { cfg.NeedsOsFS = true cfg.WorkingDir = tempDir })) // Verify that asciidoctor-diagram is caching in the correct // location. Checking one file is sufficient. err := fileExistsOsFs(filepath.Join(diagramCacheDir, "filecache/misc/asciidoctor-diagram/home_en.svg")) if err != nil { t.Fatalf("unable to locate file in diagram cache: %v", err.Error()) } tc.validate(b) }) } } // fileExistsOsFs checks if a file exists on the OS file system. func fileExistsOsFs(path string) error { fi, err := os.Stat(path) if err != nil { if os.IsNotExist(err) { return fmt.Errorf("the path %q does not exist", path) } return fmt.Errorf("unable to get file status for %q: %v", path, err) } if fi.IsDir() { return fmt.Errorf("the path %q is a directory, not a file", path) } return nil } // createContentFiles returns a txtar representation of the content files. func createContentFiles() string { contentFiles := []contentFile{ {`content/_index.de.adoc`, `home_de`}, {`content/_index.en.adoc`, `home_en`}, {`content/s1/_index.de.adoc`, `s1_de`}, {`content/s1/_index.en.adoc`, `s1_en`}, {`content/s1/p1/index.de.adoc`, `s1_p1_de`}, {`content/s1/p1/index.en.adoc`, `s1_p1_en`}, {`content/s1/p2.de.adoc`, `s1_p2_de`}, {`content/s1/p2.en.adoc`, `s1_p2_en`}, {`content/s2/_content.gotmpl`, `s2_content_gotmpl`}, {`content/s2/_index.de.adoc`, `s2_de`}, {`content/s2/_index.en.adoc`, `s2_en`}, {`content/Straßen/Frühling/_index.de.adoc`, `Straßen_Frühling_de`}, {`content/Straßen/Frühling/_index.en.adoc`, `Straßen_Frühling_en`}, {`content/Straßen/Frühling/Müll Brücke.de.adoc`, `Straßen_Frühling_Müll_Brücke_de`}, {`content/Straßen/Frühling/Müll Brücke.en.adoc`, `Straßen_Frühling_Müll_Brücke_en`}, {`content/Straßen/_index.de.adoc`, `Straßen_de`}, {`content/Straßen/_index.en.adoc`, `Straßen_en`}, } formatString := ` -- %[1]s -- --- title: %[2]s --- [goat,%[2]s] .... %[2]s ....` var txtarContentFiles strings.Builder for _, f := range contentFiles { txtarContentFiles.WriteString(fmt.Sprintf(formatString, f.path, f.title)) } return txtarContentFiles.String() } var contentAdapter = ` -- content/s2/_content.gotmpl -- {{ $title := printf "s2_p1_%s" site.Language.Lang }} {{ $markup := printf "[goat,%[1]s]\n....\n%[1]s\n...." $title }} {{ $content := dict "mediaType" "text/asciidoc" "value" $markup }} {{ $page := dict "content" $content "kind" "page" "path" "p1" "title" $title }} {{ .EnableAllLanguages }} {{ .AddPage $page }}` var layouts = ` -- layouts/all.html -- {{ .Content }}|` var configFileWithPlaceholders = ` -- hugo.toml -- BASE_URL_KEY_VALUE_PAIR disableKinds = ['rss', 'sitemap', 'taxonomy', 'term'] defaultContentLanguage = 'en' defaultContentLanguageInSubdir = DEFAULT_CONTENT_LANGUAGE_IN_SUBDIR [languages.en] LANGUAGES.EN.BASE_URL_KEY_VALUE_PAIR disabled = false weight = 1 [languages.de] LANGUAGES.DE.BASE_URL_KEY_VALUE_PAIR disabled = LANGUAGES.DE.DISABLED weight = 2 [uglyurls] s1 = UGLYURLS_S1 [markup.asciidocext] extensions = ['asciidoctor-diagram'] workingFolderCurrent = true [caches.misc] dir = 'DIAGRAM_CACHEDIR' [security.exec] allow = ['^((dart-)?sass|git|go|npx|postcss|tailwindcss|asciidoctor)$']` func validatePublishedSite_1(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/index.html`, `src="home_en.svg"`}, {`public/s1/index.html`, `src="s1_en.svg"`}, {`public/s1/p1/index.html`, `src="s1_p1_en.svg"`}, {`public/s1/p2/index.html`, `src="s1_p2_en.svg"`}, {`public/s2/index.html`, `src="s2_en.svg"`}, {`public/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/home_en.svg`, `public/s1/p1/s1_p1_en.svg`, `public/s1/p2/s1_p2_en.svg`, `public/s1/s1_en.svg`, `public/s2/p1/s2_p1_en.svg`, `public/s2/s2_en.svg`, `public/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/straßen/frühling/Straßen_Frühling_en.svg`, `public/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_2(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/index.html`, `src="home_en.svg"`}, {`public/s1/index.html`, `src="s1_en.svg"`}, {`public/s1/p1/index.html`, `src="s1_p1_en.svg"`}, {`public/s1/p2/index.html`, `src="s1_p2_en.svg"`}, {`public/s2/index.html`, `src="s2_en.svg"`}, {`public/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/home_en.svg`, `public/s1/p1/s1_p1_en.svg`, `public/s1/p2/s1_p2_en.svg`, `public/s1/s1_en.svg`, `public/s2/p1/s2_p1_en.svg`, `public/s2/s2_en.svg`, `public/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/straßen/frühling/Straßen_Frühling_en.svg`, `public/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_3(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/index.html`, `src="home_en.svg"`}, {`public/s1/index.html`, `src="s1_en.svg"`}, {`public/s1/p1.html`, `src="p1/s1_p1_en.svg"`}, {`public/s1/p2.html`, `src="p2/s1_p2_en.svg"`}, {`public/s2/index.html`, `src="s2_en.svg"`}, {`public/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/home_en.svg`, `public/s1/p1/s1_p1_en.svg`, `public/s1/p2/s1_p2_en.svg`, `public/s1/s1_en.svg`, `public/s2/p1/s2_p1_en.svg`, `public/s2/s2_en.svg`, `public/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/straßen/frühling/Straßen_Frühling_en.svg`, `public/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_4(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/index.html`, `src="home_en.svg"`}, {`public/s1/index.html`, `src="s1_en.svg"`}, {`public/s1/p1.html`, `src="p1/s1_p1_en.svg"`}, {`public/s1/p2.html`, `src="p2/s1_p2_en.svg"`}, {`public/s2/index.html`, `src="s2_en.svg"`}, {`public/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/home_en.svg`, `public/s1/p1/s1_p1_en.svg`, `public/s1/p2/s1_p2_en.svg`, `public/s1/s1_en.svg`, `public/s2/p1/s2_p1_en.svg`, `public/s2/s2_en.svg`, `public/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/straßen/frühling/Straßen_Frühling_en.svg`, `public/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_5(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/de/index.html`, `src="home_de.svg"`}, {`public/de/s1/index.html`, `src="s1_de.svg"`}, {`public/de/s1/p1/index.html`, `src="s1_p1_de.svg"`}, {`public/de/s1/p2/index.html`, `src="s1_p2_de.svg"`}, {`public/de/s2/index.html`, `src="s2_de.svg"`}, {`public/de/s2/p1/index.html`, `src="s2_p1_de.svg"`}, {`public/de/straßen/frühling/index.html`, `src="Straßen_Frühling_de.svg"`}, {`public/de/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_de.svg"`}, {`public/de/straßen/index.html`, `src="Straßen_de.svg"`}, {`public/index.html`, `src="home_en.svg"`}, {`public/s1/index.html`, `src="s1_en.svg"`}, {`public/s1/p1/index.html`, `src="s1_p1_en.svg"`}, {`public/s1/p2/index.html`, `src="s1_p2_en.svg"`}, {`public/s2/index.html`, `src="s2_en.svg"`}, {`public/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/de/home_de.svg`, `public/de/s1/p1/s1_p1_de.svg`, `public/de/s1/p2/s1_p2_de.svg`, `public/de/s1/s1_de.svg`, `public/de/s2/p1/s2_p1_de.svg`, `public/de/s2/s2_de.svg`, `public/de/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_de.svg`, `public/de/straßen/frühling/Straßen_Frühling_de.svg`, `public/de/straßen/Straßen_de.svg`, `public/home_en.svg`, `public/s1/p1/s1_p1_en.svg`, `public/s1/p2/s1_p2_en.svg`, `public/s1/s1_en.svg`, `public/s2/p1/s2_p1_en.svg`, `public/s2/s2_en.svg`, `public/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/straßen/frühling/Straßen_Frühling_en.svg`, `public/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_6(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/de/index.html`, `src="home_de.svg"`}, {`public/de/s1/index.html`, `src="s1_de.svg"`}, {`public/de/s1/p1/index.html`, `src="s1_p1_de.svg"`}, {`public/de/s1/p2/index.html`, `src="s1_p2_de.svg"`}, {`public/de/s2/index.html`, `src="s2_de.svg"`}, {`public/de/s2/p1/index.html`, `src="s2_p1_de.svg"`}, {`public/de/straßen/frühling/index.html`, `src="Straßen_Frühling_de.svg"`}, {`public/de/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_de.svg"`}, {`public/de/straßen/index.html`, `src="Straßen_de.svg"`}, {`public/index.html`, `src="home_en.svg"`}, {`public/s1/index.html`, `src="s1_en.svg"`}, {`public/s1/p1/index.html`, `src="s1_p1_en.svg"`}, {`public/s1/p2/index.html`, `src="s1_p2_en.svg"`}, {`public/s2/index.html`, `src="s2_en.svg"`}, {`public/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/de/home_de.svg`, `public/de/s1/p1/s1_p1_de.svg`, `public/de/s1/p2/s1_p2_de.svg`, `public/de/s1/s1_de.svg`, `public/de/s2/p1/s2_p1_de.svg`, `public/de/s2/s2_de.svg`, `public/de/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_de.svg`, `public/de/straßen/frühling/Straßen_Frühling_de.svg`, `public/de/straßen/Straßen_de.svg`, `public/home_en.svg`, `public/s1/p1/s1_p1_en.svg`, `public/s1/p2/s1_p2_en.svg`, `public/s1/s1_en.svg`, `public/s2/p1/s2_p1_en.svg`, `public/s2/s2_en.svg`, `public/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/straßen/frühling/Straßen_Frühling_en.svg`, `public/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_7(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/de/index.html`, `src="home_de.svg"`}, {`public/de/s1/index.html`, `src="s1_de.svg"`}, {`public/de/s1/p1.html`, `src="p1/s1_p1_de.svg"`}, {`public/de/s1/p2.html`, `src="p2/s1_p2_de.svg"`}, {`public/de/s2/index.html`, `src="s2_de.svg"`}, {`public/de/s2/p1/index.html`, `src="s2_p1_de.svg"`}, {`public/de/straßen/frühling/index.html`, `src="Straßen_Frühling_de.svg"`}, {`public/de/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_de.svg"`}, {`public/de/straßen/index.html`, `src="Straßen_de.svg"`}, {`public/index.html`, `src="home_en.svg"`}, {`public/s1/index.html`, `src="s1_en.svg"`}, {`public/s1/p1.html`, `src="p1/s1_p1_en.svg"`}, {`public/s1/p2.html`, `src="p2/s1_p2_en.svg"`}, {`public/s2/index.html`, `src="s2_en.svg"`}, {`public/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/de/home_de.svg`, `public/de/s1/p1/s1_p1_de.svg`, `public/de/s1/p2/s1_p2_de.svg`, `public/de/s1/s1_de.svg`, `public/de/s2/p1/s2_p1_de.svg`, `public/de/s2/s2_de.svg`, `public/de/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_de.svg`, `public/de/straßen/frühling/Straßen_Frühling_de.svg`, `public/de/straßen/Straßen_de.svg`, `public/home_en.svg`, `public/s1/p1/s1_p1_en.svg`, `public/s1/p2/s1_p2_en.svg`, `public/s1/s1_en.svg`, `public/s2/p1/s2_p1_en.svg`, `public/s2/s2_en.svg`, `public/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/straßen/frühling/Straßen_Frühling_en.svg`, `public/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_8(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/de/index.html`, `src="home_de.svg"`}, {`public/de/s1/index.html`, `src="s1_de.svg"`}, {`public/de/s1/p1.html`, `src="p1/s1_p1_de.svg"`}, {`public/de/s1/p2.html`, `src="p2/s1_p2_de.svg"`}, {`public/de/s2/index.html`, `src="s2_de.svg"`}, {`public/de/s2/p1/index.html`, `src="s2_p1_de.svg"`}, {`public/de/straßen/frühling/index.html`, `src="Straßen_Frühling_de.svg"`}, {`public/de/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_de.svg"`}, {`public/de/straßen/index.html`, `src="Straßen_de.svg"`}, {`public/index.html`, `src="home_en.svg"`}, {`public/s1/index.html`, `src="s1_en.svg"`}, {`public/s1/p1.html`, `src="p1/s1_p1_en.svg"`}, {`public/s1/p2.html`, `src="p2/s1_p2_en.svg"`}, {`public/s2/index.html`, `src="s2_en.svg"`}, {`public/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/de/home_de.svg`, `public/de/s1/p1/s1_p1_de.svg`, `public/de/s1/p2/s1_p2_de.svg`, `public/de/s1/s1_de.svg`, `public/de/s2/p1/s2_p1_de.svg`, `public/de/s2/s2_de.svg`, `public/de/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_de.svg`, `public/de/straßen/frühling/Straßen_Frühling_de.svg`, `public/de/straßen/Straßen_de.svg`, `public/home_en.svg`, `public/s1/p1/s1_p1_en.svg`, `public/s1/p2/s1_p2_en.svg`, `public/s1/s1_en.svg`, `public/s2/p1/s2_p1_en.svg`, `public/s2/s2_en.svg`, `public/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/straßen/frühling/Straßen_Frühling_en.svg`, `public/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_9(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/de/index.html`, `src="home_de.svg"`}, {`public/de/s1/index.html`, `src="s1_de.svg"`}, {`public/de/s1/p1/index.html`, `src="s1_p1_de.svg"`}, {`public/de/s1/p2/index.html`, `src="s1_p2_de.svg"`}, {`public/de/s2/index.html`, `src="s2_de.svg"`}, {`public/de/s2/p1/index.html`, `src="s2_p1_de.svg"`}, {`public/de/straßen/frühling/index.html`, `src="Straßen_Frühling_de.svg"`}, {`public/de/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_de.svg"`}, {`public/de/straßen/index.html`, `src="Straßen_de.svg"`}, {`public/en/index.html`, `src="home_en.svg"`}, {`public/en/s1/index.html`, `src="s1_en.svg"`}, {`public/en/s1/p1/index.html`, `src="s1_p1_en.svg"`}, {`public/en/s1/p2/index.html`, `src="s1_p2_en.svg"`}, {`public/en/s2/index.html`, `src="s2_en.svg"`}, {`public/en/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/en/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/en/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/en/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/de/home_de.svg`, `public/de/s1/p1/s1_p1_de.svg`, `public/de/s1/p2/s1_p2_de.svg`, `public/de/s1/s1_de.svg`, `public/de/s2/p1/s2_p1_de.svg`, `public/de/s2/s2_de.svg`, `public/de/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_de.svg`, `public/de/straßen/frühling/Straßen_Frühling_de.svg`, `public/de/straßen/Straßen_de.svg`, `public/en/home_en.svg`, `public/en/s1/p1/s1_p1_en.svg`, `public/en/s1/p2/s1_p2_en.svg`, `public/en/s1/s1_en.svg`, `public/en/s2/p1/s2_p1_en.svg`, `public/en/s2/s2_en.svg`, `public/en/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/en/straßen/frühling/Straßen_Frühling_en.svg`, `public/en/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_10(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/de/index.html`, `src="home_de.svg"`}, {`public/de/s1/index.html`, `src="s1_de.svg"`}, {`public/de/s1/p1/index.html`, `src="s1_p1_de.svg"`}, {`public/de/s1/p2/index.html`, `src="s1_p2_de.svg"`}, {`public/de/s2/index.html`, `src="s2_de.svg"`}, {`public/de/s2/p1/index.html`, `src="s2_p1_de.svg"`}, {`public/de/straßen/frühling/index.html`, `src="Straßen_Frühling_de.svg"`}, {`public/de/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_de.svg"`}, {`public/de/straßen/index.html`, `src="Straßen_de.svg"`}, {`public/en/index.html`, `src="home_en.svg"`}, {`public/en/s1/index.html`, `src="s1_en.svg"`}, {`public/en/s1/p1/index.html`, `src="s1_p1_en.svg"`}, {`public/en/s1/p2/index.html`, `src="s1_p2_en.svg"`}, {`public/en/s2/index.html`, `src="s2_en.svg"`}, {`public/en/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/en/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/en/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/en/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/de/home_de.svg`, `public/de/s1/p1/s1_p1_de.svg`, `public/de/s1/p2/s1_p2_de.svg`, `public/de/s1/s1_de.svg`, `public/de/s2/p1/s2_p1_de.svg`, `public/de/s2/s2_de.svg`, `public/de/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_de.svg`, `public/de/straßen/frühling/Straßen_Frühling_de.svg`, `public/de/straßen/Straßen_de.svg`, `public/en/home_en.svg`, `public/en/s1/p1/s1_p1_en.svg`, `public/en/s1/p2/s1_p2_en.svg`, `public/en/s1/s1_en.svg`, `public/en/s2/p1/s2_p1_en.svg`, `public/en/s2/s2_en.svg`, `public/en/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/en/straßen/frühling/Straßen_Frühling_en.svg`, `public/en/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_11(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/de/index.html`, `src="home_de.svg"`}, {`public/de/s1/index.html`, `src="s1_de.svg"`}, {`public/de/s1/p1.html`, `src="p1/s1_p1_de.svg"`}, {`public/de/s1/p2.html`, `src="p2/s1_p2_de.svg"`}, {`public/de/s2/index.html`, `src="s2_de.svg"`}, {`public/de/s2/p1/index.html`, `src="s2_p1_de.svg"`}, {`public/de/straßen/frühling/index.html`, `src="Straßen_Frühling_de.svg"`}, {`public/de/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_de.svg"`}, {`public/de/straßen/index.html`, `src="Straßen_de.svg"`}, {`public/en/index.html`, `src="home_en.svg"`}, {`public/en/s1/index.html`, `src="s1_en.svg"`}, {`public/en/s1/p1.html`, `src="p1/s1_p1_en.svg"`}, {`public/en/s1/p2.html`, `src="p2/s1_p2_en.svg"`}, {`public/en/s2/index.html`, `src="s2_en.svg"`}, {`public/en/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/en/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/en/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/en/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/de/home_de.svg`, `public/de/s1/p1/s1_p1_de.svg`, `public/de/s1/p2/s1_p2_de.svg`, `public/de/s1/s1_de.svg`, `public/de/s2/p1/s2_p1_de.svg`, `public/de/s2/s2_de.svg`, `public/de/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_de.svg`, `public/de/straßen/frühling/Straßen_Frühling_de.svg`, `public/de/straßen/Straßen_de.svg`, `public/en/home_en.svg`, `public/en/s1/p1/s1_p1_en.svg`, `public/en/s1/p2/s1_p2_en.svg`, `public/en/s1/s1_en.svg`, `public/en/s2/p1/s2_p1_en.svg`, `public/en/s2/s2_en.svg`, `public/en/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/en/straßen/frühling/Straßen_Frühling_en.svg`, `public/en/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_12(b *hugolib.IntegrationTestBuilder) { for _, file := range []publishedContentFile{ {`public/de/index.html`, `src="home_de.svg"`}, {`public/de/s1/index.html`, `src="s1_de.svg"`}, {`public/de/s1/p1.html`, `src="p1/s1_p1_de.svg"`}, {`public/de/s1/p2.html`, `src="p2/s1_p2_de.svg"`}, {`public/de/s2/index.html`, `src="s2_de.svg"`}, {`public/de/s2/p1/index.html`, `src="s2_p1_de.svg"`}, {`public/de/straßen/frühling/index.html`, `src="Straßen_Frühling_de.svg"`}, {`public/de/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_de.svg"`}, {`public/de/straßen/index.html`, `src="Straßen_de.svg"`}, {`public/en/index.html`, `src="home_en.svg"`}, {`public/en/s1/index.html`, `src="s1_en.svg"`}, {`public/en/s1/p1.html`, `src="p1/s1_p1_en.svg"`}, {`public/en/s1/p2.html`, `src="p2/s1_p2_en.svg"`}, {`public/en/s2/index.html`, `src="s2_en.svg"`}, {`public/en/s2/p1/index.html`, `src="s2_p1_en.svg"`}, {`public/en/straßen/frühling/index.html`, `src="Straßen_Frühling_en.svg"`}, {`public/en/straßen/frühling/müll-brücke/index.html`, `src="Straßen_Frühling_Müll_Brücke_en.svg"`}, {`public/en/straßen/index.html`, `src="Straßen_en.svg"`}, } { b.AssertFileContent(file.path, file.match) } for _, path := range []string{ `public/de/home_de.svg`, `public/de/s1/p1/s1_p1_de.svg`, `public/de/s1/p2/s1_p2_de.svg`, `public/de/s1/s1_de.svg`, `public/de/s2/p1/s2_p1_de.svg`, `public/de/s2/s2_de.svg`, `public/de/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_de.svg`, `public/de/straßen/frühling/Straßen_Frühling_de.svg`, `public/de/straßen/Straßen_de.svg`, `public/en/home_en.svg`, `public/en/s1/p1/s1_p1_en.svg`, `public/en/s1/p2/s1_p2_en.svg`, `public/en/s1/s1_en.svg`, `public/en/s2/p1/s2_p1_en.svg`, `public/en/s2/s2_en.svg`, `public/en/straßen/frühling/müll-brücke/Straßen_Frühling_Müll_Brücke_en.svg`, `public/en/straßen/frühling/Straßen_Frühling_en.svg`, `public/en/straßen/Straßen_en.svg`, } { b.AssertFileExists(path, true) } } func validatePublishedSite_13(b *hugolib.IntegrationTestBuilder) {
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
true
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/asciidocext/asciidocext_config/config.go
markup/asciidocext/asciidocext_config/config.go
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package asciidocext_config holds asciidoc related configuration. package asciidocext_config var ( // Default holds Hugo's default asciidoc configuration. Default = Config{ Backend: "html5", Extensions: []string{}, Attributes: map[string]any{}, NoHeaderOrFooter: true, SafeMode: "unsafe", SectionNumbers: false, Verbose: false, Trace: false, FailureLevel: "fatal", WorkingFolderCurrent: false, PreserveTOC: false, } // CliDefault holds Asciidoctor CLI defaults (see https://asciidoctor.org/docs/user-manual/) CliDefault = Config{ Backend: "html5", SafeMode: "unsafe", FailureLevel: "fatal", } AllowedSafeMode = map[string]bool{ "unsafe": true, "safe": true, "server": true, "secure": true, } AllowedFailureLevel = map[string]bool{ "fatal": true, "warn": true, } AllowedBackend = map[string]bool{ "html5": true, "html5s": true, "xhtml5": true, "docbook5": true, "docbook45": true, "manpage": true, } DisallowedAttributes = map[string]bool{ "outdir": true, } ) // Config configures asciidoc. type Config struct { Backend string Extensions []string Attributes map[string]any NoHeaderOrFooter bool SafeMode string SectionNumbers bool Verbose bool Trace bool FailureLevel string WorkingFolderCurrent bool PreserveTOC bool }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/asciidocext/internal/converter.go
markup/asciidocext/internal/converter.go
package internal import ( "bytes" "fmt" "net/url" "path" "path/filepath" "strings" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/markup/asciidocext/asciidocext_config" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/markup/internal" "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/spf13/cast" "golang.org/x/net/html" ) type AsciiDocConverter struct { Ctx converter.DocumentContext Cfg converter.ProviderConfig } type asciiDocResult struct { converter.ResultRender toc *tableofcontents.Fragments } type pageSubset interface { IsPage() bool RelPermalink() string Section() string } const ( // asciiDocBinaryName is name of the AsciiDoc converter CLI. asciiDocBinaryName = "asciidoctor" // asciiDocDiagramExtension is the name of the AsciiDoc converter diagram // extension. asciiDocDiagramExtension = "asciidoctor-diagram" // asciiDocDiagramCacheDirKey is the AsciiDoc converter attribute key for // setting the path to the diagram cache directory. asciiDocDiagramCacheDirKey = "diagram-cachedir" // asciiDocDiagramCacheImagesOptionKey is the AsciiDoc converter attribute // key for determining whether to cache image files in addition to // metadata files. asciiDocDiagramCacheImagesOptionKey = "diagram-cache-images-option" // gemBinaryName is the name of the RubyGems CLI. gemBinaryName = "gem" // goatBinaryName is the name of the GoAT CLI. goatBinaryName = "goat" ) func (r asciiDocResult) TableOfContents() *tableofcontents.Fragments { return r.toc } func (a *AsciiDocConverter) Convert(ctx converter.RenderContext) (converter.ResultRender, error) { b, err := a.GetAsciiDocContent(ctx.Src, a.Ctx) if err != nil { return nil, err } content, toc, err := a.extractTOC(b) if err != nil { return nil, err } return asciiDocResult{ ResultRender: converter.Bytes(content), toc: toc, }, nil } func (a *AsciiDocConverter) Supports(_ identity.Identity) bool { return false } // GetAsciiDocContent calls asciidoctor as an external helper to convert // AsciiDoc content to HTML. func (a *AsciiDocConverter) GetAsciiDocContent(src []byte, ctx converter.DocumentContext) ([]byte, error) { if ok, err := HasAsciiDoc(); !ok { a.Cfg.Logger.Errorf("leaving AsciiDoc content unrendered: %s", err.Error()) return src, nil } args, err := a.ParseArgs(ctx) if err != nil { return nil, err } args = append(args, "-") // read from stdin a.Cfg.Logger.Infof("Rendering %s using Asciidoctor args %s ...", ctx.DocumentName, args) return internal.ExternallyRenderContent(a.Cfg, ctx, src, asciiDocBinaryName, args) } func (a *AsciiDocConverter) ParseArgs(ctx converter.DocumentContext) ([]string, error) { cfg := a.Cfg.MarkupConfig().AsciiDocExt args := []string{} args = a.AppendArg(args, "-b", cfg.Backend, asciidocext_config.CliDefault.Backend, asciidocext_config.AllowedBackend) for _, extension := range cfg.Extensions { if strings.LastIndexAny(extension, `\/.`) > -1 { a.Cfg.Logger.Errorf( "The %q Asciidoctor extension is unsupported and ignored. Only installed Asciidoctor extensions are allowed.", extension, ) continue } args = append(args, "-r", extension) if extension == asciiDocDiagramExtension { cacheDir := filepath.Clean(filepath.Join(a.Cfg.Conf.CacheDirMisc(), asciiDocDiagramExtension)) args = append(args, "-a", asciiDocDiagramCacheDirKey+"="+cacheDir) args = append(args, "-a", asciiDocDiagramCacheImagesOptionKey) } } for attributeKey, attributeValue := range cfg.Attributes { if asciidocext_config.DisallowedAttributes[attributeKey] { a.Cfg.Logger.Errorf( "The %q Asciidoctor attribute is unsupported and ignored.", attributeKey, ) continue } if attributeKey == asciiDocDiagramCacheImagesOptionKey { a.Cfg.Logger.Warnf( "The %q Asciidoctor attribute is fixed and cannot be modified. To disable caching of both image and metadata files, set markup.asciidocext.attributes.diagram-nocache-option to true in your site configuration.", attributeKey, ) continue } if attributeKey == asciiDocDiagramCacheDirKey { a.Cfg.Logger.Warnf( "The %q Asciidoctor attribute is fixed and cannot be modified. To change the cache location, modify caches.misc.dir in your site configuration.", attributeKey, ) continue } // To set a document attribute to true: -a attributeKey // To set a document attribute to false: -a '!attributeKey' // For other types: -a attributeKey=attributeValue if b, ok := attributeValue.(bool); ok { arg := attributeKey if !b { arg = "'!" + attributeKey + "'" } args = append(args, "-a", arg) } else { args = append(args, "-a", attributeKey+"="+cast.ToString(attributeValue)) } } if cfg.WorkingFolderCurrent { page, ok := ctx.Document.(pageSubset) if !ok { return nil, fmt.Errorf("expected pageSubset, got %T", ctx.Document) } // Derive the outdir document attribute from the relative permalink. relPath := strings.TrimPrefix(page.RelPermalink(), a.Cfg.Conf.BaseURL().BasePathNoTrailingSlash) relPath, err := url.PathUnescape(relPath) if err != nil { return nil, err } if a.Cfg.Conf.IsMultihost() { // In a multi-host configuration, neither absolute nor relative // permalinks include the language key; prepend it. language, ok := a.Cfg.Conf.Language().(*langs.Language) if !ok { return nil, fmt.Errorf("expected *langs.Language, got %T", a.Cfg.Conf.Language()) } relPath = path.Join(language.Lang, relPath) } if a.Cfg.Conf.IsUglyURLs(page.Section()) { if page.IsPage() { // Remove the extension. relPath = strings.TrimSuffix(relPath, path.Ext(relPath)) } else { // Remove the file name. relPath = path.Dir(relPath) } // Set imagesoutdir and imagesdir attributes. imagesoutdir, err := filepath.Abs(filepath.Join(a.Cfg.Conf.BaseConfig().PublishDir, relPath)) if err != nil { return nil, err } imagesdir := filepath.Base(imagesoutdir) if page.IsPage() { args = append(args, "-a", "imagesoutdir="+imagesoutdir, "-a", "imagesdir="+imagesdir) } else { args = append(args, "-a", "imagesoutdir="+imagesoutdir) } } // Prepend the publishDir. outDir, err := filepath.Abs(filepath.Join(a.Cfg.Conf.BaseConfig().PublishDir, relPath)) if err != nil { return nil, err } args = append(args, "--base-dir", filepath.Dir(ctx.Filename), "-a", "outdir="+outDir) } if cfg.NoHeaderOrFooter { args = append(args, "--no-header-footer") } else { a.Cfg.Logger.Warnln("Asciidoctor parameter NoHeaderOrFooter is required for correct HTML rendering") } if cfg.SectionNumbers { args = append(args, "--section-numbers") } if cfg.Verbose { args = append(args, "--verbose") } if cfg.Trace { args = append(args, "--trace") } args = a.AppendArg(args, "--failure-level", cfg.FailureLevel, asciidocext_config.CliDefault.FailureLevel, asciidocext_config.AllowedFailureLevel) args = a.AppendArg(args, "--safe-mode", cfg.SafeMode, asciidocext_config.CliDefault.SafeMode, asciidocext_config.AllowedSafeMode) return args, nil } func (a *AsciiDocConverter) AppendArg(args []string, option, value, defaultValue string, allowedValues map[string]bool) []string { if value != defaultValue { if allowedValues[value] { args = append(args, option, value) } else { a.Cfg.Logger.Errorf( "Unsupported Asciidoctor value %q for option %q was passed in and will be ignored.", value, option, ) } } return args } // HasAsciiDoc reports whether the AsciiDoc converter is installed. func HasAsciiDoc() (bool, error) { if !hexec.InPath(asciiDocBinaryName) { return false, fmt.Errorf("the AsciiDoc converter (%s) is not installed", asciiDocBinaryName) } return true, nil } // CanRenderGoATDiagrams reports whether the AsciiDoc converter can render // GoAT diagrams. Only used in tests. func CanRenderGoATDiagrams() (bool, error) { // Verify that the AsciiDoc converter is installed. if ok, err := HasAsciiDoc(); !ok { return false, err } // Verify that the RubyGems CLI is installed. if !hexec.InPath(gemBinaryName) { return false, fmt.Errorf("the RubyGems CLI (%s) is not installed", gemBinaryName) } // Verify that the required AsciiDoc converter extension is installed. sc := security.DefaultConfig sc.Exec.Allow = security.MustNewWhitelist(gemBinaryName) ex := hexec.New(sc, "", loggers.NewDefault()) args := []any{"list", asciiDocDiagramExtension, "--installed"} cmd, err := ex.New(gemBinaryName, args...) if err != nil { return false, err } err = cmd.Run() if err != nil { return false, fmt.Errorf("the %s gem is not installed", asciiDocDiagramExtension) } // Verify that the GoAT CLI is installed. if !hexec.InPath(goatBinaryName) { return false, fmt.Errorf("the GoAT CLI (%s) is not installed", goatBinaryName) } return true, nil } // extractTOC extracts the toc from the given src html. // It returns the html without the TOC, and the TOC data func (a *AsciiDocConverter) extractTOC(src []byte) ([]byte, *tableofcontents.Fragments, error) { var buf bytes.Buffer buf.Write(src) node, err := html.Parse(&buf) if err != nil { return nil, nil, err } var ( f func(*html.Node) bool toc *tableofcontents.Fragments toVisit []*html.Node ) f = func(n *html.Node) bool { if n.Type == html.ElementNode && n.Data == "div" && attr(n, "id") == "toc" { toc = parseTOC(n) if !a.Cfg.MarkupConfig().AsciiDocExt.PreserveTOC { n.Parent.RemoveChild(n) } return true } if n.FirstChild != nil { toVisit = append(toVisit, n.FirstChild) } if n.NextSibling != nil && f(n.NextSibling) { return true } for len(toVisit) > 0 { nv := toVisit[0] toVisit = toVisit[1:] if f(nv) { return true } } return false } f(node) if err != nil { return nil, nil, err } buf.Reset() err = html.Render(&buf, node) if err != nil { return nil, nil, err } // ltrim <html><head></head><body> and rtrim </body></html> which are added by html.Render res := buf.Bytes()[25:] res = res[:len(res)-14] return res, toc, nil } // parseTOC returns a TOC root from the given toc Node func parseTOC(doc *html.Node) *tableofcontents.Fragments { var ( toc tableofcontents.Builder f func(*html.Node, int, int) ) f = func(n *html.Node, row, level int) { if n.Type == html.ElementNode { switch n.Data { case "ul": if level == 0 { row++ } level++ f(n.FirstChild, row, level) case "li": for c := n.FirstChild; c != nil; c = c.NextSibling { if c.Type != html.ElementNode || c.Data != "a" { continue } href := attr(c, "href")[1:] toc.AddAt(&tableofcontents.Heading{ Title: nodeContent(c), ID: href, Level: level + 1, }, row, level) } f(n.FirstChild, row, level) } } if n.NextSibling != nil { f(n.NextSibling, row, level) } } f(doc.FirstChild, -1, 0) return toc.Build() } func attr(node *html.Node, key string) string { for _, a := range node.Attr { if a.Key == key { return a.Val } } return "" } func nodeContent(node *html.Node) string { var buf bytes.Buffer for c := node.FirstChild; c != nil; c = c.NextSibling { html.Render(&buf, c) } return buf.String() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/highlight/highlight.go
markup/highlight/highlight.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package highlight import ( "context" "fmt" gohtml "html" "html/template" "io" "strings" "github.com/alecthomas/chroma/v2" "github.com/alecthomas/chroma/v2/formatters/html" "github.com/alecthomas/chroma/v2/lexers" "github.com/alecthomas/chroma/v2/styles" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/highlight/chromalexers" "github.com/gohugoio/hugo/markup/internal/attributes" ) // Markdown attributes used by the Chroma highlighter. var chromaHighlightProcessingAttributes = map[string]bool{ "anchorLineNos": true, "guessSyntax": true, "hl_Lines": true, "lineAnchors": true, "lineNos": true, "lineNoStart": true, "lineNumbersInTable": true, "noClasses": true, "style": true, "tabWidth": true, } func init() { for k, v := range chromaHighlightProcessingAttributes { chromaHighlightProcessingAttributes[strings.ToLower(k)] = v } } func New(cfg Config) Highlighter { return chromaHighlighter{ cfg: cfg, } } type Highlighter interface { Highlight(code, lang string, opts any) (string, error) HighlightCodeBlock(ctx hooks.CodeblockContext, opts any) (HighlightResult, error) hooks.CodeBlockRenderer hooks.IsDefaultCodeBlockRendererProvider } type chromaHighlighter struct { cfg Config } func (h chromaHighlighter) Highlight(code, lang string, opts any) (string, error) { cfg := h.cfg if err := applyOptions(opts, &cfg); err != nil { return "", err } var b strings.Builder if _, _, err := highlight(&b, code, lang, nil, cfg); err != nil { return "", err } return b.String(), nil } func (h chromaHighlighter) HighlightCodeBlock(ctx hooks.CodeblockContext, opts any) (HighlightResult, error) { cfg := h.cfg var b strings.Builder attributes := ctx.(hooks.AttributesOptionsSliceProvider).AttributesSlice() options := ctx.Options() if err := applyOptionsFromMap(options, &cfg); err != nil { return HighlightResult{}, err } // Apply these last so the user can override them. if err := applyOptions(opts, &cfg); err != nil { return HighlightResult{}, err } if err := applyOptionsFromCodeBlockContext(ctx, &cfg); err != nil { return HighlightResult{}, err } low, high, err := highlight(&b, ctx.Inner(), ctx.Type(), attributes, cfg) if err != nil { return HighlightResult{}, err } highlighted := b.String() if high == 0 { high = len(highlighted) } return HighlightResult{ highlighted: template.HTML(highlighted), innerLow: low, innerHigh: high, }, nil } func (h chromaHighlighter) RenderCodeblock(cctx context.Context, w hugio.FlexiWriter, ctx hooks.CodeblockContext) error { cfg := h.cfg attributes := ctx.(hooks.AttributesOptionsSliceProvider).AttributesSlice() if err := applyOptionsFromMap(ctx.Options(), &cfg); err != nil { return err } if err := applyOptionsFromCodeBlockContext(ctx, &cfg); err != nil { return err } code := text.Puts(ctx.Inner()) _, _, err := highlight(w, code, ctx.Type(), attributes, cfg) return err } func (h chromaHighlighter) IsDefaultCodeBlockRenderer() bool { return true } // HighlightResult holds the result of an highlighting operation. type HighlightResult struct { innerLow int innerHigh int highlighted template.HTML } // Wrapped returns the highlighted code wrapped in a <div>, <pre> and <code> tag. func (h HighlightResult) Wrapped() template.HTML { return h.highlighted } // Inner returns the highlighted code without the wrapping <div>, <pre> and <code> tag, suitable for inline use. func (h HighlightResult) Inner() template.HTML { return h.highlighted[h.innerLow:h.innerHigh] } func highlight(fw hugio.FlexiWriter, code, lang string, attributes []attributes.Attribute, cfg Config) (int, int, error) { var lexer chroma.Lexer if lang != "" { lexer = chromalexers.Get(lang) } if lexer == nil && cfg.GuessSyntax { lexer = lexers.Analyse(code) if lexer == nil { lexer = lexers.Fallback } lang = strings.ToLower(lexer.Config().Name) } w := &byteCountFlexiWriter{delegate: fw} if lexer == nil { if cfg.Hl_inline { fmt.Fprintf(w, "<code%s>%s</code>", inlineCodeAttrs(lang), gohtml.EscapeString(code)) } else { preWrapper := getPreWrapper(lang, w) fmt.Fprint(w, preWrapper.Start(true, "")) fmt.Fprint(w, gohtml.EscapeString(code)) fmt.Fprint(w, preWrapper.End(true)) } return 0, 0, nil } style := styles.Get(cfg.Style) if style == nil { style = styles.Fallback } lexer = chroma.Coalesce(lexer) iterator, err := lexer.Tokenise(nil, code) if err != nil { return 0, 0, err } if !cfg.Hl_inline { writeDivStart(w, attributes, cfg.WrapperClass) } options := cfg.toHTMLOptions() var wrapper html.PreWrapper if cfg.Hl_inline { wrapper = startEnd{ start: func(code bool, styleAttr string) string { if code { return fmt.Sprintf(`<code%s>`, inlineCodeAttrs(lang)) } return `` }, end: func(code bool) string { if code { return `</code>` } return `` }, } } else { wrapper = getPreWrapper(lang, w) } options = append(options, html.WithPreWrapper(wrapper)) formatter := html.New(options...) if err := formatter.Format(w, style, iterator); err != nil { return 0, 0, err } if !cfg.Hl_inline { writeDivEnd(w) } if p, ok := wrapper.(*preWrapper); ok { return p.low, p.high, nil } return 0, 0, nil } func getPreWrapper(language string, writeCounter *byteCountFlexiWriter) *preWrapper { return &preWrapper{language: language, writeCounter: writeCounter} } type preWrapper struct { low int high int writeCounter *byteCountFlexiWriter language string } func (p *preWrapper) Start(code bool, styleAttr string) string { var language string if code { language = p.language } w := &strings.Builder{} WritePreStart(w, language, styleAttr) p.low = p.writeCounter.counter + w.Len() return w.String() } func inlineCodeAttrs(lang string) string { return fmt.Sprintf(` class="code-inline language-%s"`, lang) } func WritePreStart(w io.Writer, language, styleAttr string) { fmt.Fprintf(w, `<pre tabindex="0"%s>`, styleAttr) fmt.Fprint(w, "<code") if language != "" { fmt.Fprint(w, ` class="language-`+language+`"`) fmt.Fprint(w, ` data-lang="`+language+`"`) } fmt.Fprint(w, ">") } const preEnd = "</code></pre>" func (p *preWrapper) End(code bool) string { p.high = p.writeCounter.counter return preEnd } type startEnd struct { start func(code bool, styleAttr string) string end func(code bool) string } func (s startEnd) Start(code bool, styleAttr string) string { return s.start(code, styleAttr) } func (s startEnd) End(code bool) string { return s.end(code) } func writeDivStart(w hugio.FlexiWriter, attrs []attributes.Attribute, wrapperClass string) { w.WriteString(`<div class="`) w.WriteString(wrapperClass) if attrs != nil { for _, attr := range attrs { if attr.Name == "class" { w.WriteString(" " + attr.ValueString()) break } } _, _ = w.WriteString("\"") attributes.RenderAttributes(w, true, attrs...) } else { _, _ = w.WriteString("\"") } w.WriteString(">") } func writeDivEnd(w hugio.FlexiWriter) { w.WriteString("</div>") } type byteCountFlexiWriter struct { delegate hugio.FlexiWriter counter int } func (w *byteCountFlexiWriter) Write(p []byte) (int, error) { n, err := w.delegate.Write(p) w.counter += n return n, err } func (w *byteCountFlexiWriter) WriteByte(c byte) error { w.counter++ return w.delegate.WriteByte(c) } func (w *byteCountFlexiWriter) WriteString(s string) (int, error) { n, err := w.delegate.WriteString(s) w.counter += n return n, err } func (w *byteCountFlexiWriter) WriteRune(r rune) (int, error) { n, err := w.delegate.WriteRune(r) w.counter += n return n, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/highlight/config.go
markup/highlight/config.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package highlight provides code highlighting. package highlight import ( "fmt" "strconv" "strings" "github.com/alecthomas/chroma/v2/formatters/html" "github.com/spf13/cast" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/mitchellh/mapstructure" ) const ( lineanchorsKey = "lineanchors" lineNosKey = "linenos" hlLinesKey = "hl_lines" linosStartKey = "linenostart" ) var DefaultConfig = Config{ // The highlighter style to use. // See https://xyproto.github.io/splash/docs/all.html Style: "monokai", LineNoStart: 1, CodeFences: true, NoClasses: true, LineNumbersInTable: true, TabWidth: 4, WrapperClass: "highlight", } type Config struct { Style string // Enable syntax highlighting of fenced code blocks. CodeFences bool // The class or classes to use for the outermost element of the highlighted code. WrapperClass string // Use inline CSS styles. NoClasses bool // When set, line numbers will be printed. LineNos bool LineNumbersInTable bool // When set, add links to line numbers AnchorLineNos bool LineAnchors string // Start the line numbers from this value (default is 1). LineNoStart int // A space separated list of line numbers, e.g. “3-8 10-20”. Hl_Lines string // If set, the markup will not be wrapped in any container. Hl_inline bool // A parsed and ready to use list of line ranges. HL_lines_parsed [][2]int `json:"-"` // TabWidth sets the number of characters for a tab. Defaults to 4. TabWidth int GuessSyntax bool } func (cfg Config) toHTMLOptions() []html.Option { var lineAnchors string if cfg.LineAnchors != "" { lineAnchors = cfg.LineAnchors + "-" } options := []html.Option{ html.TabWidth(cfg.TabWidth), html.WithLineNumbers(cfg.LineNos), html.BaseLineNumber(cfg.LineNoStart), html.LineNumbersInTable(cfg.LineNumbersInTable), html.WithClasses(!cfg.NoClasses), html.WithLinkableLineNumbers(cfg.AnchorLineNos, lineAnchors), html.InlineCode(cfg.Hl_inline), } if cfg.Hl_Lines != "" || cfg.HL_lines_parsed != nil { var ranges [][2]int if cfg.HL_lines_parsed != nil { ranges = cfg.HL_lines_parsed } else { var err error ranges, err = hlLinesToRanges(cfg.LineNoStart, cfg.Hl_Lines) if err != nil { ranges = nil } } if ranges != nil { options = append(options, html.HighlightLines(ranges)) } } return options } func applyOptions(opts any, cfg *Config) error { if opts == nil { return nil } switch vv := opts.(type) { case map[string]any: return applyOptionsFromMap(vv, cfg) default: s, err := cast.ToStringE(opts) if err != nil { return err } return applyOptionsFromString(s, cfg) } } func applyOptionsFromString(opts string, cfg *Config) error { optsm, err := parseHighlightOptions(opts) if err != nil { return err } return mapstructure.WeakDecode(optsm, cfg) } func applyOptionsFromMap(optsm map[string]any, cfg *Config) error { normalizeHighlightOptions(optsm) return mapstructure.WeakDecode(optsm, cfg) } func applyOptionsFromCodeBlockContext(ctx hooks.CodeblockContext, cfg *Config) error { if cfg.LineAnchors == "" { const lineAnchorPrefix = "hl-" // Set it to the ordinal with a prefix. cfg.LineAnchors = fmt.Sprintf("%s%d", lineAnchorPrefix, ctx.Ordinal()) } return nil } // ApplyLegacyConfig applies legacy config from back when we had // Pygments. func ApplyLegacyConfig(cfg config.Provider, conf *Config) error { if conf.Style == DefaultConfig.Style { if s := cfg.GetString("pygmentsStyle"); s != "" { conf.Style = s } } if conf.NoClasses == DefaultConfig.NoClasses && cfg.IsSet("pygmentsUseClasses") { conf.NoClasses = !cfg.GetBool("pygmentsUseClasses") } if conf.CodeFences == DefaultConfig.CodeFences && cfg.IsSet("pygmentsCodeFences") { conf.CodeFences = cfg.GetBool("pygmentsCodeFences") } if conf.GuessSyntax == DefaultConfig.GuessSyntax && cfg.IsSet("pygmentsCodefencesGuessSyntax") { conf.GuessSyntax = cfg.GetBool("pygmentsCodefencesGuessSyntax") } if cfg.IsSet("pygmentsOptions") { if err := applyOptionsFromString(cfg.GetString("pygmentsOptions"), conf); err != nil { return err } } return nil } func parseHighlightOptions(in string) (map[string]any, error) { in = strings.Trim(in, " ") opts := make(map[string]any) if in == "" { return opts, nil } for v := range strings.SplitSeq(in, ",") { keyVal := strings.Split(v, "=") key := strings.Trim(keyVal[0], " ") if len(keyVal) != 2 { return opts, fmt.Errorf("invalid Highlight option: %s", key) } opts[key] = keyVal[1] } normalizeHighlightOptions(opts) return opts, nil } func normalizeHighlightOptions(m map[string]any) { if m == nil { return } // lowercase all keys for k, v := range m { delete(m, k) m[strings.ToLower(k)] = v } baseLineNumber := 1 if v, ok := m[linosStartKey]; ok { baseLineNumber = cast.ToInt(v) } for k, v := range m { switch k { case lineNosKey: if v == "table" || v == "inline" { m["lineNumbersInTable"] = v == "table" } if vs, ok := v.(string); ok { m[k] = vs != "false" } case hlLinesKey: if hlRanges, ok := v.([][2]int); ok { for i := range hlRanges { hlRanges[i][0] += baseLineNumber hlRanges[i][1] += baseLineNumber } delete(m, k) m[k+"_parsed"] = hlRanges } } } } // startLine compensates for https://github.com/alecthomas/chroma/issues/30 func hlLinesToRanges(startLine int, s string) ([][2]int, error) { var ranges [][2]int s = strings.TrimSpace(s) if s == "" { return ranges, nil } // Variants: // 1 2 3 4 // 1-2 3-4 // 1-2 3 // 1 3-4 // 1 3-4 fields := strings.SplitSeq(s, " ") for field := range fields { field = strings.TrimSpace(field) if field == "" { continue } numbers := strings.Split(field, "-") var r [2]int first, err := strconv.Atoi(numbers[0]) if err != nil { return ranges, err } first = first + startLine - 1 r[0] = first if len(numbers) > 1 { second, err := strconv.Atoi(numbers[1]) if err != nil { return ranges, err } second = second + startLine - 1 r[1] = second } else { r[1] = first } ranges = append(ranges, r) } return ranges, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/highlight/highlight_integration_test.go
markup/highlight/highlight_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package highlight_test import ( "testing" "github.com/gohugoio/hugo/hugolib" ) func TestHighlightInline(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup] [markup.highlight] codeFences = true noClasses = false -- content/p1.md -- --- title: "p1" --- ## Inline in Shortcode Inline:{{< highlight emacs "hl_inline=true" >}}(message "this highlight shortcode"){{< /highlight >}}:End. Inline Unknown:{{< highlight foo "hl_inline=true" >}}(message "this highlight shortcode"){{< /highlight >}}:End. ## Inline in code block Not sure if this makes sense, but add a test for it: §§§bash {hl_inline=true} (message "highlight me") §§§ ## HighlightCodeBlock in hook §§§html (message "highlight me 2") §§§ ## Unknown lexer §§§foo {hl_inline=true} (message "highlight me 3") §§§ -- layouts/_markup/render-codeblock-html.html -- {{ $opts := dict "hl_inline" true }} {{ $result := transform.HighlightCodeBlock . $opts }} HighlightCodeBlock: Wrapped:{{ $result.Wrapped }}|Inner:{{ $result.Inner }} -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "Inline:<code class=\"code-inline language-emacs\"><span class=\"p\">(</span><span class=\"nf\">message</span> <span class=\"s\">&#34;this highlight shortcode&#34;</span><span class=\"p\">)</span></code>:End.", "Inline Unknown:<code class=\"code-inline language-foo\">(message &#34;this highlight shortcode&#34;)</code>:End.", "Not sure if this makes sense, but add a test for it:</p>\n<code class=\"code-inline language-bash\"><span class=\"o\">(</span>message <span class=\"s2\">&#34;highlight me&#34;</span><span class=\"o\">)</span>\n</code>", "HighlightCodeBlock: Wrapped:<code class=\"code-inline language-html\">(message &#34;highlight me 2&#34;)</code>|Inner:<code class=\"code-inline language-html\">(message &#34;highlight me 2&#34;)</code>", "<code class=\"code-inline language-foo\">(message &#34;highlight me 3&#34;)\n</code>", ) } // Issue #11311 func TestIssue11311(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.highlight] noClasses = false -- content/_index.md -- --- title: home --- §§§go xəx := 0 §§§ -- layouts/home.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` <span class="nx">xəx</span> `) } func TestHighlightClass(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.highlight] noClasses = false wrapperClass = "highlight no-prose" -- content/_index.md -- --- title: home --- §§§go xəx := 0 §§§ -- layouts/home.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", ` <div class="highlight no-prose"><pre `) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/highlight/highlight_test.go
markup/highlight/highlight_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package highlight provides code highlighting. package highlight import ( "testing" qt "github.com/frankban/quicktest" ) func TestHighlight(t *testing.T) { c := qt.New(t) lines := `LINE1 LINE2 LINE3 LINE4 LINE5 ` coalesceNeeded := `GET /foo HTTP/1.1 Content-Type: application/json User-Agent: foo { "hello": "world" }` c.Run("Basic", func(c *qt.C) { cfg := DefaultConfig cfg.NoClasses = false h := New(cfg) result, _ := h.Highlight(`echo "Hugo Rocks!"`, "bash", "") c.Assert(result, qt.Equals, `<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nb">echo</span> <span class="s2">&#34;Hugo Rocks!&#34;</span></span></span></code></pre></div>`) result, _ = h.Highlight(`echo "Hugo Rocks!"`, "unknown", "") c.Assert(result, qt.Equals, `<pre tabindex="0"><code class="language-unknown" data-lang="unknown">echo &#34;Hugo Rocks!&#34;</code></pre>`) }) c.Run("Highlight lines, default config", func(c *qt.C) { cfg := DefaultConfig cfg.NoClasses = false h := New(cfg) result, _ := h.Highlight(lines, "bash", "linenos=table,hl_lines=2 4-5,linenostart=3") c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4") result, _ = h.Highlight(lines, "bash", "linenos=inline,hl_lines=2") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") c.Assert(result, qt.Not(qt.Contains), "<table") result, _ = h.Highlight(lines, "bash", "linenos=true,hl_lines=2") c.Assert(result, qt.Contains, "<table") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>") }) c.Run("Highlight lines, linenumbers default on", func(c *qt.C) { cfg := DefaultConfig cfg.NoClasses = false cfg.LineNos = true h := New(cfg) result, _ := h.Highlight(lines, "bash", "") c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>") result, _ = h.Highlight(lines, "bash", "linenos=false,hl_lines=2") c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"") }) c.Run("Highlight lines, linenumbers default on, anchorlinenumbers default on", func(c *qt.C) { cfg := DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.AnchorLineNos = true h := New(cfg) result, _ := h.Highlight(lines, "bash", "") c.Assert(result, qt.Contains, "<span class=\"lnt\" id=\"2\"><a class=\"lnlinks\" href=\"#2\">2</a>\n</span>") result, _ = h.Highlight(lines, "bash", "anchorlinenos=false,hl_lines=2") c.Assert(result, qt.Not(qt.Contains), "id=\"2\"") }) c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) { cfg := DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false h := New(cfg) result, _ := h.Highlight(lines, "bash", "") c.Assert(result, qt.Contains, "<span class=\"cl\">LINE2\n</span></span>") result, _ = h.Highlight(lines, "bash", "linenos=table") c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>") }) c.Run("No language", func(c *qt.C) { cfg := DefaultConfig cfg.NoClasses = false cfg.LineNos = true h := New(cfg) result, _ := h.Highlight(lines, "", "") c.Assert(result, qt.Equals, "<pre tabindex=\"0\"><code>LINE1\nLINE2\nLINE3\nLINE4\nLINE5\n</code></pre>") }) c.Run("No language, guess syntax", func(c *qt.C) { cfg := DefaultConfig cfg.NoClasses = false cfg.GuessSyntax = true cfg.LineNos = true cfg.LineNumbersInTable = false h := New(cfg) result, _ := h.Highlight(lines, "", "") c.Assert(result, qt.Contains, "<span class=\"cl\">LINE2\n</span></span>") }) c.Run("No language, Escape HTML string", func(c *qt.C) { cfg := DefaultConfig cfg.NoClasses = false h := New(cfg) result, _ := h.Highlight("Escaping less-than in code block? <fail>", "", "") c.Assert(result, qt.Contains, "&lt;fail&gt;") }) c.Run("Highlight lines, default config", func(c *qt.C) { cfg := DefaultConfig cfg.NoClasses = false h := New(cfg) result, _ := h.Highlight(coalesceNeeded, "http", "linenos=true,hl_lines=2") c.Assert(result, qt.Contains, "hello") c.Assert(result, qt.Contains, "}") }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/highlight/config_test.go
markup/highlight/config_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package highlight provides code highlighting. package highlight import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/config" ) func TestConfig(t *testing.T) { c := qt.New(t) c.Run("applyLegacyConfig", func(c *qt.C) { v := config.New() v.Set("pygmentsStyle", "hugo") v.Set("pygmentsUseClasses", false) v.Set("pygmentsCodeFences", false) v.Set("pygmentsOptions", "linenos=inline") cfg := DefaultConfig err := ApplyLegacyConfig(v, &cfg) c.Assert(err, qt.IsNil) c.Assert(cfg.Style, qt.Equals, "hugo") c.Assert(cfg.NoClasses, qt.Equals, true) c.Assert(cfg.CodeFences, qt.Equals, false) c.Assert(cfg.LineNos, qt.Equals, true) c.Assert(cfg.LineNumbersInTable, qt.Equals, false) }) c.Run("parseOptions", func(c *qt.C) { cfg := DefaultConfig opts := "noclasses=true,linenos=inline,linenostart=32,hl_lines=3-8 10-20" err := applyOptionsFromString(opts, &cfg) c.Assert(err, qt.IsNil) c.Assert(cfg.NoClasses, qt.Equals, true) c.Assert(cfg.LineNos, qt.Equals, true) c.Assert(cfg.LineNumbersInTable, qt.Equals, false) c.Assert(cfg.LineNoStart, qt.Equals, 32) c.Assert(cfg.Hl_Lines, qt.Equals, "3-8 10-20") }) c.Run("applyOptionsFromMap", func(c *qt.C) { cfg := DefaultConfig err := applyOptionsFromMap(map[string]any{ "noclasses": true, "lineNos": "inline", // mixed case key, should work after normalization "linenostart": 32, "hl_lines": "3-8 10-20", }, &cfg) c.Assert(err, qt.IsNil) c.Assert(cfg.NoClasses, qt.Equals, true) c.Assert(cfg.LineNos, qt.Equals, true) c.Assert(cfg.LineNumbersInTable, qt.Equals, false) c.Assert(cfg.LineNoStart, qt.Equals, 32) c.Assert(cfg.Hl_Lines, qt.Equals, "3-8 10-20") }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/highlight/chromalexers/chromalexers.go
markup/highlight/chromalexers/chromalexers.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package chromalexers import ( "sync" "github.com/alecthomas/chroma/v2" "github.com/alecthomas/chroma/v2/lexers" ) type lexersMap struct { lexers map[string]chroma.Lexer mu sync.RWMutex } var lexerCache = &lexersMap{lexers: make(map[string]chroma.Lexer)} // Get returns a lexer for the given language name, nil if not found. // This is just a wrapper around chromalexers.Get that caches the result. // Reasoning for this is that chromalexers.Get is slow in the case where the lexer is not found, // which is a common case in Hugo. func Get(name string) chroma.Lexer { lexerCache.mu.RLock() lexer, found := lexerCache.lexers[name] lexerCache.mu.RUnlock() if found { return lexer } lexer = lexers.Get(name) lexerCache.mu.Lock() lexerCache.lexers[name] = lexer lexerCache.mu.Unlock() return lexer }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/org/convert_test.go
markup/org/convert_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org_test import ( "testing" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config/testconfig" "github.com/spf13/afero" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/markup/org" qt "github.com/frankban/quicktest" ) func TestConvert(t *testing.T) { c := qt.New(t) p, err := org.Provider.New(converter.ProviderConfig{ Logger: loggers.NewDefault(), Conf: testconfig.GetTestConfig(afero.NewMemMapFs(), nil), }) c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte("testContent")}) c.Assert(err, qt.IsNil) c.Assert(string(b.Bytes()), qt.Equals, "<p>testContent</p>\n") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/org/convert.go
markup/org/convert.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package org converts Emacs Org-Mode to HTML. package org import ( "bytes" "log" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/niklasfasching/go-org/org" "github.com/spf13/afero" ) // Provider is the package entry point. var Provider converter.ProviderProvider = provide{} type provide struct{} func (p provide) New(cfg converter.ProviderConfig) (converter.Provider, error) { return converter.NewProvider("org", func(ctx converter.DocumentContext) (converter.Converter, error) { return &orgConverter{ ctx: ctx, cfg: cfg, }, nil }), nil } type orgConverter struct { ctx converter.DocumentContext cfg converter.ProviderConfig } func (c *orgConverter) Convert(ctx converter.RenderContext) (converter.ResultRender, error) { logger := c.cfg.Logger config := org.New() config.Log = log.Default() // TODO(bep) config.ReadFile = func(filename string) ([]byte, error) { return afero.ReadFile(c.cfg.ContentFs, filename) } writer := org.NewHTMLWriter() writer.HighlightCodeBlock = func(source, lang string, inline bool, params map[string]string) string { highlightedSource, err := c.cfg.Highlight(source, lang, "") if err != nil { logger.Errorf("Could not highlight source as lang %s. Using raw source.", lang) return source } return highlightedSource } html, err := config.Parse(bytes.NewReader(ctx.Src), c.ctx.DocumentName).Write(writer) if err != nil { logger.Errorf("Could not render org: %s. Using unrendered content.", err) return converter.Bytes(ctx.Src), nil } return converter.Bytes([]byte(html)), nil } func (c *orgConverter) Supports(feature identity.Identity) bool { return false }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/autoid_test.go
markup/goldmark/autoid_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package goldmark import ( "strings" "testing" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" qt "github.com/frankban/quicktest" ) func TestSanitizeAnchorName(t *testing.T) { c := qt.New(t) // Tests generated manually on github.com tests := ` God is good: 神真美好 Number 32 Question? 1+2=3 Special !"#$%&(parens)=?´* chars Resumé One-Hyphen Multiple--Hyphens Trailing hyphen- Many spaces here Forward/slash Backward\slash Under_score Nonbreaking Space Tab Space ` expect := ` god-is-good-神真美好 number-32 question 123 special-parens-chars resumé one-hyphen multiple--hyphens trailing-hyphen- many---spaces--here forwardslash backwardslash under_score nonbreakingspace tabspace ` tests, expect = strings.TrimSpace(tests), strings.TrimSpace(expect) testlines, expectlines := strings.Split(tests, "\n"), strings.Split(expect, "\n") testlines = append(testlines, "Trailing Space ") expectlines = append(expectlines, "trailing-space") if len(testlines) != len(expectlines) { panic("test setup failed") } for i, input := range testlines { expect := expectlines[i] c.Run(input, func(c *qt.C) { b := []byte(input) got := string(sanitizeAnchorName(b, goldmark_config.AutoIDTypeGitHub)) c.Assert(got, qt.Equals, expect) c.Assert(sanitizeAnchorNameString(input, goldmark_config.AutoIDTypeGitHub), qt.Equals, expect) c.Assert(string(b), qt.Equals, input) }) } } func TestSanitizeAnchorNameAsciiOnly(t *testing.T) { c := qt.New(t) c.Assert(sanitizeAnchorNameString("god is神真美好 good", goldmark_config.AutoIDTypeGitHubAscii), qt.Equals, "god-is-good") c.Assert(sanitizeAnchorNameString("Resumé", goldmark_config.AutoIDTypeGitHubAscii), qt.Equals, "resume") } func TestSanitizeAnchorNameBlackfriday(t *testing.T) { c := qt.New(t) c.Assert(sanitizeAnchorNameString("Let's try this, shall we?", goldmark_config.AutoIDTypeBlackfriday), qt.Equals, "let-s-try-this-shall-we") } func BenchmarkSanitizeAnchorName(b *testing.B) { input := []byte("God is good: 神真美好") for b.Loop() { result := sanitizeAnchorName(input, goldmark_config.AutoIDTypeGitHub) if len(result) != 24 { b.Fatalf("got %d", len(result)) } } } func BenchmarkSanitizeAnchorNameAsciiOnly(b *testing.B) { input := []byte("God is good: 神真美好") for b.Loop() { result := sanitizeAnchorName(input, goldmark_config.AutoIDTypeGitHubAscii) if len(result) != 12 { b.Fatalf("got %d", len(result)) } } } func BenchmarkSanitizeAnchorNameBlackfriday(b *testing.B) { input := []byte("God is good: 神真美好") for b.Loop() { result := sanitizeAnchorName(input, goldmark_config.AutoIDTypeBlackfriday) if len(result) != 24 { b.Fatalf("got %d", len(result)) } } } func BenchmarkSanitizeAnchorNameString(b *testing.B) { input := "God is good: 神真美好" for b.Loop() { result := sanitizeAnchorNameString(input, goldmark_config.AutoIDTypeGitHub) if len(result) != 24 { b.Fatalf("got %d", len(result)) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/render_hooks.go
markup/goldmark/render_hooks.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package goldmark import ( "bytes" "strings" "github.com/gohugoio/hugo/common/types/hstring" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/goldmark/images" "github.com/gohugoio/hugo/markup/goldmark/internal/render" "github.com/gohugoio/hugo/markup/internal/attributes" "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/renderer" "github.com/yuin/goldmark/renderer/html" "github.com/yuin/goldmark/util" ) 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, }, } return r } func newLinks(cfg goldmark_config.Config) goldmark.Extender { return &links{cfg: cfg} } type linkContext struct { page any pageInner any destination string title string text hstring.HTML plainText string *attributes.AttributesHolder } func (ctx linkContext) Destination() string { return ctx.destination } func (ctx linkContext) Page() any { return ctx.page } func (ctx linkContext) PageInner() any { return ctx.pageInner } func (ctx linkContext) Text() hstring.HTML { return ctx.text } func (ctx linkContext) PlainText() string { return ctx.plainText } func (ctx linkContext) Title() string { return ctx.title } type imageLinkContext struct { linkContext ordinal int isBlock bool } func (ctx imageLinkContext) IsBlock() bool { return ctx.isBlock } func (ctx imageLinkContext) Ordinal() int { return ctx.ordinal } type headingContext struct { page any pageInner any level int anchor string text hstring.HTML plainText string *attributes.AttributesHolder } func (ctx headingContext) Page() any { return ctx.page } func (ctx headingContext) PageInner() any { return ctx.pageInner } func (ctx headingContext) Level() int { return ctx.level } func (ctx headingContext) Anchor() string { return ctx.anchor } func (ctx headingContext) Text() hstring.HTML { return ctx.text } func (ctx headingContext) PlainText() string { return ctx.plainText } type hookedRenderer struct { linkifyProtocol []byte html.Config } func (r *hookedRenderer) SetOption(name renderer.OptionName, value any) { r.Config.SetOption(name, value) } // RegisterFuncs implements NodeRenderer.RegisterFuncs. func (r *hookedRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) { reg.Register(ast.KindLink, r.renderLink) reg.Register(ast.KindAutoLink, r.renderAutoLink) reg.Register(ast.KindImage, r.renderImage) reg.Register(ast.KindHeading, r.renderHeading) } func (r *hookedRenderer) renderImage(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { n := node.(*ast.Image) var lr hooks.LinkRenderer ctx, ok := w.(*render.Context) if ok { h := ctx.RenderContext().GetRenderer(hooks.ImageRendererType, nil) ok = h != nil if ok { lr = h.(hooks.LinkRenderer) } } if !ok { return r.renderImageDefault(w, source, node, entering) } if entering { // Store the current pos so we can capture the rendered text. ctx.PushPos(ctx.Buffer.Len()) return ast.WalkContinue, nil } text := ctx.PopRenderedString() var ( isBlock bool ordinal int ) if b, ok := n.AttributeString(images.AttrIsBlock); ok && b.(bool) { isBlock = true } if n, ok := n.AttributeString(images.AttrOrdinal); ok { ordinal = n.(int) } // We use the attributes to signal from the parser whether the image is in // a block context or not. // We may find a better way to do that, but for now, we'll need to remove any // internal attributes before rendering. attrs := r.filterInternalAttributes(n.Attributes()) page, pageInner := render.GetPageAndPageInner(ctx) err := lr.RenderLink( ctx.RenderContext().Ctx, w, imageLinkContext{ linkContext: linkContext{ page: page, pageInner: pageInner, destination: string(n.Destination), title: string(n.Title), text: hstring.HTML(text), plainText: render.TextPlain(n, source), AttributesHolder: attributes.New(attrs, attributes.AttributesOwnerGeneral), }, ordinal: ordinal, isBlock: isBlock, }, ) return ast.WalkContinue, err } func (r *hookedRenderer) filterInternalAttributes(attrs []ast.Attribute) []ast.Attribute { n := 0 for _, x := range attrs { if !bytes.HasPrefix(x.Name, []byte(internalAttrPrefix)) { attrs[n] = x n++ } } return attrs[:n] } // Fall back to the default Goldmark render funcs. Method below borrowed from: // https://github.com/yuin/goldmark func (r *hookedRenderer) renderImageDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { if !entering { return ast.WalkContinue, nil } n := node.(*ast.Image) _, _ = w.WriteString("<img src=\"") if r.Unsafe || !html.IsDangerousURL(n.Destination) { _, _ = w.Write(util.EscapeHTML(util.URLEscape(n.Destination, true))) } _, _ = w.WriteString(`" alt="`) r.renderTexts(w, source, n) _ = w.WriteByte('"') if n.Title != nil { _, _ = w.WriteString(` title="`) r.Writer.Write(w, n.Title) _ = w.WriteByte('"') } if n.Attributes() != nil { html.RenderAttributes(w, n, html.ImageAttributeFilter) } if r.XHTML { _, _ = w.WriteString(" />") } else { _, _ = w.WriteString(">") } return ast.WalkSkipChildren, nil } func (r *hookedRenderer) renderLink(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { n := node.(*ast.Link) var lr hooks.LinkRenderer ctx, ok := w.(*render.Context) if ok { h := ctx.RenderContext().GetRenderer(hooks.LinkRendererType, nil) ok = h != nil if ok { lr = h.(hooks.LinkRenderer) } } if !ok { return r.renderLinkDefault(w, source, node, entering) } if entering { // Store the current pos so we can capture the rendered text. ctx.PushPos(ctx.Buffer.Len()) return ast.WalkContinue, nil } text := ctx.PopRenderedString() page, pageInner := render.GetPageAndPageInner(ctx) err := lr.RenderLink( ctx.RenderContext().Ctx, w, linkContext{ page: page, pageInner: pageInner, destination: string(n.Destination), title: string(n.Title), text: hstring.HTML(text), plainText: render.TextPlain(n, source), AttributesHolder: attributes.Empty, }, ) return ast.WalkContinue, err } // Borrowed from Goldmark's HTML renderer. func (r *hookedRenderer) renderTexts(w util.BufWriter, source []byte, n ast.Node) { for c := n.FirstChild(); c != nil; c = c.NextSibling() { if s, ok := c.(*ast.String); ok { _, _ = r.renderString(w, source, s, true) } else if t, ok := c.(*ast.Text); ok { _, _ = r.renderText(w, source, t, true) } else { r.renderTexts(w, source, c) } } } // Borrowed from Goldmark's HTML renderer. func (r *hookedRenderer) renderString(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { if !entering { return ast.WalkContinue, nil } n := node.(*ast.String) if n.IsCode() { _, _ = w.Write(n.Value) } else { if n.IsRaw() { r.Writer.RawWrite(w, n.Value) } else { r.Writer.Write(w, n.Value) } } return ast.WalkContinue, nil } // Borrowed from Goldmark's HTML renderer. func (r *hookedRenderer) renderText(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { if !entering { return ast.WalkContinue, nil } n := node.(*ast.Text) segment := n.Segment if n.IsRaw() { r.Writer.RawWrite(w, segment.Value(source)) } else { value := segment.Value(source) r.Writer.Write(w, value) if n.HardLineBreak() || (n.SoftLineBreak() && r.HardWraps) { if r.XHTML { _, _ = w.WriteString("<br />\n") } else { _, _ = w.WriteString("<br>\n") } } else if n.SoftLineBreak() { // TODO(bep) we use these methods a fallback to default rendering when no image/link hooks are defined. // I don't think the below is relevant in these situations, but if so, we need to create a PR // upstream to export softLineBreak. /*if r.EastAsianLineBreaks != html.EastAsianLineBreaksNone && len(value) != 0 { sibling := node.NextSibling() if sibling != nil && sibling.Kind() == ast.KindText { if siblingText := sibling.(*ast.Text).Value(source); len(siblingText) != 0 { thisLastRune := util.ToRune(value, len(value)-1) siblingFirstRune, _ := utf8.DecodeRune(siblingText) if r.EastAsianLineBreaks.softLineBreak(thisLastRune, siblingFirstRune) { _ = w.WriteByte('\n') } } } } else { _ = w.WriteByte('\n') }*/ _ = w.WriteByte('\n') } } return ast.WalkContinue, nil } // Fall back to the default Goldmark render funcs. Method below borrowed from: // https://github.com/yuin/goldmark/blob/b611cd333a492416b56aa8d94b04a67bf0096ab2/renderer/html/html.go#L404 func (r *hookedRenderer) renderLinkDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { n := node.(*ast.Link) if entering { _, _ = w.WriteString("<a href=\"") if r.Unsafe || !html.IsDangerousURL(n.Destination) { _, _ = w.Write(util.EscapeHTML(util.URLEscape(n.Destination, true))) } _ = w.WriteByte('"') if n.Title != nil { _, _ = w.WriteString(` title="`) r.Writer.Write(w, n.Title) _ = w.WriteByte('"') } _ = w.WriteByte('>') } else { _, _ = w.WriteString("</a>") } return ast.WalkContinue, nil } func (r *hookedRenderer) renderAutoLink(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { if !entering { return ast.WalkContinue, nil } n := node.(*ast.AutoLink) var lr hooks.LinkRenderer ctx, ok := w.(*render.Context) if ok { h := ctx.RenderContext().GetRenderer(hooks.LinkRendererType, nil) ok = h != nil if ok { lr = h.(hooks.LinkRenderer) } } if !ok { return r.renderAutoLinkDefault(w, source, node, entering) } url := string(r.autoLinkURL(n, source)) label := string(n.Label(source)) if n.AutoLinkType == ast.AutoLinkEmail && !strings.HasPrefix(strings.ToLower(url), "mailto:") { url = "mailto:" + url } page, pageInner := render.GetPageAndPageInner(ctx) err := lr.RenderLink( ctx.RenderContext().Ctx, w, linkContext{ page: page, pageInner: pageInner, destination: url, text: hstring.HTML(label), plainText: label, AttributesHolder: attributes.Empty, }, ) return ast.WalkContinue, err } // Fall back to the default Goldmark render funcs. Method below borrowed from: // https://github.com/yuin/goldmark/blob/5588d92a56fe1642791cf4aa8e9eae8227cfeecd/renderer/html/html.go#L439 func (r *hookedRenderer) renderAutoLinkDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { n := node.(*ast.AutoLink) if !entering { return ast.WalkContinue, nil } _, _ = w.WriteString(`<a href="`) url := r.autoLinkURL(n, source) label := n.Label(source) if n.AutoLinkType == ast.AutoLinkEmail && !bytes.HasPrefix(bytes.ToLower(url), []byte("mailto:")) { _, _ = w.WriteString("mailto:") } _, _ = w.Write(util.EscapeHTML(util.URLEscape(url, false))) if n.Attributes() != nil { _ = w.WriteByte('"') html.RenderAttributes(w, n, html.LinkAttributeFilter) _ = w.WriteByte('>') } else { _, _ = w.WriteString(`">`) } _, _ = w.Write(util.EscapeHTML(label)) _, _ = w.WriteString(`</a>`) return ast.WalkContinue, nil } func (r *hookedRenderer) autoLinkURL(n *ast.AutoLink, source []byte) []byte { url := n.URL(source) if len(n.Protocol) > 0 && !bytes.Equal(n.Protocol, r.linkifyProtocol) { // The CommonMark spec says "http" is the correct protocol for links, // but this doesn't make much sense (the fact that they should care about the rendered output). // Note that n.Protocol is not set if protocol is provided by user. url = append(r.linkifyProtocol, url[len(n.Protocol):]...) } return url } func (r *hookedRenderer) renderHeading(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { n := node.(*ast.Heading) var hr hooks.HeadingRenderer ctx, ok := w.(*render.Context) if ok { h := ctx.RenderContext().GetRenderer(hooks.HeadingRendererType, nil) ok = h != nil if ok { hr = h.(hooks.HeadingRenderer) } } if !ok { return r.renderHeadingDefault(w, source, node, entering) } if entering { // Store the current pos so we can capture the rendered text. ctx.PushPos(ctx.Buffer.Len()) return ast.WalkContinue, nil } text := ctx.PopRenderedString() var anchor []byte if anchori, ok := n.AttributeString("id"); ok { anchor, _ = anchori.([]byte) } page, pageInner := render.GetPageAndPageInner(ctx) err := hr.RenderHeading( ctx.RenderContext().Ctx, w, headingContext{ page: page, pageInner: pageInner, level: n.Level, anchor: string(anchor), text: hstring.HTML(text), plainText: render.TextPlain(n, source), AttributesHolder: attributes.New(n.Attributes(), attributes.AttributesOwnerGeneral), }, ) return ast.WalkContinue, err } func (r *hookedRenderer) renderHeadingDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { n := node.(*ast.Heading) if entering { _, _ = w.WriteString("<h") _ = w.WriteByte("0123456"[n.Level]) if n.Attributes() != nil { attributes.RenderASTAttributes(w, node.Attributes()...) } _ = w.WriteByte('>') } else { _, _ = w.WriteString("</h") _ = w.WriteByte("0123456"[n.Level]) _, _ = w.WriteString(">\n") } return ast.WalkContinue, nil } type links struct { cfg goldmark_config.Config } // Extend implements goldmark.Extender. func (e *links) Extend(m goldmark.Markdown) { m.Renderer().AddOptions(renderer.WithNodeRenderers( util.Prioritized(newLinkRenderer(e.cfg), 100), )) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/convert_test.go
markup/goldmark/convert_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package goldmark_test import ( "context" "fmt" "strings" "testing" "github.com/pelletier/go-toml/v2" "github.com/spf13/cast" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/testconfig" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" ) var cfgStrHighlichgtNoClasses = ` [markup] [markup.highlight] noclasses=false ` func convert(c *qt.C, conf config.AllProvider, content string) converter.ResultRender { pconf := converter.ProviderConfig{ Logger: loggers.NewDefault(), Conf: conf, } p, err := goldmark.Provider.New( pconf, ) c.Assert(err, qt.IsNil) mconf := pconf.MarkupConfig() h := highlight.New(mconf.Highlight) getRenderer := func(t hooks.RendererType, id any) any { switch t { case hooks.CodeBlockRendererType: return h case hooks.TableRendererType: return tableRenderer(0) } return nil } conv, err := p.New(converter.DocumentContext{DocumentID: "thedoc"}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{RenderTOC: true, Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return b } func TestConvert(t *testing.T) { c := qt.New(t) // Smoke test of the default configuration. content := ` ## Links https://github.com/gohugoio/hugo/issues/6528 [Live Demo here!](https://docuapi.netlify.com/) [I'm an inline-style link with title](https://www.google.com "Google's Homepage") <https://foo.bar/> https://bar.baz/ <fake@example.com> <mailto:fake2@example.com> ## Code Fences §§§bash LINE1 §§§ ## Code Fences No Lexer §§§moo LINE1 §§§ ## Custom ID {#custom} ## Auto ID * Autolink: https://gohugo.io/ * Strikethrough:~~Hi~~ Hello, world! ## Table | foo | bar | | --- | --- | | baz | bim | ## Task Lists (default on) - [x] Finish my changes[^1] - [ ] Push my commits to GitHub - [ ] Open a pull request ## Smartypants (default on) * Straight double "quotes" and single 'quotes' into “curly” quote HTML entities * Dashes (“--” and “---”) into en- and em-dash entities * Three consecutive dots (“...”) into an ellipsis entity * Apostrophes are also converted: "That was back in the '90s, that's a long time ago" ## Footnotes That's some text with a footnote.[^1] ## Definition Lists date : the datetime assigned to this page. description : the description for the content. ## 神真美好 ## 神真美好 ## 神真美好 [^1]: And that's the footnote. ` // Code fences content = strings.Replace(content, "§§§", "```", -1) cfg := config.FromTOMLConfigString(` [markup] [markup.highlight] noClasses = false [markup.goldmark.renderer] unsafe = true `) b := convert(c, testconfig.GetTestConfig(nil, cfg), content) got := string(b.Bytes()) // Links c.Assert(got, qt.Contains, `<a href="https://docuapi.netlify.com/">Live Demo here!</a>`) c.Assert(got, qt.Contains, `<a href="https://foo.bar/">https://foo.bar/</a>`) c.Assert(got, qt.Contains, `<a href="https://bar.baz/">https://bar.baz/</a>`) c.Assert(got, qt.Contains, `<a href="mailto:fake@example.com">fake@example.com</a>`) c.Assert(got, qt.Contains, `<a href="mailto:fake2@example.com">mailto:fake2@example.com</a></p>`) // Header IDs c.Assert(got, qt.Contains, `<h2 id="custom">Custom ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="auto-id">Auto ID</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="神真美好">神真美好</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="神真美好-1">神真美好</h2>`, qt.Commentf(got)) c.Assert(got, qt.Contains, `<h2 id="神真美好-2">神真美好</h2>`, qt.Commentf(got)) // Code fences c.Assert(got, qt.Contains, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>") c.Assert(got, qt.Contains, "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>") // Extensions c.Assert(got, qt.Contains, `Autolink: <a href="https://gohugo.io/">https://gohugo.io/</a>`) c.Assert(got, qt.Contains, `Strikethrough:<del>Hi</del> Hello, world`) c.Assert(got, qt.Contains, `Table`) c.Assert(got, qt.Contains, `<li><input disabled="" type="checkbox"> Push my commits to GitHub</li>`) c.Assert(got, qt.Contains, `Straight double &ldquo;quotes&rdquo; and single &lsquo;quotes&rsquo;`) c.Assert(got, qt.Contains, `Dashes (“&ndash;” and “&mdash;”) `) c.Assert(got, qt.Contains, `Three consecutive dots (“&hellip;”)`) c.Assert(got, qt.Contains, `&ldquo;That was back in the &rsquo;90s, that&rsquo;s a long time ago&rdquo;`) c.Assert(got, qt.Contains, `footnote.<sup id="fnref1:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>`) c.Assert(got, qt.Contains, `<div class="footnotes" role="doc-endnotes">`) c.Assert(got, qt.Contains, `<dt>date</dt>`) toc, ok := b.(converter.TableOfContentsProvider) c.Assert(ok, qt.Equals, true) tocHTML, _ := toc.TableOfContents().ToHTML(1, 2, false) c.Assert(string(tocHTML), qt.Contains, "TableOfContents") } func TestConvertAutoIDAsciiOnly(t *testing.T) { c := qt.New(t) content := ` ## God is Good: 神真美好 ` cfg := config.FromTOMLConfigString(` [markup] [markup.goldmark] [markup.goldmark.parser] autoHeadingIDType = 'github-ascii' `) b := convert(c, testconfig.GetTestConfig(nil, cfg), content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"god-is-good-\">") } func TestConvertAutoIDBlackfriday(t *testing.T) { c := qt.New(t) content := ` ## Let's try this, shall we? ` cfg := config.FromTOMLConfigString(` [markup] [markup.goldmark] [markup.goldmark.parser] autoHeadingIDType = 'blackfriday' `) b := convert(c, testconfig.GetTestConfig(nil, cfg), content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<h2 id=\"let-s-try-this-shall-we\">") } func TestConvertAttributes(t *testing.T) { c := qt.New(t) withBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = false } withTitleAndBlockAttributes := func(conf *markup_config.Config) { conf.Goldmark.Parser.Attribute.Block = true conf.Goldmark.Parser.Attribute.Title = true } for _, test := range []struct { name string withConfig func(conf *markup_config.Config) input string expect any }{ { "Title", nil, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n", }, { "Blockquote", withBlockAttributes, "> foo\n> bar\n{#id .className attrName=attrValue class=\"class1 class2\"}\n", "<blockquote id=\"id\" class=\"className class1 class2\"><p>foo\nbar</p>\n</blockquote>\n", }, /*{ // TODO(bep) this needs an upstream fix, see https://github.com/yuin/goldmark/issues/195 "Code block, CodeFences=false", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = false }, "```bash\necho 'foo';\n```\n{.myclass}", "TODO", },*/ { "Code block, CodeFences=true", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {.myclass id=\"myid\"}\necho 'foo';\n````\n", "<div class=\"highlight myclass\" id=\"myid\"><pre style", }, { "Code block, CodeFences=true,linenos=table", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true }, "```bash {linenos=table .myclass id=\"myid\"}\necho 'foo';\n````\n{ .adfadf }", []string{ "div class=\"highlight myclass\" id=\"myid\"><div s", "table style", }, }, { "Code block, CodeFences=true,lineanchors", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true conf.Highlight.NoClasses = false }, "```bash {linenos=table, anchorlinenos=true, lineanchors=org-coderef--xyz}\necho 'foo';\n```", "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class=\"lnt\" id=\"org-coderef--xyz-1\"><a href=\"#org-coderef--xyz-1\">1</a>\n</span></code></pre></td>\n<td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s1\">&#39;foo&#39;</span><span class=\"p\">;</span>\n</span></span></code></pre></td></tr></table>\n</div>\n</div>", }, { "Code block, CodeFences=true,lineanchors, default ordinal", func(conf *markup_config.Config) { withBlockAttributes(conf) conf.Highlight.CodeFences = true conf.Highlight.NoClasses = false }, "```bash {linenos=inline, anchorlinenos=true}\necho 'foo';\nnecho 'bar';\n```\n\n```bash {linenos=inline, anchorlinenos=true}\necho 'baz';\nnecho 'qux';\n```", []string{ "<span class=\"ln\" id=\"hl-0-1\"><a class=\"lnlinks\" href=\"#hl-0-1\">1</a></span><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s1\">&#39;foo&#39;</span>", "<span class=\"ln\" id=\"hl-0-2\"><a class=\"lnlinks\" href=\"#hl-0-2\">2</a></span><span class=\"cl\">necho <span class=\"s1\">&#39;bar&#39;</span>", "<span class=\"ln\" id=\"hl-1-2\"><a class=\"lnlinks\" href=\"#hl-1-2\">2</a></span><span class=\"cl\">necho <span class=\"s1\">&#39;qux&#39;</span>", }, }, { "Paragraph", withBlockAttributes, "\nHi there.\n{.myclass }", "<p class=\"myclass\">Hi there.</p>\n", }, { "Ordered list", withBlockAttributes, "\n1. First\n2. Second\n{.myclass }", "<ol class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ol>\n", }, { "Unordered list", withBlockAttributes, "\n* First\n* Second\n{.myclass }", "<ul class=\"myclass\">\n<li>First</li>\n<li>Second</li>\n</ul>\n", }, { "Unordered list, indented", withBlockAttributes, `* Fruit * Apple * Orange * Banana {.fruits} * Dairy * Milk * Cheese {.dairies} {.list}`, []string{"<ul class=\"list\">\n<li>Fruit\n<ul class=\"fruits\">", "<li>Dairy\n<ul class=\"dairies\">"}, }, { "Table", withBlockAttributes, `| A | B | | ------------- |:-------------:| -----:| | AV | BV | {.myclass }`, "Table", }, { "Title and Blockquote", withTitleAndBlockAttributes, "## heading {#id .className attrName=attrValue class=\"class1 class2\"}\n> foo\n> bar\n{.myclass}", "<h2 id=\"id\" class=\"className class1 class2\" attrName=\"attrValue\">heading</h2>\n<blockquote class=\"myclass\"><p>foo\nbar</p>\n</blockquote>\n", }, } { c.Run(test.name, func(c *qt.C) { mconf := markup_config.Default if test.withConfig != nil { test.withConfig(&mconf) } data, err := toml.Marshal(mconf) c.Assert(err, qt.IsNil) m := maps.Params{ "markup": config.FromTOMLConfigString(string(data)).Get(""), } conf := testconfig.GetTestConfig(nil, config.NewFrom(m)) b := convert(c, conf, test.input) got := string(b.Bytes()) for _, s := range cast.ToStringSlice(test.expect) { c.Assert(got, qt.Contains, s) } }) } } func TestConvertIssues(t *testing.T) { c := qt.New(t) // https://github.com/gohugoio/hugo/issues/7619 c.Run("Hyphen in HTML attributes", func(c *qt.C) { mconf := markup_config.Default mconf.Goldmark.Renderer.Unsafe = true input := `<custom-element> <div>This will be "slotted" into the custom element.</div> </custom-element> ` b := convert(c, unsafeConf(), input) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<custom-element>\n <div>This will be \"slotted\" into the custom element.</div>\n</custom-element>\n") }) } func TestCodeFence(t *testing.T) { c := qt.New(t) lines := `LINE1 LINE2 LINE3 LINE4 LINE5 ` convertForConfig := func(c *qt.C, confStr, code, language string) string { cfg := config.FromTOMLConfigString(confStr) conf := testconfig.GetTestConfig(nil, cfg) pcfg := converter.ProviderConfig{ Conf: conf, Logger: loggers.NewDefault(), } p, err := goldmark.Provider.New( pcfg, ) h := highlight.New(pcfg.MarkupConfig().Highlight) getRenderer := func(t hooks.RendererType, id any) any { if t == hooks.CodeBlockRendererType { return h } return nil } content := "```" + language + "\n" + code + "\n```" c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte(content), GetRenderer: getRenderer}) c.Assert(err, qt.IsNil) return string(b.Bytes()) } c.Run("Basic", func(c *qt.C) { confStr := ` [markup] [markup.highlight] noclasses=false ` result := convertForConfig(c, confStr, `echo "Hugo Rocks!"`, "bash") // TODO(bep) there is a whitespace mismatch (\n) between this and the highlight template func. c.Assert(result, qt.Equals, "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;Hugo Rocks!&#34;</span>\n</span></span></code></pre></div>") result = convertForConfig(c, confStr, `echo "Hugo Rocks!"`, "unknown") c.Assert(result, qt.Equals, "<pre tabindex=\"0\"><code class=\"language-unknown\" data-lang=\"unknown\">echo &#34;Hugo Rocks!&#34;\n</code></pre>") }) c.Run("Highlight lines, default config", func(c *qt.C) { result := convertForConfig(c, cfgStrHighlichgtNoClasses, lines, `bash {linenos=table,hl_lines=[2 "4-5"],linenostart=3}`) c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre tabindex=\"0\" class=\"chroma\"><code><span class") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4") result = convertForConfig(c, cfgStrHighlichgtNoClasses, lines, "bash {linenos=inline,hl_lines=[2]}") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") c.Assert(result, qt.Not(qt.Contains), "<table") result = convertForConfig(c, cfgStrHighlichgtNoClasses, lines, "bash {linenos=true,hl_lines=[2]}") c.Assert(result, qt.Contains, "<table") c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>") }) c.Run("Highlight lines, linenumbers default on", func(c *qt.C) { confStr := ` [markup] [markup.highlight] noclasses=false linenos=true ` result := convertForConfig(c, confStr, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>") result = convertForConfig(c, confStr, lines, "bash {linenos=false,hl_lines=[2]}") c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"") }) c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) { confStr := ` [markup] [markup.highlight] noClasses = false lineNos = true lineNumbersInTable = false ` result := convertForConfig(c, confStr, lines, "bash") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span>") result = convertForConfig(c, confStr, lines, "bash {linenos=table}") c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>") }) c.Run("No language", func(c *qt.C) { confStr := ` [markup] [markup.highlight] noClasses = false lineNos = true lineNumbersInTable = false ` cfg := highlight.DefaultConfig cfg.NoClasses = false cfg.LineNos = true cfg.LineNumbersInTable = false result := convertForConfig(c, confStr, lines, "") c.Assert(result, qt.Contains, "<pre tabindex=\"0\"><code>LINE1\n") }) c.Run("No language, guess syntax", func(c *qt.C) { confStr := ` [markup] [markup.highlight] noClasses = false lineNos = true lineNumbersInTable = false guessSyntax = true ` result := convertForConfig(c, confStr, lines, "") c.Assert(result, qt.Contains, "<span class=\"ln\">2</span><span class=\"cl\">LINE2\n</span></span>") }) } func TestTypographerConfig(t *testing.T) { c := qt.New(t) content := ` A "quote" and 'another quote' and a "quote with a 'nested' quote" and a 'quote with a "nested" quote' and an ellipsis... ` confStr := ` [markup] [markup.goldmark] [markup.goldmark.extensions] [markup.goldmark.extensions.typographer] leftDoubleQuote = "&laquo;" rightDoubleQuote = "&raquo;" ` cfg := config.FromTOMLConfigString(confStr) conf := testconfig.GetTestConfig(nil, cfg) b := convert(c, conf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<p>A &laquo;quote&raquo; and &lsquo;another quote&rsquo; and a &laquo;quote with a &rsquo;nested&rsquo; quote&raquo; and a &lsquo;quote with a &laquo;nested&raquo; quote&rsquo; and an ellipsis&hellip;</p>\n") } // Issue #11045 func TestTypographerImageAltText(t *testing.T) { c := qt.New(t) content := ` !["They didn't even say 'hello'!" I exclaimed.](https://example.com/image.jpg) ` confStr := ` [markup] [markup.goldmark] ` cfg := config.FromTOMLConfigString(confStr) conf := testconfig.GetTestConfig(nil, cfg) b := convert(c, conf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "&ldquo;They didn&rsquo;t even say &lsquo;hello&rsquo;!&rdquo; I exclaimed.") } func unsafeConf() config.AllProvider { cfg := config.FromTOMLConfigString(` [markup] [markup.goldmark.renderer] unsafe = true `) return testconfig.GetTestConfig(nil, cfg) } func TestConvertCJK(t *testing.T) { c := qt.New(t) content := ` 私は太郎です。 プログラミングが好きです。\ 運動が苦手です。 ` confStr := ` [markup] [markup.goldmark] ` cfg := config.FromTOMLConfigString(confStr) conf := testconfig.GetTestConfig(nil, cfg) b := convert(c, conf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<p>私は太郎です。\nプログラミングが好きです。\\ 運動が苦手です。</p>\n") } func TestConvertCJKWithExtensionWithEastAsianLineBreaksOption(t *testing.T) { c := qt.New(t) content := ` 私は太郎です。 プログラミングが好きで、 運動が苦手です。 ` confStr := ` [markup] [markup.goldmark] [markup.goldmark.extensions.CJK] enable=true eastAsianLineBreaks=true ` cfg := config.FromTOMLConfigString(confStr) conf := testconfig.GetTestConfig(nil, cfg) b := convert(c, conf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<p>私は太郎です。プログラミングが好きで、運動が苦手です。</p>\n") } func TestConvertCJKWithExtensionWithEastAsianLineBreaksOptionWithSimple(t *testing.T) { c := qt.New(t) content := ` 私は太郎です。 Programming が好きで、 運動が苦手です。 ` confStr := ` [markup] [markup.goldmark] [markup.goldmark.extensions.CJK] enable=true eastAsianLineBreaks=true eastAsianLineBreaksStyle="simple" ` cfg := config.FromTOMLConfigString(confStr) conf := testconfig.GetTestConfig(nil, cfg) b := convert(c, conf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<p>私は太郎です。\nProgramming が好きで、運動が苦手です。</p>\n") } func TestConvertCJKWithExtensionWithEastAsianLineBreaksOptionWithStyle(t *testing.T) { c := qt.New(t) content := ` 私は太郎です。 Programming が好きで、 運動が苦手です。 ` confStr := ` [markup] [markup.goldmark] [markup.goldmark.extensions.CJK] enable=true eastAsianLineBreaks=true eastAsianLineBreaksStyle="css3draft" ` cfg := config.FromTOMLConfigString(confStr) conf := testconfig.GetTestConfig(nil, cfg) b := convert(c, conf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<p>私は太郎です。Programming が好きで、運動が苦手です。</p>\n") } func TestConvertCJKWithExtensionWithEscapedSpaceOption(t *testing.T) { c := qt.New(t) content := ` 私は太郎です。 プログラミングが好きです。\ 運動が苦手です。 ` confStr := ` [markup] [markup.goldmark] [markup.goldmark.extensions.CJK] enable=true escapedSpace=true ` cfg := config.FromTOMLConfigString(confStr) conf := testconfig.GetTestConfig(nil, cfg) b := convert(c, conf, content) got := string(b.Bytes()) c.Assert(got, qt.Contains, "<p>私は太郎です。\nプログラミングが好きです。運動が苦手です。</p>\n") } type tableRenderer int func (hr tableRenderer) RenderTable(cctx context.Context, w hugio.FlexiWriter, ctx hooks.TableContext) error { // This is set up with a render hook in the hugolib package, make it simple here. fmt.Fprintln(w, "Table") return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/convert.go
markup/goldmark/convert.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package goldmark converts Markdown to HTML using Goldmark. package goldmark import ( "bytes" "github.com/gohugoio/hugo-goldmark-extensions/extras" "github.com/gohugoio/hugo/markup/goldmark/blockquotes" "github.com/gohugoio/hugo/markup/goldmark/codeblocks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/goldmark/hugocontext" "github.com/gohugoio/hugo/markup/goldmark/images" "github.com/gohugoio/hugo/markup/goldmark/internal/extensions/attributes" "github.com/gohugoio/hugo/markup/goldmark/internal/render" "github.com/gohugoio/hugo/markup/goldmark/passthrough" "github.com/gohugoio/hugo/markup/goldmark/tables" "github.com/yuin/goldmark/util" "github.com/yuin/goldmark" emoji "github.com/yuin/goldmark-emoji" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/renderer" "github.com/yuin/goldmark/renderer/html" "github.com/yuin/goldmark/text" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/markup/tableofcontents" ) const ( // Don't change this. This pattern is lso used in the image render hooks. internalAttrPrefix = "_h__" ) // Provider is the package entry point. var Provider converter.ProviderProvider = provide{} type provide struct{} func (p provide) New(cfg converter.ProviderConfig) (converter.Provider, error) { md := newMarkdown(cfg) return converter.NewProvider("goldmark", func(ctx converter.DocumentContext) (converter.Converter, error) { return &goldmarkConverter{ ctx: ctx, cfg: cfg, md: md, sanitizeAnchorName: func(s string) string { return sanitizeAnchorNameString(s, cfg.MarkupConfig().Goldmark.Parser.AutoIDType) }, }, nil }), nil } var _ converter.AnchorNameSanitizer = (*goldmarkConverter)(nil) type goldmarkConverter struct { md goldmark.Markdown ctx converter.DocumentContext cfg converter.ProviderConfig sanitizeAnchorName func(s string) string } func (c *goldmarkConverter) SanitizeAnchorName(s string) string { return c.sanitizeAnchorName(s) } func newMarkdown(pcfg converter.ProviderConfig) goldmark.Markdown { mcfg := pcfg.MarkupConfig() cfg := mcfg.Goldmark var rendererOptions []renderer.Option if cfg.Renderer.HardWraps { rendererOptions = append(rendererOptions, html.WithHardWraps()) } if cfg.Renderer.XHTML { rendererOptions = append(rendererOptions, html.WithXHTML()) } if cfg.Renderer.Unsafe { rendererOptions = append(rendererOptions, html.WithUnsafe()) } tocRendererOptions := make([]renderer.Option, len(rendererOptions)) if rendererOptions != nil { copy(tocRendererOptions, rendererOptions) } tocRendererOptions = append(tocRendererOptions, renderer.WithNodeRenderers(util.Prioritized(extension.NewStrikethroughHTMLRenderer(), 500)), renderer.WithNodeRenderers(util.Prioritized(emoji.NewHTMLRenderer(), 200)), ) inlineTags := []extras.InlineTag{ extras.DeleteTag, extras.InsertTag, extras.MarkTag, extras.SubscriptTag, extras.SuperscriptTag, } for _, tag := range inlineTags { tocRendererOptions = append(tocRendererOptions, renderer.WithNodeRenderers(util.Prioritized(extras.NewInlineTagHTMLRenderer(tag), tag.RenderPriority)), ) } var ( extensions = []goldmark.Extender{ hugocontext.New(pcfg.Logger), newLinks(cfg), newTocExtension(tocRendererOptions), blockquotes.New(), } parserOptions []parser.Option ) extensions = append(extensions, images.New(cfg.Parser.WrapStandAloneImageWithinParagraph)) extensions = append(extensions, extras.New( extras.Config{ Delete: extras.DeleteConfig{Enable: cfg.Extensions.Extras.Delete.Enable}, Insert: extras.InsertConfig{Enable: cfg.Extensions.Extras.Insert.Enable}, Mark: extras.MarkConfig{Enable: cfg.Extensions.Extras.Mark.Enable}, Subscript: extras.SubscriptConfig{Enable: cfg.Extensions.Extras.Subscript.Enable}, Superscript: extras.SuperscriptConfig{Enable: cfg.Extensions.Extras.Superscript.Enable}, }, )) if mcfg.Highlight.CodeFences { extensions = append(extensions, codeblocks.New()) } if cfg.Extensions.Table { extensions = append(extensions, extension.Table) extensions = append(extensions, tables.New()) } if cfg.Extensions.Strikethrough { extensions = append(extensions, extension.Strikethrough) } if cfg.Extensions.Linkify { extensions = append(extensions, extension.Linkify) } if cfg.Extensions.TaskList { extensions = append(extensions, extension.TaskList) } if !cfg.Extensions.Typographer.Disable { t := extension.NewTypographer( extension.WithTypographicSubstitutions(toTypographicPunctuationMap(cfg.Extensions.Typographer)), ) extensions = append(extensions, t) } if cfg.Extensions.DefinitionList { extensions = append(extensions, extension.DefinitionList) } if cfg.Extensions.Footnote.Enable { opts := []extension.FootnoteOption{} opts = append(opts, extension.WithFootnoteBacklinkHTML(cfg.Extensions.Footnote.BacklinkHTML)) if cfg.Extensions.Footnote.EnableAutoIDPrefix { opts = append(opts, extension.WithFootnoteIDPrefixFunction(func(n ast.Node) []byte { documentID := n.OwnerDocument().Meta()["documentID"].(string) return []byte("h" + documentID) })) } f := extension.NewFootnote(opts...) extensions = append(extensions, f) } if cfg.Extensions.CJK.Enable { opts := []extension.CJKOption{} if cfg.Extensions.CJK.EastAsianLineBreaks { if cfg.Extensions.CJK.EastAsianLineBreaksStyle == "css3draft" { opts = append(opts, extension.WithEastAsianLineBreaks(extension.EastAsianLineBreaksCSS3Draft)) } else { opts = append(opts, extension.WithEastAsianLineBreaks()) } } if cfg.Extensions.CJK.EscapedSpace { opts = append(opts, extension.WithEscapedSpace()) } c := extension.NewCJK(opts...) extensions = append(extensions, c) } if cfg.Extensions.Passthrough.Enable { extensions = append(extensions, passthrough.New(cfg.Extensions.Passthrough)) } if pcfg.Conf.EnableEmoji() { extensions = append(extensions, emoji.Emoji) } if cfg.Parser.Attribute.Title { parserOptions = append(parserOptions, parser.WithAttribute()) } if cfg.Parser.Attribute.Block || cfg.Parser.AutoHeadingID || cfg.Parser.AutoDefinitionTermID { extensions = append(extensions, attributes.New(cfg.Parser)) } md := goldmark.New( goldmark.WithExtensions( extensions..., ), goldmark.WithParserOptions( parserOptions..., ), goldmark.WithRendererOptions( rendererOptions..., ), ) return md } type parserResult struct { doc any toc *tableofcontents.Fragments } func (p parserResult) Doc() any { return p.doc } func (p parserResult) TableOfContents() *tableofcontents.Fragments { return p.toc } type renderResult struct { converter.ResultRender } type converterResult struct { converter.ResultRender tableOfContentsProvider } type tableOfContentsProvider interface { TableOfContents() *tableofcontents.Fragments } func (c *goldmarkConverter) Parse(ctx converter.RenderContext) (converter.ResultParse, error) { pctx := c.newParserContext(ctx) reader := text.NewReader(ctx.Src) doc := c.md.Parser().Parse( reader, parser.WithContext(pctx), ) doc.OwnerDocument().AddMeta("documentID", c.ctx.DocumentID) return parserResult{ doc: doc, toc: pctx.TableOfContents(), }, nil } func (c *goldmarkConverter) Render(ctx converter.RenderContext, doc any) (converter.ResultRender, error) { n := doc.(ast.Node) buf := &render.BufWriter{Buffer: &bytes.Buffer{}} rcx := &render.RenderContextDataHolder{ Rctx: ctx, Dctx: c.ctx, } w := &render.Context{ BufWriter: buf, ContextData: rcx, } if err := c.md.Renderer().Render(w, ctx.Src, n); err != nil { return nil, err } return renderResult{ ResultRender: buf, }, nil } func (c *goldmarkConverter) Convert(ctx converter.RenderContext) (converter.ResultRender, error) { parseResult, err := c.Parse(ctx) if err != nil { return nil, err } renderResult, err := c.Render(ctx, parseResult.Doc()) if err != nil { return nil, err } return converterResult{ ResultRender: renderResult, tableOfContentsProvider: parseResult, }, nil } func (c *goldmarkConverter) newParserContext(rctx converter.RenderContext) *parserContext { ctx := parser.NewContext(parser.WithIDs(newIDFactory(c.cfg.MarkupConfig().Goldmark.Parser.AutoIDType))) ctx.Set(tocEnableKey, rctx.RenderTOC) return &parserContext{ Context: ctx, } } type parserContext struct { parser.Context } func (p *parserContext) TableOfContents() *tableofcontents.Fragments { if v := p.Get(tocResultKey); v != nil { return v.(*tableofcontents.Fragments) } return nil } // Note: It's tempting to put this in the config package, but that doesn't work. // TODO(bep) create upstream issue. func toTypographicPunctuationMap(t goldmark_config.Typographer) map[extension.TypographicPunctuation][]byte { return map[extension.TypographicPunctuation][]byte{ extension.LeftSingleQuote: []byte(t.LeftSingleQuote), extension.RightSingleQuote: []byte(t.RightSingleQuote), extension.LeftDoubleQuote: []byte(t.LeftDoubleQuote), extension.RightDoubleQuote: []byte(t.RightDoubleQuote), extension.EnDash: []byte(t.EnDash), extension.EmDash: []byte(t.EmDash), extension.Ellipsis: []byte(t.Ellipsis), extension.LeftAngleQuote: []byte(t.LeftAngleQuote), extension.RightAngleQuote: []byte(t.RightAngleQuote), extension.Apostrophe: []byte(t.Apostrophe), } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/autoid.go
markup/goldmark/autoid.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package goldmark import ( "bytes" "strconv" "unicode" "unicode/utf8" "github.com/gohugoio/hugo/markup/blackfriday" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/common/text" "github.com/yuin/goldmark/ast" east "github.com/yuin/goldmark/extension/ast" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/util" bp "github.com/gohugoio/hugo/bufferpool" ) func sanitizeAnchorNameString(s string, idType string) string { return string(sanitizeAnchorName([]byte(s), idType)) } func sanitizeAnchorName(b []byte, idType string) []byte { return sanitizeAnchorNameWithHook(b, idType, nil) } func sanitizeAnchorNameWithHook(b []byte, idType string, hook func(buf *bytes.Buffer)) []byte { buf := bp.GetBuffer() if idType == goldmark_config.AutoIDTypeBlackfriday { // TODO(bep) make it more efficient. buf.WriteString(blackfriday.SanitizedAnchorName(string(b))) } else { asciiOnly := idType == goldmark_config.AutoIDTypeGitHubAscii if asciiOnly { // Normalize it to preserve accents if possible. b = text.RemoveAccents(b) } b = bytes.TrimSpace(b) for len(b) > 0 { r, size := utf8.DecodeRune(b) switch { case asciiOnly && size != 1: case r == '-' || r == ' ': buf.WriteRune('-') case isAlphaNumeric(r): buf.WriteRune(unicode.ToLower(r)) default: } b = b[size:] } } if hook != nil { hook(buf) } result := make([]byte, buf.Len()) copy(result, buf.Bytes()) bp.PutBuffer(buf) return result } func isAlphaNumeric(r rune) bool { return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) } var _ parser.IDs = (*idFactory)(nil) type idFactory struct { idType string vals map[string]struct{} duplicates []string } func newIDFactory(idType string) *idFactory { return &idFactory{ vals: make(map[string]struct{}), idType: idType, } } type stringValuesProvider interface { StringValues() []string } var _ stringValuesProvider = (*idFactory)(nil) func (ids *idFactory) StringValues() []string { values := make([]string, 0, len(ids.vals)) for k := range ids.vals { values = append(values, k) } values = append(values, ids.duplicates...) return values } func (ids *idFactory) Generate(value []byte, kind ast.NodeKind) []byte { return sanitizeAnchorNameWithHook(value, ids.idType, func(buf *bytes.Buffer) { if buf.Len() == 0 { if kind == ast.KindHeading { buf.WriteString("heading") } else if kind == east.KindDefinitionTerm { buf.WriteString("term") } else { buf.WriteString("id") } } if _, found := ids.vals[util.BytesToReadOnlyString(buf.Bytes())]; found { // Append a hyphen and a number, starting with 1. buf.WriteRune('-') pos := buf.Len() for i := 1; ; i++ { buf.WriteString(strconv.Itoa(i)) if _, found := ids.vals[util.BytesToReadOnlyString(buf.Bytes())]; !found { break } buf.Truncate(pos) } } ids.put(buf.String()) }) } func (ids *idFactory) put(s string) { if _, found := ids.vals[s]; found { ids.duplicates = append(ids.duplicates, s) } else { ids.vals[s] = struct{}{} } } func (ids *idFactory) Put(value []byte) { ids.put(string(value)) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/goldmark_integration_test.go
markup/goldmark/goldmark_integration_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package goldmark_test import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) // Issue 9463 func TestAttributeExclusion(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- ## Heading {class="a" onclick="alert('heading')"} > Blockquote {class="b" ondblclick="alert('blockquote')"} ~~~bash {id="c" onmouseover="alert('code fence')" LINENOS=true} foo ~~~ -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` <h2 class="a" id="heading"> <blockquote class="b"> <div class="highlight" id="c"> `) } // Issue 9511 func TestAttributeExclusionWithRenderHook(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading {onclick="alert('renderhook')" data-foo="bar"} -- layouts/single.html -- {{ .Content }} -- layouts/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text }}</h{{ .Level }}> ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` <h2 data-foo="bar" id="heading">Heading</h2> `) } func TestAttributesDefaultRenderer(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="a < b" } -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` class="a &lt; b" `) } // Issue 9558. func TestAttributesHookNoEscape(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- ## Heading Attribute Which Needs Escaping { class="Smith & Wesson" } -- layouts/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` plain: |class: Smith &amp; Wesson|id: heading-attribute-which-needs-escaping| safeHTML: |class: Smith & Wesson|id: heading-attribute-which-needs-escaping| `) } // Issue 9504 func TestLinkInTitle(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/single.html -- {{ .Content }} -- layouts/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text }}</a> ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-test\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-test\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Code Fences §§§bash LINE1 §§§ ## Code Fences No Lexer §§§moo LINE1 §§§ ## Code Fences Simple Attributes §§A§bash { .myclass id="myid" } LINE1 §§A§ ## Code Fences Line Numbers §§§bash {linenos=table,hl_lines=[8,"15-17"],linenostart=199} LINE1 LINE2 LINE3 LINE4 LINE5 LINE6 LINE7 LINE8 §§§ ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"cl\">LINE1\n</span></span></code></pre></div>", "Code Fences No Lexer</h2>\n<pre tabindex=\"0\"><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>", "lnt", ) } func BenchmarkRenderHooks(b *testing.B) { files := ` -- hugo.toml -- -- layouts/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text }}</a> -- layouts/single.html -- {{ .Content }} ` content := ` ## Hello1 [Test](https://example.com) A. ## Hello2 [Test](https://example.com) B. ## Hello3 [Test](https://example.com) C. ## Hello4 [Test](https://example.com) D. [Test](https://example.com) ## Hello5 ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } for b.Loop() { b.StopTimer() bb := hugolib.NewIntegrationTestBuilder(cfg) b.StartTimer() bb.Build() } } func BenchmarkCodeblocks(b *testing.B) { filesTemplate := ` -- hugo.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = true style = 'monokai' tabWidth = 4 -- layouts/single.html -- {{ .Content }} ` content := ` FENCEgo package main import "fmt" func main() { fmt.Println("hello world") } FENCE FENCEunknownlexer hello FENCE ` content = strings.ReplaceAll(content, "FENCE", "```") for i := 1; i < 100; i++ { filesTemplate += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } runBenchmark := func(files string, b *testing.B) { cfg := hugolib.IntegrationTestConfig{ T: b, TxtarString: files, } for b.Loop() { b.StopTimer() bb := hugolib.NewIntegrationTestBuilder(cfg) b.StartTimer() bb.Build() } } b.Run("Default", func(b *testing.B) { runBenchmark(filesTemplate, b) }) b.Run("Hook no higlight", func(b *testing.B) { files := filesTemplate + ` -- layouts/_markup/render-codeblock.html -- {{ .Inner }} ` runBenchmark(files, b) }) } // Iisse #8959 func TestHookInfiniteRecursion(t *testing.T) { t.Parallel() for _, renderFunc := range []string{"markdownify", ".Page.RenderString"} { t.Run(renderFunc, func(t *testing.T) { files := ` -- hugo.toml -- -- layouts/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | RENDERFUNC }}</a> -- layouts/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- https://example.org a@b.com ` files = strings.ReplaceAll(files, "RENDERFUNC", renderFunc) b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "text is already rendered, repeating it may cause infinite recursion") }) } } // Issue 9594 func TestQuotesInImgAltAttr(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` <img src="b.jpg" alt="&quot;a&quot;"> `) } func TestLinkifyProtocol(t *testing.T) { t.Parallel() runTest := func(protocol string, withHook bool) *hugolib.IntegrationTestBuilder { files := ` -- hugo.toml -- [markup.goldmark] [markup.goldmark.extensions] linkify = true linkifyProtocol = "PROTOCOL" -- content/p1.md -- --- title: "p1" --- Link no procol: www.example.org Link http procol: http://www.example.org Link https procol: https://www.example.org -- layouts/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text }}</a>` } return hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() } for _, withHook := range []bool{false, true} { b := runTest("https", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"https://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("http", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"http://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) b = runTest("gopher", withHook) b.AssertFileContent("public/p1/index.html", "Link no procol: <a href=\"gopher://www.example.org\">www.example.org</a>", "Link http procol: <a href=\"http://www.example.org\">http://www.example.org</a>", "Link https procol: <a href=\"https://www.example.org\">https://www.example.org</a></p>", ) } } func TestGoldmarkBugs(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.renderer] unsafe = true -- content/p1.md -- --- title: "p1" --- ## Issue 9650 a <!-- b --> c ## Issue 9658 - This is a list item <!-- Comment: an innocent-looking comment --> -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContentExact("public/p1/index.html", // Issue 9650 "<p>a <!-- b --> c</p>", // Issue 9658 (crash) "<li>This is a list item <!-- Comment: an innocent-looking comment --></li>", ) } // Issue 13286 func TestImageAltApostrophesWithTypographer(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.extensions.typographer] disable = false [markup.goldmark.renderHooks.image] enableDefault = true -- content/p1.md -- --- title: "p1" --- ## Image ![A's is > than B's](some-image.png) -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContentExact("public/p1/index.html", // Note that this markup is slightly different than the one produced by the default Goldmark renderer, // see issue 13292. "alt=\"A’s is &gt; than B’s\">", ) } // Issue #7332 // Issue #11587 func TestGoldmarkEmojiExtension(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- enableEmoji = true -- content/p1.md -- --- title: "p1" --- ~~~text :x: ~~~ {{% include "/p2" %}} {{< sc1 >}}:smiley:{{< /sc1 >}} {{< sc2 >}}:+1:{{< /sc2 >}} {{% sc3 %}}:-1:{{% /sc3 %}} -- content/p2.md -- --- title: "p2" --- :heavy_check_mark: -- layouts/_shortcodes/include.html -- {{ $p := site.GetPage (.Get 0) }} {{ $p.RenderShortcodes }} -- layouts/_shortcodes/sc1.html -- sc1_begin|{{ .Inner }}|sc1_end -- layouts/_shortcodes/sc2.html -- sc2_begin|{{ .Inner | .Page.RenderString }}|sc2_end -- layouts/_shortcodes/sc3.html -- sc3_begin|{{ .Inner }}|sc3_end -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContentExact("public/p1/index.html", // Issue #7332 "<span>:x:\n</span>", // Issue #11587 "<p>&#x2714;&#xfe0f;</p>", // Should not be converted to emoji "sc1_begin|:smiley:|sc1_end", // Should be converted to emoji "sc2_begin|&#x1f44d;|sc2_end", // Should be converted to emoji "sc3_begin|&#x1f44e;|sc3_end", ) } func TestEmojiDisabled(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- enableEmoji = false -- content/p1.md -- --- title: "p1" --- :x: -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContentExact("public/p1/index.html", "<p>:x:</p>") } func TestEmojiDefaultConfig(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- :x: -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContentExact("public/p1/index.html", "<p>:x:</p>") } // Issue #5748 func TestGoldmarkTemplateDelims(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [minify] minifyOutput = true [minify.tdewolff.html] templateDelims = ["<?php","?>"] -- layouts/home.html -- <div class="foo"> {{ safeHTML "<?php" }} echo "hello"; {{ safeHTML "?>" }} </div> ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "<div class=foo><?php\necho \"hello\";\n?>\n</div>") } // Issue #10894 func TestPassthroughInlineFences(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.extensions.passthrough] enable = true [markup.goldmark.extensions.passthrough.delimiters] inline = [['$', '$'], ['\(', '\)']] -- content/p1.md -- --- title: "p1" --- ## LaTeX test Inline equation that would be mangled by default parser: $a^*=x-b^*$ -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` $a^*=x-b^*$ `) } func TestPassthroughBlockFences(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.extensions.passthrough] enable = true [markup.goldmark.extensions.passthrough.delimiters] block = [['$$', '$$']] -- content/p1.md -- --- title: "p1" --- ## LaTeX test Block equation that would be mangled by default parser: $$a^*=x-b^*$$ -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` $$a^*=x-b^*$$ `) } func TestPassthroughWithAlternativeFences(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.extensions.passthrough] enable = true [markup.goldmark.extensions.passthrough.delimiters] inline = [['(((', ')))']] block = [['%!%', '%!%']] -- content/p1.md -- --- title: "p1" --- ## LaTeX test Inline equation that would be mangled by default parser: (((a^*=x-b^*))) Inline equation that should be mangled by default parser: $a^*=x-b^*$ Block equation that would be mangled by default parser: %!% a^*=x-b^* %!% -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` (((a^*=x-b^*))) `) b.AssertFileContent("public/p1/index.html", ` $a^<em>=x-b^</em>$ `) b.AssertFileContent("public/p1/index.html", ` %!% a^*=x-b^* %!% `) } func TestExtrasExtension(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] [markup.goldmark.extensions] strikethrough = false [markup.goldmark.extensions.extras.delete] enable = false [markup.goldmark.extensions.extras.insert] enable = false [markup.goldmark.extensions.extras.mark] enable = false [markup.goldmark.extensions.extras.subscript] enable = false [markup.goldmark.extensions.extras.superscript] enable = false -- layouts/home.html -- {{ .Content }} -- content/_index.md -- --- title: home --- ~~delete~~ ++insert++ ==mark== H~2~0 1^st^ ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "<p>~~delete~~</p>", "<p>++insert++</p>", "<p>==mark==</p>", "<p>H~2~0</p>", "<p>1^st^</p>", ) files = strings.ReplaceAll(files, "enable = false", "enable = true") b = hugolib.Test(t, files) b.AssertFileContent("public/index.html", "<p><del>delete</del></p>", "<p><ins>insert</ins></p>", "<p><mark>mark</mark></p>", "<p>H<sub>2</sub>0</p>", "<p>1<sup>st</sup></p>", ) } // Issue 12997. func TestGoldmarkRawHTMLWarningBlocks(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] markup.goldmark.renderer.unsafe = false -- content/p1.md -- --- title: "p1" --- <div>Some raw HTML</div> -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files, hugolib.TestOptWarn()) b.AssertFileContent("public/p1/index.html", "<!-- raw HTML omitted -->") b.AssertLogContains("WARN Raw HTML omitted while rendering \"/content/p1.md\"; see https://gohugo.io/getting-started/configuration-markup/#rendererunsafe\nYou can suppress this warning by adding the following to your site configuration:\nignoreLogs = ['warning-goldmark-raw-html']") b = hugolib.Test(t, strings.ReplaceAll(files, "markup.goldmark.renderer.unsafe = false", "markup.goldmark.renderer.unsafe = true"), hugolib.TestOptWarn()) b.AssertFileContent("public/p1/index.html", "! <!-- raw HTML omitted -->") b.AssertLogContains("! WARN") } func TestGoldmarkRawHTMLWarningInline(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] markup.goldmark.renderer.unsafe = false -- content/p1.md -- --- title: "p1" --- <em>raw HTML</em> -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files, hugolib.TestOptWarn()) b.AssertFileContent("public/p1/index.html", "<!-- raw HTML omitted -->") b.AssertLogContains("WARN Raw HTML omitted while rendering \"/content/p1.md\"; see https://gohugo.io/getting-started/configuration-markup/#rendererunsafe\nYou can suppress this warning by adding the following to your site configuration:\nignoreLogs = ['warning-goldmark-raw-html']") b = hugolib.Test(t, strings.ReplaceAll(files, "markup.goldmark.renderer.unsafe = false", "markup.goldmark.renderer.unsafe = true"), hugolib.TestOptWarn()) b.AssertFileContent("public/p1/index.html", "! <!-- raw HTML omitted -->") b.AssertLogContains("! WARN") } // See https://github.com/gohugoio/hugo/issues/13278#issuecomment-2603280548 func TestGoldmarkRawHTMLCommentNoWarning(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] markup.goldmark.renderer.unsafe = false -- content/p1.md -- --- title: "p1" --- # HTML comments ## Simple <!-- This is a comment --> <!-- This is a comment indented --> **Hello**<!-- This is a comment indented with markup surrounding. -->_world_. ## With HTML <!-- <p>This is another paragraph </p> --> ## With HTML and JS <!-- <script>alert('hello');</script> --> ## With Block <!-- <p>Look at this cool image:</p> <img border="0" src="pic_trulli.jpg" alt="Trulli"> --> ## XSS <!-- --><script>alert("I just escaped the HTML comment")</script><!-- --> ## More This is a <!--hidden--> word. This is a <!-- hidden--> word. This is a <!-- hidden --> word. This is a <!-- hidden --> word. This is a <!-- hidden --> word. -- layouts/single.html -- {{ .Content }} ` b := hugolib.Test(t, files, hugolib.TestOptWarn()) b.AssertFileContent("public/p1/index.html", "! <!-- raw HTML omitted -->", "! <!-- hidden -->", "! <!-- This is a comment -->", "! script", ) b.AssertLogContains("! WARN") b = hugolib.Test(t, strings.ReplaceAll(files, "markup.goldmark.renderer.unsafe = false", "markup.goldmark.renderer.unsafe = true"), hugolib.TestOptWarn()) b.AssertFileContent("public/p1/index.html", "! <!-- raw HTML omitted -->", "<!-- hidden -->", "<!-- This is a comment -->", ) b.AssertLogContains("! WARN") } func TestFootnoteExtension(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] [markup.goldmark.extensions.footnote] enable = false enableAutoIDPrefix = false TBD = 'back' -- layouts/all.html -- {{ .Content }} -- content/p1.md -- --- title: p1 --- foo[^1] and bar[^2] [^1]: footnote one [^2]: footnote two -- content/p2.md -- --- title: p2 --- foo[^1] and bar[^2] [^1]: footnote one [^2]: footnote two -- content/_content.gotmpl -- {{ range slice 3 4 }} {{ $page := dict "content" (dict "mediaType" "text/markdown" "value" "foo[^1] and bar[^2]\n\n[^1]: footnote one\n[^2]: footnote two") "path" (printf "p%d" .) "title" (printf "p%d" .) }} {{ $.AddPage $page }} {{ end }} ` // test enableAutoIDPrefix want := "<p>foo[^1] and bar[^2]</p>\n<p>[^1]: footnote one\n[^2]: footnote two</p>" b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", want) b.AssertFileContent("public/p2/index.html", want) b.AssertFileContent("public/p3/index.html", want) b.AssertFileContent("public/p4/index.html", want) files = strings.ReplaceAll(files, "enable = false", "enable = true") want = "<p>foo<sup id=\"fnref:1\"><a href=\"#fn:1\" class=\"footnote-ref\" role=\"doc-noteref\">1</a></sup> and bar<sup id=\"fnref:2\"><a href=\"#fn:2\" class=\"footnote-ref\" role=\"doc-noteref\">2</a></sup></p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n<hr>\n<ol>\n<li id=\"fn:1\">\n<p>footnote one&#160;<a href=\"#fnref:1\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n<li id=\"fn:2\">\n<p>footnote two&#160;<a href=\"#fnref:2\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n</ol>\n</div>" b = hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", want) b.AssertFileContent("public/p2/index.html", want) b.AssertFileContent("public/p3/index.html", want) b.AssertFileContent("public/p4/index.html", want) files = strings.ReplaceAll(files, "enableAutoIDPrefix = false", "enableAutoIDPrefix = true") b = hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "<p>foo<sup id=\"hb5cdcabc9e678612fnref:1\"><a href=\"#hb5cdcabc9e678612fn:1\" class=\"footnote-ref\" role=\"doc-noteref\">1</a></sup> and bar<sup id=\"hb5cdcabc9e678612fnref:2\"><a href=\"#hb5cdcabc9e678612fn:2\" class=\"footnote-ref\" role=\"doc-noteref\">2</a></sup></p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n<hr>\n<ol>\n<li id=\"hb5cdcabc9e678612fn:1\">\n<p>footnote one&#160;<a href=\"#hb5cdcabc9e678612fnref:1\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n<li id=\"hb5cdcabc9e678612fn:2\">\n<p>footnote two&#160;<a href=\"#hb5cdcabc9e678612fnref:2\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n</ol>\n</div>", ) b.AssertFileContent("public/p2/index.html", "<p>foo<sup id=\"h58e8265a0c07b195fnref:1\"><a href=\"#h58e8265a0c07b195fn:1\" class=\"footnote-ref\" role=\"doc-noteref\">1</a></sup> and bar<sup id=\"h58e8265a0c07b195fnref:2\"><a href=\"#h58e8265a0c07b195fn:2\" class=\"footnote-ref\" role=\"doc-noteref\">2</a></sup></p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n<hr>\n<ol>\n<li id=\"h58e8265a0c07b195fn:1\">\n<p>footnote one&#160;<a href=\"#h58e8265a0c07b195fnref:1\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n<li id=\"h58e8265a0c07b195fn:2\">\n<p>footnote two&#160;<a href=\"#h58e8265a0c07b195fnref:2\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n</ol>\n</div>", ) b.AssertFileContent("public/p3/index.html", "<p>foo<sup id=\"h0aab769290d7e233fnref:1\"><a href=\"#h0aab769290d7e233fn:1\" class=\"footnote-ref\" role=\"doc-noteref\">1</a></sup> and bar<sup id=\"h0aab769290d7e233fnref:2\"><a href=\"#h0aab769290d7e233fn:2\" class=\"footnote-ref\" role=\"doc-noteref\">2</a></sup></p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n<hr>\n<ol>\n<li id=\"h0aab769290d7e233fn:1\">\n<p>footnote one&#160;<a href=\"#h0aab769290d7e233fnref:1\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n<li id=\"h0aab769290d7e233fn:2\">\n<p>footnote two&#160;<a href=\"#h0aab769290d7e233fnref:2\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n</ol>\n</div>", ) b.AssertFileContent("public/p4/index.html", "<p>foo<sup id=\"ha35b794ad6e8626cfnref:1\"><a href=\"#ha35b794ad6e8626cfn:1\" class=\"footnote-ref\" role=\"doc-noteref\">1</a></sup> and bar<sup id=\"ha35b794ad6e8626cfnref:2\"><a href=\"#ha35b794ad6e8626cfn:2\" class=\"footnote-ref\" role=\"doc-noteref\">2</a></sup></p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n<hr>\n<ol>\n<li id=\"ha35b794ad6e8626cfn:1\">\n<p>footnote one&#160;<a href=\"#ha35b794ad6e8626cfnref:1\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n<li id=\"ha35b794ad6e8626cfn:2\">\n<p>footnote two&#160;<a href=\"#ha35b794ad6e8626cfnref:2\" class=\"footnote-backref\" role=\"doc-backlink\">&#x21a9;&#xfe0e;</a></p>\n</li>\n</ol>\n</div>", ) // test backlinkHTML files = strings.ReplaceAll(files, "TBD", "backlinkHTML") b = hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "<p>foo<sup id=\"hb5cdcabc9e678612fnref:1\"><a href=\"#hb5cdcabc9e678612fn:1\" class=\"footnote-ref\" role=\"doc-noteref\">1</a></sup> and bar<sup id=\"hb5cdcabc9e678612fnref:2\"><a href=\"#hb5cdcabc9e678612fn:2\" class=\"footnote-ref\" role=\"doc-noteref\">2</a></sup></p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n<hr>\n<ol>\n<li id=\"hb5cdcabc9e678612fn:1\">\n<p>footnote one&#160;<a href=\"#hb5cdcabc9e678612fnref:1\" class=\"footnote-backref\" role=\"doc-backlink\">back</a></p>\n</li>\n<li id=\"hb5cdcabc9e678612fn:2\">\n<p>footnote two&#160;<a href=\"#hb5cdcabc9e678612fnref:2\" class=\"footnote-backref\" role=\"doc-backlink\">back</a></p>\n</li>\n</ol>\n</div>", ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/toc.go
markup/goldmark/toc.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package goldmark import ( "bytes" "regexp" "strings" "github.com/microcosm-cc/bluemonday" strikethroughAst "github.com/yuin/goldmark/extension/ast" emojiAst "github.com/yuin/goldmark-emoji/ast" "github.com/gohugoio/hugo-goldmark-extensions/extras" "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/renderer" "github.com/yuin/goldmark/text" "github.com/yuin/goldmark/util" ) var ( tocResultKey = parser.NewContextKey() tocEnableKey = parser.NewContextKey() ) type tocTransformer struct { r renderer.Renderer } func (t *tocTransformer) Transform(n *ast.Document, reader text.Reader, pc parser.Context) { if b, ok := pc.Get(tocEnableKey).(bool); !ok || !b { return } var ( toc tableofcontents.Builder tocHeading = &tableofcontents.Heading{} level int row = -1 inHeading bool headingText bytes.Buffer ) if ids := pc.IDs().(stringValuesProvider).StringValues(); len(ids) > 0 { toc.SetIdentifiers(ids) } ast.Walk(n, func(n ast.Node, entering bool) (ast.WalkStatus, error) { s := ast.WalkStatus(ast.WalkContinue) if n.Kind() == ast.KindHeading { if inHeading && !entering { tocHeading.Title = sanitizeTOCHeadingTitle(headingText.String()) headingText.Reset() toc.AddAt(tocHeading, row, level-1) tocHeading = &tableofcontents.Heading{} inHeading = false return s, nil } inHeading = true } if !(inHeading && entering) { return s, nil } switch n.Kind() { case ast.KindHeading: heading := n.(*ast.Heading) level = heading.Level if level == 1 || row == -1 { row++ } id, found := heading.AttributeString("id") if found { tocHeading.ID = string(id.([]byte)) tocHeading.Level = level } case ast.KindCodeSpan, ast.KindLink, ast.KindImage, ast.KindEmphasis, strikethroughAst.KindStrikethrough, emojiAst.KindEmoji, extras.KindDelete, extras.KindInsert, extras.KindMark, extras.KindSubscript, extras.KindSuperscript: err := t.r.Render(&headingText, reader.Source(), n) if err != nil { return s, err } return ast.WalkSkipChildren, nil case ast.KindAutoLink, ast.KindRawHTML, ast.KindText, ast.KindString: err := t.r.Render(&headingText, reader.Source(), n) if err != nil { return s, err } } return s, nil }) pc.Set(tocResultKey, toc.Build()) } type tocExtension struct { options []renderer.Option } func newTocExtension(options []renderer.Option) goldmark.Extender { return &tocExtension{ options: options, } } func (e *tocExtension) Extend(m goldmark.Markdown) { r := goldmark.DefaultRenderer() r.AddOptions(e.options...) m.Parser().AddOptions(parser.WithASTTransformers(util.Prioritized(&tocTransformer{ r: r, }, // This must run after the ID generation (priority 100). 110))) } var tocSanitizerPolicy = newTOCSanitizerPolicy() // newTOCSanitizerPolicy returns a bluemonday policy for sanitizing TOC heading // titles against an allowlist of inline HTML elements and attributes, // specifically excluding anchor elements to prevent links within TOC heading // titles. func newTOCSanitizerPolicy() *bluemonday.Policy { p := bluemonday.NewPolicy() p.AllowElements( "abbr", "b", "bdi", "bdo", "br", "cite", "code", "data", "del", "dfn", "em", "i", "ins", "kbd", "mark", "q", "rp", "rt", "ruby", "s", "samp", "small", "span", "strong", "sub", "sup", "time", "u", "var", "wbr", ) p.AllowStandardAttributes() p.AllowStyling() p.AllowImages() p.AllowAttrs("cite").OnElements("del", "ins", "q") p.AllowAttrs("datetime").OnElements("del", "ins", "time") p.AllowAttrs("value").OnElements("data") return p } var whiteSpaceRe = regexp.MustCompile(`\s+`) // sanitizeTOCHeadingTitle sanitizes s for use as a TOC heading title. func sanitizeTOCHeadingTitle(s string) string { if strings.IndexByte(s, '<') == -1 { return s } // Sanitize the string. ss := tocSanitizerPolicy.Sanitize(s) // Remove extraneous whitespace. return whiteSpaceRe.ReplaceAllString(strings.TrimSpace(ss), " ") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/toc_integration_test.go
markup/goldmark/toc_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package goldmark_test import ( "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) func TestTableOfContents(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] enableEmoji = false [markup.tableOfContents] startLevel = 2 endLevel = 4 ordered = false [markup.goldmark.extensions] strikethrough = false [markup.goldmark.extensions.typographer] disable = true [markup.goldmark.parser] autoHeadingID = false autoHeadingIDType = 'github' [markup.goldmark.renderer] unsafe = false xhtml = false -- layouts/single.html -- {{ .TableOfContents }} -- content/p1.md -- --- title: p1 (basic) --- # Title ## Section 1 ### Section 1.1 ### Section 1.2 #### Section 1.2.1 ##### Section 1.2.1.1 -- content/p2.md -- --- title: p2 (markdown) --- ## Some *emphasized* text ## Some ` + "`" + `inline` + "`" + ` code ## Something to escape A < B && C > B --- -- content/p3.md -- --- title: p3 (image) --- ## An image ![kitten](a.jpg) -- content/p4.md -- --- title: p4 (raw html) --- ## Some <span>raw</span> HTML -- content/p5.md -- --- title: p5 (typographer) --- ## Some "typographer" markup -- content/p6.md -- --- title: p6 (strikethrough) --- ## Some ~~deleted~~ text -- content/p7.md -- --- title: p7 (emoji) --- ## A :snake: emoji -- content/p8.md -- --- title: p8 (link) --- ## A [link](https://example.org) ` b := hugolib.Test(t, files) // basic b.AssertFileContentExact("public/p1/index.html", `<nav id="TableOfContents"> <ul> <li><a href="#">Section 1</a> <ul> <li><a href="#">Section 1.1</a></li> <li><a href="#">Section 1.2</a> <ul> <li><a href="#">Section 1.2.1</a></li> </ul> </li> </ul> </li> </ul> </nav>`) // markdown b.AssertFileContent("public/p2/index.html", `<li><a href="#">Some <em>emphasized</em> text</a></li>`, `<li><a href="#">Some <code>inline</code> code</a></li>`, `<li><a href="#">Something to escape A &lt; B &amp;&amp; C &gt; B</a></li>`, ) // image b.AssertFileContent("public/p3/index.html", `<li><a href="#">An image <img src="a.jpg" alt="kitten"></a></li>`, ) // raw html b.AssertFileContent("public/p4/index.html", `<li><a href="#">Some raw HTML</a></li>`, ) // typographer b.AssertFileContent("public/p5/index.html", `<li><a href="#">Some &quot;typographer&quot; markup</a></li>`, ) // strikethrough b.AssertFileContent("public/p6/index.html", `<li><a href="#">Some ~~deleted~~ text</a></li>`, ) // emoji b.AssertFileContent("public/p7/index.html", `<li><a href="#">A :snake: emoji</a></li>`, ) // link b.AssertFileContent("public/p8/index.html", `<li><a href="#">A link</a></li>`, ) } func TestTableOfContentsAdvanced(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] enableEmoji = true [markup.tableOfContents] startLevel = 2 endLevel = 3 ordered = true [markup.goldmark.extensions] strikethrough = true [markup.goldmark.extensions.typographer] disable = false [markup.goldmark.parser] autoHeadingID = true autoHeadingIDType = 'github' [markup.goldmark.renderer] unsafe = true xhtml = true -- layouts/single.html -- {{ .TableOfContents }} -- content/p1.md -- --- title: p1 (basic) --- # Title ## Section 1 ### Section 1.1 ### Section 1.2 #### Section 1.2.1 ##### Section 1.2.1.1 -- content/p2.md -- --- title: p2 (markdown) --- ## Some *emphasized* text ## Some ` + "`" + `inline` + "`" + ` code ## Something to escape A < B && C > B --- -- content/p3.md -- --- title: p3 (image) --- ## An image ![kitten](a.jpg) -- content/p4.md -- --- title: p4 (raw html) --- ## Some <span>raw</span> HTML -- content/p5.md -- --- title: p5 (typographer) --- ## Some "typographer" markup -- content/p6.md -- --- title: p6 (strikethrough) --- ## Some ~~deleted~~ text -- content/p7.md -- --- title: p7 (emoji) --- ## A :snake: emoji -- content/p8.md -- --- title: p8 (link) --- ## A [link](https://example.org) ` b := hugolib.Test(t, files) // basic b.AssertFileContentExact("public/p1/index.html", `<nav id="TableOfContents"> <ol> <li><a href="#section-1">Section 1</a> <ol> <li><a href="#section-11">Section 1.1</a></li> <li><a href="#section-12">Section 1.2</a></li> </ol> </li> </ol> </nav>`) // markdown b.AssertFileContent("public/p2/index.html", `<li><a href="#some-emphasized-text">Some <em>emphasized</em> text</a></li>`, `<li><a href="#some-inline-code">Some <code>inline</code> code</a></li>`, `<li><a href="#something-to-escape-a--b--c--b">Something to escape A &lt; B &amp;&amp; C &gt; B</a></li>`, ) // image b.AssertFileContent("public/p3/index.html", `<li><a href="#an-image-kitten">An image <img src="a.jpg" alt="kitten"/></a></li>`, ) // raw html b.AssertFileContent("public/p4/index.html", `<li><a href="#some-raw-html">Some <span>raw</span> HTML</a></li>`, ) // typographer b.AssertFileContent("public/p5/index.html", `<li><a href="#some-typographer-markup">Some &ldquo;typographer&rdquo; markup</a></li>`, ) // strikethrough b.AssertFileContent("public/p6/index.html", `<li><a href="#some-deleted-text">Some <del>deleted</del> text</a></li>`, ) // emoji b.AssertFileContent("public/p7/index.html", `<li><a href="#a-snake-emoji">A &#x1f40d; emoji</a></li>`, ) // link b.AssertFileContent("public/p8/index.html", `<li><a href="#a-link">A link</a></li>`, ) } func TestIssue13416(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- Content:{{ .Content }}| -- layouts/_markup/render-heading.html -- -- content/_index.md -- --- title: home --- # ` b := hugolib.Test(t, files) b.AssertFileExists("public/index.html", true) } // Issue 12605 func TestTableOfContentsWithGoldmarkExtras(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] [markup.goldmark.extensions] strikethrough = false [markup.goldmark.extensions.extras.delete] enable = true [markup.goldmark.extensions.extras.insert] enable = true [markup.goldmark.extensions.extras.mark] enable = true [markup.goldmark.extensions.extras.subscript] enable = true [markup.goldmark.extensions.extras.superscript] enable = true -- content/_index.md -- --- title: home --- ## ~~deleted~~ ## ++inserted++ ## ==marked== ## H~2~O ## 1^st^ -- layouts/home.html -- {{ .TableOfContents }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", `<li><a href="#deleted"><del>deleted</del></a></li>`, `<li><a href="#inserted"><ins>inserted</ins></a></li>`, `<li><a href="#marked"><mark>marked</mark></a></li>`, `<li><a href="#h2o">H<sub>2</sub>O</a></li>`, `<li><a href="#1st">1<sup>st</sup></a></li>`, ) files = strings.ReplaceAll(files, "enable = true", "enable = false") b = hugolib.Test(t, files) b.AssertFileContent("public/index.html", `<li><a href="#deleted">~~deleted~~</a></li>`, `<li><a href="#inserted">++inserted++</a></li>`, `<li><a href="#marked">==marked==</a></li>`, `<li><a href="#h2o">H~2~O</a></li>`, `<li><a href="#1st">1^st^</a></li>`, ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/passthrough/passthrough_integration_test.go
markup/goldmark/passthrough/passthrough_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package passthrough_test import ( "testing" "github.com/gohugoio/hugo/hugolib" ) func TestPassthroughRenderHook(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.extensions.passthrough] enable = true [markup.goldmark.extensions.passthrough.delimiters] block = [['$$', '$$']] inline = [['$', '$']] -- content/p1.md -- --- title: "p1" --- ## LaTeX test Some inline LaTeX 1: $a^*=x-b^*$. Block equation that would be mangled by default parser: $$a^*=x-b^*$$ Some inline LaTeX 2: $a^*=x-b^*$. -- layouts/single.html -- {{ .Content }} -- layouts/_markup/render-passthrough-block.html -- Passthrough block: {{ .Inner | safeHTML }}|{{ .Type }}|{{ .Ordinal }}:END -- layouts/_markup/render-passthrough-inline.html -- Passthrough inline: {{ .Inner | safeHTML }}|{{ .Type }}|{{ .Ordinal }}:END ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` Some inline LaTeX 1: Passthrough inline: a^*=x-b^*|inline|0:END Passthrough block: a^*=x-b^*|block|1:END Some inline LaTeX 2: Passthrough inline: a^*=x-b^*|inline|2:END `) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/passthrough/passthrough.go
markup/goldmark/passthrough/passthrough.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package passthrough import ( "bytes" "github.com/gohugoio/hugo-goldmark-extensions/passthrough" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/goldmark/internal/render" "github.com/gohugoio/hugo/markup/internal/attributes" "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/renderer" "github.com/yuin/goldmark/util" ) func New(cfg goldmark_config.Passthrough) goldmark.Extender { if !cfg.Enable { return nil } return &passthroughExtension{cfg: cfg} } type ( passthroughExtension struct { cfg goldmark_config.Passthrough } htmlRenderer struct{} ) func (e *passthroughExtension) Extend(m goldmark.Markdown) { configuredInlines := e.cfg.Delimiters.Inline configuredBlocks := e.cfg.Delimiters.Block inlineDelimiters := make([]passthrough.Delimiters, len(configuredInlines)) blockDelimiters := make([]passthrough.Delimiters, len(configuredBlocks)) for i, d := range configuredInlines { inlineDelimiters[i] = passthrough.Delimiters{ Open: d[0], Close: d[1], } } for i, d := range configuredBlocks { blockDelimiters[i] = passthrough.Delimiters{ Open: d[0], Close: d[1], } } pse := passthrough.New( passthrough.Config{ InlineDelimiters: inlineDelimiters, BlockDelimiters: blockDelimiters, }, ) pse.Extend(m) // Set up render hooks if configured. // Upstream passthrough inline = 101 // Upstream passthrough block = 99 m.Renderer().AddOptions(renderer.WithNodeRenderers( util.Prioritized(newHTMLRenderer(), 90), )) } func newHTMLRenderer() renderer.NodeRenderer { r := &htmlRenderer{} return r } func (r *htmlRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) { reg.Register(passthrough.KindPassthroughBlock, r.renderPassthroughBlock) reg.Register(passthrough.KindPassthroughInline, r.renderPassthroughBlock) } func (r *htmlRenderer) renderPassthroughBlock(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { ctx := w.(*render.Context) if entering { return ast.WalkContinue, nil } var ( s string typ string delims *passthrough.Delimiters ) switch nn := node.(type) { case *passthrough.PassthroughInline: s = string(nn.Text(src)) typ = "inline" delims = nn.Delimiters case (*passthrough.PassthroughBlock): l := nn.Lines().Len() var buff bytes.Buffer for i := range l { line := nn.Lines().At(i) buff.Write(line.Value(src)) } s = buff.String() typ = "block" delims = nn.Delimiters } renderer := ctx.RenderContext().GetRenderer(hooks.PassthroughRendererType, typ) if renderer == nil { // Write the raw content if no renderer is found. ctx.WriteString(s) return ast.WalkContinue, nil } // Inline and block passthroughs share the same ordinal counter. ordinal := ctx.GetAndIncrementOrdinal(passthrough.KindPassthroughBlock) // Trim the delimiters. s = s[len(delims.Open) : len(s)-len(delims.Close)] pctx := &passthroughContext{ BaseContext: render.NewBaseContext(ctx, renderer, node, src, nil, ordinal), inner: s, typ: typ, AttributesHolder: attributes.New(node.Attributes(), attributes.AttributesOwnerGeneral), } pr := renderer.(hooks.PassthroughRenderer) if err := pr.RenderPassthrough(ctx.RenderContext().Ctx, w, pctx); err != nil { return ast.WalkStop, err } return ast.WalkContinue, nil } type passthroughContext struct { hooks.BaseContext typ string // inner or block inner string *attributes.AttributesHolder } func (p *passthroughContext) Type() string { return p.typ } func (p *passthroughContext) Inner() string { return p.inner }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/goldmark_config/config.go
markup/goldmark/goldmark_config/config.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package goldmark_config holds Goldmark related configuration. package goldmark_config const ( AutoIDTypeBlackfriday = "blackfriday" AutoIDTypeGitHub = "github" AutoIDTypeGitHubAscii = "github-ascii" RenderHookUseEmbeddedAlways = "always" RenderHookUseEmbeddedAuto = "auto" RenderHookUseEmbeddedFallback = "fallback" RenderHookUseEmbeddedNever = "never" ) // Default holds the default Goldmark configuration. var Default = Config{ Extensions: Extensions{ Typographer: Typographer{ Disable: false, LeftSingleQuote: "&lsquo;", RightSingleQuote: "&rsquo;", LeftDoubleQuote: "&ldquo;", RightDoubleQuote: "&rdquo;", EnDash: "&ndash;", EmDash: "&mdash;", Ellipsis: "&hellip;", LeftAngleQuote: "&laquo;", RightAngleQuote: "&raquo;", Apostrophe: "&rsquo;", }, Footnote: Footnote{ Enable: true, EnableAutoIDPrefix: false, BacklinkHTML: "&#x21a9;&#xfe0e;", }, DefinitionList: true, Table: true, Strikethrough: true, Linkify: true, LinkifyProtocol: "https", TaskList: true, CJK: CJK{ Enable: false, EastAsianLineBreaks: false, EastAsianLineBreaksStyle: "simple", EscapedSpace: false, }, Extras: Extras{ Delete: Delete{ Enable: false, }, Insert: Insert{ Enable: false, }, Mark: Mark{ Enable: false, }, Subscript: Subscript{ Enable: false, }, Superscript: Superscript{ Enable: false, }, }, Passthrough: Passthrough{ Enable: false, Delimiters: DelimitersConfig{ Inline: [][]string{}, Block: [][]string{}, }, }, }, Renderer: Renderer{ Unsafe: false, }, Parser: Parser{ AutoHeadingID: true, AutoDefinitionTermID: false, AutoIDType: AutoIDTypeGitHub, WrapStandAloneImageWithinParagraph: true, Attribute: ParserAttribute{ Title: true, Block: false, }, }, RenderHooks: RenderHooks{ Image: ImageRenderHook{ UseEmbedded: RenderHookUseEmbeddedAuto, }, Link: LinkRenderHook{ UseEmbedded: RenderHookUseEmbeddedAuto, }, }, } // Config configures Goldmark. type Config struct { Renderer Renderer Parser Parser Extensions Extensions DuplicateResourceFiles bool RenderHooks RenderHooks } func (c *Config) Init() error { if err := c.Parser.Init(); err != nil { return err } if c.Parser.AutoDefinitionTermID && !c.Extensions.DefinitionList { c.Parser.AutoDefinitionTermID = false } return nil } // RenderHooks contains configuration for Goldmark render hooks. type RenderHooks struct { Image ImageRenderHook Link LinkRenderHook } // ImageRenderHook contains configuration for the image render hook. type ImageRenderHook struct { // Enable the default image render hook. // We need to know if it is set or not, hence the pointer. // Deprecated: Use UseEmbedded instead. EnableDefault *bool // When to use the embedded image render hook. // One of auto, never, always, or fallback. Default is auto. UseEmbedded string } // LinkRenderHook contains configuration for the link render hook. type LinkRenderHook struct { // Disable the default image render hook. // We need to know if it is set or not, hence the pointer. // Deprecated: Use UseEmbedded instead. EnableDefault *bool // When to use the embedded link render hook. // One of auto, never, always, or fallback. Default is auto. UseEmbedded string } type Extensions struct { Typographer Typographer Footnote Footnote DefinitionList bool Extras Extras Passthrough Passthrough // GitHub flavored markdown Table bool Strikethrough bool Linkify bool LinkifyProtocol string TaskList bool CJK CJK } // Footnote holds footnote configuration. type Footnote struct { Enable bool EnableAutoIDPrefix bool BacklinkHTML string } // Typographer holds typographer configuration. type Typographer struct { // Whether to disable typographer. Disable bool // Value used for left single quote. LeftSingleQuote string // Value used for right single quote. RightSingleQuote string // Value used for left double quote. LeftDoubleQuote string // Value used for right double quote. RightDoubleQuote string // Value used for en dash. EnDash string // Value used for em dash. EmDash string // Value used for ellipsis. Ellipsis string // Value used for left angle quote. LeftAngleQuote string // Value used for right angle quote. RightAngleQuote string // Value used for apostrophe. Apostrophe string } // Extras holds extras configuration. // github.com/hugoio/hugo-goldmark-extensions/extras type Extras struct { Delete Delete Insert Insert Mark Mark Subscript Subscript Superscript Superscript } type Delete struct { Enable bool } type Insert struct { Enable bool } type Mark struct { Enable bool } type Subscript struct { Enable bool } type Superscript struct { Enable bool } // Passthrough holds passthrough configuration. // github.com/hugoio/hugo-goldmark-extensions/passthrough type Passthrough struct { // Whether to enable the extension Enable bool // The delimiters to use for inline and block passthroughs. Delimiters DelimitersConfig } type DelimitersConfig struct { // The delimiters to use for inline passthroughs. Each entry in the list // is a size-2 list of strings, where the first string is the opening delimiter // and the second string is the closing delimiter, e.g., // // [["$", "$"], ["\\(", "\\)"]] Inline [][]string // The delimiters to use for block passthroughs. Same format as Inline. Block [][]string } type CJK struct { // Whether to enable CJK support. Enable bool // Whether softline breaks between east asian wide characters should be ignored. EastAsianLineBreaks bool // Styles of Line Breaking of EastAsianLineBreaks: "simple" or "css3draft" EastAsianLineBreaksStyle string // Whether a '\' escaped half-space(0x20) should not be rendered. EscapedSpace bool } type Renderer struct { // Whether softline breaks should be rendered as '<br>' HardWraps bool // XHTML instead of HTML5. XHTML bool // Allow raw HTML etc. Unsafe bool } type Parser struct { // Enables custom heading ids and // auto generated heading ids. AutoHeadingID bool // Enables auto definition term ids. AutoDefinitionTermID bool // The strategy to use when generating IDs. // Available options are "github", "github-ascii", and "blackfriday". // Default is "github", which will create GitHub-compatible anchor names. AutoIDType string // Enables custom attributes. Attribute ParserAttribute // Whether to wrap stand-alone images within a paragraph or not. WrapStandAloneImageWithinParagraph bool // Renamed to AutoIDType in 0.144.0. AutoHeadingIDType string `json:"-"` } func (p *Parser) Init() error { // Renamed from AutoHeadingIDType to AutoIDType in 0.144.0. if p.AutoHeadingIDType != "" { p.AutoIDType = p.AutoHeadingIDType } return nil } type ParserAttribute struct { // Enables custom attributes for titles. Title bool // Enables custom attributes for blocks. Block bool }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/blockquotes/blockquotes.go
markup/goldmark/blockquotes/blockquotes.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blockquotes import ( "regexp" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/types/hstring" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/internal/render" "github.com/gohugoio/hugo/markup/internal/attributes" "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/renderer" "github.com/yuin/goldmark/renderer/html" "github.com/yuin/goldmark/util" ) type ( blockquotesExtension struct{} htmlRenderer struct{} ) func New() goldmark.Extender { return &blockquotesExtension{} } func (e *blockquotesExtension) Extend(m goldmark.Markdown) { m.Renderer().AddOptions(renderer.WithNodeRenderers( util.Prioritized(newHTMLRenderer(), 100), )) } func newHTMLRenderer() renderer.NodeRenderer { r := &htmlRenderer{} return r } func (r *htmlRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) { reg.Register(ast.KindBlockquote, r.renderBlockquote) } const ( typeRegular = "regular" typeAlert = "alert" ) func (r *htmlRenderer) renderBlockquote(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { ctx := w.(*render.Context) n := node.(*ast.Blockquote) if entering { // Store the current pos so we can capture the rendered text. ctx.PushPos(ctx.Buffer.Len()) return ast.WalkContinue, nil } text := ctx.PopRenderedString() ordinal := ctx.GetAndIncrementOrdinal(ast.KindBlockquote) typ := typeRegular alert := resolveBlockQuoteAlert(text) if alert.typ != "" { typ = typeAlert } renderer := ctx.RenderContext().GetRenderer(hooks.BlockquoteRendererType, typ) if renderer == nil { return r.renderBlockquoteDefault(w, n, text) } if typ == typeAlert { // Parse the blockquote content to determine the alert text. The alert // text begins after the first newline, but we need to add an opening p // tag if the first line of the blockquote content does not have a // closing p tag. At some point we might want to move this to the // parser. before, after, found := strings.Cut(strings.TrimSpace(text), "\n") if found { if strings.HasSuffix(before, "</p>") { text = after } else { text = "<p>" + after } } else { text = "" } } bqctx := &blockquoteContext{ BaseContext: render.NewBaseContext(ctx, renderer, n, src, nil, ordinal), typ: typ, alert: alert, text: hstring.HTML(text), AttributesHolder: attributes.New(n.Attributes(), attributes.AttributesOwnerGeneral), } cr := renderer.(hooks.BlockquoteRenderer) err := cr.RenderBlockquote( ctx.RenderContext().Ctx, w, bqctx, ) if err != nil { return ast.WalkContinue, herrors.NewFileErrorFromPos(err, bqctx.Position()) } return ast.WalkContinue, nil } // Code borrowed from goldmark's html renderer. func (r *htmlRenderer) renderBlockquoteDefault( w util.BufWriter, n ast.Node, text string, ) (ast.WalkStatus, error) { if n.Attributes() != nil { _, _ = w.WriteString("<blockquote") html.RenderAttributes(w, n, html.BlockquoteAttributeFilter) _ = w.WriteByte('>') } else { _, _ = w.WriteString("<blockquote>\n") } _, _ = w.WriteString(text) _, _ = w.WriteString("</blockquote>\n") return ast.WalkContinue, nil } type blockquoteContext struct { hooks.BaseContext text hstring.HTML typ string alert blockQuoteAlert *attributes.AttributesHolder } func (c *blockquoteContext) Type() string { return c.typ } func (c *blockquoteContext) AlertType() string { return c.alert.typ } func (c *blockquoteContext) AlertTitle() hstring.HTML { return hstring.HTML(c.alert.title) } func (c *blockquoteContext) AlertSign() string { return c.alert.sign } func (c *blockquoteContext) Text() hstring.HTML { return c.text } var blockQuoteAlertRe = regexp.MustCompile(`^<p>\[!([a-zA-Z]+)\](-|\+)?[^\S\r\n]?([^\n]*)\n?`) func resolveBlockQuoteAlert(s string) blockQuoteAlert { m := blockQuoteAlertRe.FindStringSubmatch(strings.TrimSpace(s)) if len(m) == 4 { title := strings.TrimSpace(m[3]) title = strings.TrimSuffix(title, "</p>") return blockQuoteAlert{ typ: strings.ToLower(m[1]), sign: m[2], title: title, } } return blockQuoteAlert{} } // Blockquote alert syntax was introduced by GitHub, but is also used // by Obsidian which also support some extended attributes: More types, alert titles and a +/- sign for folding. type blockQuoteAlert struct { typ string sign string title string }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/blockquotes/blockquotes_integration_test.go
markup/goldmark/blockquotes/blockquotes_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blockquotes_test import ( "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) func TestBlockquoteHook(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup] [markup.goldmark] [markup.goldmark.parser] [markup.goldmark.parser.attribute] block = true title = true -- layouts/_markup/render-blockquote.html -- Blockquote: |{{ .Text }}|{{ .Type }}| -- layouts/_markup/render-blockquote-alert.html -- {{ $text := .Text }} Blockquote Alert: |{{ $text }}|{{ .Type }}| Blockquote Alert Attributes: |{{ $text }}|{{ .Attributes }}| Blockquote Alert Page: |{{ $text }}|{{ .Page.Title }}|{{ .PageInner.Title }}| {{ if .Attributes.showpos }} Blockquote Alert Position: |{{ $text }}|{{ .Position | safeHTML }}| {{ end }} -- layouts/single.html -- Content: {{ .Content }} -- content/p1.md -- --- title: "p1" --- > [!NOTE] > This is a note with some whitespace after the alert type. > [!TIP] > This is a tip. > [!CAUTION] > This is a caution with some whitespace before the alert type. > A regular blockquote. > [!TIP] > This is a tip with attributes. {class="foo bar" id="baz"} > [!NOTE] > Note triggering showing the position. {showpos="true"} > [!nOtE] > Mixed case alert type. ` b := hugolib.Test(t, files) b.AssertFileContentExact("public/p1/index.html", "Blockquote Alert: |<p>This is a note with some whitespace after the alert type.</p>|alert|", "Blockquote Alert: |<p>This is a tip.</p>", "Blockquote Alert: |<p>This is a caution with some whitespace before the alert type.</p>|alert|", "Blockquote: |<p>A regular blockquote.</p>\n|regular|", "Blockquote Alert Attributes: |<p>This is a tip with attributes.</p>|map[class:foo bar id:baz]|", filepath.FromSlash("/content/p1.md:19:3"), "Blockquote Alert Page: |<p>This is a tip with attributes.</p>|p1|p1|", // Issue 12767. "Blockquote Alert: |<p>Mixed case alert type.</p>|alert", ) } func TestBlockquoteEmptyIssue12756(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/p1.md -- --- title: "p1" --- > -- layouts/single.html -- Content: {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContentExact("public/p1/index.html", "Content: <blockquote>\n</blockquote>\n") } func TestBlockquObsidianWithTitleAndSign(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/_index.md -- --- title: "Home" --- > [!danger] > Do not approach or handle without protective gear. > [!tip] Callouts can have custom titles > Like this one. > [!tip] Title-only callout > [!faq]- Foldable negated callout > Yes! In a foldable callout, the contents are hidden when the callout is collapsed > [!faq]+ Foldable callout > Yes! In a foldable callout, the contents are hidden when the callout is collapsed > [!info] Can callouts be nested? > > [!important] Yes!, they can. > > > [!tip] You can even use multiple layers of nesting. -- layouts/home.html -- {{ .Content }} -- layouts/_markup/render-blockquote.html -- AlertType: {{ .AlertType }}|AlertTitle: {{ .AlertTitle }}|AlertSign: {{ .AlertSign | safeHTML }}|Text: {{ .Text }}| ` b := hugolib.Test(t, files) b.AssertFileContentExact("public/index.html", "AlertType: tip|AlertTitle: Callouts can have custom titles|AlertSign: |", "AlertType: tip|AlertTitle: Title-only callout|AlertSign: |", "AlertType: faq|AlertTitle: Foldable negated callout|AlertSign: -|Text: <p>Yes! In a foldable callout, the contents are hidden when the callout is collapsed</p>|", "AlertType: faq|AlertTitle: Foldable callout|AlertSign: +|Text: <p>Yes! In a foldable callout, the contents are hidden when the callout is collapsed</p>|", "AlertType: danger|AlertTitle: |AlertSign: |Text: <p>Do not approach or handle without protective gear.</p>|", "AlertTitle: Can callouts be nested?|", "AlertTitle: You can even use multiple layers of nesting.|", ) } // Issue 12913 // Issue 13119 // Issue 13302 func TestBlockquoteRenderHookTextParsing(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term'] -- layouts/home.html -- {{ .Content }} -- layouts/_markup/render-blockquote.html -- AlertType: {{ .AlertType }}|AlertTitle: {{ .AlertTitle }}|Text: {{ .Text }}| -- content/_index.md -- --- title: home --- > [!one] > [!two] title > [!three] > line 1 > [!four] title > line 1 > [!five] > line 1 > line 2 > [!six] title > line 1 > line 2 > [!seven] > - list item > [!eight] title > - list item > [!nine] > line 1 > - list item > [!ten] title > line 1 > - list item > [!eleven] > line 1 > - list item > > line 2 > [!twelve] title > line 1 > - list item > > line 2 > [!thirteen] > ![alt](a.jpg) > [!fourteen] title > ![alt](a.jpg) > [!fifteen] _title_ > [!sixteen] _title_ > line one > seventeen ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.html", "AlertType: one|AlertTitle: |Text: |", "AlertType: two|AlertTitle: title|Text: |", "AlertType: three|AlertTitle: |Text: <p>line 1</p>|", "AlertType: four|AlertTitle: title|Text: <p>line 1</p>|", "AlertType: five|AlertTitle: |Text: <p>line 1\nline 2</p>|", "AlertType: six|AlertTitle: title|Text: <p>line 1\nline 2</p>|", "AlertType: seven|AlertTitle: |Text: <ul>\n<li>list item</li>\n</ul>|", "AlertType: eight|AlertTitle: title|Text: <ul>\n<li>list item</li>\n</ul>|", "AlertType: nine|AlertTitle: |Text: <p>line 1</p>\n<ul>\n<li>list item</li>\n</ul>|", "AlertType: ten|AlertTitle: title|Text: <p>line 1</p>\n<ul>\n<li>list item</li>\n</ul>|", "AlertType: eleven|AlertTitle: |Text: <p>line 1</p>\n<ul>\n<li>list item</li>\n</ul>\n<p>line 2</p>|", "AlertType: twelve|AlertTitle: title|Text: <p>line 1</p>\n<ul>\n<li>list item</li>\n</ul>\n<p>line 2</p>|", "AlertType: thirteen|AlertTitle: |Text: <p><img src=\"a.jpg\" alt=\"alt\"></p>|", "AlertType: fourteen|AlertTitle: title|Text: <p><img src=\"a.jpg\" alt=\"alt\"></p>|", "AlertType: fifteen|AlertTitle: <em>title</em>|Text: |", "AlertType: sixteen|AlertTitle: <em>title</em>|Text: <p>line one</p>|", "AlertType: |AlertTitle: |Text: <p>seventeen</p>\n|", ) } // Issue14046 func TestBlockquoteDefaultOutput(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ['home','rss','section','sitemap','taxonomy','term'] -- content/p1.md -- --- title: p1 --- > foo -- layouts/page.html -- |{{ .Content }}| -- xxx -- <blockquote> {{ .Text }} </blockquote> ` want := "|<blockquote>\n<p>foo</p>\n</blockquote>\n|" b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", want) // fail files = strings.ReplaceAll(files, "xxx", "layouts/_markup/render-blockquote.html") b = hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", want) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/blockquotes/blockquotes_test.go
markup/goldmark/blockquotes/blockquotes_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package blockquotes import ( "testing" qt "github.com/frankban/quicktest" ) func TestResolveBlockQuoteAlert(t *testing.T) { t.Parallel() c := qt.New(t) tests := []struct { input string expected blockQuoteAlert }{ { input: "[!NOTE]", expected: blockQuoteAlert{typ: "note"}, }, { input: "[!FaQ]", expected: blockQuoteAlert{typ: "faq"}, }, { input: "[!NOTE]+", expected: blockQuoteAlert{typ: "note", sign: "+"}, }, { input: "[!NOTE]-", expected: blockQuoteAlert{typ: "note", sign: "-"}, }, { input: "[!NOTE] This is a note", expected: blockQuoteAlert{typ: "note", title: "This is a note"}, }, { input: "[!NOTE]+ This is a note", expected: blockQuoteAlert{typ: "note", sign: "+", title: "This is a note"}, }, { input: "[!NOTE]+ This is a title\nThis is not.", expected: blockQuoteAlert{typ: "note", sign: "+", title: "This is a title"}, }, { input: "[!NOTE]\nThis is not.", expected: blockQuoteAlert{typ: "note"}, }, } for i, test := range tests { c.Assert(resolveBlockQuoteAlert("<p>"+test.input+"</p>"), qt.Equals, test.expected, qt.Commentf("Test %d", i)) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/hugocontext/hugocontext_test.go
markup/goldmark/hugocontext/hugocontext_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugocontext import ( "testing" qt "github.com/frankban/quicktest" ) func TestWrap(t *testing.T) { c := qt.New(t) b := []byte("test") c.Assert(Wrap(b, 42), qt.Equals, "{{__hugo_ctx pid=42}}\ntest\n{{__hugo_ctx/}}\n") } func BenchmarkWrap(b *testing.B) { for b.Loop() { Wrap([]byte("test"), 42) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/hugocontext/hugocontext.go
markup/goldmark/hugocontext/hugocontext.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugocontext import ( "bytes" "fmt" "regexp" "strconv" "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/common/constants" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/markup/goldmark/internal/render" "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/renderer" "github.com/yuin/goldmark/renderer/html" "github.com/yuin/goldmark/text" "github.com/yuin/goldmark/util" ) func New(logger loggers.Logger) goldmark.Extender { return &hugoContextExtension{logger: logger} } // Wrap wraps the given byte slice in a Hugo context that used to determine the correct Page // in .RenderShortcodes. func Wrap(b []byte, pid uint64) string { buf := bufferpool.GetBuffer() defer bufferpool.PutBuffer(buf) buf.Write(hugoCtxPrefix) buf.WriteString(" pid=") buf.WriteString(strconv.FormatUint(pid, 10)) buf.Write(hugoCtxEndDelim) buf.WriteByte('\n') buf.Write(b) // To make sure that we're able to parse it, make sure it ends with a newline. if len(b) > 0 && b[len(b)-1] != '\n' { buf.WriteByte('\n') } buf.Write(hugoCtxPrefix) buf.Write(hugoCtxClosingDelim) buf.WriteByte('\n') return buf.String() } var kindHugoContext = ast.NewNodeKind("HugoContext") // HugoContext is a node that represents a Hugo context. type HugoContext struct { ast.BaseInline Closing bool // Internal page ID. Not persisted. Pid uint64 } // Dump implements Node.Dump. func (n *HugoContext) Dump(source []byte, level int) { m := map[string]string{} m["Pid"] = fmt.Sprintf("%v", n.Pid) ast.DumpHelper(n, source, level, m, nil) } func (n *HugoContext) parseAttrs(attrBytes []byte) { keyPairs := bytes.SplitSeq(attrBytes, []byte(" ")) for keyPair := range keyPairs { kv := bytes.Split(keyPair, []byte("=")) if len(kv) != 2 { continue } key := string(kv[0]) val := string(kv[1]) switch key { case "pid": pid, _ := strconv.ParseUint(val, 10, 64) n.Pid = pid } } } func (h *HugoContext) Kind() ast.NodeKind { return kindHugoContext } var ( hugoCtxPrefix = []byte("{{__hugo_ctx") hugoCtxEndDelim = []byte("}}") hugoCtxClosingDelim = []byte("/}}") hugoCtxRe = regexp.MustCompile(`{{__hugo_ctx( pid=\d+)?/?}}\n?`) ) var _ parser.InlineParser = (*hugoContextParser)(nil) type hugoContextParser struct{} func (a *hugoContextParser) Trigger() []byte { return []byte{'{'} } func (s *hugoContextParser) Parse(parent ast.Node, reader text.Reader, pc parser.Context) ast.Node { line, _ := reader.PeekLine() if !bytes.HasPrefix(line, hugoCtxPrefix) { return nil } end := bytes.Index(line, hugoCtxEndDelim) if end == -1 { return nil } reader.Advance(end + len(hugoCtxEndDelim) + 1) // +1 for the newline if line[end-1] == '/' { return &HugoContext{Closing: true} } attrBytes := line[len(hugoCtxPrefix)+1 : end] h := &HugoContext{} h.parseAttrs(attrBytes) return h } type hugoContextRenderer struct { logger loggers.Logger html.Config } func (r *hugoContextRenderer) SetOption(name renderer.OptionName, value any) { r.Config.SetOption(name, value) } func (r *hugoContextRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) { reg.Register(kindHugoContext, r.handleHugoContext) reg.Register(ast.KindRawHTML, r.renderRawHTML) reg.Register(ast.KindHTMLBlock, r.renderHTMLBlock) } func (r *hugoContextRenderer) stripHugoCtx(b []byte) ([]byte, bool) { if !bytes.Contains(b, hugoCtxPrefix) { return b, false } return hugoCtxRe.ReplaceAll(b, nil), true } func (r *hugoContextRenderer) logRawHTMLEmittedWarn(w util.BufWriter) { r.logger.Warnidf(constants.WarnGoldmarkRawHTML, "Raw HTML omitted while rendering %q; see https://gohugo.io/getting-started/configuration-markup/#rendererunsafe", r.getPage(w)) } func (r *hugoContextRenderer) getPage(w util.BufWriter) any { var p any ctx, ok := w.(*render.Context) if ok { p, _ = render.GetPageAndPageInner(ctx) } return p } func (r *hugoContextRenderer) isHTMLComment(b []byte) bool { return len(b) > 4 && b[0] == '<' && b[1] == '!' && b[2] == '-' && b[3] == '-' } // HTML rendering based on Goldmark implementation. func (r *hugoContextRenderer) renderHTMLBlock( w util.BufWriter, source []byte, node ast.Node, entering bool, ) (ast.WalkStatus, error) { n := node.(*ast.HTMLBlock) if entering { if r.Unsafe { l := n.Lines().Len() for i := range l { line := n.Lines().At(i) linev := line.Value(source) var stripped bool linev, stripped = r.stripHugoCtx(linev) if stripped { r.logger.Warnidf(constants.WarnRenderShortcodesInHTML, ".RenderShortcodes detected inside HTML block in %q; this may not be what you intended, see https://gohugo.io/methods/page/rendershortcodes/#limitations", r.getPage(w)) } r.Writer.SecureWrite(w, linev) } } else { l := n.Lines().At(0) v := l.Value(source) if !r.isHTMLComment(v) { r.logRawHTMLEmittedWarn(w) _, _ = w.WriteString("<!-- raw HTML omitted -->\n") } } } else { if n.HasClosure() { if r.Unsafe { closure := n.ClosureLine r.Writer.SecureWrite(w, closure.Value(source)) } else { l := n.Lines().At(0) v := l.Value(source) if !r.isHTMLComment(v) { _, _ = w.WriteString("<!-- raw HTML omitted -->\n") } } } } return ast.WalkContinue, nil } func (r *hugoContextRenderer) renderRawHTML( w util.BufWriter, source []byte, node ast.Node, entering bool, ) (ast.WalkStatus, error) { if !entering { return ast.WalkSkipChildren, nil } n := node.(*ast.RawHTML) l := n.Segments.Len() if r.Unsafe { for i := range l { segment := n.Segments.At(i) _, _ = w.Write(segment.Value(source)) } return ast.WalkSkipChildren, nil } segment := n.Segments.At(0) v := segment.Value(source) if !r.isHTMLComment(v) { r.logRawHTMLEmittedWarn(w) _, _ = w.WriteString("<!-- raw HTML omitted -->") } return ast.WalkSkipChildren, nil } func (r *hugoContextRenderer) handleHugoContext(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { if !entering { return ast.WalkContinue, nil } hctx := node.(*HugoContext) ctx, ok := w.(*render.Context) if !ok { return ast.WalkContinue, nil } if hctx.Closing { _ = ctx.PopPid() } else { ctx.PushPid(hctx.Pid) } return ast.WalkContinue, nil } type hugoContextTransformer struct{} var _ parser.ASTTransformer = (*hugoContextTransformer)(nil) func (a *hugoContextTransformer) Transform(n *ast.Document, reader text.Reader, pc parser.Context) { ast.Walk(n, func(n ast.Node, entering bool) (ast.WalkStatus, error) { s := ast.WalkContinue if !entering || n.Kind() != kindHugoContext { return s, nil } if p, ok := n.Parent().(*ast.Paragraph); ok { if p.ChildCount() == 1 { // Avoid empty paragraphs. p.Parent().ReplaceChild(p.Parent(), p, n) } else { if t, ok := n.PreviousSibling().(*ast.Text); ok { // Remove the newline produced by the Hugo context markers. if t.SoftLineBreak() { if t.Segment.Len() == 0 { p.RemoveChild(p, t) } else { t.SetSoftLineBreak(false) } } } } } return s, nil }) } type hugoContextExtension struct { logger loggers.Logger } func (a *hugoContextExtension) Extend(m goldmark.Markdown) { m.Parser().AddOptions( parser.WithInlineParsers( util.Prioritized(&hugoContextParser{}, 50), ), parser.WithASTTransformers(util.Prioritized(&hugoContextTransformer{}, 10)), ) m.Renderer().AddOptions( renderer.WithNodeRenderers( util.Prioritized(&hugoContextRenderer{ logger: a.logger, Config: html.Config{ Writer: html.DefaultWriter, }, }, 50), ), ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/internal/extensions/attributes/attributes_integration_test.go
markup/goldmark/internal/extensions/attributes/attributes_integration_test.go
package attributes_test import ( "testing" "github.com/gohugoio/hugo/hugolib" ) func TestDescriptionListAutoID(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.parser] autoHeadingID = true autoDefinitionTermID = true autoIDType = 'github-ascii' -- content/p1.md -- --- title: "Title" --- ## Title with id set {#title-with-id} ## Title with id set duplicate {#title-with-id} ## My Title Base Name : Base name of the file. Base Name : Duplicate term name. My Title : Term with same name as title. Foo@Bar : The foo bar. foo [something](/a/b/) bar : A foo bar. 良善天父 : The good father. Ā ā Ă ă Ą ą Ć ć Ĉ ĉ Ċ ċ Č č Ď : Testing accents. Multiline set text header Second line --------------- ## Example [hyperlink](https://example.com/) in a header -- layouts/single.html -- {{ .Content }}|Identifiers: {{ .Fragments.Identifiers }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", `<dt id="base-name">Base Name</dt>`, `<dt id="base-name-1">Base Name</dt>`, `<dt id="foobar">Foo@Bar</dt>`, `<h2 id="my-title">My Title</h2>`, `<dt id="foo-something-bar">foo <a href="/a/b/">something</a> bar</dt>`, `<h2 id="title-with-id">Title with id set</h2>`, `<h2 id="title-with-id">Title with id set duplicate</h2>`, `<dt id="my-title-1">My Title</dt>`, `<dt id="term">良善天父</dt>`, `<dt id="a-a-a-a-a-a-c-c-c-c-c-c-c-c-d">Ā ā Ă ă Ą ą Ć ć Ĉ ĉ Ċ ċ Č č Ď</dt>`, `<h2 id="second-line">`, `<h2 id="example-hyperlink-in-a-header">`, "|Identifiers: [a-a-a-a-a-a-c-c-c-c-c-c-c-c-d base-name base-name-1 example-hyperlink-in-a-header foo-something-bar foobar my-title my-title-1 second-line term title-with-id title-with-id]|", ) } func TestSolitaryAttributesCrash(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.parser.attribute] block = true -- layouts/single.html -- Content: {{ .Content }} -- content/p1.md -- --- title: "Title" --- 1. a {.x} 1. b {.x} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` <li>a</li>`, ) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/internal/extensions/attributes/attributes.go
markup/goldmark/internal/extensions/attributes/attributes.go
package attributes import ( "strings" "github.com/gohugoio/hugo/markup/goldmark/goldmark_config" "github.com/gohugoio/hugo/markup/goldmark/internal/render" "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" east "github.com/yuin/goldmark/extension/ast" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/text" "github.com/yuin/goldmark/util" ) // This extension is based on/inspired by https://github.com/mdigger/goldmark-attributes // MIT License // Copyright (c) 2019 Dmitry Sedykh var ( kindAttributesBlock = ast.NewNodeKind("AttributesBlock") attrNameID = []byte("id") defaultParser = new(attrParser) ) func New(cfg goldmark_config.Parser) goldmark.Extender { return &attrExtension{cfg: cfg} } type attrExtension struct { cfg goldmark_config.Parser } func (a *attrExtension) Extend(m goldmark.Markdown) { if a.cfg.Attribute.Block { m.Parser().AddOptions( parser.WithBlockParsers( util.Prioritized(defaultParser, 100)), ) } m.Parser().AddOptions( parser.WithASTTransformers( util.Prioritized(&transformer{cfg: a.cfg}, 100), ), ) } type attrParser struct{} func (a *attrParser) CanAcceptIndentedLine() bool { return false } func (a *attrParser) CanInterruptParagraph() bool { return true } func (a *attrParser) Close(node ast.Node, reader text.Reader, pc parser.Context) { } func (a *attrParser) Continue(node ast.Node, reader text.Reader, pc parser.Context) parser.State { return parser.Close } func (a *attrParser) Open(parent ast.Node, reader text.Reader, pc parser.Context) (ast.Node, parser.State) { if attrs, ok := parser.ParseAttributes(reader); ok { // add attributes node := &attributesBlock{ BaseBlock: ast.BaseBlock{}, } for _, attr := range attrs { node.SetAttribute(attr.Name, attr.Value) } return node, parser.NoChildren } return nil, parser.RequireParagraph } func (a *attrParser) Trigger() []byte { return []byte{'{'} } type attributesBlock struct { ast.BaseBlock } func (a *attributesBlock) Dump(source []byte, level int) { attrs := a.Attributes() list := make(map[string]string, len(attrs)) for _, attr := range attrs { var ( name = util.BytesToReadOnlyString(attr.Name) value = util.BytesToReadOnlyString(util.EscapeHTML(attr.Value.([]byte))) ) list[name] = value } ast.DumpHelper(a, source, level, list, nil) } func (a *attributesBlock) Kind() ast.NodeKind { return kindAttributesBlock } type transformer struct { cfg goldmark_config.Parser } func (a *transformer) isFragmentNode(n ast.Node) bool { switch n.Kind() { case east.KindDefinitionTerm, ast.KindHeading: return true default: return false } } func (a *transformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) { var attributes []ast.Node var solitaryAttributeNodes []ast.Node if a.cfg.Attribute.Block { attributes = make([]ast.Node, 0, 100) } ast.Walk(node, func(node ast.Node, entering bool) (ast.WalkStatus, error) { if !entering { return ast.WalkContinue, nil } if a.isFragmentNode(node) { if id, found := node.Attribute(attrNameID); !found { a.generateAutoID(node, reader, pc) } else { pc.IDs().Put(id.([]byte)) } } if a.cfg.Attribute.Block && node.Kind() == kindAttributesBlock { // Attributes for fenced code blocks are handled in their own extension, // but note that we currently only support code block attributes when // CodeFences=true. if node.PreviousSibling() != nil && node.PreviousSibling().Kind() != ast.KindFencedCodeBlock && !node.HasBlankPreviousLines() { attributes = append(attributes, node) return ast.WalkSkipChildren, nil } else { solitaryAttributeNodes = append(solitaryAttributeNodes, node) } } return ast.WalkContinue, nil }) for _, attr := range attributes { if prev := attr.PreviousSibling(); prev != nil && prev.Type() == ast.TypeBlock { for _, attr := range attr.Attributes() { if _, found := prev.Attribute(attr.Name); !found { prev.SetAttribute(attr.Name, attr.Value) } } } // remove attributes node attr.Parent().RemoveChild(attr.Parent(), attr) } // Remove any solitary attribute nodes. for _, n := range solitaryAttributeNodes { n.Parent().RemoveChild(n.Parent(), n) } } func (a *transformer) generateAutoID(n ast.Node, reader text.Reader, pc parser.Context) { var text []byte switch n := n.(type) { case *ast.Heading: if a.cfg.AutoHeadingID { text = textHeadingID(n, reader) } case *east.DefinitionTerm: if a.cfg.AutoDefinitionTermID { text = []byte(render.TextPlain(n, reader.Source())) } } if len(text) > 0 { headingID := pc.IDs().Generate(text, n.Kind()) n.SetAttribute(attrNameID, headingID) } } // Markdown settext headers can have multiple lines, use the last line for the ID. func textHeadingID(n *ast.Heading, reader text.Reader) []byte { text := render.TextPlain(n, reader.Source()) if n.Lines().Len() > 1 { // For multiline headings, Goldmark's extension for headings returns the last line. // We have a slightly different approach, but in most cases the end result should be the same. // Instead of looking at the text segments in Lines (see #13405 for issues with that), // we split the text above and use the last line. parts := strings.Split(text, "\n") text = parts[len(parts)-1] } return []byte(text) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/internal/render/context.go
markup/goldmark/internal/render/context.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package render import ( "bytes" "math/bits" "strings" "sync" "github.com/gohugoio/hugo-goldmark-extensions/passthrough" bp "github.com/gohugoio/hugo/bufferpool" east "github.com/yuin/goldmark-emoji/ast" htext "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/util" ) type BufWriter struct { *bytes.Buffer } const maxInt = 1<<(bits.UintSize-1) - 1 func (b *BufWriter) Available() int { return maxInt } func (b *BufWriter) Buffered() int { return b.Len() } func (b *BufWriter) Flush() error { return nil } type Context struct { *BufWriter ContextData positions []int pids []uint64 ordinals map[ast.NodeKind]int values map[ast.NodeKind][]any } func (ctx *Context) GetAndIncrementOrdinal(kind ast.NodeKind) int { if ctx.ordinals == nil { ctx.ordinals = make(map[ast.NodeKind]int) } i := ctx.ordinals[kind] ctx.ordinals[kind]++ return i } func (ctx *Context) PushPos(n int) { ctx.positions = append(ctx.positions, n) } func (ctx *Context) PopPos() int { i := len(ctx.positions) - 1 p := ctx.positions[i] ctx.positions = ctx.positions[:i] return p } func (ctx *Context) PopRenderedString() string { pos := ctx.PopPos() text := string(ctx.Bytes()[pos:]) ctx.Truncate(pos) return text } // PushPid pushes a new page ID to the stack. func (ctx *Context) PushPid(pid uint64) { ctx.pids = append(ctx.pids, pid) } // PeekPid returns the current page ID without removing it from the stack. func (ctx *Context) PeekPid() uint64 { if len(ctx.pids) == 0 { return 0 } return ctx.pids[len(ctx.pids)-1] } // PopPid pops the last page ID from the stack. func (ctx *Context) PopPid() uint64 { if len(ctx.pids) == 0 { return 0 } i := len(ctx.pids) - 1 p := ctx.pids[i] ctx.pids = ctx.pids[:i] return p } func (ctx *Context) PushValue(k ast.NodeKind, v any) { if ctx.values == nil { ctx.values = make(map[ast.NodeKind][]any) } ctx.values[k] = append(ctx.values[k], v) } func (ctx *Context) PopValue(k ast.NodeKind) any { if ctx.values == nil { return nil } v := ctx.values[k] if len(v) == 0 { return nil } i := len(v) - 1 r := v[i] ctx.values[k] = v[:i] return r } func (ctx *Context) PeekValue(k ast.NodeKind) any { if ctx.values == nil { return nil } v := ctx.values[k] if len(v) == 0 { return nil } return v[len(v)-1] } type ContextData interface { RenderContext() converter.RenderContext DocumentContext() converter.DocumentContext } type RenderContextDataHolder struct { Rctx converter.RenderContext Dctx converter.DocumentContext } func (ctx *RenderContextDataHolder) RenderContext() converter.RenderContext { return ctx.Rctx } func (ctx *RenderContextDataHolder) DocumentContext() converter.DocumentContext { return ctx.Dctx } // extractSourceSample returns a sample of the source for the given node. // Note that this is not a copy of the source, but a slice of it, // so it assumes that the source is not mutated. func extractSourceSample(n ast.Node, src []byte) []byte { if n.Type() == ast.TypeInline { switch n := n.(type) { case *passthrough.PassthroughInline: return n.Segment.Value(src) } return nil } var sample []byte getStartStop := func(n ast.Node) (int, int) { if n == nil { return 0, 0 } var start, stop int for i := 0; i < n.Lines().Len() && i < 2; i++ { line := n.Lines().At(i) if i == 0 { start = line.Start } stop = line.Stop } return start, stop } start, stop := getStartStop(n) if stop == 0 { // Try first child. start, stop = getStartStop(n.FirstChild()) } if stop > 0 { // We do not mutate the source, so this is safe. sample = src[start:stop] } return sample } // GetPageAndPageInner returns the current page and the inner page for the given context. func GetPageAndPageInner(rctx *Context) (any, any) { p := rctx.DocumentContext().Document pid := rctx.PeekPid() if pid > 0 { if lookup := rctx.DocumentContext().DocumentLookup; lookup != nil { if v := rctx.DocumentContext().DocumentLookup(pid); v != nil { return p, v } } } return p, p } // NewBaseContext creates a new BaseContext. func NewBaseContext(rctx *Context, renderer any, n ast.Node, src []byte, getSourceSample func() []byte, ordinal int) hooks.BaseContext { if getSourceSample == nil { getSourceSample = func() []byte { return extractSourceSample(n, src) } } page, pageInner := GetPageAndPageInner(rctx) b := &hookBase{ page: page, pageInner: pageInner, getSourceSample: getSourceSample, ordinal: ordinal, } b.createPos = func() htext.Position { if resolver, ok := renderer.(hooks.ElementPositionResolver); ok { return resolver.ResolvePosition(b) } return htext.Position{ Filename: rctx.DocumentContext().Filename, LineNumber: 1, ColumnNumber: 1, } } return b } var _ hooks.PositionerSourceTargetProvider = (*hookBase)(nil) type hookBase struct { page any pageInner any ordinal int // This is only used in error situations and is expensive to create, // so delay creation until needed. pos htext.Position posInit sync.Once createPos func() htext.Position getSourceSample func() []byte } func (c *hookBase) Page() any { return c.page } func (c *hookBase) PageInner() any { return c.pageInner } func (c *hookBase) Ordinal() int { return c.ordinal } func (c *hookBase) Position() htext.Position { c.posInit.Do(func() { c.pos = c.createPos() }) return c.pos } // For internal use. func (c *hookBase) PositionerSourceTarget() []byte { return c.getSourceSample() } // TextPlain returns a plain text representation of the given node. // This will resolve any leftover HTML entities. This will typically be // entities inserted by e.g. the typographer extension. // Goldmark's Node.Text was deprecated in 1.7.8. func TextPlain(n ast.Node, source []byte) string { buf := bp.GetBuffer() defer bp.PutBuffer(buf) for c := n.FirstChild(); c != nil; c = c.NextSibling() { textPlainTo(c, source, buf) } return string(util.ResolveEntityNames(buf.Bytes())) } func textPlainTo(c ast.Node, source []byte, buf *bytes.Buffer) { if c == nil { return } switch c := c.(type) { case *ast.RawHTML: s := strings.TrimSpace(tpl.StripHTML(string(c.Segments.Value(source)))) buf.WriteString(s) case *ast.String: buf.Write(c.Value) case *ast.Text: buf.Write(c.Segment.Value(source)) if c.HardLineBreak() || c.SoftLineBreak() { buf.WriteByte('\n') } case *east.Emoji: buf.WriteString(string(c.ShortName)) default: textPlainTo(c.FirstChild(), source, buf) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/tables/tables_integration_test.go
markup/goldmark/tables/tables_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tables_test import ( "testing" "github.com/gohugoio/hugo/hugolib" ) func TestTableHook(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- ## Table 1 | Item | In Stock | Price | | :---------------- | :------: | ----: | | Python Hat | True | 23.99 | | SQL **Hat** | True | 23.99 | | Codecademy Tee | False | 19.99 | | Codecademy Hoodie | False | 42.99 | {.foo foo="bar"} ## Table 2 | Month | Savings | | -------- | ------- | | January | $250 | | February | $80 | | March | $420 | -- layouts/single.html -- {{ .Content }} -- layouts/_markup/render-table.html -- Attributes: {{ .Attributes }}| {{ template "print" (dict "what" (printf "table-%d-thead" $.Ordinal) "rows" .THead) }} {{ template "print" (dict "what" (printf "table-%d-tbody" $.Ordinal) "rows" .TBody) }} {{ define "print" }} {{ .what }}:{{ range $i, $a := .rows }} {{ $i }}:{{ range $j, $b := . }} {{ $j }}: {{ .Alignment }}: {{ .Text }}|{{ end }}{{ end }}$ {{ end }} ` for range 2 { b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "Attributes: map[class:foo foo:bar]|", "table-0-thead: 0: 0: left: Item| 1: center: In Stock| 2: right: Price|$", "table-0-tbody: 0: 0: left: Python Hat| 1: center: True| 2: right: 23.99| 1: 0: left: SQL <strong>Hat</strong>| 1: center: True| 2: right: 23.99| 2: 0: left: Codecademy Tee| 1: center: False| 2: right: 19.99| 3: 0: left: Codecademy Hoodie| 1: center: False| 2: right: 42.99|$", ) b.AssertFileContent("public/p1/index.html", "table-1-thead: 0: 0: : Month| 1: : Savings|$", "table-1-tbody: 0: 0: : January| 1: : $250| 1: 0: : February| 1: : $80| 2: 0: : March| 1: : $420|$", ) } } func TestTableDefault(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- ## Table 1 | Item | In Stock | Price | | :---------------- | :------: | ----: | | Python Hat | True | 23.99 | | SQL Hat | True | 23.99 | | Codecademy Tee | False | 19.99 | | Codecademy Hoodie | False | 42.99 | {.foo} ## Table 2 a|b ---|--- 1|2 {id="\"><script>alert()</script>"} -- layouts/single.html -- Summary: {{ .Summary }} Content: {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", `<table class="foo">`) b.AssertFileContent("public/p1/index.html", `<table id="&#34;&gt;&lt;script&gt;alert()&lt;/script&gt;">`) } // Issue 12811. func TestTableDefaultRSSAndHTML(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [outputFormats] [outputFormats.rss] weight = 30 [outputFormats.html] weight = 20 -- content/_index.md -- --- title: "Home" output: ["rss", "html"] --- | Item | In Stock | Price | | :---------------- | :------: | ----: | | Python Hat | True | 23.99 | | SQL Hat | True | 23.99 | | Codecademy Tee | False | 19.99 | | Codecademy Hoodie | False | 42.99 | {{< foo >}} -- layouts/home.html -- Content: {{ .Content }} -- layouts/index.xml -- Content: {{ .Content }} -- layouts/_shortcodes/foo.xml -- foo xml -- layouts/_shortcodes/foo.html -- foo html ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.xml", "<table>") b.AssertFileContent("public/index.html", "<table>") } func TestTableDefaultRSSOnly(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [outputs] home = ['rss'] section = ['rss'] taxonomy = ['rss'] term = ['rss'] page = ['rss'] disableKinds = ["taxonomy", "term", "page", "section"] -- content/_index.md -- --- title: "Home" --- ## Table 1 | Item | In Stock | Price | | :---------------- | :------: | ----: | | Python Hat | True | 23.99 | | SQL Hat | True | 23.99 | | Codecademy Tee | False | 19.99 | | Codecademy Hoodie | False | 42.99 | -- layouts/index.xml -- Content: {{ .Content }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/index.xml", "<table>") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/tables/tables.go
markup/goldmark/tables/tables.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tables import ( "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/types/hstring" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/internal/render" "github.com/gohugoio/hugo/markup/internal/attributes" "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" gast "github.com/yuin/goldmark/extension/ast" "github.com/yuin/goldmark/renderer" "github.com/yuin/goldmark/util" ) type ( ext struct{} htmlRenderer struct{} ) func New() goldmark.Extender { return &ext{} } func (e *ext) Extend(m goldmark.Markdown) { m.Renderer().AddOptions(renderer.WithNodeRenderers( util.Prioritized(newHTMLRenderer(), 100), )) } func newHTMLRenderer() renderer.NodeRenderer { r := &htmlRenderer{} return r } func (r *htmlRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) { reg.Register(gast.KindTable, r.renderTable) reg.Register(gast.KindTableHeader, r.renderHeaderOrRow) reg.Register(gast.KindTableRow, r.renderHeaderOrRow) reg.Register(gast.KindTableCell, r.renderCell) } func (r *htmlRenderer) renderTable(w util.BufWriter, source []byte, n ast.Node, entering bool) (ast.WalkStatus, error) { ctx := w.(*render.Context) if entering { // This will be modified below. table := &hooks.Table{} ctx.PushValue(gast.KindTable, table) return ast.WalkContinue, nil } v := ctx.PopValue(gast.KindTable) if v == nil { panic("table not found") } table := v.(*hooks.Table) renderer := ctx.RenderContext().GetRenderer(hooks.TableRendererType, nil) if renderer == nil { panic("table hook renderer not found") } ordinal := ctx.GetAndIncrementOrdinal(gast.KindTable) tctx := &tableContext{ BaseContext: render.NewBaseContext(ctx, renderer, n, source, nil, ordinal), AttributesHolder: attributes.New(n.Attributes(), attributes.AttributesOwnerGeneral), tHead: table.THead, tBody: table.TBody, } cr := renderer.(hooks.TableRenderer) err := cr.RenderTable( ctx.RenderContext().Ctx, w, tctx, ) if err != nil { return ast.WalkContinue, herrors.NewFileErrorFromPos(err, tctx.Position()) } return ast.WalkContinue, nil } func (r *htmlRenderer) peekTable(ctx *render.Context) *hooks.Table { v := ctx.PeekValue(gast.KindTable) if v == nil { panic("table not found") } return v.(*hooks.Table) } func (r *htmlRenderer) renderCell(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { ctx := w.(*render.Context) if entering { // Store the current pos so we can capture the rendered text. ctx.PushPos(ctx.Buffer.Len()) return ast.WalkContinue, nil } n := node.(*gast.TableCell) text := ctx.PopRenderedString() table := r.peekTable(ctx) var alignment string switch n.Alignment { case gast.AlignLeft: alignment = "left" case gast.AlignRight: alignment = "right" case gast.AlignCenter: alignment = "center" default: alignment = "" } cell := hooks.TableCell{Text: hstring.HTML(text), Alignment: alignment} if node.Parent().Kind() == gast.KindTableHeader { table.THead[len(table.THead)-1] = append(table.THead[len(table.THead)-1], cell) } else { table.TBody[len(table.TBody)-1] = append(table.TBody[len(table.TBody)-1], cell) } return ast.WalkContinue, nil } func (r *htmlRenderer) renderHeaderOrRow(w util.BufWriter, source []byte, n ast.Node, entering bool) (ast.WalkStatus, error) { ctx := w.(*render.Context) table := r.peekTable(ctx) if entering { if n.Kind() == gast.KindTableHeader { table.THead = append(table.THead, hooks.TableRow{}) } else { table.TBody = append(table.TBody, hooks.TableRow{}) } return ast.WalkContinue, nil } return ast.WalkContinue, nil } type tableContext struct { hooks.BaseContext *attributes.AttributesHolder tHead []hooks.TableRow tBody []hooks.TableRow } func (c *tableContext) THead() []hooks.TableRow { return c.tHead } func (c *tableContext) TBody() []hooks.TableRow { return c.tBody }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/images/transform.go
markup/goldmark/images/transform.go
package images import ( "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/text" "github.com/yuin/goldmark/util" ) type ( imagesExtension struct { wrapStandAloneImageWithinParagraph bool } ) const ( // Used to signal to the rendering step that an image is used in a block context. // Dont's change this; the prefix must match the internalAttrPrefix in the root goldmark package. AttrIsBlock = "_h__isBlock" AttrOrdinal = "_h__ordinal" ) func New(wrapStandAloneImageWithinParagraph bool) goldmark.Extender { return &imagesExtension{wrapStandAloneImageWithinParagraph: wrapStandAloneImageWithinParagraph} } func (e *imagesExtension) Extend(m goldmark.Markdown) { m.Parser().AddOptions( parser.WithASTTransformers( util.Prioritized(&Transformer{wrapStandAloneImageWithinParagraph: e.wrapStandAloneImageWithinParagraph}, 300), ), ) } type Transformer struct { wrapStandAloneImageWithinParagraph bool } // Transform transforms the provided Markdown AST. func (t *Transformer) Transform(doc *ast.Document, reader text.Reader, pctx parser.Context) { var ordinal int ast.Walk(doc, func(node ast.Node, enter bool) (ast.WalkStatus, error) { if !enter { return ast.WalkContinue, nil } if n, ok := node.(*ast.Image); ok { parent := n.Parent() n.SetAttributeString(AttrOrdinal, ordinal) ordinal++ if !t.wrapStandAloneImageWithinParagraph { isBlock := parent.ChildCount() == 1 if isBlock { n.SetAttributeString(AttrIsBlock, true) } if isBlock && parent.Kind() == ast.KindParagraph { for _, attr := range parent.Attributes() { // Transfer any attribute set down to the image. // Image elements does not support attributes on its own, // so it's safe to just set without checking first. n.SetAttribute(attr.Name, attr.Value) } grandParent := parent.Parent() grandParent.ReplaceChild(grandParent, parent, n) } } } return ast.WalkContinue, nil }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/images/images_integration_test.go
markup/goldmark/images/images_integration_test.go
package images_test import ( "strings" "testing" "github.com/gohugoio/hugo/hugolib" ) func TestDisableWrapStandAloneImageWithinParagraph(t *testing.T) { t.Parallel() filesTemplate := ` -- hugo.toml -- [markup.goldmark.renderer] unsafe = false [markup.goldmark.parser] wrapStandAloneImageWithinParagraph = CONFIG_VALUE [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- This is an inline image: ![Inline Image](/inline.jpg). Some more text. ![Block Image](/block.jpg) {.b} -- layouts/single.html -- {{ .Content }} ` t.Run("With Hook, no wrap", func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "CONFIG_VALUE", "false") files = files + `-- layouts/_markup/render-image.html -- {{ if .IsBlock }} <figure class="{{ .Attributes.class }}"> <img src="{{ .Destination | safeURL }}" alt="{{ .Text }}|{{ .Ordinal }}" /> </figure> {{ else }} <img src="{{ .Destination | safeURL }}" alt="{{ .Text }}|{{ .Ordinal }}" /> {{ end }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "This is an inline image: \n\t<img src=\"/inline.jpg\" alt=\"Inline Image|0\" />\n. Some more text.</p>", "<figure class=\"b\">\n\t<img src=\"/block.jpg\" alt=\"Block Image|1\" />", ) }) t.Run("With Hook, wrap", func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "CONFIG_VALUE", "true") files = files + `-- layouts/_markup/render-image.html -- {{ if .IsBlock }} <figure class="{{ .Attributes.class }}"> <img src="{{ .Destination | safeURL }}" alt="{{ .Text }}" /> </figure> {{ else }} <img src="{{ .Destination | safeURL }}" alt="{{ .Text }}" /> {{ end }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "This is an inline image: \n\t<img src=\"/inline.jpg\" alt=\"Inline Image\" />\n. Some more text.</p>", "<p class=\"b\">\n\t<img src=\"/block.jpg\" alt=\"Block Image\" />\n</p>", ) }) t.Run("No Hook, no wrap", func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "CONFIG_VALUE", "false") b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "<p>This is an inline image: <img src=\"/inline.jpg\" alt=\"Inline Image\">. Some more text.</p>\n<img src=\"/block.jpg\" alt=\"Block Image\" class=\"b\">") }) t.Run("No Hook, wrap", func(t *testing.T) { files := strings.ReplaceAll(filesTemplate, "CONFIG_VALUE", "true") b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "<p class=\"b\"><img src=\"/block.jpg\" alt=\"Block Image\"></p>") }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/codeblocks/render.go
markup/goldmark/codeblocks/render.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package codeblocks import ( "bytes" "errors" "fmt" "strings" "github.com/gohugoio/hugo/common/herrors" htext "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/markup/converter/hooks" "github.com/gohugoio/hugo/markup/goldmark/internal/render" "github.com/gohugoio/hugo/markup/highlight/chromalexers" "github.com/gohugoio/hugo/markup/internal/attributes" "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/renderer" "github.com/yuin/goldmark/text" "github.com/yuin/goldmark/util" ) type ( codeBlocksExtension struct{} htmlRenderer struct{} ) func New() goldmark.Extender { return &codeBlocksExtension{} } func (e *codeBlocksExtension) Extend(m goldmark.Markdown) { m.Renderer().AddOptions(renderer.WithNodeRenderers( util.Prioritized(newHTMLRenderer(), 100), )) } func newHTMLRenderer() renderer.NodeRenderer { r := &htmlRenderer{} return r } func (r *htmlRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) { reg.Register(ast.KindFencedCodeBlock, r.renderCodeBlock) } func (r *htmlRenderer) renderCodeBlock(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { ctx := w.(*render.Context) if entering { return ast.WalkContinue, nil } n := node.(*ast.FencedCodeBlock) lang := getLang(n, src) renderer := ctx.RenderContext().GetRenderer(hooks.CodeBlockRendererType, lang) if renderer == nil { return ast.WalkStop, fmt.Errorf("no code renderer found for %q", lang) } ordinal := ctx.GetAndIncrementOrdinal(ast.KindFencedCodeBlock) var buff bytes.Buffer l := n.Lines().Len() for i := range l { line := n.Lines().At(i) buff.Write(line.Value(src)) } s := htext.Chomp(buff.String()) var info []byte if n.Info != nil { info = n.Info.Segment.Value(src) } attrtp := attributes.AttributesOwnerCodeBlockCustom if isd, ok := renderer.(hooks.IsDefaultCodeBlockRendererProvider); (ok && isd.IsDefaultCodeBlockRenderer()) || chromalexers.Get(lang) != nil { // We say that this is a Chroma code block if it's the default code block renderer // or if the language is supported by Chroma. attrtp = attributes.AttributesOwnerCodeBlockChroma } attrs, attrStr, err := getAttributes(n, info) if err != nil { return ast.WalkStop, &herrors.TextSegmentError{Err: err, Segment: attrStr} } cbctx := &codeBlockContext{ BaseContext: render.NewBaseContext(ctx, renderer, node, src, func() []byte { return []byte(s) }, ordinal), lang: lang, code: s, AttributesHolder: attributes.New(attrs, attrtp), } cr := renderer.(hooks.CodeBlockRenderer) err = cr.RenderCodeblock( ctx.RenderContext().Ctx, w, cbctx, ) if err != nil { return ast.WalkContinue, herrors.NewFileErrorFromPos(err, cbctx.Position()) } return ast.WalkContinue, nil } type codeBlockContext struct { hooks.BaseContext lang string code string *attributes.AttributesHolder } func (c *codeBlockContext) Type() string { return c.lang } func (c *codeBlockContext) Inner() string { return c.code } func getLang(node *ast.FencedCodeBlock, src []byte) string { langWithAttributes := string(node.Language(src)) lang, _, _ := strings.Cut(langWithAttributes, "{") return lang } func getAttributes(node *ast.FencedCodeBlock, infostr []byte) ([]ast.Attribute, string, error) { if node.Attributes() != nil { return node.Attributes(), "", nil } if infostr != nil { attrStartIdx := -1 attrEndIdx := -1 for idx, char := range infostr { if attrEndIdx == -1 && char == '{' { attrStartIdx = idx } if attrStartIdx != -1 && char == '}' { attrEndIdx = idx break } } if attrStartIdx != -1 && attrEndIdx != -1 { n := ast.NewTextBlock() // dummy node for storing attributes attrStr := infostr[attrStartIdx : attrEndIdx+1] if attrs, hasAttr := parser.ParseAttributes(text.NewReader(attrStr)); hasAttr { for _, attr := range attrs { n.SetAttribute(attr.Name, attr.Value) } return n.Attributes(), "", nil } else { return nil, string(attrStr), errors.New("failed to parse Markdown attributes; you may need to quote the values") } } } return nil, "", nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/goldmark/codeblocks/codeblocks_integration_test.go
markup/goldmark/codeblocks/codeblocks_integration_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package codeblocks_test import ( "path/filepath" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§go fmt.Println("Hello, Golang!"); §§§ ## Bash Code §§§bash { linenos=inline,hl_lines=[2,"5-6"],linenostart=32 class=blue } echo "l1"; echo "l2"; echo "l3"; echo "l4"; echo "l5"; echo "l6"; echo "l7"; echo "l8"; §§§ ` for range 6 { b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` Goat SVG:<svg class='diagram' Goat Attribute: 600| Go Language: go| Go Code: fmt.Println("Hello, World!"); Go Code: fmt.Println("Hello, Golang!"); Go Language: go| `, "Goat SVG:<svg class='diagram' xmlns='http://www.w3.org/2000/svg' version='1.1' height='25' width='40'", "Goat Attribute: 600|", "<h2 id=\"go-code\">Go Code</h2>\nGo Code: fmt.Println(\"Hello, World!\");\n|\nGo Language: go|", "<h2 id=\"golang-code\">Golang Code</h2>\nGo Code: fmt.Println(\"Hello, Golang!\");\n|\nGo Language: go|", "<h2 id=\"bash-code\">Bash Code</h2>\n<div class=\"highlight blue\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\"><span class=\"line\"><span class=\"ln\">32</span><span class=\"cl\"><span class=\"nb\">echo</span> <span class=\"s2\">&#34;l1&#34;</span><span class=\"p\">;</span>\n</span></span><span class=\"line hl\"><span class=\"ln\">33</span>", ) } } func TestHighlightCodeblock(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- [markup] [markup.highlight] anchorLineNos = false codeFences = true guessSyntax = false hl_Lines = '' lineAnchors = '' lineNoStart = 1 lineNos = false lineNumbersInTable = true noClasses = false style = 'monokai' tabWidth = 4 -- layouts/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "Inner: |<span class=\"line\"><span class=\"cl\"><span class=\"nx\">fmt</span><span class=\"p\">.</span><span class=\"nf\">Println</span><span class=\"p\">(</span><span class=\"s\">&#34;Hello, World!&#34;</span><span class=\"p\">);</span></span></span>|", "Wrapped: |<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-go\" data-lang=\"go\"><span class=\"line\"><span class=\"cl\"><span class=\"nx\">fmt</span><span class=\"p\">.</span><span class=\"nf\">Println</span><span class=\"p\">(</span><span class=\"s\">&#34;Hello, World!&#34;</span><span class=\"p\">);</span></span></span></code></pre></div>|", ) } func TestCodeblocksBugs(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- layouts/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", ` # Issue 9627: For the Position in code blocks we try to match the .Inner with the original source. This isn't always possible. p1.md:0:0 `, ) } func TestCodeChomp(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/single.html -- {{ .Content }} -- layouts/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/single.html -- {{ .Content }} -- layouts/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 10118 func TestAttributes(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/p1.md -- --- title: "p1" --- ## Issue 10118 §§§ {foo="bar"} Hello, World! §§§ -- layouts/single.html -- {{ .Content }} -- layouts/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Type: {{ .Type }}| ` b := hugolib.Test(t, files) b.AssertFileContent("public/p1/index.html", "<h2 id=\"issue-10118\">Issue 10118</h2>\nAttributes: map[foo:bar]|Type: |") } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/single.html -- {{ .Content }} -- layouts/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Options: {{ .Options }}| ` testLanguage := func(language, expect string) { b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: strings.ReplaceAll(files, "LANGUAGE", language), }, ).Build() b.AssertFileContent("public/p1/index.html", expect) } testLanguage("bash", "Attributes: map[]|Options: map[style:monokai]|") testLanguage("hugo", "Attributes: map[style:monokai]|Options: map[]|") } func TestPanics(t *testing.T) { files := ` -- hugo.toml -- [markup] [markup.goldmark] [markup.goldmark.parser] autoHeadingID = true autoHeadingIDType = "github" [markup.goldmark.parser.attribute] block = true title = true -- content/p1.md -- --- title: "p1" --- BLOCK Common -- layouts/single.html -- {{ .Content }} ` for _, test := range []struct { name string markdown string }{ {"issue-9819", "asdf\n: {#myid}"}, } { t.Run(test.name, func(t *testing.T) { t.Parallel() b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: strings.ReplaceAll(files, "BLOCK", test.markdown), }, ).Build() b.AssertFileContent("public/p1/index.html", "Common") }) } } // Issue 10835 func TestAttributesValidation(t *testing.T) { t.Parallel() files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term"] -- content/p1.md -- --- title: "p1" --- ## Issue 10835 §§§bash { color=red dimensions=300x200 } Hello, World! §§§ -- layouts/home.html -- -- layouts/single.html -- {{ .Content }} -- layouts/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Type: {{ .Type }}| ` b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, "p1.md:7:9\": failed to parse Markdown attributes; you may need to quote the values") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/pandoc/convert_test.go
markup/pandoc/convert_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pandoc import ( "testing" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" ) func TestConvert(t *testing.T) { if !Supports() { t.Skip("pandoc not installed") } c := qt.New(t) sc := security.DefaultConfig var err error sc.Exec.Allow, err = security.NewWhitelist("pandoc") c.Assert(err, qt.IsNil) p, err := Provider.New(converter.ProviderConfig{Exec: hexec.New(sc, "", loggers.NewDefault()), Logger: loggers.NewDefault()}) c.Assert(err, qt.IsNil) conv, err := p.New(converter.DocumentContext{}) c.Assert(err, qt.IsNil) b, err := conv.Convert(converter.RenderContext{Src: []byte("testContent")}) c.Assert(err, qt.IsNil) c.Assert(string(b.Bytes()), qt.Equals, "<p>testContent</p>\n") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/markup/pandoc/convert.go
markup/pandoc/convert.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package pandoc converts content to HTML using Pandoc as an external helper. package pandoc import ( "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/markup/internal" ) // Provider is the package entry point. var Provider converter.ProviderProvider = provider{} type provider struct{} func (p provider) New(cfg converter.ProviderConfig) (converter.Provider, error) { return converter.NewProvider("pandoc", func(ctx converter.DocumentContext) (converter.Converter, error) { return &pandocConverter{ ctx: ctx, cfg: cfg, }, nil }), nil } type pandocConverter struct { ctx converter.DocumentContext cfg converter.ProviderConfig } func (c *pandocConverter) Convert(ctx converter.RenderContext) (converter.ResultRender, error) { b, err := c.getPandocContent(ctx.Src, c.ctx) if err != nil { return nil, err } return converter.Bytes(b), nil } func (c *pandocConverter) Supports(feature identity.Identity) bool { return false } // getPandocContent calls pandoc as an external helper to convert pandoc markdown to HTML. func (c *pandocConverter) getPandocContent(src []byte, ctx converter.DocumentContext) ([]byte, error) { logger := c.cfg.Logger binaryName := getPandocBinaryName() if binaryName == "" { logger.Println("pandoc not found in $PATH: Please install.\n", " Leaving pandoc content unrendered.") return src, nil } args := []string{"--mathjax"} return internal.ExternallyRenderContent(c.cfg, ctx, src, binaryName, args) } const pandocBinary = "pandoc" func getPandocBinaryName() string { if hexec.InPath(pandocBinary) { return pandocBinary } return "" } // Supports returns whether Pandoc is installed on this computer. func Supports() bool { hasBin := getPandocBinaryName() != "" if htesting.SupportsAll() { if !hasBin { panic("pandoc not installed") } return true } return hasBin }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/livereload/livereload.go
livereload/livereload.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Contains an embedded version of livereload.js // // Copyright (c) 2010-2015 Andrey Tarantsov // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package livereload import ( "fmt" "net" "net/http" "net/url" "path/filepath" _ "embed" "github.com/gohugoio/hugo/media" "github.com/gorilla/websocket" ) // Prefix to signal to LiveReload that we need to navigate to another path. // Do not change this. const hugoNavigatePrefix = "__hugo_navigate" var upgrader = &websocket.Upgrader{ // Hugo may potentially spin up multiple HTTP servers, so we need to exclude the // port when checking the origin. CheckOrigin: func(r *http.Request) bool { origin := r.Header["Origin"] if len(origin) == 0 { return true } u, err := url.Parse(origin[0]) if err != nil { return false } rHost := r.Host // For Github codespace in browser #9936 if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" { rHost = forwardedHost } if u.Host == rHost { return true } h1, _, err := net.SplitHostPort(u.Host) if err != nil { return false } h2, _, err := net.SplitHostPort(r.Host) if err != nil { return false } return h1 == h2 }, ReadBufferSize: 1024, WriteBufferSize: 1024, } // Handler is a HandlerFunc handling the livereload // Websocket interaction. func Handler(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != nil { return } c := &connection{send: make(chan []byte, 256), ws: ws} wsHub.register <- c defer func() { wsHub.unregister <- c }() go c.writer() c.reader() } // Initialize starts the Websocket Hub handling live reloads. func Initialize() { go wsHub.run() } // ForceRefresh tells livereload to force a hard refresh. func ForceRefresh() { RefreshPath("/x.js") } // NavigateToPathForPort is similar to NavigateToPath but will also // set window.location.port to the given port value. func NavigateToPathForPort(path string, port int) { refreshPathForPort(hugoNavigatePrefix+path, port) } // RefreshPath tells livereload to refresh only the given path. // If that path points to a CSS stylesheet or an image, only the changes // will be updated in the browser, not the entire page. func RefreshPath(s string) { refreshPathForPort(s, -1) } func refreshPathForPort(s string, port int) { // Tell livereload a file has changed - will force a hard refresh if not CSS or an image urlPath := filepath.ToSlash(s) portStr := "" if port > 0 { portStr = fmt.Sprintf(`, "overrideURL": %d`, port) } msg := fmt.Sprintf(`{"command":"reload","path":%q,"originalPath":"","liveCSS":true,"liveImg":true%s}`, urlPath, portStr) wsHub.broadcast <- []byte(msg) } // ServeJS serves the livereload.js who's reference is injected into the page. func ServeJS(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", media.Builtin.JavascriptType.Type) w.Write(liveReloadJS()) } func liveReloadJS() []byte { return []byte(livereloadJS) } //go:embed livereload.min.js var livereloadJS string
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/livereload/hub.go
livereload/hub.go
// Copyright 2015 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package livereload type hub struct { // Registered connections. connections map[*connection]bool // Inbound messages from the connections. broadcast chan []byte // Register requests from the connections. register chan *connection // Unregister requests from connections. unregister chan *connection } var wsHub = hub{ broadcast: make(chan []byte), register: make(chan *connection), unregister: make(chan *connection), connections: make(map[*connection]bool), } func (h *hub) run() { for { select { case c := <-h.register: h.connections[c] = true case c := <-h.unregister: delete(h.connections, c) c.close() case m := <-h.broadcast: for c := range h.connections { select { case c.send <- m: default: delete(h.connections, c) c.close() } } } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/livereload/connection.go
livereload/connection.go
// Copyright 2015 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package livereload import ( "bytes" "sync" "github.com/gorilla/websocket" ) type connection struct { // The websocket connection. ws *websocket.Conn // Buffered channel of outbound messages. send chan []byte // There is a potential data race, especially visible with large files. // This is protected by synchronization of the send channel's close. closer sync.Once } func (c *connection) close() { c.closer.Do(func() { close(c.send) }) } func (c *connection) reader() { for { _, message, err := c.ws.ReadMessage() if err != nil { break } if bytes.Contains(message, []byte(`"command":"hello"`)) { c.send <- []byte(`{ "command": "hello", "protocols": [ "http://livereload.com/protocols/official-7" ], "serverName": "Hugo" }`) } } c.ws.Close() } func (c *connection) writer() { for message := range c.send { err := c.ws.WriteMessage(websocket.TextMessage, message) if err != nil { break } } c.ws.Close() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/livereload/gen/main.go
livereload/gen/main.go
//go:generate go run main.go package main import ( _ "embed" "fmt" "io" "log" "net/http" "os" "github.com/evanw/esbuild/pkg/api" ) //go:embed livereload-hugo-plugin.js var livereloadHugoPluginJS string func main() { // 4.0.2 // To upgrade to a new version, change to the commit hash of the version you want to upgrade to // then run mage generate from the root. const liveReloadCommit = "d803a41804d2d71e0814c4e9e3233e78991024d9" liveReloadSourceURL := fmt.Sprintf("https://raw.githubusercontent.com/livereload/livereload-js/%s/dist/livereload.js", liveReloadCommit) func() { resp, err := http.Get(liveReloadSourceURL) must(err) defer resp.Body.Close() b, err := io.ReadAll(resp.Body) must(err) // Write the unminified livereload.js file. err = os.WriteFile("../livereload.js", b, 0o644) must(err) // Bundle and minify with ESBuild. result := api.Build(api.BuildOptions{ Stdin: &api.StdinOptions{ Contents: string(b) + livereloadHugoPluginJS, }, Outfile: "../livereload.min.js", Bundle: true, Target: api.ES2015, Write: true, MinifyWhitespace: true, MinifyIdentifiers: true, MinifySyntax: true, }) if len(result.Errors) > 0 { log.Fatal(result.Errors) } }() } func must(err error) { if err != nil { log.Fatal(err) } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/walk.go
hugofs/walk.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "context" "fmt" "path/filepath" "sort" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/media" "github.com/spf13/afero" ) type ( WalkFunc func(ctx context.Context, path string, info FileMetaInfo) error WalkHook func(ctx context.Context, dir FileMetaInfo, path string, readdir []FileMetaInfo) ([]FileMetaInfo, error) ) type Walkway struct { logger loggers.Logger // Prevent a walkway to be walked more than once. walked bool // Config from client. cfg WalkwayConfig } type WalkwayConfig struct { // The filesystem to walk. Fs afero.Fs // The root to start from in Fs. Root string // The logger to use. Logger loggers.Logger PathParser *paths.PathParser // One or both of these may be pre-set. Info FileMetaInfo // The start info. DirEntries []FileMetaInfo // The start info's dir entries. Ctx context.Context // Optional starting context. IgnoreFile func(filename string) bool // Optional // Will be called in order. HookPre WalkHook // Optional. WalkFn WalkFunc HookPost WalkHook // Optional. // Some optional flags. FailOnNotExist bool // If set, return an error if a directory is not found. SortDirEntries bool // If set, sort the dir entries by Name before calling the WalkFn, default is ReaDir order. } func NewWalkway(cfg WalkwayConfig) *Walkway { if cfg.Fs == nil { panic("fs must be set") } if cfg.PathParser == nil { cfg.PathParser = media.DefaultPathParser } logger := cfg.Logger if logger == nil { logger = loggers.NewDefault() } return &Walkway{ cfg: cfg, logger: logger, } } func (w *Walkway) Walk() error { if w.walked { panic("this walkway is already walked") } w.walked = true if w.cfg.Fs == NoOpFs { return nil } ctx := w.cfg.Ctx if ctx == nil { ctx = context.Background() } return w.walk(ctx, w.cfg.Root, w.cfg.Info, w.cfg.DirEntries) } // checkErr returns true if the error is handled. func (w *Walkway) checkErr(filename string, err error) bool { if herrors.IsNotExist(err) && !w.cfg.FailOnNotExist { // The file may be removed in process. // This may be a ERROR situation, but it is not possible // to determine as a general case. w.logger.Warnf("File %q not found, skipping.", filename) return true } return false } // walk recursively descends path, calling walkFn. func (w *Walkway) walk(ctx context.Context, path string, info FileMetaInfo, dirEntries []FileMetaInfo) error { pathRel := strings.TrimPrefix(path, w.cfg.Root) if info == nil { var err error fi, err := w.cfg.Fs.Stat(path) if err != nil { if path == w.cfg.Root && herrors.IsNotExist(err) { return nil } if w.checkErr(path, err) { return nil } return fmt.Errorf("walk: stat: %s", err) } info = fi.(FileMetaInfo) } err := w.cfg.WalkFn(ctx, path, info) if err != nil { if info.IsDir() && err == filepath.SkipDir { return nil } return err } if !info.IsDir() { return nil } if dirEntries == nil { f, err := w.cfg.Fs.Open(path) if err != nil { if w.checkErr(path, err) { return nil } return fmt.Errorf("walk: open: path: %q filename: %q: %s", path, info.Meta().Filename, err) } fis, newCtx, err := ReadDirWithContext(ctx, f, -1) ctx = newCtx f.Close() if err != nil { if w.checkErr(path, err) { return nil } return fmt.Errorf("walk: Readdir: %w", err) } dirEntries = DirEntriesToFileMetaInfos(fis) for _, fi := range dirEntries { if fi.Meta().PathInfo == nil { fi.Meta().PathInfo = w.cfg.PathParser.Parse("", filepath.Join(pathRel, fi.Name())) } } if w.cfg.SortDirEntries { sort.Slice(dirEntries, func(i, j int) bool { return dirEntries[i].Name() < dirEntries[j].Name() }) } } if w.cfg.IgnoreFile != nil { n := 0 for _, fi := range dirEntries { if !w.cfg.IgnoreFile(fi.Meta().Filename) { dirEntries[n] = fi n++ } } dirEntries = dirEntries[:n] } if w.cfg.HookPre != nil { var err error dirEntries, err = w.cfg.HookPre(ctx, info, path, dirEntries) if err != nil { if err == filepath.SkipDir { return nil } return err } } for _, fim := range dirEntries { nextPath := filepath.Join(path, fim.Name()) err := w.walk(ctx, nextPath, fim, nil) if err != nil { if !fim.IsDir() || err != filepath.SkipDir { return err } } } if w.cfg.HookPost != nil { var err error dirEntries, err = w.cfg.HookPost(ctx, info, path, dirEntries) if err != nil { if err == filepath.SkipDir { return nil } return err } } return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/stacktracer_fs.go
hugofs/stacktracer_fs.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "fmt" "os" "regexp" "runtime" "github.com/gohugoio/hugo/common/types" "github.com/spf13/afero" ) var ( // Make sure we don't accidentally use this in the real Hugo. _ types.DevMarker = (*stacktracerFs)(nil) _ FilesystemUnwrapper = (*stacktracerFs)(nil) ) // NewStacktracerFs wraps the given fs printing stack traces for file creates // matching the given regexp pattern. func NewStacktracerFs(fs afero.Fs, pattern string) afero.Fs { return &stacktracerFs{Fs: fs, re: regexp.MustCompile(pattern)} } // stacktracerFs can be used in hard-to-debug development situations where // you get some input you don't understand where comes from. type stacktracerFs struct { afero.Fs // Will print stacktrace for every file creates matching this pattern. re *regexp.Regexp } func (fs *stacktracerFs) DevOnly() { } func (fs *stacktracerFs) UnwrapFilesystem() afero.Fs { return fs.Fs } func (fs *stacktracerFs) onCreate(filename string) { if fs.re.MatchString(filename) { trace := make([]byte, 1500) runtime.Stack(trace, true) fmt.Printf("\n===========\n%q:\n%s\n", filename, trace) } } func (fs *stacktracerFs) Create(name string) (afero.File, error) { f, err := fs.Fs.Create(name) if err == nil { fs.onCreate(name) } return f, err } func (fs *stacktracerFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { f, err := fs.Fs.OpenFile(name, flag, perm) if err == nil && isWrite(flag) { fs.onCreate(name) } return f, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/filename_filter_fs.go
hugofs/filename_filter_fs.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "io/fs" "os" "strings" "syscall" "time" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/spf13/afero" ) var _ FilesystemUnwrapper = (*filenameFilterFs)(nil) func newFilenameFilterFs(fs afero.Fs, base string, filter *hglob.FilenameFilter) afero.Fs { return &filenameFilterFs{ fs: fs, base: base, filter: filter, } } // filenameFilterFs is a filesystem that filters by filename. type filenameFilterFs struct { base string fs afero.Fs filter *hglob.FilenameFilter } func (fs *filenameFilterFs) UnwrapFilesystem() afero.Fs { return fs.fs } func (fs *filenameFilterFs) Open(name string) (afero.File, error) { fi, err := fs.fs.Stat(name) if err != nil { return nil, err } if !fs.filter.Match(name, fi.IsDir()) { return nil, os.ErrNotExist } f, err := fs.fs.Open(name) if err != nil { return nil, err } if !fi.IsDir() { return f, nil } return &filenameFilterDir{ File: f, base: fs.base, filter: fs.filter, }, nil } func (fs *filenameFilterFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { return fs.Open(name) } func (fs *filenameFilterFs) Stat(name string) (os.FileInfo, error) { fi, err := fs.fs.Stat(name) if err != nil { return nil, err } if !fs.filter.Match(name, fi.IsDir()) { return nil, os.ErrNotExist } return fi, nil } type filenameFilterDir struct { afero.File base string filter *hglob.FilenameFilter } func (f *filenameFilterDir) ReadDir(n int) ([]fs.DirEntry, error) { des, err := f.File.(fs.ReadDirFile).ReadDir(n) if err != nil { return nil, err } i := 0 for _, de := range des { fim := de.(FileMetaInfo) rel := strings.TrimPrefix(fim.Meta().Filename, f.base) if f.filter.Match(rel, de.IsDir()) { des[i] = de i++ } } return des[:i], nil } func (f *filenameFilterDir) Readdir(count int) ([]os.FileInfo, error) { panic("not supported: Use ReadDir") } func (f *filenameFilterDir) Readdirnames(count int) ([]string, error) { des, err := f.ReadDir(count) if err != nil { return nil, err } dirs := make([]string, len(des)) for i, d := range des { dirs[i] = d.Name() } return dirs, nil } func (fs *filenameFilterFs) Chmod(n string, m os.FileMode) error { return syscall.EPERM } func (fs *filenameFilterFs) Chtimes(n string, a, m time.Time) error { return syscall.EPERM } func (fs *filenameFilterFs) Chown(n string, uid, gid int) error { return syscall.EPERM } func (fs *filenameFilterFs) ReadDir(name string) ([]os.FileInfo, error) { panic("not implemented") } func (fs *filenameFilterFs) Remove(n string) error { return syscall.EPERM } func (fs *filenameFilterFs) RemoveAll(p string) error { return syscall.EPERM } func (fs *filenameFilterFs) Rename(o, n string) error { return syscall.EPERM } func (fs *filenameFilterFs) Create(n string) (afero.File, error) { return nil, syscall.EPERM } func (fs *filenameFilterFs) Name() string { return "FinameFilterFS" } func (fs *filenameFilterFs) Mkdir(n string, p os.FileMode) error { return syscall.EPERM } func (fs *filenameFilterFs) MkdirAll(n string, p os.FileMode) error { return syscall.EPERM }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/fileinfo_test.go
hugofs/fileinfo_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "testing" qt "github.com/frankban/quicktest" ) func TestFileMeta(t *testing.T) { c := qt.New(t) c.Run("Merge", func(c *qt.C) { src := &FileMeta{ Filename: "fs1", } dst := &FileMeta{ Filename: "fd1", } dst.Merge(src) c.Assert(dst.Filename, qt.Equals, "fd1") }) c.Run("Copy", func(c *qt.C) { src := &FileMeta{ Filename: "fs1", } dst := src.Copy() c.Assert(dst, qt.Not(qt.Equals), src) c.Assert(dst, qt.DeepEquals, src) }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/hugofs_integration_test.go
hugofs/hugofs_integration_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" ) func TestMountRestrictTheme(t *testing.T) { files := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss"] theme = "mytheme" [[module.mounts]] source = '../file2.txt' target = 'assets/file2.txt' -- themes/mytheme/hugo.toml -- [[module.mounts]] source = '../../file1.txt' target = 'assets/file1.txt' -- file1.txt -- file1 -- file2.txt -- file2 -- layouts/all.html -- All. ` b, err := hugolib.TestE(t, files) b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "mount source must be a local path for modules/themes") } // Issue 14089. func TestMountNodeMoudulesFromTheme(t *testing.T) { filesTemplate := ` -- hugo.toml -- disableKinds = ["taxonomy", "term", "rss"] theme = "mytheme" -- node_modules/bootstrap/foo.txt -- foo project. -- layouts/all.html -- {{ $foo := resources.Get "vendor/bootstrap/foo.txt" }} Foo: {{ with $foo }}{{ .Content }}{{ else }}Fail{{ end }} -- themes/mytheme/hugo.toml -- [[module.mounts]] source = 'NODE_MODULES_SOURCE' # tries first in theme, then in project root target = 'assets/vendor/bootstrap' ` runFiles := func(files string) *hugolib.IntegrationTestBuilder { return hugolib.Test(t, files, hugolib.TestOptOsFs()) } files := strings.ReplaceAll(filesTemplate, "NODE_MODULES_SOURCE", "node_modules/bootstrap") b := runFiles(files) b.AssertFileContent("public/index.html", "Foo: foo project.") // This is for backwards compatibility. ../../node_modules/bootstrap works exactly the same as node_modules/bootstrap. files = strings.ReplaceAll(filesTemplate, "NODE_MODULES_SOURCE", "../../node_modules/bootstrap") b = runFiles(files) b.AssertFileContent("public/index.html", "Foo: foo project.") files = strings.ReplaceAll(filesTemplate, "NODE_MODULES_SOURCE", "node_modules/bootstrap") files += ` -- themes/mytheme/node_modules/bootstrap/foo.txt -- foo theme. ` b = runFiles(files) b.AssertFileContent("public/index.html", "Foo: foo theme.") } func TestMultipleMountsOfTheSameContentDirectoryIssue13818(t *testing.T) { files := ` -- hugo.toml -- [[module.mounts]] source = 'shared/tutorials' target = 'content/product1/tutorials' [[module.mounts]] source = 'shared/tutorials' target = 'content/product2/tutorials' -- shared/tutorials/tutorial1.md -- --- title: "Tutorial 1" --- -- shared/tutorials/tutorial2.md -- --- title: "Tutorial 2" --- -- layouts/all.html -- Title: {{ .Title }}| ` b := hugolib.Test(t, files) b.AssertPublishDir(` product1/tutorials/tutorial1/index.html product1/tutorials/tutorial2/index.html product2/tutorials/tutorial1/index.html product2/tutorials/tutorial2/index.html `) } func TestContentDirPerLangNoDeprecationPleaseIssue14287(t *testing.T) { files := ` -- hugo.toml -- defaultContentLanguage = "en" defaultContentLanguageInSubdir = true [languages] [languages.en] contentDir = "content/en" [languages.fr] contentDir = "content/fr" -- content/en/page.md -- --- title: "English Page" --- -- content/fr/page.md -- --- title: "Page Française" --- -- layouts/all.html -- Title: {{ .Title }}| -- ` b := hugolib.Test(t, files, hugolib.TestOptInfo()) b.AssertFileContent("public/en/page/index.html", "Title: English Page|") b.AssertFileContent("public/fr/page/index.html", "Title: Page Française|") b.AssertLogContains("! deprecated") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/rootmapping_fs.go
hugofs/rootmapping_fs.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "errors" "fmt" iofs "io/fs" "os" "path" "path/filepath" "strings" "sync/atomic" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/paths" "github.com/bep/overlayfs" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugofs/hglob" radix "github.com/gohugoio/go-radix" "github.com/spf13/afero" ) var filepathSeparator = string(filepath.Separator) var _ ReverseLookupProvder = (*RootMappingFs)(nil) // NewRootMappingFs creates a new RootMappingFs on top of the provided with // root mappings with some optional metadata about the root. // Note that From represents a virtual root that maps to the actual filename in To. func NewRootMappingFs(fs afero.Fs, rms ...*RootMapping) (*RootMappingFs, error) { rootMapToReal := radix.New[[]*RootMapping]() realMapToRoot := radix.New[[]*RootMapping]() id := fmt.Sprintf("rfs-%d", rootMappingFsCounter.Add(1)) addMapping := func(key string, rm *RootMapping, to *radix.Tree[[]*RootMapping]) { mappings, _ := to.Get(key) mappings = append(mappings, rm) to.Insert(key, mappings) } for _, rm := range rms { rm.clean() rm.FromBase = files.ResolveComponentFolder(rm.From) if len(rm.To) < 2 { panic(fmt.Sprintf("invalid root mapping; from/to: %s/%s", rm.From, rm.To)) } fi, err := fs.Stat(rm.To) if err != nil { if os.IsNotExist(err) { continue } return nil, err } if rm.Meta == nil { rm.Meta = NewFileMeta() } if rm.FromBase == "" { panic(" rm.FromBase is empty") } rm.Meta.Component = rm.FromBase rm.Meta.Module = rm.Module rm.Meta.ModuleOrdinal = rm.ModuleOrdinal rm.Meta.IsProject = rm.IsProject rm.Meta.BaseDir = rm.ToBase if !fi.IsDir() { // We do allow single file mounts. // However, the file system logic will be much simpler with just directories. // So, convert this mount into a directory mount with a renamer, // which will tell the caller if name should be included. dirFrom, nameFrom := filepath.Split(rm.From) dirTo, nameTo := filepath.Split(rm.To) dirFrom, dirTo = strings.TrimSuffix(dirFrom, filepathSeparator), strings.TrimSuffix(dirTo, filepathSeparator) rm.From = dirFrom singleFileMeta := rm.Meta.Copy() singleFileMeta.Name = nameFrom rm.fiSingleFile = NewFileMetaInfo(fi, singleFileMeta) rm.To = dirTo rm.Meta.Rename = func(name string, toFrom bool) (string, bool) { if toFrom { if name == nameTo { return nameFrom, true } return "", false } if name == nameFrom { return nameTo, true } return "", false } nameToFilename := filepathSeparator + nameTo rm.Meta.InclusionFilter = rm.Meta.InclusionFilter.Append(hglob.NewFilenameFilterForInclusionFunc( func(filename string) bool { return nameToFilename == filename }, )) // Refresh the FileInfo object. fi, err = fs.Stat(rm.To) if err != nil { if herrors.IsNotExist(err) { continue } return nil, err } } // Extract "blog" from "content/blog" rm.path = strings.TrimPrefix(strings.TrimPrefix(rm.From, rm.FromBase), filepathSeparator) rm.Meta.SourceRoot = fi.(MetaProvider).Meta().Filename meta := rm.Meta.Copy() if !fi.IsDir() { _, name := filepath.Split(rm.From) meta.Name = name } rm.fi = NewFileMetaInfo(fi, meta) addMapping(filepathSeparator+rm.From, rm, rootMapToReal) rev := rm.To if !strings.HasPrefix(rev, filepathSeparator) { rev = filepathSeparator + rev } addMapping(rev, rm, realMapToRoot) } rfs := &RootMappingFs{ id: id, Fs: fs, rootMapToReal: rootMapToReal, realMapToRoot: realMapToRoot, } return rfs, nil } func newRootMappingFsFromFromTo( baseDir string, fs afero.Fs, fromTo ...string, ) (*RootMappingFs, error) { rms := make([]*RootMapping, len(fromTo)/2) for i, j := 0, 0; j < len(fromTo); i, j = i+1, j+2 { rms[i] = &RootMapping{ From: fromTo[j], To: fromTo[j+1], ToBase: baseDir, } } return NewRootMappingFs(fs, rms...) } // RootMapping describes a virtual file or directory mount. type RootMapping struct { From string // The virtual mount. FromBase string // The base directory of the virtual mount. To string // The source directory or file. ToBase string // The base of To. May be empty if an absolute path was provided. Module string // The module path/ID. ModuleOrdinal int // The module ordinal starting with 0 which is the project. IsProject bool // Whether this is a mount in the main project. Meta *FileMeta // File metadata (lang etc.) fi FileMetaInfo fiSingleFile FileMetaInfo // Also set when this mounts represents a single file with a rename func. path string // The virtual mount point, e.g. "blog". } type keyRootMappings struct { key string roots []*RootMapping } func (rm *RootMapping) clean() { rm.From = strings.Trim(filepath.Clean(rm.From), filepathSeparator) rm.To = filepath.Clean(rm.To) } func (r RootMapping) filename(name string) string { if name == "" { return r.To } return filepath.Join(r.To, strings.TrimPrefix(name, r.From)) } func (r RootMapping) trimFrom(name string) string { if name == "" { return "" } return strings.TrimPrefix(name, r.From) } var _ FilesystemUnwrapper = (*RootMappingFs)(nil) // A RootMappingFs maps several roots into one. Note that the root of this filesystem // is directories only, and they will be returned in Readdir and Readdirnames // in the order given. type RootMappingFs struct { id string afero.Fs rootMapToReal *radix.Tree[[]*RootMapping] realMapToRoot *radix.Tree[[]*RootMapping] } var rootMappingFsCounter atomic.Int32 func (fs *RootMappingFs) Mounts(base string) ([]FileMetaInfo, error) { base = filepathSeparator + fs.cleanName(base) roots := fs.getRootsWithPrefix(base) if roots == nil { return nil, nil } fss := make([]FileMetaInfo, 0, len(roots)) for _, r := range roots { if r.fiSingleFile != nil { // A single file mount. fss = append(fss, r.fiSingleFile) continue } bfs := NewBasePathFs(fs.Fs, r.To) fs := bfs if r.Meta.InclusionFilter != nil { fs = newFilenameFilterFs(fs, r.To, r.Meta.InclusionFilter) } fs = decorateDirs(fs, r.Meta) fi, err := fs.Stat("") if err != nil { continue } fss = append(fss, fi.(FileMetaInfo)) } return fss, nil } func (fs *RootMappingFs) Key() string { return fs.id } func (fs *RootMappingFs) UnwrapFilesystem() afero.Fs { return fs.Fs } // Filter creates a copy of this filesystem with only mappings matching a filter. func (fs RootMappingFs) Filter(f func(m *RootMapping) bool) *RootMappingFs { rootMapToReal := radix.New[[]*RootMapping]() var walkFn radix.WalkFn[[]*RootMapping] = func(b string, rms []*RootMapping) (radix.WalkFlag, []*RootMapping, error) { var nrms []*RootMapping for _, rm := range rms { if f(rm) { nrms = append(nrms, rm) } } if len(nrms) != 0 { rootMapToReal.Insert(b, nrms) } return radix.WalkContinue, nil, nil } fs.rootMapToReal.Walk(walkFn) fs.rootMapToReal = rootMapToReal return &fs } // Open opens the named file for reading. func (fs *RootMappingFs) Open(name string) (afero.File, error) { fis, err := fs.doStat(name) if err != nil { return nil, err } return fs.newUnionFile(fis...) } // Stat returns the os.FileInfo structure describing a given file. If there is // an error, it will be of type *os.PathError. // If multiple roots are found, the last one will be used. func (fs *RootMappingFs) Stat(name string) (os.FileInfo, error) { fis, err := fs.doStat(name) if err != nil { return nil, err } return fis[len(fis)-1], nil } type ComponentPath struct { Component string Path string Watch bool } func (c ComponentPath) ComponentPathJoined() string { return path.Join(c.Component, c.Path) } type ReverseLookupProvder interface { ReverseLookup(filename string) ([]ComponentPath, error) ReverseLookupComponent(component, filename string) ([]ComponentPath, error) } // func (fs *RootMappingFs) ReverseStat(filename string) ([]FileMetaInfo, error) func (fs *RootMappingFs) ReverseLookup(filename string) ([]ComponentPath, error) { return fs.ReverseLookupComponent("", filename) } func (fs *RootMappingFs) ReverseLookupComponent(component, filename string) ([]ComponentPath, error) { filename = fs.cleanName(filename) key := filepathSeparator + filename s, roots := fs.getRootsReverse(key) if len(roots) == 0 { return nil, nil } var cps []ComponentPath base := strings.TrimPrefix(key, s) dir, name := filepath.Split(base) for _, first := range roots { if component != "" && first.FromBase != component { continue } var filename string if first.Meta.Rename != nil { // Single file mount. if newname, ok := first.Meta.Rename(name, true); ok { filename = filepathSeparator + filepath.Join(first.path, dir, newname) } else { continue } } else { // Now we know that this file _could_ be in this fs. filename = filepathSeparator + filepath.Join(first.path, dir, name) } cps = append(cps, ComponentPath{ Component: first.FromBase, Path: paths.ToSlashTrimLeading(filename), Watch: first.Meta.Watch, }) } return cps, nil } func (fs *RootMappingFs) hasPrefix(prefix string) bool { hasPrefix := false var walkFn radix.WalkFn[[]*RootMapping] = func(b string, rms []*RootMapping) (radix.WalkFlag, []*RootMapping, error) { hasPrefix = true return radix.WalkStop, nil, nil } fs.rootMapToReal.WalkPrefix(prefix, walkFn) return hasPrefix } func (fs *RootMappingFs) getRoot(key string) []*RootMapping { v, _ := fs.rootMapToReal.Get(key) return v } func (fs *RootMappingFs) getRoots(key string) (string, []*RootMapping) { tree := fs.rootMapToReal levels := strings.Count(key, filepathSeparator) seen := make(map[*RootMapping]bool) var roots []*RootMapping var s string for { var found bool ss, vv, found := tree.LongestPrefix(key) if !found || (levels < 2 && ss == key) { break } for _, rm := range vv { if !seen[rm] { seen[rm] = true roots = append(roots, rm) } } s = ss // We may have more than one root for this key, so walk up. oldKey := key key = filepath.Dir(key) if key == oldKey { break } } return s, roots } func (fs *RootMappingFs) getRootsReverse(key string) (string, []*RootMapping) { tree := fs.realMapToRoot s, v, _ := tree.LongestPrefix(key) return s, v } func (fs *RootMappingFs) getRootsWithPrefix(prefix string) []*RootMapping { var roots []*RootMapping var walkFn radix.WalkFn[[]*RootMapping] = func(b string, v []*RootMapping) (radix.WalkFlag, []*RootMapping, error) { roots = append(roots, v...) return radix.WalkContinue, nil, nil } fs.rootMapToReal.WalkPrefix(prefix, walkFn) return roots } func (fs *RootMappingFs) getAncestors(prefix string) []keyRootMappings { var roots []keyRootMappings var walkFn radix.WalkFn[[]*RootMapping] = func(s string, v []*RootMapping) (radix.WalkFlag, []*RootMapping, error) { if strings.HasPrefix(prefix, s+filepathSeparator) { roots = append(roots, keyRootMappings{ key: s, roots: v, }) } return radix.WalkContinue, nil, nil } fs.rootMapToReal.WalkPath(prefix, walkFn) return roots } func (fs *RootMappingFs) newUnionFile(fis ...FileMetaInfo) (afero.File, error) { if len(fis) == 1 { return fis[0].Meta().Open() } if !fis[0].IsDir() { // Pick the last file mount. return fis[len(fis)-1].Meta().Open() } openers := make([]func() (afero.File, error), len(fis)) for i := len(fis) - 1; i >= 0; i-- { fi := fis[i] openers[i] = func() (afero.File, error) { meta := fi.Meta() f, err := meta.Open() if err != nil { return nil, err } return &rootMappingDir{DirOnlyOps: f, fs: fs, name: meta.Name, meta: meta}, nil } } merge := func(lofi, bofi []iofs.DirEntry) []iofs.DirEntry { // Ignore duplicate directory entries for _, fi1 := range bofi { var found bool for _, fi2 := range lofi { if !fi2.IsDir() { continue } if fi1.Name() == fi2.Name() { found = true break } } if !found { lofi = append(lofi, fi1) } } return lofi } info := func() (os.FileInfo, error) { return fis[0], nil } return overlayfs.OpenDir(merge, info, openers...) } func (fs *RootMappingFs) cleanName(name string) string { name = strings.Trim(filepath.Clean(name), filepathSeparator) if name == "." { name = "" } return name } func (rfs *RootMappingFs) collectDirEntries(prefix string) ([]iofs.DirEntry, error) { prefix = filepathSeparator + rfs.cleanName(prefix) var fis []iofs.DirEntry seen := make(map[string]bool) // Prevent duplicate directories level := strings.Count(prefix, filepathSeparator) collectDir := func(rm *RootMapping, fi FileMetaInfo) error { f, err := fi.Meta().Open() if err != nil { return err } direntries, err := f.(iofs.ReadDirFile).ReadDir(-1) if err != nil { f.Close() return err } for _, fi := range direntries { meta := fi.(FileMetaInfo).Meta() meta.Merge(rm.Meta) if !rm.Meta.InclusionFilter.Match(strings.TrimPrefix(meta.Filename, meta.SourceRoot), fi.IsDir()) { continue } if fi.IsDir() { name := fi.Name() if seen[name] { continue } seen[name] = true opener := func() (afero.File, error) { return rfs.Open(filepath.Join(rm.From, name)) } fi = newDirNameOnlyFileInfo(name, meta, opener) } else if rm.Meta.Rename != nil { n, ok := rm.Meta.Rename(fi.Name(), true) if !ok { continue } fi.(MetaProvider).Meta().Name = n } fis = append(fis, fi) } f.Close() return nil } // First add any real files/directories. rms := rfs.getRoot(prefix) for _, rm := range rms { if err := collectDir(rm, rm.fi); err != nil { return nil, err } } // Next add any file mounts inside the given directory. prefixInside := prefix + filepathSeparator var walkFn radix.WalkFn[[]*RootMapping] = func(s string, rms []*RootMapping) (radix.WalkFlag, []*RootMapping, error) { if (strings.Count(s, filepathSeparator) - level) != 1 { // This directory is not part of the current, but we // need to include the first name part to make it // navigable. path := strings.TrimPrefix(s, prefixInside) parts := strings.Split(path, filepathSeparator) name := parts[0] if seen[name] { return radix.WalkContinue, nil, nil } seen[name] = true opener := func() (afero.File, error) { return rfs.Open(path) } fi := newDirNameOnlyFileInfo(name, nil, opener) fis = append(fis, fi) return radix.WalkContinue, nil, nil } for _, rm := range rms { name := filepath.Base(rm.From) if seen[name] { continue } seen[name] = true opener := func() (afero.File, error) { return rfs.Open(rm.From) } fi := newDirNameOnlyFileInfo(name, rm.Meta, opener) fis = append(fis, fi) } return radix.WalkContinue, nil, nil } rfs.rootMapToReal.WalkPrefix(prefixInside, walkFn) // Finally add any ancestor dirs with files in this directory. ancestors := rfs.getAncestors(prefix) for _, root := range ancestors { subdir := strings.TrimPrefix(prefix, root.key) for _, rm := range root.roots { if rm.fi.IsDir() { fi, err := rm.fi.Meta().JoinStat(subdir) if err == nil { if err := collectDir(rm, fi); err != nil { return nil, err } } } } } return fis, nil } func (fs *RootMappingFs) doStat(name string) ([]FileMetaInfo, error) { fis, err := fs.doDoStat(name) if err != nil { return nil, err } // Sanity check. Check that all is either file or directories. var isDir, isFile bool for _, fi := range fis { if fi.IsDir() { isDir = true } else { isFile = true } } if isDir && isFile { // For now. return nil, os.ErrNotExist } return fis, nil } func (fs *RootMappingFs) doDoStat(name string) ([]FileMetaInfo, error) { name = fs.cleanName(name) key := filepathSeparator + name roots := fs.getRoot(key) if roots == nil { if fs.hasPrefix(key) { // We have directories mounted below this. // Make it look like a directory. return []FileMetaInfo{newDirNameOnlyFileInfo(name, nil, fs.virtualDirOpener(name))}, nil } // Find any real directories with this key. _, roots := fs.getRoots(key) if roots == nil { return nil, &os.PathError{Op: "LStat", Path: name, Err: os.ErrNotExist} } var err error var fis []FileMetaInfo for _, rm := range roots { var fi FileMetaInfo fi, err = fs.statRoot(rm, name) if err == nil { fis = append(fis, fi) } } if fis != nil { return fis, nil } if err == nil { err = &os.PathError{Op: "LStat", Path: name, Err: err} } return nil, err } return []FileMetaInfo{newDirNameOnlyFileInfo(name, roots[0].Meta, fs.virtualDirOpener(name))}, nil } func (fs *RootMappingFs) statRoot(root *RootMapping, filename string) (FileMetaInfo, error) { dir, name := filepath.Split(filename) if root.Meta.Rename != nil { n, ok := root.Meta.Rename(name, false) if !ok { return nil, os.ErrNotExist } filename = filepath.Join(dir, n) } if !root.Meta.InclusionFilter.Match(root.trimFrom(filename), true) { return nil, os.ErrNotExist } filename = root.filename(filename) fi, err := fs.Fs.Stat(filename) if err != nil { return nil, err } var opener func() (afero.File, error) if !fi.IsDir() { // Open the file directly. // Opens the real file directly. opener = func() (afero.File, error) { return fs.Fs.Open(filename) } } else if root.Meta.Rename != nil { // A single file mount where we have mounted the containing directory. n, ok := root.Meta.Rename(fi.Name(), true) if !ok { return nil, os.ErrNotExist } meta := fi.(MetaProvider).Meta() meta.Name = n // Opens the real file directly. opener = func() (afero.File, error) { return fs.Fs.Open(filename) } } else { // Make sure metadata gets applied in ReadDir. opener = fs.realDirOpener(filename, root.Meta) } fim := decorateFileInfo(fi, opener, "", root.Meta) return fim, nil } func (fs *RootMappingFs) virtualDirOpener(name string) func() (afero.File, error) { return func() (afero.File, error) { return &rootMappingDir{name: name, fs: fs}, nil } } func (fs *RootMappingFs) realDirOpener(name string, meta *FileMeta) func() (afero.File, error) { return func() (afero.File, error) { f, err := fs.Fs.Open(name) if err != nil { return nil, err } return &rootMappingDir{name: name, meta: meta, fs: fs, DirOnlyOps: f}, nil } } var _ iofs.ReadDirFile = (*rootMappingDir)(nil) type rootMappingDir struct { *noOpRegularFileOps DirOnlyOps fs *RootMappingFs name string meta *FileMeta } func (f *rootMappingDir) Close() error { if f.DirOnlyOps == nil { return nil } return f.DirOnlyOps.Close() } func (f *rootMappingDir) Name() string { return f.name } func (f *rootMappingDir) ReadDir(count int) ([]iofs.DirEntry, error) { if f.DirOnlyOps != nil { fis, err := f.DirOnlyOps.(iofs.ReadDirFile).ReadDir(count) if err != nil { return nil, err } var result []iofs.DirEntry for _, fi := range fis { fim := decorateFileInfo(fi, nil, "", f.meta) meta := fim.Meta() if f.meta.InclusionFilter.Match(strings.TrimPrefix(meta.Filename, meta.SourceRoot), fim.IsDir()) { result = append(result, fim) } } return result, nil } return f.fs.collectDirEntries(f.name) } // Sentinel error to signal that a file is a directory. var errIsDir = errors.New("isDir") func (f *rootMappingDir) Stat() (iofs.FileInfo, error) { return nil, errIsDir } func (f *rootMappingDir) Readdir(count int) ([]os.FileInfo, error) { panic("not supported: use ReadDir") } // Note that Readdirnames preserves the order of the underlying filesystem(s), // which is usually directory order. func (f *rootMappingDir) Readdirnames(count int) ([]string, error) { dirs, err := f.ReadDir(count) if err != nil { return nil, err } return dirEntriesToNames(dirs), nil } func dirEntriesToNames(fis []iofs.DirEntry) []string { names := make([]string, len(fis)) for i, d := range fis { names[i] = d.Name() } return names }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/walk_test.go
hugofs/walk_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "context" "errors" "fmt" "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/common/para" "github.com/spf13/afero" qt "github.com/frankban/quicktest" ) func TestWalk(t *testing.T) { c := qt.New(t) fs := NewBaseFileDecorator(afero.NewMemMapFs()) afero.WriteFile(fs, "b.txt", []byte("content"), 0o777) afero.WriteFile(fs, "c.txt", []byte("content"), 0o777) afero.WriteFile(fs, "a.txt", []byte("content"), 0o777) names, err := collectPaths(fs, "") c.Assert(err, qt.IsNil) c.Assert(names, qt.DeepEquals, []string{"/a.txt", "/b.txt", "/c.txt"}) } func TestWalkRootMappingFs(t *testing.T) { c := qt.New(t) prepare := func(c *qt.C) afero.Fs { fs := NewBaseFileDecorator(afero.NewMemMapFs()) testfile := "test.txt" c.Assert(afero.WriteFile(fs, filepath.Join("a/b", testfile), []byte("some content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("c/d", testfile), []byte("some content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("e/f", testfile), []byte("some content"), 0o755), qt.IsNil) rm := []*RootMapping{ { From: "static/b", To: "e/f", }, { From: "static/a", To: "c/d", }, { From: "static/c", To: "a/b", }, } rfs, err := NewRootMappingFs(fs, rm...) c.Assert(err, qt.IsNil) return NewBasePathFs(rfs, "static") } c.Run("Basic", func(c *qt.C) { bfs := prepare(c) names, err := collectPaths(bfs, "") c.Assert(err, qt.IsNil) c.Assert(names, qt.DeepEquals, []string{"/a/test.txt", "/b/test.txt", "/c/test.txt"}) }) c.Run("Para", func(c *qt.C) { bfs := prepare(c) p := para.New(4) r, _ := p.Start(context.Background()) for range 8 { r.Run(func() error { _, err := collectPaths(bfs, "") if err != nil { return err } fi, err := bfs.Stat("b/test.txt") if err != nil { return err } meta := fi.(FileMetaInfo).Meta() if meta.Filename == "" { return errors.New("fail") } return nil }) } c.Assert(r.Wait(), qt.IsNil) }) } func collectPaths(fs afero.Fs, root string) ([]string, error) { var names []string walkFn := func(ctx context.Context, path string, info FileMetaInfo) error { if info.IsDir() { return nil } names = append(names, info.Meta().PathInfo.Path()) return nil } w := NewWalkway(WalkwayConfig{Fs: fs, Root: root, WalkFn: walkFn, SortDirEntries: true, FailOnNotExist: true}) err := w.Walk() return names, err } func collectFileinfos(fs afero.Fs, root string) ([]FileMetaInfo, error) { var fis []FileMetaInfo walkFn := func(ctx context.Context, path string, info FileMetaInfo) error { fis = append(fis, info) return nil } w := NewWalkway(WalkwayConfig{Fs: fs, Root: root, WalkFn: walkFn, SortDirEntries: true, FailOnNotExist: true}) err := w.Walk() return fis, err } func BenchmarkWalk(b *testing.B) { c := qt.New(b) fs := NewBaseFileDecorator(afero.NewMemMapFs()) writeFiles := func(dir string, numfiles int) { for i := range numfiles { filename := filepath.Join(dir, fmt.Sprintf("file%d.txt", i)) c.Assert(afero.WriteFile(fs, filename, []byte("content"), 0o777), qt.IsNil) } } const numFilesPerDir = 20 writeFiles("root", numFilesPerDir) writeFiles("root/l1_1", numFilesPerDir) writeFiles("root/l1_1/l2_1", numFilesPerDir) writeFiles("root/l1_1/l2_2", numFilesPerDir) writeFiles("root/l1_2", numFilesPerDir) writeFiles("root/l1_2/l2_1", numFilesPerDir) writeFiles("root/l1_3", numFilesPerDir) walkFn := func(ctx context.Context, path string, info FileMetaInfo) error { if info.IsDir() { return nil } filename := info.Meta().Filename if !strings.HasPrefix(filename, "root") { return errors.New(filename) } return nil } for b.Loop() { w := NewWalkway(WalkwayConfig{Fs: fs, Root: "root", WalkFn: walkFn}) if err := w.Walk(); err != nil { b.Fatal(err) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/component_fs.go
hugofs/component_fs.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "context" iofs "io/fs" "os" "path" "runtime" "sort" "github.com/bep/helpers/contexthelpers" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "github.com/spf13/afero" "golang.org/x/text/unicode/norm" ) // NewComponentFs creates a new component filesystem. func NewComponentFs(opts ComponentFsOptions) *componentFs { if opts.Component == "" { panic("ComponentFsOptions.PathParser.Component must be set") } if opts.Fs == nil { panic("ComponentFsOptions.Fs must be set") } bfs := NewBasePathFs(opts.Fs, opts.Component) return &componentFs{Fs: bfs, opts: opts} } var ( _ FilesystemUnwrapper = (*componentFs)(nil) _ ReadDirWithContextDir = (*componentFsDir)(nil) ) // componentFs is a filesystem that holds one of the Hugo components, e.g. content, layouts etc. type componentFs struct { afero.Fs opts ComponentFsOptions } func (fs *componentFs) UnwrapFilesystem() afero.Fs { return fs.Fs } type componentFsDir struct { *noOpRegularFileOps DirOnlyOps name string // the name passed to Open fs *componentFs } type ( contextKey uint8 ) const ( contextKeyIsInLeafBundle contextKey = iota ) var componentFsContext = struct { IsInLeafBundle contexthelpers.ContextDispatcher[bool] }{ IsInLeafBundle: contexthelpers.NewContextDispatcher[bool](contextKeyIsInLeafBundle), } func (f *componentFsDir) ReadDirWithContext(ctx context.Context, count int) ([]iofs.DirEntry, context.Context, error) { fis, err := f.DirOnlyOps.(iofs.ReadDirFile).ReadDir(-1) if err != nil { return nil, ctx, err } // Filter out any symlinks. n := 0 for _, fi := range fis { // IsDir will always be false for symlinks. keep := fi.IsDir() if !keep { // This is unfortunate, but is the only way to determine if it is a symlink. info, err := fi.Info() if err != nil { if herrors.IsNotExist(err) { continue } return nil, ctx, err } if info.Mode()&os.ModeSymlink == 0 { keep = true } } if keep { fis[n] = fi n++ } } fis = fis[:n] n = 0 for _, fi := range fis { s := path.Join(f.name, fi.Name()) if _, ok := f.fs.applyMeta(fi, s); ok { fis[n] = fi n++ } } fis = fis[:n] n = 0 sort.Slice(fis, func(i, j int) bool { fimi, fimj := fis[i].(FileMetaInfo), fis[j].(FileMetaInfo) if fimi.IsDir() != fimj.IsDir() { return fimi.IsDir() } fimim, fimjm := fimi.Meta(), fimj.Meta() bi, bj := fimim.PathInfo.Base(), fimjm.PathInfo.Base() if bi == bj { matrixi, matrixj := fimim.SitesMatrix, fimjm.SitesMatrix l1, l2 := matrixi.LenVectors(), matrixj.LenVectors() if l1 != l2 { // Pull the ones with the least number of sites defined to the top. return l1 < l2 } } if fimim.ModuleOrdinal != fimjm.ModuleOrdinal { switch f.fs.opts.Component { case files.ComponentFolderI18n: // The way the language files gets loaded means that // we need to provide the least important files first (e.g. the theme files). return fimim.ModuleOrdinal > fimjm.ModuleOrdinal default: return fimim.ModuleOrdinal < fimjm.ModuleOrdinal } } pii, pij := fimim.PathInfo, fimjm.PathInfo if pii != nil { basei, basej := pii.Base(), pij.Base() exti, extj := pii.Ext(), pij.Ext() if f.fs.opts.Component == files.ComponentFolderContent { // Pull bundles to the top. if pii.IsBundle() != pij.IsBundle() { return pii.IsBundle() } } if exti != extj { return exti > extj } if basei != basej { return basei < basej } } if fimim.Weight != fimjm.Weight { return fimim.Weight > fimjm.Weight } return fimi.Name() < fimj.Name() }) if f.fs.opts.Component == files.ComponentFolderContent { isInLeafBundle := componentFsContext.IsInLeafBundle.Get(ctx) var isCurrentLeafBundle bool for _, fi := range fis { if fi.IsDir() { continue } pi := fi.(FileMetaInfo).Meta().PathInfo if pi.IsLeafBundle() { isCurrentLeafBundle = true break } } if !isInLeafBundle && isCurrentLeafBundle { ctx = componentFsContext.IsInLeafBundle.Set(ctx, true) } if isInLeafBundle || isCurrentLeafBundle { for _, fi := range fis { if fi.IsDir() { continue } pi := fi.(FileMetaInfo).Meta().PathInfo if pi.Type() != paths.TypeContentData { // Everything below a leaf bundle is a resource. isResource := isInLeafBundle && pi.Type() > paths.TypeFile // Every sibling of a leaf bundle is a resource. isResource = isResource || (isCurrentLeafBundle && !pi.IsLeafBundle()) if isResource { paths.ModifyPathBundleTypeResource(pi) } } } } } type typeBase struct { Type paths.Type Base string } variants := make(map[typeBase][]sitesmatrix.VectorProvider) for _, fi := range fis { if !fi.IsDir() { meta := fi.(FileMetaInfo).Meta() pi := meta.PathInfo if pi.Component() == files.ComponentFolderLayouts || pi.Component() == files.ComponentFolderContent { var base string switch pi.Component() { case files.ComponentFolderContent: base = pi.Base() + pi.Custom() default: base = pi.PathNoLang() } baseName := typeBase{pi.Type(), base} // There may be multiple languge/version/role combinations for the same file. // The most important come early. matrixes, found := variants[baseName] if found { complement := meta.SitesMatrix.Complement(matrixes...) if complement == nil || complement.LenVectors() == 0 { continue } matrixes = append(matrixes, meta.SitesMatrix) meta.SitesMatrix = complement variants[baseName] = matrixes } else { matrixes = []sitesmatrix.VectorProvider{meta.SitesMatrix} variants[baseName] = matrixes } } } fis[n] = fi n++ } fis = fis[:n] return fis, ctx, nil } // ReadDir reads count entries from this virtual directory and // sorts the entries according to the component filesystem rules. func (f *componentFsDir) ReadDir(count int) ([]iofs.DirEntry, error) { v, _, err := ReadDirWithContext(context.Background(), f.DirOnlyOps, count) return v, err } func (f *componentFsDir) Stat() (iofs.FileInfo, error) { fi, err := f.DirOnlyOps.Stat() if err != nil { return nil, err } fim, _ := f.fs.applyMeta(fi, f.name) return fim, nil } func (fs *componentFs) Stat(name string) (os.FileInfo, error) { fi, err := fs.Fs.Stat(name) if err != nil { return nil, err } fim, _ := fs.applyMeta(fi, name) return fim, nil } func (fs *componentFs) applyMeta(fi FileNameIsDir, name string) (FileMetaInfo, bool) { if runtime.GOOS == "darwin" { name = norm.NFC.String(name) } fim := fi.(FileMetaInfo) meta := fim.Meta() pi := fs.opts.Cfg.PathParser().Parse(fs.opts.Component, name) if pi.Disabled() { return fim, false } meta.PathInfo = pi if !fim.IsDir() { if fileLang := meta.PathInfo.Lang(); fileLang != "" { if idx, ok := fs.opts.Cfg.PathParser().LanguageIndex[fileLang]; ok { // A valid lang set in filename. // Give priority to myfile.sv.txt inside the sv filesystem. meta.Weight++ meta.SitesMatrix = meta.SitesMatrix.WithLanguageIndices(idx) if idx > 0 { // Not the default language, add some weight. meta.SitesMatrix = sitesmatrix.NewWeightedVectorStore(meta.SitesMatrix, 10) } } } switch meta.Component { case files.ComponentFolderLayouts: // Eg. index.fr.html when French isn't defined, // we want e.g. index.html to be used instead. if len(pi.IdentifiersUnknown()) > 0 { meta.Weight-- } } } if fi.IsDir() { meta.OpenFunc = func() (afero.File, error) { return fs.Open(name) } } return fim, true } func (f *componentFsDir) Readdir(count int) ([]os.FileInfo, error) { panic("not supported: Use ReadDir") } func (f *componentFsDir) Readdirnames(count int) ([]string, error) { dirsi, err := f.DirOnlyOps.(iofs.ReadDirFile).ReadDir(count) if err != nil { return nil, err } dirs := make([]string, len(dirsi)) for i, d := range dirsi { dirs[i] = d.Name() } return dirs, nil } type ComponentFsOptions struct { // The filesystem where one or more components are mounted. Fs afero.Fs // The component name, e.g. "content", "layouts" etc. Component string Cfg config.AllProvider } func (fs *componentFs) Open(name string) (afero.File, error) { f, err := fs.Fs.Open(name) if err != nil { return nil, err } fi, err := f.Stat() if err != nil { if err != errIsDir { f.Close() return nil, err } } else if !fi.IsDir() { return f, nil } return &componentFsDir{ DirOnlyOps: f, name: name, fs: fs, }, nil } func (fs *componentFs) ReadDir(name string) ([]os.FileInfo, error) { panic("not implemented") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/hashing_fs_test.go
hugofs/hashing_fs_test.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "fmt" "strings" "testing" qt "github.com/frankban/quicktest" "github.com/spf13/afero" ) type testHashReceiver struct { name string sum uint64 } func (t *testHashReceiver) OnFileClose(name string, checksum uint64) { t.name = name t.sum = checksum } func TestHashingFs(t *testing.T) { c := qt.New(t) fs := afero.NewMemMapFs() observer := &testHashReceiver{} ofs := NewHashingFs(fs, observer) f, err := ofs.Create("hashme") c.Assert(err, qt.IsNil) _, err = f.Write([]byte("content")) c.Assert(err, qt.IsNil) c.Assert(f.Close(), qt.IsNil) c.Assert(observer.sum, qt.Equals, uint64(7807861979271768572)) c.Assert(observer.name, qt.Equals, "hashme") f, err = ofs.Create("nowrites") c.Assert(err, qt.IsNil) c.Assert(f.Close(), qt.IsNil) c.Assert(observer.sum, qt.Equals, uint64(17241709254077376921)) } func BenchmarkHashingFs(b *testing.B) { fs := afero.NewMemMapFs() observer := &testHashReceiver{} ofs := NewHashingFs(fs, observer) content := []byte(strings.Repeat("lorem ipsum ", 1000)) for i := 0; b.Loop(); i++ { f, err := ofs.Create(fmt.Sprintf("file%d", i)) if err != nil { b.Fatal(err) } _, err = f.Write(content) if err != nil { b.Fatal(err) } if err := f.Close(); err != nil { b.Fatal(err) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/noop_fs.go
hugofs/noop_fs.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "errors" "os" "time" "github.com/spf13/afero" ) var ( errNoOp = errors.New("this operation is not supported") _ afero.Fs = (*noOpFs)(nil) // NoOpFs provides a no-op filesystem that implements the afero.Fs // interface. NoOpFs = &noOpFs{} ) type noOpFs struct{} func (fs noOpFs) Create(name string) (afero.File, error) { panic(errNoOp) } func (fs noOpFs) Mkdir(name string, perm os.FileMode) error { return nil } func (fs noOpFs) MkdirAll(path string, perm os.FileMode) error { return nil } func (fs noOpFs) Open(name string) (afero.File, error) { return nil, os.ErrNotExist } func (fs noOpFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { return nil, os.ErrNotExist } func (fs noOpFs) Remove(name string) error { return nil } func (fs noOpFs) RemoveAll(path string) error { return nil } func (fs noOpFs) Rename(oldname string, newname string) error { panic(errNoOp) } func (fs noOpFs) Stat(name string) (os.FileInfo, error) { return nil, os.ErrNotExist } func (fs noOpFs) Name() string { return "noOpFs" } func (fs noOpFs) Chmod(name string, mode os.FileMode) error { panic(errNoOp) } func (fs noOpFs) Chtimes(name string, atime time.Time, mtime time.Time) error { panic(errNoOp) } func (fs *noOpFs) Chown(name string, uid int, gid int) error { panic(errNoOp) } // noOpRegularFileOps implements the non-directory operations of a afero.File // panicking for all operations. type noOpRegularFileOps struct{} func (f *noOpRegularFileOps) Read(p []byte) (n int, err error) { panic(errNoOp) } func (f *noOpRegularFileOps) ReadAt(p []byte, off int64) (n int, err error) { panic(errNoOp) } func (f *noOpRegularFileOps) Seek(offset int64, whence int) (int64, error) { panic(errNoOp) } func (f *noOpRegularFileOps) Write(p []byte) (n int, err error) { panic(errNoOp) } func (f *noOpRegularFileOps) WriteAt(p []byte, off int64) (n int, err error) { panic(errNoOp) } func (f *noOpRegularFileOps) Readdir(count int) ([]os.FileInfo, error) { panic(errNoOp) } func (f *noOpRegularFileOps) Readdirnames(n int) ([]string, error) { panic(errNoOp) } func (f *noOpRegularFileOps) Sync() error { panic(errNoOp) } func (f *noOpRegularFileOps) Truncate(size int64) error { panic(errNoOp) } func (f *noOpRegularFileOps) WriteString(s string) (ret int, err error) { panic(errNoOp) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/dirsmerger.go
hugofs/dirsmerger.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "io/fs" "github.com/bep/overlayfs" ) // AppendDirsMerger merges two directories keeping all regular files // with the first slice as the base. // Duplicate directories in the second slice will be ignored. var AppendDirsMerger overlayfs.DirsMerger = func(lofi, bofi []fs.DirEntry) []fs.DirEntry { for _, fi1 := range bofi { var found bool // Remove duplicate directories. if fi1.IsDir() { for _, fi2 := range lofi { if fi2.IsDir() && fi2.Name() == fi1.Name() { found = true break } } } if !found { lofi = append(lofi, fi1) } } return lofi }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/glob.go
hugofs/glob.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "context" "errors" "path/filepath" "strings" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/spf13/afero" ) // Glob walks the fs and passes all matches to the handle func. // The handle func can return true to signal a stop. func Glob(fs afero.Fs, pattern string, handle func(fi FileMetaInfo) (bool, error)) error { pattern = hglob.NormalizePathNoLower(pattern) if pattern == "" { return nil } root := hglob.ResolveRootDir(pattern) if !strings.HasPrefix(root, "/") { root = "/" + root } pattern = strings.ToLower(pattern) g, err := hglob.GetGlob(pattern) if err != nil { return err } hasSuperAsterisk := strings.Contains(pattern, "**") levels := strings.Count(pattern, "/") // Signals that we're done. done := errors.New("done") wfn := func(ctx context.Context, p string, info FileMetaInfo) error { p = hglob.NormalizePath(p) if info.IsDir() { if !hasSuperAsterisk { // Avoid walking to the bottom if we can avoid it. if p != "" && strings.Count(p, "/") >= levels { return filepath.SkipDir } } return nil } if g.Match(p) { d, err := handle(info) if err != nil { return err } if d { return done } } return nil } w := NewWalkway( WalkwayConfig{ Root: root, Fs: fs, WalkFn: wfn, FailOnNotExist: true, }) err = w.Walk() if err != done { return err } return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/fileinfo.go
hugofs/fileinfo.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package hugofs provides the file systems used by Hugo. package hugofs import ( "errors" "fmt" "io" "io/fs" "os" "path/filepath" "reflect" "runtime" "sort" "sync" "time" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/hugolib/sitesmatrix" "golang.org/x/text/unicode/norm" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/paths" "github.com/spf13/afero" ) func NewFileMeta() *FileMeta { return &FileMeta{} } type FileMeta struct { PathInfo *paths.Path Name string Filename string BaseDir string SourceRoot string Module string ModuleOrdinal int Component string Weight int IsProject bool Watch bool // This file/directory will be built for these sites. SitesMatrix sitesmatrix.VectorStore // This file/directory complements these other sites. SitesComplements sitesmatrix.VectorStore OpenFunc func() (afero.File, error) JoinStatFunc func(name string) (FileMetaInfo, error) // Include only files or directories that match. InclusionFilter *hglob.FilenameFilter // Rename the name part of the file (not the directory). // Returns the new name and a boolean indicating if the file // should be included. Rename func(name string, toFrom bool) (string, bool) } func (m *FileMeta) Copy() *FileMeta { if m == nil { return NewFileMeta() } c := *m return &c } func (m *FileMeta) Merge(from *FileMeta) { if m == nil || from == nil { return } dstv := reflect.Indirect(reflect.ValueOf(m)) srcv := reflect.Indirect(reflect.ValueOf(from)) for i := range dstv.NumField() { v := dstv.Field(i) if !v.CanSet() { continue } if !hreflect.IsTruthfulValue(v) { v.Set(srcv.Field(i)) } } if m.InclusionFilter == nil { m.InclusionFilter = from.InclusionFilter } } func (f *FileMeta) Open() (afero.File, error) { if f.OpenFunc == nil { return nil, errors.New("OpenFunc not set") } return f.OpenFunc() } func (f *FileMeta) ReadAll() ([]byte, error) { file, err := f.Open() if err != nil { return nil, err } defer file.Close() return io.ReadAll(file) } func (f *FileMeta) JoinStat(name string) (FileMetaInfo, error) { if f.JoinStatFunc == nil { return nil, os.ErrNotExist } return f.JoinStatFunc(name) } type FileMetaInfo interface { fs.DirEntry MetaProvider // This is a real hybrid as it also implements the fs.FileInfo interface. FileInfoOptionals } type MetaProvider interface { Meta() *FileMeta } type FileInfoOptionals interface { Size() int64 Mode() fs.FileMode ModTime() time.Time Sys() any } type FileNameIsDir interface { Name() string IsDir() bool } type FileInfoProvider interface { FileInfo() FileMetaInfo } // DirOnlyOps is a subset of the afero.File interface covering // the methods needed for directory operations. type DirOnlyOps interface { io.Closer Name() string Readdir(count int) ([]os.FileInfo, error) Readdirnames(n int) ([]string, error) Stat() (os.FileInfo, error) } type dirEntryMeta struct { fs.DirEntry m *FileMeta fi fs.FileInfo fiInit sync.Once } func (fi *dirEntryMeta) Meta() *FileMeta { return fi.m } // Filename returns the full filename. func (fi *dirEntryMeta) Filename() string { return fi.m.Filename } func (fi *dirEntryMeta) fileInfo() fs.FileInfo { var err error fi.fiInit.Do(func() { fi.fi, err = fi.DirEntry.Info() }) if err != nil { panic(err) } return fi.fi } func (fi *dirEntryMeta) Size() int64 { return fi.fileInfo().Size() } func (fi *dirEntryMeta) Mode() fs.FileMode { return fi.fileInfo().Mode() } func (fi *dirEntryMeta) ModTime() time.Time { return fi.fileInfo().ModTime() } func (fi *dirEntryMeta) Sys() any { return fi.fileInfo().Sys() } // Name returns the file's name. func (fi *dirEntryMeta) Name() string { if name := fi.m.Name; name != "" { return name } return fi.DirEntry.Name() } // dirEntry is an adapter from os.FileInfo to fs.DirEntry type dirEntry struct { fs.FileInfo } var _ fs.DirEntry = dirEntry{} func (d dirEntry) Type() fs.FileMode { return d.FileInfo.Mode().Type() } func (d dirEntry) Info() (fs.FileInfo, error) { return d.FileInfo, nil } func NewFileMetaInfo(fi FileNameIsDir, m *FileMeta) FileMetaInfo { if m == nil { panic("FileMeta must be set") } if fim, ok := fi.(MetaProvider); ok { m.Merge(fim.Meta()) } switch v := fi.(type) { case fs.DirEntry: return &dirEntryMeta{DirEntry: v, m: m} case fs.FileInfo: return &dirEntryMeta{DirEntry: dirEntry{v}, m: m} case nil: return &dirEntryMeta{DirEntry: dirEntry{}, m: m} default: panic(fmt.Sprintf("Unsupported type: %T", fi)) } } type dirNameOnlyFileInfo struct { name string modTime time.Time } func (fi *dirNameOnlyFileInfo) Name() string { return fi.name } func (fi *dirNameOnlyFileInfo) Size() int64 { panic("not implemented") } func (fi *dirNameOnlyFileInfo) Mode() os.FileMode { return os.ModeDir } func (fi *dirNameOnlyFileInfo) ModTime() time.Time { return fi.modTime } func (fi *dirNameOnlyFileInfo) IsDir() bool { return true } func (fi *dirNameOnlyFileInfo) Sys() any { return nil } func newDirNameOnlyFileInfo(name string, meta *FileMeta, fileOpener func() (afero.File, error)) FileMetaInfo { name = normalizeFilename(name) _, base := filepath.Split(name) m := meta.Copy() if m.Filename == "" { m.Filename = name } m.OpenFunc = fileOpener return NewFileMetaInfo( &dirNameOnlyFileInfo{name: base, modTime: htime.Now()}, m, ) } func decorateFileInfo(fi FileNameIsDir, opener func() (afero.File, error), filename string, inMeta *FileMeta) FileMetaInfo { var meta *FileMeta var fim FileMetaInfo var ok bool if fim, ok = fi.(FileMetaInfo); ok { meta = fim.Meta() } else { meta = NewFileMeta() fim = NewFileMetaInfo(fi, meta) } if opener != nil { meta.OpenFunc = opener } nfilename := normalizeFilename(filename) if nfilename != "" { meta.Filename = nfilename } meta.Merge(inMeta) return fim } func DirEntriesToFileMetaInfos(fis []fs.DirEntry) []FileMetaInfo { fims := make([]FileMetaInfo, len(fis)) for i, v := range fis { fim := v.(FileMetaInfo) fims[i] = fim } return fims } func normalizeFilename(filename string) string { if filename == "" { return "" } if runtime.GOOS == "darwin" { // When a file system is HFS+, its filepath is in NFD form. return norm.NFC.String(filename) } return filename } func sortDirEntries(fis []fs.DirEntry) { sort.Slice(fis, func(i, j int) bool { fimi, fimj := fis[i].(FileMetaInfo), fis[j].(FileMetaInfo) return fimi.Meta().Filename < fimj.Meta().Filename }) } // AddFileInfoToError adds file info to the given error. func AddFileInfoToError(err error, fi FileMetaInfo, fs afero.Fs) error { if err == nil { return nil } meta := fi.Meta() filename := meta.Filename // Check if it's already added. for _, ferr := range herrors.UnwrapFileErrors(err) { pos := ferr.Position() errfilename := pos.Filename if errfilename == "" { pos.Filename = filename ferr.UpdatePosition(pos) } if errfilename == "" || errfilename == filename { if filename != "" && ferr.ErrorContext() == nil { f, ioerr := fs.Open(filename) if ioerr != nil { return err } defer f.Close() ferr.UpdateContent(f, nil) } return err } } lineMatcher := herrors.NopLineMatcher if textSegmentErr, ok := err.(*herrors.TextSegmentError); ok { lineMatcher = herrors.ContainsMatcher(textSegmentErr.Segment) } return herrors.NewFileErrorFromFile(err, filename, fs, lineMatcher) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/hashing_fs.go
hugofs/hashing_fs.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "hash" "os" "github.com/cespare/xxhash/v2" "github.com/spf13/afero" ) var ( _ afero.Fs = (*hashingFs)(nil) _ FilesystemUnwrapper = (*hashingFs)(nil) ) // FileHashReceiver will receive the filename an the content's MD5 sum on file close. type FileHashReceiver interface { OnFileClose(name string, checksum uint64) } type hashingFs struct { afero.Fs hashReceiver FileHashReceiver } // NewHashingFs creates a new filesystem that will receive MD5 checksums of // any written file content on Close. Note that this is probably not a good // idea for "full build" situations, but when doing fast render mode, the amount // of files published is low, and it would be really nice to know exactly which // of these files where actually changed. // Note that this will only work for file operations that use the io.Writer // to write content to file, but that is fine for the "publish content" use case. func NewHashingFs(delegate afero.Fs, hashReceiver FileHashReceiver) afero.Fs { return &hashingFs{Fs: delegate, hashReceiver: hashReceiver} } func (fs *hashingFs) UnwrapFilesystem() afero.Fs { return fs.Fs } func (fs *hashingFs) Create(name string) (afero.File, error) { f, err := fs.Fs.Create(name) if err == nil { f = fs.wrapFile(f) } return f, err } func (fs *hashingFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { f, err := fs.Fs.OpenFile(name, flag, perm) if err == nil && isWrite(flag) { f = fs.wrapFile(f) } return f, err } func (fs *hashingFs) wrapFile(f afero.File) afero.File { return &hashingFile{File: f, h: xxhash.New(), hashReceiver: fs.hashReceiver} } func (fs *hashingFs) Name() string { return "hashingFs" } type hashingFile struct { hashReceiver FileHashReceiver h hash.Hash64 afero.File } func (h *hashingFile) Write(p []byte) (n int, err error) { n, err = h.File.Write(p) if err != nil { return } return h.h.Write(p) } func (h *hashingFile) Close() error { h.hashReceiver.OnFileClose(h.Name(), h.h.Sum64()) return h.File.Close() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/fs_test.go
hugofs/fs_test.go
// Copyright 2016 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "testing" "github.com/gohugoio/hugo/config" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/htesting/hqt" "github.com/spf13/afero" ) func TestIsOsFs(t *testing.T) { c := qt.New(t) c.Assert(IsOsFs(Os), qt.Equals, true) c.Assert(IsOsFs(&afero.MemMapFs{}), qt.Equals, false) c.Assert(IsOsFs(NewBasePathFs(&afero.MemMapFs{}, "/public")), qt.Equals, false) c.Assert(IsOsFs(NewBasePathFs(Os, t.TempDir())), qt.Equals, true) } func TestNewDefault(t *testing.T) { c := qt.New(t) v := config.New() v.Set("workingDir", t.TempDir()) v.Set("publishDir", "public") f := NewDefault(v) c.Assert(f.Source, qt.IsNotNil) c.Assert(f.Source, hqt.IsSameType, new(afero.OsFs)) c.Assert(f.Os, qt.IsNotNil) c.Assert(f.WorkingDirReadOnly, qt.IsNotNil) c.Assert(IsOsFs(f.WorkingDirReadOnly), qt.IsTrue) c.Assert(IsOsFs(f.Source), qt.IsTrue) c.Assert(IsOsFs(f.PublishDir), qt.IsTrue) c.Assert(IsOsFs(f.Os), qt.IsTrue) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/createcounting_fs.go
hugofs/createcounting_fs.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "fmt" "os" "sort" "strings" "sync" "github.com/spf13/afero" ) // Reseter is implemented by some of the stateful filesystems. type Reseter interface { Reset() } // DuplicatesReporter reports about duplicate filenames. type DuplicatesReporter interface { ReportDuplicates() string } var _ FilesystemUnwrapper = (*createCountingFs)(nil) func NewCreateCountingFs(fs afero.Fs) afero.Fs { return &createCountingFs{Fs: fs, fileCount: make(map[string]int)} } func (fs *createCountingFs) UnwrapFilesystem() afero.Fs { return fs.Fs } // ReportDuplicates reports filenames written more than once. func (c *createCountingFs) ReportDuplicates() string { c.mu.Lock() defer c.mu.Unlock() var dupes []string for k, v := range c.fileCount { if v > 1 { dupes = append(dupes, fmt.Sprintf("%s (%d)", k, v)) } } if len(dupes) == 0 { return "" } sort.Strings(dupes) return strings.Join(dupes, ", ") } // createCountingFs counts filenames of created files or files opened // for writing. type createCountingFs struct { afero.Fs mu sync.Mutex fileCount map[string]int } func (c *createCountingFs) Reset() { c.mu.Lock() defer c.mu.Unlock() c.fileCount = make(map[string]int) } func (fs *createCountingFs) onCreate(filename string) { fs.mu.Lock() defer fs.mu.Unlock() fs.fileCount[filename] = fs.fileCount[filename] + 1 } func (fs *createCountingFs) Create(name string) (afero.File, error) { f, err := fs.Fs.Create(name) if err == nil { fs.onCreate(name) } return f, err } func (fs *createCountingFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { f, err := fs.Fs.OpenFile(name, flag, perm) if err == nil && isWrite(flag) { fs.onCreate(name) } return f, err }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/filename_filter_fs_test.go
hugofs/filename_filter_fs_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "errors" "fmt" "os" "path/filepath" "testing" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/spf13/afero" qt "github.com/frankban/quicktest" ) func TestFilenameFilterFs(t *testing.T) { c := qt.New(t) base := filepath.FromSlash("/mybase") fs := NewBaseFileDecorator(afero.NewMemMapFs()) for _, letter := range []string{"a", "b", "c"} { for i := 1; i <= 3; i++ { c.Assert(afero.WriteFile(fs, filepath.Join(base, letter, fmt.Sprintf("my%d.txt", i)), []byte("some text file for"+letter), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join(base, letter, fmt.Sprintf("my%d.json", i)), []byte("some json file for"+letter), 0o755), qt.IsNil) } } fs = NewBasePathFs(fs, base) filter, err := hglob.NewFilenameFilter(nil, []string{"/b/**.txt"}) c.Assert(err, qt.IsNil) fs = newFilenameFilterFs(fs, base, filter) assertExists := func(filename string, shouldExist bool) { filename = filepath.Clean(filename) _, err1 := fs.Stat(filename) f, err2 := fs.Open(filename) if shouldExist { c.Assert(err1, qt.IsNil) c.Assert(err2, qt.IsNil) defer f.Close() } else { for _, err := range []error{err1, err2} { c.Assert(err, qt.Not(qt.IsNil)) c.Assert(errors.Is(err, os.ErrNotExist), qt.IsTrue) } } } assertExists("/a/my1.txt", true) assertExists("/b/my1.txt", false) dirB, err := fs.Open("/b") c.Assert(err, qt.IsNil) defer dirB.Close() dirBEntries, err := dirB.Readdirnames(-1) c.Assert(err, qt.IsNil) c.Assert(dirBEntries, qt.DeepEquals, []string{"my1.json", "my2.json", "my3.json"}) dirC, err := fs.Open("/c") c.Assert(err, qt.IsNil) defer dirC.Close() dirCEntries, err := dirC.Readdirnames(-1) c.Assert(err, qt.IsNil) c.Assert(dirCEntries, qt.DeepEquals, []string{"my1.json", "my1.txt", "my2.json", "my2.txt", "my3.json", "my3.txt"}) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/openfiles_fs.go
hugofs/openfiles_fs.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "io/fs" "os" "sync" "github.com/spf13/afero" ) var _ FilesystemUnwrapper = (*OpenFilesFs)(nil) // OpenFilesFs is a wrapper around afero.Fs that keeps track of open files. type OpenFilesFs struct { afero.Fs mu sync.Mutex openFiles map[string]int } func (fs *OpenFilesFs) UnwrapFilesystem() afero.Fs { return fs.Fs } func (fs *OpenFilesFs) Create(name string) (afero.File, error) { f, err := fs.Fs.Create(name) if err != nil { return nil, err } return fs.trackAndWrapFile(f), nil } func (fs *OpenFilesFs) Open(name string) (afero.File, error) { f, err := fs.Fs.Open(name) if err != nil { return nil, err } return fs.trackAndWrapFile(f), nil } func (fs *OpenFilesFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { f, err := fs.Fs.OpenFile(name, flag, perm) if err != nil { return nil, err } return fs.trackAndWrapFile(f), nil } func (fs *OpenFilesFs) trackAndWrapFile(f afero.File) afero.File { fs.mu.Lock() defer fs.mu.Unlock() if fs.openFiles == nil { fs.openFiles = make(map[string]int) } fs.openFiles[f.Name()]++ return &openFilesFsFile{fs: fs, File: f} } type openFilesFsFile struct { fs *OpenFilesFs afero.File } func (f *openFilesFsFile) ReadDir(count int) ([]fs.DirEntry, error) { return f.File.(fs.ReadDirFile).ReadDir(count) } func (f *openFilesFsFile) Close() (err error) { f.fs.mu.Lock() defer f.fs.mu.Unlock() err = f.File.Close() if f.fs.openFiles == nil { return } name := f.Name() f.fs.openFiles[name]-- if f.fs.openFiles[name] <= 0 { delete(f.fs.openFiles, name) } return } func (fs *OpenFilesFs) OpenFiles() map[string]int { fs.mu.Lock() defer fs.mu.Unlock() return fs.openFiles }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/decorators.go
hugofs/decorators.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "fmt" "io/fs" "os" "path/filepath" "github.com/spf13/afero" ) var _ FilesystemUnwrapper = (*baseFileDecoratorFs)(nil) func decorateDirs(fs afero.Fs, meta *FileMeta) afero.Fs { ffs := &baseFileDecoratorFs{Fs: fs} decorator := func(fi FileNameIsDir, name string) (FileNameIsDir, error) { if !fi.IsDir() { // Leave regular files as they are. return fi, nil } return decorateFileInfo(fi, nil, "", meta), nil } ffs.decorate = decorator return ffs } // NewBaseFileDecorator decorates the given Fs to provide the real filename // and an Opener func. func NewBaseFileDecorator(fs afero.Fs, callbacks ...func(fi FileMetaInfo)) afero.Fs { ffs := &baseFileDecoratorFs{Fs: fs} decorator := func(fi FileNameIsDir, filename string) (FileNameIsDir, error) { // Store away the original in case it's a symlink. meta := NewFileMeta() meta.Name = fi.Name() if fi.IsDir() { meta.JoinStatFunc = func(name string) (FileMetaInfo, error) { joinedFilename := filepath.Join(filename, name) fi, err := fs.Stat(joinedFilename) if err != nil { return nil, err } fim, err := ffs.decorate(fi, joinedFilename) if err != nil { return nil, err } return fim.(FileMetaInfo), nil } } opener := func() (afero.File, error) { return ffs.open(filename) } fim := decorateFileInfo(fi, opener, filename, meta) for _, cb := range callbacks { cb(fim) } return fim, nil } ffs.decorate = decorator return ffs } type baseFileDecoratorFs struct { afero.Fs decorate func(fi FileNameIsDir, name string) (FileNameIsDir, error) } func (fs *baseFileDecoratorFs) UnwrapFilesystem() afero.Fs { return fs.Fs } func (fs *baseFileDecoratorFs) Stat(name string) (os.FileInfo, error) { fi, err := fs.Fs.Stat(name) if err != nil { return nil, err } fim, err := fs.decorate(fi, name) if err != nil { return nil, err } return fim.(os.FileInfo), nil } func (fs *baseFileDecoratorFs) Open(name string) (afero.File, error) { return fs.open(name) } func (fs *baseFileDecoratorFs) open(name string) (afero.File, error) { f, err := fs.Fs.Open(name) if err != nil { return nil, err } return &baseFileDecoratorFile{File: f, fs: fs}, nil } type baseFileDecoratorFile struct { afero.File fs *baseFileDecoratorFs } func (l *baseFileDecoratorFile) ReadDir(n int) ([]fs.DirEntry, error) { fis, err := l.File.(fs.ReadDirFile).ReadDir(-1) if err != nil { return nil, err } fisp := make([]fs.DirEntry, len(fis)) for i, fi := range fis { filename := fi.Name() if l.Name() != "" { filename = filepath.Join(l.Name(), fi.Name()) } fid, err := l.fs.decorate(fi, filename) if err != nil { return nil, fmt.Errorf("decorate: %w", err) } fisp[i] = fid.(fs.DirEntry) } return fisp, err } func (l *baseFileDecoratorFile) Readdir(c int) (ofi []os.FileInfo, err error) { panic("not supported: Use ReadDir") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/glob_test.go
hugofs/glob_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "os" "path/filepath" "testing" "github.com/spf13/afero" qt "github.com/frankban/quicktest" ) func TestGlob(t *testing.T) { c := qt.New(t) fs := NewBaseFileDecorator(afero.NewMemMapFs()) create := func(filename string) { filename = filepath.FromSlash(filename) dir := filepath.Dir(filename) if dir != "." { err := fs.MkdirAll(dir, 0o777) c.Assert(err, qt.IsNil) } err := afero.WriteFile(fs, filename, []byte("content "+filename), 0o777) c.Assert(err, qt.IsNil) } collect := func(pattern string) []string { var paths []string h := func(fi FileMetaInfo) (bool, error) { p := fi.Meta().PathInfo.Path() paths = append(paths, p) return false, nil } err := Glob(fs, pattern, h) c.Assert(err, qt.IsNil) return paths } create("/root.json") create("/jsonfiles/d1.json") create("/jsonfiles/d2.json") create("/jsonfiles/sub/d3.json") create("/jsonfiles/d1.xml") create("/a/b/c/e/f.json") create("/UPPER/sub/style.css") create("/root/UPPER/sub/style.css") afero.Walk(fs, "/", func(path string, info os.FileInfo, err error) error { c.Assert(err, qt.IsNil) return nil }) c.Assert(collect(filepath.FromSlash("/jsonfiles/*.json")), qt.HasLen, 2) c.Assert(collect("/*.json"), qt.HasLen, 1) c.Assert(collect("**.json"), qt.HasLen, 5) c.Assert(collect("**"), qt.HasLen, 8) c.Assert(collect(""), qt.HasLen, 0) c.Assert(collect("jsonfiles/*.json"), qt.HasLen, 2) c.Assert(collect("*.json"), qt.HasLen, 1) c.Assert(collect("**.xml"), qt.HasLen, 1) c.Assert(collect("root/UPPER/sub/style.css"), qt.HasLen, 1) c.Assert(collect("UPPER/sub/style.css"), qt.HasLen, 1) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/rootmapping_fs_test.go
hugofs/rootmapping_fs_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "fmt" "path/filepath" "sort" "testing" iofs "io/fs" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugofs/hglob" "github.com/gohugoio/hugo/hugolib/sitesmatrix" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/htesting" "github.com/spf13/afero" ) const ( eni = iota svi noi fri ) var ( en = sitesMatrixForLangs(eni) sv = sitesMatrixForLangs(svi) no = sitesMatrixForLangs(noi) fr = sitesMatrixForLangs(fri) ) func TestLanguageRootMapping(t *testing.T) { c := qt.New(t) v := config.New() v.Set("contentDir", "content") fs := NewBaseFileDecorator(afero.NewMemMapFs()) c.Assert(afero.WriteFile(fs, filepath.Join("content/sv/svdir", "main.txt"), []byte("main sv"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mysvblogcontent", "sv-f.txt"), []byte("some sv blog content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/myenblogcontent", "en-f.txt"), []byte("some en blog content in a"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mysvblogcontent/d1", "sv-d1-f.txt"), []byte("some sv blog content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/myenblogcontent/d1", "en-d1-f.txt"), []byte("some en blog content in a"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/myotherenblogcontent", "en-f2.txt"), []byte("some en content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mysvdocs", "sv-docs.txt"), []byte("some sv docs content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/b/myenblogcontent", "en-b-f.txt"), []byte("some en content"), 0o755), qt.IsNil) rfs, err := NewRootMappingFs(fs, &RootMapping{ From: "content/blog", // Virtual path, first element is one of content, static, layouts etc. To: "themes/a/mysvblogcontent", // Real path Meta: &FileMeta{SitesMatrix: sv}, }, &RootMapping{ From: "content/blog", To: "themes/a/myenblogcontent", Meta: &FileMeta{SitesMatrix: en}, }, &RootMapping{ From: "content/blog", To: "content/sv", Meta: &FileMeta{SitesMatrix: sv}, }, &RootMapping{ From: "content/blog", To: "themes/a/myotherenblogcontent", Meta: &FileMeta{SitesMatrix: en}, }, &RootMapping{ From: "content/docs", To: "themes/a/mysvdocs", Meta: &FileMeta{SitesMatrix: sv}, }, ) c.Assert(err, qt.IsNil) collected, err := collectPaths(rfs, "content") c.Assert(err, qt.IsNil) c.Assert(collected, qt.DeepEquals, []string{"/blog/d1/en-d1-f.txt", "/blog/d1/sv-d1-f.txt", "/blog/en-f.txt", "/blog/en-f2.txt", "/blog/sv-f.txt", "/blog/svdir/main.txt", "/docs/sv-docs.txt"}, qt.Commentf("%#v", collected)) dirs, err := rfs.Mounts(filepath.FromSlash("content/blog")) c.Assert(err, qt.IsNil) c.Assert(len(dirs), qt.Equals, 4) for _, dir := range dirs { f, err := dir.Meta().Open() c.Assert(err, qt.IsNil) f.Close() } blog, err := rfs.Open(filepath.FromSlash("content/blog")) c.Assert(err, qt.IsNil) fis, err := blog.(iofs.ReadDirFile).ReadDir(-1) c.Assert(err, qt.IsNil) for _, fi := range fis { f, err := fi.(FileMetaInfo).Meta().Open() c.Assert(err, qt.IsNil) f.Close() } blog.Close() getDirnames := func(name string, rfs *RootMappingFs) []string { c.Helper() filename := filepath.FromSlash(name) f, err := rfs.Open(filename) c.Assert(err, qt.IsNil) names, err := f.Readdirnames(-1) f.Close() c.Assert(err, qt.IsNil) info, err := rfs.Stat(filename) c.Assert(err, qt.IsNil) f2, err := info.(FileMetaInfo).Meta().Open() c.Assert(err, qt.IsNil) names2, err := f2.Readdirnames(-1) c.Assert(err, qt.IsNil) c.Assert(names2, qt.DeepEquals, names) f2.Close() return names } rfsEn := rfs.Filter(func(rm *RootMapping) bool { return rm.Meta.SitesMatrix.HasLanguage(eni) }) c.Assert(getDirnames("content/blog", rfsEn), qt.DeepEquals, []string{"d1", "en-f.txt", "en-f2.txt"}) rfsSv := rfs.Filter(func(rm *RootMapping) bool { return rm.Meta.SitesMatrix.HasLanguage(svi) }) c.Assert(getDirnames("content/blog", rfsSv), qt.DeepEquals, []string{"d1", "sv-f.txt", "svdir"}) // Make sure we have not messed with the original c.Assert(getDirnames("content/blog", rfs), qt.DeepEquals, []string{"d1", "sv-f.txt", "en-f.txt", "svdir", "en-f2.txt"}) c.Assert(getDirnames("content", rfsSv), qt.DeepEquals, []string{"blog", "docs"}) c.Assert(getDirnames("content", rfs), qt.DeepEquals, []string{"blog", "docs"}) } func TestRootMappingFsDirnames(t *testing.T) { c := qt.New(t) fs := NewBaseFileDecorator(afero.NewMemMapFs()) testfile := "myfile.txt" c.Assert(fs.Mkdir("f1t", 0o755), qt.IsNil) c.Assert(fs.Mkdir("f2t", 0o755), qt.IsNil) c.Assert(fs.Mkdir("f3t", 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("f2t", testfile), []byte("some content"), 0o755), qt.IsNil) rfs, err := newRootMappingFsFromFromTo("", fs, "static/bf1", "f1t", "static/cf2", "f2t", "static/af3", "f3t") c.Assert(err, qt.IsNil) fif, err := rfs.Stat(filepath.Join("static/cf2", testfile)) c.Assert(err, qt.IsNil) c.Assert(fif.Name(), qt.Equals, "myfile.txt") fifm := fif.(FileMetaInfo).Meta() c.Assert(fifm.Filename, qt.Equals, filepath.FromSlash("f2t/myfile.txt")) root, err := rfs.Open("static") c.Assert(err, qt.IsNil) dirnames, err := root.Readdirnames(-1) c.Assert(err, qt.IsNil) c.Assert(dirnames, qt.DeepEquals, []string{"af3", "bf1", "cf2"}) } func TestRootMappingFsFilename(t *testing.T) { c := qt.New(t) workDir, clean, err := htesting.CreateTempDir(Os, "hugo-root-filename") c.Assert(err, qt.IsNil) defer clean() fs := NewBaseFileDecorator(Os) testfilename := filepath.Join(workDir, "f1t/foo/file.txt") c.Assert(fs.MkdirAll(filepath.Join(workDir, "f1t/foo"), 0o777), qt.IsNil) c.Assert(afero.WriteFile(fs, testfilename, []byte("content"), 0o666), qt.IsNil) rfs, err := newRootMappingFsFromFromTo(workDir, fs, "static/f1", filepath.Join(workDir, "f1t"), "static/f2", filepath.Join(workDir, "f2t")) c.Assert(err, qt.IsNil) fi, err := rfs.Stat(filepath.FromSlash("static/f1/foo/file.txt")) c.Assert(err, qt.IsNil) fim := fi.(FileMetaInfo) c.Assert(fim.Meta().Filename, qt.Equals, testfilename) _, err = rfs.Stat(filepath.FromSlash("static/f1")) c.Assert(err, qt.IsNil) } func TestRootMappingFsMount(t *testing.T) { c := qt.New(t) fs := NewBaseFileDecorator(afero.NewMemMapFs()) testfile := "test.txt" c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mynoblogcontent", testfile), []byte("some no content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/myenblogcontent", testfile), []byte("some en content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mysvblogcontent", testfile), []byte("some sv content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mysvblogcontent", "other.txt"), []byte("some sv content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/singlefiles", "no.txt"), []byte("no text"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/singlefiles", "sv.txt"), []byte("sv text"), 0o755), qt.IsNil) bfs := NewBasePathFs(fs, "themes/a") rm := []*RootMapping{ // Directories { From: "content/blog", To: "mynoblogcontent", Meta: &FileMeta{SitesMatrix: no}, }, { From: "content/blog", To: "myenblogcontent", Meta: &FileMeta{SitesMatrix: en}, }, { From: "content/blog", To: "mysvblogcontent", Meta: &FileMeta{SitesMatrix: sv}, }, // Files { From: "content/singles/p1.md", To: "singlefiles/no.txt", ToBase: "singlefiles", Meta: &FileMeta{SitesMatrix: no}, }, { From: "content/singles/p1.md", To: "singlefiles/sv.txt", ToBase: "singlefiles", Meta: &FileMeta{SitesMatrix: sv}, }, } rfs, err := NewRootMappingFs(bfs, rm...) c.Assert(err, qt.IsNil) blog, err := rfs.Stat(filepath.FromSlash("content/blog")) c.Assert(err, qt.IsNil) c.Assert(blog.IsDir(), qt.Equals, true) blogm := blog.(FileMetaInfo).Meta() c.Assert(blogm.SitesMatrix.HasLanguage(noi), qt.IsTrue) // First match f, err := blogm.Open() c.Assert(err, qt.IsNil) defer f.Close() dirs1, err := f.Readdirnames(-1) c.Assert(err, qt.IsNil) // Union with duplicate dir names filtered. c.Assert(dirs1, qt.DeepEquals, []string{"test.txt", "test.txt", "other.txt", "test.txt"}) d, err := rfs.Open(filepath.FromSlash("content/blog")) c.Assert(err, qt.IsNil) files, err := d.(iofs.ReadDirFile).ReadDir(-1) c.Assert(err, qt.IsNil) c.Assert(len(files), qt.Equals, 4) singlesDir, err := rfs.Open(filepath.FromSlash("content/singles")) c.Assert(err, qt.IsNil) defer singlesDir.Close() singles, err := singlesDir.(iofs.ReadDirFile).ReadDir(-1) c.Assert(err, qt.IsNil) c.Assert(singles, qt.HasLen, 2) for i, langi := range []int{noi, svi} { fi := singles[i].(FileMetaInfo) c.Assert(fi.Meta().SitesMatrix.HasLanguage(langi), qt.IsTrue) c.Assert(fi.Name(), qt.Equals, "p1.md") } } func TestRootMappingFsMountOverlap(t *testing.T) { c := qt.New(t) fs := NewBaseFileDecorator(afero.NewMemMapFs()) c.Assert(afero.WriteFile(fs, filepath.FromSlash("da/a.txt"), []byte("some no content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.FromSlash("db/b.txt"), []byte("some no content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.FromSlash("dc/c.txt"), []byte("some no content"), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.FromSlash("de/e.txt"), []byte("some no content"), 0o755), qt.IsNil) rm := []*RootMapping{ { From: "static", To: "da", }, { From: "static/b", To: "db", }, { From: "static/b/c", To: "dc", }, { From: "/static/e/", To: "de", }, } rfs, err := NewRootMappingFs(fs, rm...) c.Assert(err, qt.IsNil) checkDirnames := func(name string, expect []string) { c.Helper() name = filepath.FromSlash(name) f, err := rfs.Open(name) c.Assert(err, qt.IsNil) defer f.Close() names, err := f.Readdirnames(-1) c.Assert(err, qt.IsNil) c.Assert(names, qt.DeepEquals, expect, qt.Commentf(fmt.Sprintf("%#v", names))) } checkDirnames("static", []string{"a.txt", "b", "e"}) checkDirnames("static/b", []string{"b.txt", "c"}) checkDirnames("static/b/c", []string{"c.txt"}) fi, err := rfs.Stat(filepath.FromSlash("static/b/b.txt")) c.Assert(err, qt.IsNil) c.Assert(fi.Name(), qt.Equals, "b.txt") } func TestRootMappingFsOs(t *testing.T) { c := qt.New(t) fs := NewBaseFileDecorator(afero.NewOsFs()) d, clean, err := htesting.CreateTempDir(fs, "hugo-root-mapping-os") c.Assert(err, qt.IsNil) defer clean() testfile := "myfile.txt" c.Assert(fs.Mkdir(filepath.Join(d, "f1t"), 0o755), qt.IsNil) c.Assert(fs.Mkdir(filepath.Join(d, "f2t"), 0o755), qt.IsNil) c.Assert(fs.Mkdir(filepath.Join(d, "f3t"), 0o755), qt.IsNil) // Deep structure deepDir := filepath.Join(d, "d1", "d2", "d3", "d4", "d5") c.Assert(fs.MkdirAll(deepDir, 0o755), qt.IsNil) for i := 1; i <= 3; i++ { c.Assert(fs.MkdirAll(filepath.Join(d, "d1", "d2", "d3", "d4", fmt.Sprintf("d4-%d", i)), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join(d, "d1", "d2", "d3", fmt.Sprintf("f-%d.txt", i)), []byte("some content"), 0o755), qt.IsNil) } c.Assert(afero.WriteFile(fs, filepath.Join(d, "f2t", testfile), []byte("some content"), 0o755), qt.IsNil) // https://github.com/gohugoio/hugo/issues/6854 mystaticDir := filepath.Join(d, "mystatic", "a", "b", "c") c.Assert(fs.MkdirAll(mystaticDir, 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join(mystaticDir, "ms-1.txt"), []byte("some content"), 0o755), qt.IsNil) rfs, err := newRootMappingFsFromFromTo( d, fs, "static/bf1", filepath.Join(d, "f1t"), "static/cf2", filepath.Join(d, "f2t"), "static/af3", filepath.Join(d, "f3t"), "static", filepath.Join(d, "mystatic"), "static/a/b/c", filepath.Join(d, "d1", "d2", "d3"), "layouts", filepath.Join(d, "d1"), ) c.Assert(err, qt.IsNil) fif, err := rfs.Stat(filepath.Join("static/cf2", testfile)) c.Assert(err, qt.IsNil) c.Assert(fif.Name(), qt.Equals, "myfile.txt") root, err := rfs.Open("static") c.Assert(err, qt.IsNil) dirnames, err := root.Readdirnames(-1) c.Assert(err, qt.IsNil) c.Assert(dirnames, qt.DeepEquals, []string{"a", "af3", "bf1", "cf2"}, qt.Commentf(fmt.Sprintf("%#v", dirnames))) getDirnames := func(dirname string) []string { dirname = filepath.FromSlash(dirname) f, err := rfs.Open(dirname) c.Assert(err, qt.IsNil) defer f.Close() dirnames, err := f.Readdirnames(-1) c.Assert(err, qt.IsNil) sort.Strings(dirnames) return dirnames } c.Assert(getDirnames("static/a/b"), qt.DeepEquals, []string{"c"}) c.Assert(getDirnames("static/a/b/c"), qt.DeepEquals, []string{"d4", "f-1.txt", "f-2.txt", "f-3.txt", "ms-1.txt"}) c.Assert(getDirnames("static/a/b/c/d4"), qt.DeepEquals, []string{"d4-1", "d4-2", "d4-3", "d5"}) all, err := collectPaths(rfs, "static") c.Assert(err, qt.IsNil) c.Assert(all, qt.DeepEquals, []string{"/a/b/c/f-1.txt", "/a/b/c/f-2.txt", "/a/b/c/f-3.txt", "/a/b/c/ms-1.txt", "/cf2/myfile.txt"}) fis, err := collectFileinfos(rfs, "static") c.Assert(err, qt.IsNil) dirc := fis[3].Meta() f, err := dirc.Open() c.Assert(err, qt.IsNil) defer f.Close() dirEntries, err := f.(iofs.ReadDirFile).ReadDir(-1) c.Assert(err, qt.IsNil) sortDirEntries(dirEntries) i := 0 for _, fi := range dirEntries { if fi.IsDir() || fi.Name() == "ms-1.txt" { continue } i++ meta := fi.(FileMetaInfo).Meta() c.Assert(meta.Filename, qt.Equals, filepath.Join(d, fmt.Sprintf("/d1/d2/d3/f-%d.txt", i))) } _, err = rfs.Stat(filepath.FromSlash("layouts/d2/d3/f-1.txt")) c.Assert(err, qt.IsNil) _, err = rfs.Stat(filepath.FromSlash("layouts/d2/d3")) c.Assert(err, qt.IsNil) } func TestRootMappingFsOsBase(t *testing.T) { c := qt.New(t) fs := NewBaseFileDecorator(afero.NewOsFs()) d, clean, err := htesting.CreateTempDir(fs, "hugo-root-mapping-os-base") c.Assert(err, qt.IsNil) defer clean() // Deep structure deepDir := filepath.Join(d, "d1", "d2", "d3", "d4", "d5") c.Assert(fs.MkdirAll(deepDir, 0o755), qt.IsNil) for i := 1; i <= 3; i++ { c.Assert(fs.MkdirAll(filepath.Join(d, "d1", "d2", "d3", "d4", fmt.Sprintf("d4-%d", i)), 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join(d, "d1", "d2", "d3", fmt.Sprintf("f-%d.txt", i)), []byte("some content"), 0o755), qt.IsNil) } mystaticDir := filepath.Join(d, "mystatic", "a", "b", "c") c.Assert(fs.MkdirAll(mystaticDir, 0o755), qt.IsNil) c.Assert(afero.WriteFile(fs, filepath.Join(mystaticDir, "ms-1.txt"), []byte("some content"), 0o755), qt.IsNil) bfs := NewBasePathFs(fs, d) rfs, err := newRootMappingFsFromFromTo( "", bfs, "static", "mystatic", "static/a/b/c", filepath.Join("d1", "d2", "d3"), ) c.Assert(err, qt.IsNil) getDirnames := func(dirname string) []string { dirname = filepath.FromSlash(dirname) f, err := rfs.Open(dirname) c.Assert(err, qt.IsNil) defer f.Close() dirnames, err := f.Readdirnames(-1) c.Assert(err, qt.IsNil) sort.Strings(dirnames) return dirnames } c.Assert(getDirnames("static/a/b/c"), qt.DeepEquals, []string{"d4", "f-1.txt", "f-2.txt", "f-3.txt", "ms-1.txt"}) } func TestRootMappingFileFilter(t *testing.T) { c := qt.New(t) fs := NewBaseFileDecorator(afero.NewMemMapFs()) for _, lang := range []string{"no", "en", "fr"} { for i := 1; i <= 3; i++ { c.Assert(afero.WriteFile(fs, filepath.Join(lang, fmt.Sprintf("my%s%d.txt", lang, i)), []byte("some text file for"+lang), 0o755), qt.IsNil) } } for _, lang := range []string{"no", "en", "fr"} { for i := 1; i <= 3; i++ { c.Assert(afero.WriteFile(fs, filepath.Join(lang, "sub", fmt.Sprintf("mysub%s%d.txt", lang, i)), []byte("some text file for"+lang), 0o755), qt.IsNil) } } rm := []*RootMapping{ { From: "content", To: "no", Meta: &FileMeta{SitesMatrix: no, InclusionFilter: hglob.MustNewFilenameFilter(nil, []string{"**.txt"})}, }, { From: "content", To: "en", Meta: &FileMeta{SitesMatrix: en}, }, { From: "content", To: "fr", Meta: &FileMeta{SitesMatrix: fr, InclusionFilter: hglob.MustNewFilenameFilter(nil, []string{"**.txt"})}, }, } rfs, err := NewRootMappingFs(fs, rm...) c.Assert(err, qt.IsNil) assertExists := func(filename string, shouldExist bool) { c.Helper() filename = filepath.Clean(filename) _, err1 := rfs.Stat(filename) f, err2 := rfs.Open(filename) if shouldExist { c.Assert(err1, qt.IsNil) c.Assert(err2, qt.IsNil) c.Assert(f.Close(), qt.IsNil) } else { c.Assert(err1, qt.Not(qt.IsNil)) c.Assert(err2, qt.Not(qt.IsNil)) } } assertExists("content/myno1.txt", false) assertExists("content/myen1.txt", true) assertExists("content/myfr1.txt", false) dirEntriesSub, err := afero.ReadDir(rfs, filepath.Join("content", "sub")) c.Assert(err, qt.IsNil) c.Assert(len(dirEntriesSub), qt.Equals, 3) f, err := rfs.Open("content") c.Assert(err, qt.IsNil) defer f.Close() dirEntries, err := f.(iofs.ReadDirFile).ReadDir(-1) c.Assert(err, qt.IsNil) c.Assert(len(dirEntries), qt.Equals, 4) } var testDims = sitesmatrix.NewTestingDimensions([]string{"en", "no"}, []string{"v1", "v2", "v3"}, []string{"admin", "editor", "viewer", "guest"}) func sitesMatrixForLangs(langs ...int) *sitesmatrix.IntSets { return sitesmatrix.NewIntSetsBuilder(testDims).WithSets(maps.NewOrderedIntSet(langs...), nil, nil).Build() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/fs.go
hugofs/fs.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package hugofs provides the file systems used by Hugo. package hugofs import ( "context" "fmt" iofs "io/fs" "os" "strings" "github.com/bep/overlayfs" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/config" "github.com/spf13/afero" ) // Os points to the (real) Os filesystem. var Os = &afero.OsFs{} // Fs holds the core filesystems used by Hugo. type Fs struct { // Source is Hugo's source file system. // Note that this will always be a "plain" Afero filesystem: // * afero.OsFs when running in production // * afero.MemMapFs for many of the tests. Source afero.Fs // PublishDir is where Hugo publishes its rendered content. // It's mounted inside publishDir (default /public). PublishDir afero.Fs // PublishDirStatic is the file system used for static files. PublishDirStatic afero.Fs // PublishDirServer is the file system used for serving the public directory with Hugo's development server. // This will typically be the same as PublishDir, but not if --renderStaticToDisk is set. PublishDirServer afero.Fs // Os is an OS file system. // NOTE: Field is currently unused. Os afero.Fs // WorkingDirReadOnly is a read-only file system // restricted to the project working dir. WorkingDirReadOnly afero.Fs // WorkingDirWritable is a writable file system // restricted to the project working dir. WorkingDirWritable afero.Fs } func NewDefault(cfg config.Provider) *Fs { workingDir, publishDir := getWorkingPublishDir(cfg) fs := Os return newFs(fs, fs, workingDir, publishDir) } // NewFrom creates a new Fs based on the provided Afero Fs // as source and destination file systems. // Useful for testing. func NewFrom(fs afero.Fs, conf config.BaseConfig) *Fs { return newFs(fs, fs, conf.WorkingDir, conf.PublishDir) } func NewFromOld(fs afero.Fs, cfg config.Provider) *Fs { workingDir, publishDir := getWorkingPublishDir(cfg) return newFs(fs, fs, workingDir, publishDir) } // NewFromSourceAndDestination creates a new Fs based on the provided Afero Fss // as the source and destination file systems. func NewFromSourceAndDestination(source, destination afero.Fs, cfg config.Provider) *Fs { workingDir, publishDir := getWorkingPublishDir(cfg) return newFs(source, destination, workingDir, publishDir) } func getWorkingPublishDir(cfg config.Provider) (string, string) { workingDir := cfg.GetString("workingDir") publishDir := cfg.GetString("publishDirDynamic") if publishDir == "" { publishDir = cfg.GetString("publishDir") } return workingDir, publishDir } func newFs(source, destination afero.Fs, workingDir, publishDir string) *Fs { if publishDir == "" { panic("publishDir is empty") } if workingDir == "." { workingDir = "" } // Sanity check if IsOsFs(source) && len(workingDir) < 2 { panic("workingDir is too short") } // If this does not exist, it will be created later. absPublishDir := paths.AbsPathify(workingDir, publishDir) pubFs := NewBasePathFs(destination, absPublishDir) return &Fs{ Source: source, PublishDir: pubFs, PublishDirServer: pubFs, PublishDirStatic: pubFs, Os: &afero.OsFs{}, WorkingDirReadOnly: getWorkingDirFsReadOnly(source, workingDir), WorkingDirWritable: getWorkingDirFsWritable(source, workingDir), } } func getWorkingDirFsReadOnly(base afero.Fs, workingDir string) afero.Fs { if workingDir == "" { return NewReadOnlyFs(base) } return NewBasePathFs(NewReadOnlyFs(base), workingDir) } func getWorkingDirFsWritable(base afero.Fs, workingDir string) afero.Fs { if workingDir == "" { return base } return NewBasePathFs(base, workingDir) } func isWrite(flag int) bool { return flag&os.O_RDWR != 0 || flag&os.O_WRONLY != 0 } // MakeReadableAndRemoveAllModulePkgDir makes any subdir in dir readable and then // removes the root. // TODO(bep) move this to a more suitable place. func MakeReadableAndRemoveAllModulePkgDir(fs afero.Fs, dir string) (int, error) { // Safe guard // Note that the base directory changed from pkg to gomod_cache in Go 1.23. if !strings.Contains(dir, "pkg") && !strings.Contains(dir, "gomod") { panic(fmt.Sprint("invalid dir:", dir)) } counter := 0 afero.Walk(fs, dir, func(path string, info os.FileInfo, err error) error { if err != nil { return nil } if info.IsDir() { counter++ fs.Chmod(path, 0o777) } return nil }) return counter, fs.RemoveAll(dir) } // IsOsFs returns whether fs is an OsFs or if it fs wraps an OsFs. // TODO(bep) make this more robust. func IsOsFs(fs afero.Fs) bool { var isOsFs bool WalkFilesystems(fs, func(fs afero.Fs) bool { switch fs.(type) { case *afero.MemMapFs: isOsFs = false case *afero.OsFs: isOsFs = true } return isOsFs }) return isOsFs } // FilesystemsUnwrapper returns the underlying filesystems. type FilesystemsUnwrapper interface { UnwrapFilesystems() []afero.Fs } // FilesystemUnwrapper returns the underlying filesystem. type FilesystemUnwrapper interface { UnwrapFilesystem() afero.Fs } // WalkFn is the walk func for WalkFilesystems. type WalkFn func(fs afero.Fs) bool // WalkFilesystems walks fs recursively and calls fn. // If fn returns true, walking is stopped. func WalkFilesystems(fs afero.Fs, fn WalkFn) bool { if fn(fs) { return true } if afs, ok := fs.(FilesystemUnwrapper); ok { if WalkFilesystems(afs.UnwrapFilesystem(), fn) { return true } } else if bfs, ok := fs.(FilesystemsUnwrapper); ok { for _, sf := range bfs.UnwrapFilesystems() { if WalkFilesystems(sf, fn) { return true } } } else if cfs, ok := fs.(overlayfs.FilesystemIterator); ok { for i := range cfs.NumFilesystems() { if WalkFilesystems(cfs.Filesystem(i), fn) { return true } } } return false } var _ FilesystemUnwrapper = (*filesystemsWrapper)(nil) // NewBasePathFs creates a new BasePathFs. func NewBasePathFs(source afero.Fs, path string) afero.Fs { return WrapFilesystem(afero.NewBasePathFs(source, path), source) } // NewReadOnlyFs creates a new ReadOnlyFs. func NewReadOnlyFs(source afero.Fs) afero.Fs { return WrapFilesystem(afero.NewReadOnlyFs(source), source) } // WrapFilesystem is typically used to wrap a afero.BasePathFs to allow // access to the underlying filesystem if needed. func WrapFilesystem(container, content afero.Fs) afero.Fs { return filesystemsWrapper{Fs: container, content: content} } type filesystemsWrapper struct { afero.Fs content afero.Fs } func (w filesystemsWrapper) UnwrapFilesystem() afero.Fs { return w.content } type ReadDirWithContextDir interface { ReadDirWithContext(context context.Context, count int) ([]iofs.DirEntry, context.Context, error) } func ReadDirWithContext(ctx context.Context, f DirOnlyOps, count int) ([]iofs.DirEntry, context.Context, error) { if ff, ok := f.(ReadDirWithContextDir); ok { return ff.ReadDirWithContext(ctx, count) } v, err := f.(iofs.ReadDirFile).ReadDir(count) if err != nil { return nil, ctx, err } return v, ctx, nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/hasbytes_fs.go
hugofs/hasbytes_fs.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hugofs import ( "os" "github.com/gohugoio/hugo/common/hugio" "github.com/spf13/afero" ) var ( _ afero.Fs = (*hasBytesFs)(nil) _ FilesystemUnwrapper = (*hasBytesFs)(nil) ) type hasBytesFs struct { afero.Fs shouldCheck func(name string) bool hasBytesCallback func(name string, match []byte) patterns [][]byte } func NewHasBytesReceiver(delegate afero.Fs, shouldCheck func(name string) bool, hasBytesCallback func(name string, match []byte), patterns ...[]byte) afero.Fs { return &hasBytesFs{Fs: delegate, shouldCheck: shouldCheck, hasBytesCallback: hasBytesCallback, patterns: patterns} } func (fs *hasBytesFs) UnwrapFilesystem() afero.Fs { return fs.Fs } func (fs *hasBytesFs) Create(name string) (afero.File, error) { f, err := fs.Fs.Create(name) if err == nil { f = fs.wrapFile(f) } return f, err } func (fs *hasBytesFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { f, err := fs.Fs.OpenFile(name, flag, perm) if err == nil && isWrite(flag) { f = fs.wrapFile(f) } return f, err } func (fs *hasBytesFs) wrapFile(f afero.File) afero.File { if !fs.shouldCheck(f.Name()) { return f } patterns := make([]*hugio.HasBytesPattern, len(fs.patterns)) for i, p := range fs.patterns { patterns[i] = &hugio.HasBytesPattern{Pattern: p} } return &hasBytesFile{ File: f, hbw: &hugio.HasBytesWriter{ Patterns: patterns, }, hasBytesCallback: fs.hasBytesCallback, } } func (fs *hasBytesFs) Name() string { return "hasBytesFs" } type hasBytesFile struct { hasBytesCallback func(name string, match []byte) hbw *hugio.HasBytesWriter afero.File } func (h *hasBytesFile) Write(p []byte) (n int, err error) { n, err = h.File.Write(p) if err != nil { return } return h.hbw.Write(p) } func (h *hasBytesFile) Close() error { for _, p := range h.hbw.Patterns { if p.Match { h.hasBytesCallback(h.Name(), p.Pattern) } } return h.File.Close() }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/files/classifier.go
hugofs/files/classifier.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package files import ( "os" "path/filepath" "sort" "strings" ) const ( // The NPM package.json "template" file. FilenamePackageHugoJSON = "package.hugo.json" // The NPM package file. FilenamePackageJSON = "package.json" FilenameHugoStatsJSON = "hugo_stats.json" ) func IsGoTmplExt(ext string) bool { return ext == "gotmpl" } // Supported data file extensions for _content.* files. func IsContentDataExt(ext string) bool { return IsGoTmplExt(ext) } const ( ComponentFolderArchetypes = "archetypes" ComponentFolderStatic = "static" ComponentFolderLayouts = "layouts" ComponentFolderContent = "content" ComponentFolderData = "data" ComponentFolderAssets = "assets" ComponentFolderI18n = "i18n" FolderResources = "resources" FolderJSConfig = "_jsconfig" // Mounted below /assets with postcss.config.js etc. NameContentData = "_content" ) var ( JsConfigFolderMountPrefix = filepath.Join(ComponentFolderAssets, FolderJSConfig) ComponentFolders = []string{ ComponentFolderArchetypes, ComponentFolderStatic, ComponentFolderLayouts, ComponentFolderContent, ComponentFolderData, ComponentFolderAssets, ComponentFolderI18n, } componentFoldersSet = make(map[string]bool) ) func init() { sort.Strings(ComponentFolders) for _, f := range ComponentFolders { componentFoldersSet[f] = true } } // ResolveComponentFolder returns "content" from "content/blog/foo.md" etc. func ResolveComponentFolder(filename string) string { filename = strings.TrimPrefix(filename, string(os.PathSeparator)) for _, cf := range ComponentFolders { if strings.HasPrefix(filename, cf) { return cf } } return "" } func IsComponentFolder(name string) bool { return componentFoldersSet[name] }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/files/classifier_test.go
hugofs/files/classifier_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package files import ( "testing" qt "github.com/frankban/quicktest" ) func TestComponentFolders(t *testing.T) { c := qt.New(t) // It's important that these are absolutely right and not changed. c.Assert(len(componentFoldersSet), qt.Equals, len(ComponentFolders)) c.Assert(IsComponentFolder("archetypes"), qt.Equals, true) c.Assert(IsComponentFolder("layouts"), qt.Equals, true) c.Assert(IsComponentFolder("data"), qt.Equals, true) c.Assert(IsComponentFolder("i18n"), qt.Equals, true) c.Assert(IsComponentFolder("assets"), qt.Equals, true) c.Assert(IsComponentFolder("resources"), qt.Equals, false) c.Assert(IsComponentFolder("static"), qt.Equals, true) c.Assert(IsComponentFolder("content"), qt.Equals, true) c.Assert(IsComponentFolder("foo"), qt.Equals, false) c.Assert(IsComponentFolder(""), qt.Equals, false) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/hglob/glob.go
hugofs/hglob/glob.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hglob import ( "os" "path" "path/filepath" "runtime" "strings" "github.com/gobwas/glob" "github.com/gobwas/glob/syntax" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/identity" ) const filepathSeparator = string(os.PathSeparator) var ( isWindows = runtime.GOOS == "windows" defaultGlobCache = &pathGlobCache{ isWindows: isWindows, cache: maps.NewCache[string, globErr](), } dotGlobCache = maps.NewCache[string, globErr]() ) type globErr struct { glob glob.Glob err error } type pathGlobCache struct { // Config isWindows bool // Cache cache *maps.Cache[string, globErr] } // GetGlobDot returns a glob.Glob that matches the given pattern, using '.' as the path separator. func GetGlobDot(pattern string) (glob.Glob, error) { v, err := dotGlobCache.GetOrCreate(pattern, func() (globErr, error) { g, err := glob.Compile(pattern, '.') return globErr{ glob: g, err: err, }, nil }) if err != nil { return nil, err } return v.glob, v.err } func (gc *pathGlobCache) GetGlob(pattern string) (glob.Glob, error) { v, err := gc.cache.GetOrCreate(pattern, func() (globErr, error) { pattern = filepath.ToSlash(pattern) g, err := glob.Compile(strings.ToLower(pattern), '/') return globErr{ glob: globDecorator{ isWindows: gc.isWindows, g: g, }, err: err, }, nil }) if err != nil { return nil, err } return v.glob, v.err } // Or creates a new Glob from the given globs. func Or(globs ...glob.Glob) glob.Glob { return globSlice{globs: globs} } // MatchesFunc is a convenience type to create a glob.Glob from a function. type MatchesFunc func(s string) bool func (m MatchesFunc) Match(s string) bool { return m(s) } type globSlice struct { globs []glob.Glob } func (g globSlice) Match(s string) bool { for _, g := range g.globs { if g.Match(s) { return true } } return false } type globDecorator struct { // On Windows we may get filenames with Windows slashes to match, // which we need to normalize. isWindows bool g glob.Glob } func (g globDecorator) Match(s string) bool { if g.isWindows { s = filepath.ToSlash(s) } s = strings.ToLower(s) return g.g.Match(s) } func GetGlob(pattern string) (glob.Glob, error) { return defaultGlobCache.GetGlob(pattern) } func NormalizePath(p string) string { return strings.ToLower(NormalizePathNoLower(p)) } func NormalizePathNoLower(p string) string { return strings.Trim(path.Clean(filepath.ToSlash(p)), "/.") } // ResolveRootDir takes a normalized path on the form "assets/**.json" and // determines any root dir, i.e. any start path without any wildcards. func ResolveRootDir(p string) string { parts := strings.Split(path.Dir(p), "/") var roots []string for _, part := range parts { if HasGlobChar(part) { break } roots = append(roots, part) } if len(roots) == 0 { return "" } return strings.Join(roots, "/") } // FilterGlobParts removes any string with glob wildcard. func FilterGlobParts(a []string) []string { b := a[:0] for _, x := range a { if !HasGlobChar(x) { b = append(b, x) } } return b } // HasGlobChar returns whether s contains any glob wildcards. func HasGlobChar(s string) bool { for i := range len(s) { if syntax.Special(s[i]) { return true } } return false } // NewGlobIdentity creates a new Identity that // is probably dependent on any other Identity // that matches the given pattern. func NewGlobIdentity(pattern string) identity.Identity { glob, err := GetGlob(pattern) if err != nil { panic(err) } predicate := func(other identity.Identity) bool { return glob.Match(other.IdentifierBase()) } return identity.NewPredicateIdentity(predicate, nil) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/hglob/filename_filter_test.go
hugofs/hglob/filename_filter_test.go
// Copyright 2025 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hglob import ( "path/filepath" "strings" "testing" qt "github.com/frankban/quicktest" ) func TestFilenameFilter(t *testing.T) { c := qt.New(t) excludeAlmostAllJSON, err := NewFilenameFilter([]string{"/a/b/c/foo.json"}, []string{"**.json"}) c.Assert(err, qt.IsNil) c.Assert(excludeAlmostAllJSON.Match(filepath.FromSlash("/data/my.json"), false), qt.Equals, false) c.Assert(excludeAlmostAllJSON.Match(filepath.FromSlash("/a/b/c/foo.json"), false), qt.Equals, true) c.Assert(excludeAlmostAllJSON.Match(filepath.FromSlash("/a/b/c/foo.bar"), false), qt.Equals, false) c.Assert(excludeAlmostAllJSON.Match(filepath.FromSlash("/a/b/c"), true), qt.Equals, true) c.Assert(excludeAlmostAllJSON.Match(filepath.FromSlash("/a/b"), true), qt.Equals, true) c.Assert(excludeAlmostAllJSON.Match(filepath.FromSlash("/a"), true), qt.Equals, true) c.Assert(excludeAlmostAllJSON.Match(filepath.FromSlash("/"), true), qt.Equals, true) c.Assert(excludeAlmostAllJSON.Match("", true), qt.Equals, true) excludeAllButFooJSON, err := NewFilenameFilter([]string{"/a/**/foo.json"}, []string{"**.json"}) c.Assert(err, qt.IsNil) c.Assert(excludeAllButFooJSON.Match(filepath.FromSlash("/data/my.json"), false), qt.Equals, false) c.Assert(excludeAllButFooJSON.Match(filepath.FromSlash("/a/b/c/d/e/foo.json"), false), qt.Equals, true) c.Assert(excludeAllButFooJSON.Match(filepath.FromSlash("/a/b/c"), true), qt.Equals, true) c.Assert(excludeAllButFooJSON.Match(filepath.FromSlash("/a/b/"), true), qt.Equals, true) c.Assert(excludeAllButFooJSON.Match(filepath.FromSlash("/"), true), qt.Equals, true) c.Assert(excludeAllButFooJSON.Match(filepath.FromSlash("/b"), true), qt.Equals, false) excludeAllButFooJSONMixedCasePattern, err := NewFilenameFilter([]string{"/**/Foo.json"}, nil) c.Assert(excludeAllButFooJSONMixedCasePattern.Match(filepath.FromSlash("/a/b/c/d/e/foo.json"), false), qt.Equals, true) c.Assert(excludeAllButFooJSONMixedCasePattern.Match(filepath.FromSlash("/a/b/c/d/e/FOO.json"), false), qt.Equals, true) c.Assert(err, qt.IsNil) nopFilter, err := NewFilenameFilter(nil, nil) c.Assert(err, qt.IsNil) c.Assert(nopFilter.Match("ab.txt", false), qt.Equals, true) includeOnlyFilter, err := NewFilenameFilter([]string{"**.json", "**.jpg"}, nil) c.Assert(err, qt.IsNil) c.Assert(includeOnlyFilter.Match("ab.json", false), qt.Equals, true) c.Assert(includeOnlyFilter.Match("ab.jpg", false), qt.Equals, true) c.Assert(includeOnlyFilter.Match("ab.gif", false), qt.Equals, false) excludeOnlyFilter, err := NewFilenameFilter(nil, []string{"**.json", "**.jpg"}) c.Assert(err, qt.IsNil) c.Assert(excludeOnlyFilter.Match("ab.json", false), qt.Equals, false) c.Assert(excludeOnlyFilter.Match("ab.jpg", false), qt.Equals, false) c.Assert(excludeOnlyFilter.Match("ab.gif", false), qt.Equals, true) var nilFilter *FilenameFilter c.Assert(nilFilter.Match("ab.gif", false), qt.Equals, true) funcFilter := NewFilenameFilterForInclusionFunc(func(s string) bool { return strings.HasSuffix(s, ".json") }) c.Assert(funcFilter.Match("ab.json", false), qt.Equals, true) c.Assert(funcFilter.Match("ab.bson", false), qt.Equals, false) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/hglob/filename_filter.go
hugofs/hglob/filename_filter.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hglob import ( "path" "path/filepath" "slices" "strings" "github.com/gobwas/glob" ) type FilenameFilter struct { shouldInclude func(filename string) bool entries []globFilenameFilterEntry isWindows bool nested []*FilenameFilter } type globFilenameFilterEntryType int const ( globFilenameFilterEntryTypeInclusion globFilenameFilterEntryType = iota globFilenameFilterEntryTypeInclusionDir globFilenameFilterEntryTypeExclusion ) // NegationPrefix is the prefix that makes a pattern an exclusion. const NegationPrefix = "! " type globFilenameFilterEntry struct { g glob.Glob t globFilenameFilterEntryType } func normalizeFilenameGlobPattern(s string) string { // Use Unix separators even on Windows. s = filepath.ToSlash(s) if !strings.HasPrefix(s, "/") { s = "/" + s } return s } func NewFilenameFilterV2(patterns []string) (*FilenameFilter, error) { if len(patterns) == 0 { return nil, nil } filter := &FilenameFilter{isWindows: isWindows} for _, p := range patterns { var t globFilenameFilterEntryType if strings.HasPrefix(p, NegationPrefix) { t = globFilenameFilterEntryTypeExclusion p = strings.TrimPrefix(p, NegationPrefix) } else { t = globFilenameFilterEntryTypeInclusion } p = normalizeFilenameGlobPattern(p) g, err := GetGlob(p) if err != nil { return nil, err } filter.entries = append(filter.entries, globFilenameFilterEntry{t: t, g: g}) if t == globFilenameFilterEntryTypeInclusion { // For mounts that do directory walking (e.g. content) we // must make sure that all directories up to this inclusion also // gets included. dir := path.Dir(p) parts := strings.Split(dir, "/") for i := range parts { pattern := "/" + filepath.Join(parts[:i+1]...) g, err := GetGlob(pattern) if err != nil { return nil, err } filter.entries = append(filter.entries, globFilenameFilterEntry{t: globFilenameFilterEntryTypeInclusionDir, g: g}) } } } return filter, nil } // NewFilenameFilter creates a new Glob where the Match method will // return true if the file should be included. // Note that the exclusions will be checked first. // Deprecated: Use NewFilenameFilterV2. func NewFilenameFilter(inclusions, exclusions []string) (*FilenameFilter, error) { for i, p := range exclusions { if !strings.HasPrefix(p, NegationPrefix) { exclusions[i] = NegationPrefix + p } } all := slices.Concat(inclusions, exclusions) return NewFilenameFilterV2(all) } // MustNewFilenameFilter invokes NewFilenameFilter and panics on error. // Deprecated: Use NewFilenameFilterV2. func MustNewFilenameFilter(inclusions, exclusions []string) *FilenameFilter { filter, err := NewFilenameFilter(inclusions, exclusions) if err != nil { panic(err) } return filter } // NewFilenameFilterForInclusionFunc create a new filter using the provided inclusion func. func NewFilenameFilterForInclusionFunc(shouldInclude func(filename string) bool) *FilenameFilter { return &FilenameFilter{shouldInclude: shouldInclude, isWindows: isWindows} } // Match returns whether filename should be included. func (f *FilenameFilter) Match(filename string, isDir bool) bool { if f == nil { return true } if !f.doMatch(filename, isDir) { return false } for _, nested := range f.nested { if !nested.Match(filename, isDir) { return false } } return true } // Append appends a filter to the chain. The receiver will be copied if needed. func (f *FilenameFilter) Append(other *FilenameFilter) *FilenameFilter { if f == nil { return other } clone := *f nested := make([]*FilenameFilter, len(clone.nested)+1) copy(nested, clone.nested) nested[len(nested)-1] = other clone.nested = nested return &clone } func (f *FilenameFilter) doMatch(filename string, isDir bool) bool { if f == nil { return true } if !strings.HasPrefix(filename, filepathSeparator) { filename = filepathSeparator + filename } if f.shouldInclude != nil { if f.shouldInclude(filename) { return true } if f.isWindows { // The Glob matchers below handles this by themselves, // for the shouldInclude we need to take some extra steps // to make this robust. winFilename := filepath.FromSlash(filename) if filename != winFilename { if f.shouldInclude(winFilename) { return true } } } } var hasInclude bool for _, entry := range f.entries { switch entry.t { case globFilenameFilterEntryTypeExclusion: if entry.g.Match(filename) { return false } case globFilenameFilterEntryTypeInclusion: if entry.g.Match(filename) { return true } hasInclude = true case globFilenameFilterEntryTypeInclusionDir: if isDir && entry.g.Match(filename) { return true } } } return !hasInclude && f.shouldInclude == nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/hugofs/hglob/glob_test.go
hugofs/hglob/glob_test.go
// Copyright 2021 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hglob import ( "path/filepath" "testing" qt "github.com/frankban/quicktest" ) func TestResolveRootDir(t *testing.T) { c := qt.New(t) for _, test := range []struct { input string expected string }{ {"data/foo.json", "data"}, {"a/b/**/foo.json", "a/b"}, {"dat?a/foo.json", ""}, {"a/b[a-c]/foo.json", "a"}, } { c.Assert(ResolveRootDir(test.input), qt.Equals, test.expected) } } func TestFilterGlobParts(t *testing.T) { c := qt.New(t) for _, test := range []struct { input []string expected []string }{ {[]string{"a", "*", "c"}, []string{"a", "c"}}, } { c.Assert(FilterGlobParts(test.input), qt.DeepEquals, test.expected) } } func TestNormalizePath(t *testing.T) { c := qt.New(t) for _, test := range []struct { input string expected string }{ {filepath.FromSlash("data/FOO.json"), "data/foo.json"}, {filepath.FromSlash("/data/FOO.json"), "data/foo.json"}, {filepath.FromSlash("./FOO.json"), "foo.json"}, {"//", ""}, } { c.Assert(NormalizePath(test.input), qt.Equals, test.expected) } } func TestGetGlob(t *testing.T) { for _, cache := range []*pathGlobCache{defaultGlobCache} { c := qt.New(t) g, err := cache.GetGlob("**.JSON") c.Assert(err, qt.IsNil) c.Assert(g.Match("data/my.jSon"), qt.Equals, true) } } func BenchmarkGetGlob(b *testing.B) { runBench := func(name string, cache *pathGlobCache, search string) { b.Run(name, func(b *testing.B) { g, err := GetGlob("**/foo") if err != nil { b.Fatal(err) } for b.Loop() { _ = g.Match(search) } }) } runBench("Default cache", defaultGlobCache, "abcde") runBench("Filenames cache, lowercase searches", defaultGlobCache, "abcde") runBench("Filenames cache, mixed case searches", defaultGlobCache, "abCDe") b.Run("GetGlob", func(b *testing.B) { for b.Loop() { _, err := GetGlob("**/foo") if err != nil { b.Fatal(err) } } }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/output/config.go
output/config.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package output import ( "fmt" "reflect" "sort" "strings" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/mitchellh/mapstructure" ) // OutputFormatConfig configures a single output format. type OutputFormatConfig struct { // The MediaType string. This must be a configured media type. MediaType string Format } var defaultOutputFormat = Format{ BaseName: "index", Rel: "alternate", } func DecodeConfig(mediaTypes media.Types, in any) (*config.ConfigNamespace[map[string]OutputFormatConfig, Formats], error) { buildConfig := func(in any) (Formats, any, error) { f := make(Formats, len(DefaultFormats)) copy(f, DefaultFormats) if in != nil { m, err := maps.ToStringMapE(in) if err != nil { return nil, nil, fmt.Errorf("failed convert config to map: %s", err) } m = maps.CleanConfigStringMap(m) for k, v := range m { found := false for i, vv := range f { // Both are lower case. if k == vv.Name { // Merge it with the existing if err := decode(mediaTypes, v, &f[i]); err != nil { return f, nil, err } found = true } } if found { continue } newOutFormat := defaultOutputFormat if err := decode(mediaTypes, v, &newOutFormat); err != nil { return f, nil, err } newOutFormat.Name = k f = append(f, newOutFormat) } } // Also format is a map for documentation purposes. docm := make(map[string]OutputFormatConfig, len(f)) for _, ff := range f { docm[ff.Name] = OutputFormatConfig{ MediaType: ff.MediaType.Type, Format: ff, } } sort.Sort(f) return f, docm, nil } return config.DecodeNamespace[map[string]OutputFormatConfig](in, buildConfig) } func decode(mediaTypes media.Types, input any, output *Format) error { config := &mapstructure.DecoderConfig{ Metadata: nil, Result: output, WeaklyTypedInput: true, DecodeHook: func(a reflect.Type, b reflect.Type, c any) (any, error) { if a.Kind() == reflect.Map { dataVal := reflect.Indirect(reflect.ValueOf(c)) for _, key := range dataVal.MapKeys() { keyStr, ok := key.Interface().(string) if !ok { // Not a string key continue } if strings.EqualFold(keyStr, "mediaType") { // If mediaType is a string, look it up and replace it // in the map. vv := dataVal.MapIndex(key) vvi := vv.Interface() switch vviv := vvi.(type) { case media.Type: // OK case string: mediaType, found := mediaTypes.GetByType(vviv) if !found { return c, fmt.Errorf("media type %q not found", vviv) } dataVal.SetMapIndex(key, reflect.ValueOf(mediaType)) default: return nil, fmt.Errorf("invalid output format configuration; wrong type for media type, expected string (e.g. text/html), got %T", vvi) } } } } return c, nil }, } decoder, err := mapstructure.NewDecoder(config) if err != nil { return err } if err = decoder.Decode(input); err != nil { return fmt.Errorf("failed to decode output format configuration: %w", err) } return nil }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/output/config_test.go
output/config_test.go
// Copyright 2024 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package output import ( "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/media" ) func TestDecodeConfig(t *testing.T) { c := qt.New(t) mediaTypes := media.Types{media.Builtin.JSONType, media.Builtin.XMLType} tests := []struct { name string m map[string]any shouldError bool assert func(t *testing.T, name string, f Formats) }{ { "Redefine JSON", map[string]any{ "json": map[string]any{ "baseName": "myindex", "isPlainText": "false", }, }, false, func(t *testing.T, name string, f Formats) { msg := qt.Commentf(name) c.Assert(len(f), qt.Equals, len(DefaultFormats), msg) json, _ := f.GetByName("JSON") c.Assert(json.BaseName, qt.Equals, "myindex") c.Assert(json.MediaType, qt.Equals, media.Builtin.JSONType) c.Assert(json.IsPlainText, qt.Equals, false) }, }, { "Add XML format with string as mediatype", map[string]any{ "MYXMLFORMAT": map[string]any{ "baseName": "myxml", "mediaType": "application/xml", }, }, false, func(t *testing.T, name string, f Formats) { c.Assert(len(f), qt.Equals, len(DefaultFormats)+1) xml, found := f.GetByName("MYXMLFORMAT") c.Assert(found, qt.Equals, true) c.Assert(xml.BaseName, qt.Equals, "myxml") c.Assert(xml.MediaType, qt.Equals, media.Builtin.XMLType) // Verify that we haven't changed the DefaultFormats slice. json, _ := f.GetByName("JSON") c.Assert(json.BaseName, qt.Equals, "index") }, }, { "Add format unknown mediatype", map[string]any{ "MYINVALID": map[string]any{ "baseName": "mymy", "mediaType": "application/hugo", }, }, true, func(t *testing.T, name string, f Formats) { }, }, } for _, test := range tests { result, err := DecodeConfig(mediaTypes, test.m) msg := qt.Commentf(test.name) if test.shouldError { c.Assert(err, qt.Not(qt.IsNil), msg) } else { c.Assert(err, qt.IsNil, msg) test.assert(t, test.name, result.Config) } } }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/output/outputFormat.go
output/outputFormat.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package output contains Output Format types and functions. package output import ( "encoding/json" "fmt" "sort" "strings" "github.com/gohugoio/hugo/media" ) // Format represents an output representation, usually to a file on disk. // <docsmeta>{ "name": "OutputFormat" }</docsmeta> type Format struct { // The Name is used as an identifier. Internal output formats (i.e. html and rss) // can be overridden by providing a new definition for those types. // <docsmeta>{ "identifiers": ["html", "rss"] }</docsmeta> Name string `json:"-"` MediaType media.Type `json:"-"` // Must be set to a value when there are two or more conflicting mediatype for the same resource. Path string `json:"path"` // The base output file name used when not using "ugly URLs", defaults to "index". BaseName string `json:"baseName"` // The value to use for rel links. Rel string `json:"rel"` // The protocol to use, i.e. "webcal://". Defaults to the protocol of the baseURL. Protocol string `json:"protocol"` // IsPlainText decides whether to use text/template or html/template // as template parser. IsPlainText bool `json:"isPlainText"` // IsHTML returns whether this format is int the HTML family. This includes // HTML, AMP etc. This is used to decide when to create alias redirects etc. IsHTML bool `json:"isHTML"` // Enable to ignore the global uglyURLs setting. NoUgly bool `json:"noUgly"` // Enable to override the global uglyURLs setting. Ugly bool `json:"ugly"` // Enable if it doesn't make sense to include this format in an alternative // format listing, CSS being one good example. // Note that we use the term "alternative" and not "alternate" here, as it // does not necessarily replace the other format, it is an alternative representation. NotAlternative bool `json:"notAlternative"` // Eneable if this is a resource which path always starts at the root, // e.g. /robots.txt. Root bool `json:"root"` // Setting this will make this output format control the value of // .Permalink and .RelPermalink for a rendered Page. // If not set, these values will point to the main (first) output format // configured. That is probably the behavior you want in most situations, // as you probably don't want to link back to the RSS version of a page, as an // example. AMP would, however, be a good example of an output format where this // behavior is wanted. Permalinkable bool `json:"permalinkable"` // Setting this to a non-zero value will be used as the first sort criteria. Weight int `json:"weight"` } // Built-in output formats. var ( AMPFormat = Format{ Name: "amp", MediaType: media.Builtin.HTMLType, BaseName: "index", Path: "amp", Rel: "amphtml", IsHTML: true, Permalinkable: true, // See https://www.ampproject.org/learn/overview/ } CalendarFormat = Format{ Name: "calendar", MediaType: media.Builtin.CalendarType, IsPlainText: true, Protocol: "webcal://", BaseName: "index", Rel: "alternate", } CSSFormat = Format{ Name: "css", MediaType: media.Builtin.CSSType, BaseName: "styles", IsPlainText: true, Rel: "stylesheet", NotAlternative: true, } CSVFormat = Format{ Name: "csv", MediaType: media.Builtin.CSVType, BaseName: "index", IsPlainText: true, Rel: "alternate", } HTMLFormat = Format{ Name: "html", MediaType: media.Builtin.HTMLType, BaseName: "index", Rel: "canonical", IsHTML: true, Permalinkable: true, // Weight will be used as first sort criteria. HTML will, by default, // be rendered first, but set it to 10 so it's easy to put one above it. Weight: 10, } // Alias is the output format used for alias redirects. AliasHTMLFormat = Format{ Name: "alias", MediaType: media.Builtin.HTMLType, IsHTML: true, Ugly: true, Permalinkable: false, } MarkdownFormat = Format{ Name: "markdown", MediaType: media.Builtin.MarkdownType, BaseName: "index", Rel: "alternate", IsPlainText: true, } JSONFormat = Format{ Name: "json", MediaType: media.Builtin.JSONType, BaseName: "index", IsPlainText: true, Rel: "alternate", } WebAppManifestFormat = Format{ Name: "webappmanifest", MediaType: media.Builtin.WebAppManifestType, BaseName: "manifest", IsPlainText: true, NotAlternative: true, Rel: "manifest", } RobotsTxtFormat = Format{ Name: "robots", MediaType: media.Builtin.TextType, BaseName: "robots", IsPlainText: true, Root: true, Rel: "alternate", } RSSFormat = Format{ Name: "rss", MediaType: media.Builtin.RSSType, BaseName: "index", NoUgly: true, Rel: "alternate", } SitemapFormat = Format{ Name: "sitemap", MediaType: media.Builtin.XMLType, BaseName: "sitemap", Ugly: true, Rel: "sitemap", } SitemapIndexFormat = Format{ Name: "sitemapindex", MediaType: media.Builtin.XMLType, BaseName: "sitemap", Ugly: true, Root: true, Rel: "sitemap", } GotmplFormat = Format{ Name: "gotmpl", MediaType: media.Builtin.GotmplType, IsPlainText: true, NotAlternative: true, } // I'm not sure having a 404 format is a good idea, // for one, we would want to have multiple formats for this. HTTPStatus404HTMLFormat = Format{ Name: "404", MediaType: media.Builtin.HTMLType, NotAlternative: true, Ugly: true, IsHTML: true, Permalinkable: true, } ) // DefaultFormats contains the default output formats supported by Hugo. var DefaultFormats = Formats{ AMPFormat, CalendarFormat, CSSFormat, CSVFormat, HTMLFormat, GotmplFormat, HTTPStatus404HTMLFormat, AliasHTMLFormat, JSONFormat, MarkdownFormat, WebAppManifestFormat, RobotsTxtFormat, RSSFormat, SitemapFormat, SitemapIndexFormat, } func init() { sort.Sort(DefaultFormats) } // Formats is a slice of Format. // <docsmeta>{ "name": "OutputFormats" }</docsmeta> type Formats []Format func (formats Formats) Len() int { return len(formats) } func (formats Formats) Swap(i, j int) { formats[i], formats[j] = formats[j], formats[i] } func (formats Formats) Less(i, j int) bool { fi, fj := formats[i], formats[j] if fi.Weight == fj.Weight { return fi.Name < fj.Name } if fj.Weight == 0 { return true } return fi.Weight > 0 && fi.Weight < fj.Weight } // GetBySuffix gets a output format given as suffix, e.g. "html". // It will return false if no format could be found, or if the suffix given // is ambiguous. // The lookup is case insensitive. func (formats Formats) GetBySuffix(suffix string) (f Format, found bool) { for _, ff := range formats { for _, suffix2 := range ff.MediaType.Suffixes() { if strings.EqualFold(suffix, suffix2) { if found { // ambiguous found = false return } f = ff found = true } } } return } // GetByName gets a format by its identifier name. func (formats Formats) GetByName(name string) (f Format, found bool) { for _, ff := range formats { if strings.EqualFold(name, ff.Name) { f = ff found = true return } } return } // GetByNames gets a list of formats given a list of identifiers. func (formats Formats) GetByNames(names ...string) (Formats, error) { var types []Format for _, name := range names { tpe, ok := formats.GetByName(name) if !ok { return types, fmt.Errorf("OutputFormat with key %q not found", name) } types = append(types, tpe) } return types, nil } // FromFilename gets a Format given a filename. func (formats Formats) FromFilename(filename string) (f Format, found bool) { // mytemplate.amp.html // mytemplate.html // mytemplate var ext, outFormat string parts := strings.Split(filename, ".") if len(parts) > 2 { outFormat = parts[1] ext = parts[2] } else if len(parts) > 1 { ext = parts[1] } if outFormat != "" { return formats.GetByName(outFormat) } if ext != "" { f, found = formats.GetBySuffix(ext) if !found && len(parts) == 2 { // For extensionless output formats (e.g. Netlify's _redirects) // we must fall back to using the extension as format lookup. f, found = formats.GetByName(ext) } } return } // BaseFilename returns the base filename of f including an extension (ie. // "index.xml"). func (f Format) BaseFilename() string { return f.BaseName + f.MediaType.FirstSuffix.FullSuffix } // IsZero returns true if f represents a zero value. func (f Format) IsZero() bool { return f.Name == "" } // MarshalJSON returns the JSON encoding of f. // For internal use only. func (f Format) MarshalJSON() ([]byte, error) { type Alias Format return json.Marshal(&struct { MediaType string `json:"mediaType"` Alias }{ MediaType: f.MediaType.String(), Alias: (Alias)(f), }) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/output/docshelper.go
output/docshelper.go
package output import ( // "fmt" "github.com/gohugoio/hugo/docshelper" ) // This is is just some helpers used to create some JSON used in the Hugo docs. func init() { docsProvider := func() docshelper.DocProvider { return docshelper.DocProvider{ "output": map[string]any{ // TODO(bep), maybe revisit this later, but I hope this isn't needed. // "layouts": createLayoutExamples(), "layouts": map[string]any{}, }, } } docshelper.AddDocProviderFunc(docsProvider) }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
gohugoio/hugo
https://github.com/gohugoio/hugo/blob/5ea3e13db6e436904ee8154bba77af8247b7e534/output/outputFormat_test.go
output/outputFormat_test.go
// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package output import ( "sort" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/media" ) func TestDefaultTypes(t *testing.T) { c := qt.New(t) c.Assert(CalendarFormat.Name, qt.Equals, "calendar") c.Assert(CalendarFormat.MediaType, qt.Equals, media.Builtin.CalendarType) c.Assert(CalendarFormat.Protocol, qt.Equals, "webcal://") c.Assert(CalendarFormat.Path, qt.HasLen, 0) c.Assert(CalendarFormat.IsPlainText, qt.Equals, true) c.Assert(CalendarFormat.IsHTML, qt.Equals, false) c.Assert(CSSFormat.Name, qt.Equals, "css") c.Assert(CSSFormat.MediaType, qt.Equals, media.Builtin.CSSType) c.Assert(CSSFormat.Path, qt.HasLen, 0) c.Assert(CSSFormat.Protocol, qt.HasLen, 0) // Will inherit the BaseURL protocol. c.Assert(CSSFormat.IsPlainText, qt.Equals, true) c.Assert(CSSFormat.IsHTML, qt.Equals, false) c.Assert(CSVFormat.Name, qt.Equals, "csv") c.Assert(CSVFormat.MediaType, qt.Equals, media.Builtin.CSVType) c.Assert(CSVFormat.Path, qt.HasLen, 0) c.Assert(CSVFormat.Protocol, qt.HasLen, 0) c.Assert(CSVFormat.IsPlainText, qt.Equals, true) c.Assert(CSVFormat.IsHTML, qt.Equals, false) c.Assert(CSVFormat.Permalinkable, qt.Equals, false) c.Assert(HTMLFormat.Name, qt.Equals, "html") c.Assert(HTMLFormat.MediaType, qt.Equals, media.Builtin.HTMLType) c.Assert(HTMLFormat.Path, qt.HasLen, 0) c.Assert(HTMLFormat.Protocol, qt.HasLen, 0) c.Assert(HTMLFormat.IsPlainText, qt.Equals, false) c.Assert(HTMLFormat.IsHTML, qt.Equals, true) c.Assert(AMPFormat.Permalinkable, qt.Equals, true) c.Assert(AMPFormat.Name, qt.Equals, "amp") c.Assert(AMPFormat.MediaType, qt.Equals, media.Builtin.HTMLType) c.Assert(AMPFormat.Path, qt.Equals, "amp") c.Assert(AMPFormat.Protocol, qt.HasLen, 0) c.Assert(AMPFormat.IsPlainText, qt.Equals, false) c.Assert(AMPFormat.IsHTML, qt.Equals, true) c.Assert(AMPFormat.Permalinkable, qt.Equals, true) c.Assert(RSSFormat.Name, qt.Equals, "rss") c.Assert(RSSFormat.MediaType, qt.Equals, media.Builtin.RSSType) c.Assert(RSSFormat.Path, qt.HasLen, 0) c.Assert(RSSFormat.IsPlainText, qt.Equals, false) c.Assert(RSSFormat.NoUgly, qt.Equals, true) c.Assert(CalendarFormat.IsHTML, qt.Equals, false) c.Assert(len(DefaultFormats), qt.Equals, 15) } func TestGetFormatByName(t *testing.T) { c := qt.New(t) formats := Formats{AMPFormat, CalendarFormat} tp, _ := formats.GetByName("AMp") c.Assert(tp, qt.Equals, AMPFormat) _, found := formats.GetByName("HTML") c.Assert(found, qt.Equals, false) _, found = formats.GetByName("FOO") c.Assert(found, qt.Equals, false) } func TestGetFormatByExt(t *testing.T) { c := qt.New(t) formats1 := Formats{AMPFormat, CalendarFormat} formats2 := Formats{AMPFormat, HTMLFormat, CalendarFormat} tp, _ := formats1.GetBySuffix("html") c.Assert(tp, qt.Equals, AMPFormat) tp, _ = formats1.GetBySuffix("ics") c.Assert(tp, qt.Equals, CalendarFormat) _, found := formats1.GetBySuffix("not") c.Assert(found, qt.Equals, false) // ambiguous _, found = formats2.GetBySuffix("html") c.Assert(found, qt.Equals, false) } func TestGetFormatByFilename(t *testing.T) { c := qt.New(t) noExtNoDelimMediaType := media.Builtin.TextType noExtNoDelimMediaType.Delimiter = "" noExtMediaType := media.Builtin.TextType var ( noExtDelimFormat = Format{ Name: "NEM", MediaType: noExtNoDelimMediaType, BaseName: "_redirects", } noExt = Format{ Name: "NEX", MediaType: noExtMediaType, BaseName: "next", } ) formats := Formats{AMPFormat, HTMLFormat, noExtDelimFormat, noExt, CalendarFormat} f, found := formats.FromFilename("my.amp.html") c.Assert(found, qt.Equals, true) c.Assert(f, qt.Equals, AMPFormat) _, found = formats.FromFilename("my.ics") c.Assert(found, qt.Equals, true) f, found = formats.FromFilename("my.html") c.Assert(found, qt.Equals, true) c.Assert(f, qt.Equals, HTMLFormat) f, found = formats.FromFilename("my.nem") c.Assert(found, qt.Equals, true) c.Assert(f, qt.Equals, noExtDelimFormat) f, found = formats.FromFilename("my.nex") c.Assert(found, qt.Equals, true) c.Assert(f, qt.Equals, noExt) _, found = formats.FromFilename("my.css") c.Assert(found, qt.Equals, false) } func TestSort(t *testing.T) { c := qt.New(t) c.Assert(DefaultFormats[0].Name, qt.Equals, "html") c.Assert(DefaultFormats[1].Name, qt.Equals, "404") json := JSONFormat json.Weight = 1 formats := Formats{ AMPFormat, HTMLFormat, json, } sort.Sort(formats) c.Assert(formats[0].Name, qt.Equals, "json") c.Assert(formats[1].Name, qt.Equals, "html") c.Assert(formats[2].Name, qt.Equals, "amp") }
go
Apache-2.0
5ea3e13db6e436904ee8154bba77af8247b7e534
2026-01-07T08:35:43.452707Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/proxy.go
zrpc/proxy.go
package zrpc import ( "context" "sync" "github.com/zeromicro/go-zero/core/syncx" "github.com/zeromicro/go-zero/zrpc/internal" "github.com/zeromicro/go-zero/zrpc/internal/auth" "google.golang.org/grpc" ) // A RpcProxy is a rpc proxy. type RpcProxy struct { backend string clients map[string]Client options []internal.ClientOption singleFlight syncx.SingleFlight lock sync.Mutex } // NewProxy returns a RpcProxy. func NewProxy(backend string, opts ...internal.ClientOption) *RpcProxy { return &RpcProxy{ backend: backend, clients: make(map[string]Client), options: opts, singleFlight: syncx.NewSingleFlight(), } } // TakeConn returns a grpc.ClientConn. func (p *RpcProxy) TakeConn(ctx context.Context) (*grpc.ClientConn, error) { cred := auth.ParseCredential(ctx) key := cred.App + "/" + cred.Token val, err := p.singleFlight.Do(key, func() (any, error) { p.lock.Lock() client, ok := p.clients[key] p.lock.Unlock() if ok { return client, nil } opts := append(p.options, WithDialOption(grpc.WithPerRPCCredentials(&auth.Credential{ App: cred.App, Token: cred.Token, }))) client, err := NewClientWithTarget(p.backend, opts...) if err != nil { return nil, err } p.lock.Lock() p.clients[key] = client p.lock.Unlock() return client, nil }) if err != nil { return nil, err } return val.(Client).Conn(), nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/client.go
zrpc/client.go
package zrpc import ( "context" "fmt" "time" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/zrpc/internal" "github.com/zeromicro/go-zero/zrpc/internal/auth" "github.com/zeromicro/go-zero/zrpc/internal/balancer/consistenthash" "github.com/zeromicro/go-zero/zrpc/internal/balancer/p2c" "github.com/zeromicro/go-zero/zrpc/internal/clientinterceptors" "google.golang.org/grpc" "google.golang.org/grpc/keepalive" ) var ( // WithDialOption is an alias of internal.WithDialOption. WithDialOption = internal.WithDialOption // WithNonBlock sets the dialing to be nonblock. WithNonBlock = internal.WithNonBlock // WithBlock sets the dialing to be blocking. // Deprecated: blocking dials are not recommended by gRPC. WithBlock = internal.WithBlock // WithStreamClientInterceptor is an alias of internal.WithStreamClientInterceptor. WithStreamClientInterceptor = internal.WithStreamClientInterceptor // WithTimeout is an alias of internal.WithTimeout. WithTimeout = internal.WithTimeout // WithTransportCredentials return a func to make the gRPC calls secured with given credentials. WithTransportCredentials = internal.WithTransportCredentials // WithUnaryClientInterceptor is an alias of internal.WithUnaryClientInterceptor. WithUnaryClientInterceptor = internal.WithUnaryClientInterceptor ) type ( // Client is an alias of internal.Client. Client = internal.Client // ClientOption is an alias of internal.ClientOption. ClientOption = internal.ClientOption // A RpcClient is a rpc client. RpcClient struct { client Client } ) // MustNewClient returns a Client, exits on any error. func MustNewClient(c RpcClientConf, options ...ClientOption) Client { cli, err := NewClient(c, options...) logx.Must(err) return cli } // NewClient returns a Client. func NewClient(c RpcClientConf, options ...ClientOption) (Client, error) { var opts []ClientOption if c.HasCredential() { opts = append(opts, WithDialOption(grpc.WithPerRPCCredentials(&auth.Credential{ App: c.App, Token: c.Token, }))) } if c.NonBlock { opts = append(opts, WithNonBlock()) } else { opts = append(opts, WithBlock()) } if c.Timeout > 0 { opts = append(opts, WithTimeout(time.Duration(c.Timeout)*time.Millisecond)) } if c.KeepaliveTime > 0 { opts = append(opts, WithDialOption(grpc.WithKeepaliveParams(keepalive.ClientParameters{ Time: c.KeepaliveTime, }))) } svcCfg := makeLBServiceConfig(c.BalancerName) opts = append(opts, WithDialOption(grpc.WithDefaultServiceConfig(svcCfg))) opts = append(opts, options...) target, err := c.BuildTarget() if err != nil { return nil, err } client, err := internal.NewClient(target, c.Middlewares, opts...) if err != nil { return nil, err } return &RpcClient{ client: client, }, nil } // NewClientWithTarget returns a Client with connecting to given target. func NewClientWithTarget(target string, opts ...ClientOption) (Client, error) { var config RpcClientConf if err := conf.FillDefault(&config); err != nil { return nil, err } config.Target = target return NewClient(config, opts...) } // Conn returns the underlying grpc.ClientConn. func (rc *RpcClient) Conn() *grpc.ClientConn { return rc.client.Conn() } // DontLogClientContentForMethod disable logging content for given method. func DontLogClientContentForMethod(method string) { clientinterceptors.DontLogContentForMethod(method) } // SetClientSlowThreshold sets the slow threshold on client side. func SetClientSlowThreshold(threshold time.Duration) { clientinterceptors.SetSlowThreshold(threshold) } // SetHashKey sets the hash key into context. func SetHashKey(ctx context.Context, key string) context.Context { return consistenthash.SetHashKey(ctx, key) } // WithCallTimeout return a call option with given timeout to make a method call. func WithCallTimeout(timeout time.Duration) grpc.CallOption { return clientinterceptors.WithCallTimeout(timeout) } func makeLBServiceConfig(balancerName string) string { if len(balancerName) == 0 { balancerName = p2c.Name } return fmt.Sprintf(`{"loadBalancingPolicy":"%s"}`, balancerName) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/server_test.go
zrpc/server_test.go
package zrpc import ( "context" "testing" "time" "github.com/alicebob/miniredis/v2" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/discov" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/service" "github.com/zeromicro/go-zero/core/stat" "github.com/zeromicro/go-zero/core/stores/redis" "github.com/zeromicro/go-zero/zrpc/internal" "github.com/zeromicro/go-zero/zrpc/internal/serverinterceptors" "google.golang.org/grpc" ) func TestServer(t *testing.T) { DontLogContentForMethod("foo") SetServerSlowThreshold(time.Second) svr := MustNewServer(RpcServerConf{ ServiceConf: service.ServiceConf{ Log: logx.LogConf{ ServiceName: "foo", Mode: "console", }, }, ListenOn: "localhost:0", Etcd: discov.EtcdConf{}, Auth: false, Redis: redis.RedisKeyConf{}, StrictControl: false, Timeout: 0, CpuThreshold: 0, Middlewares: ServerMiddlewaresConf{ Trace: true, Recover: true, Stat: true, Prometheus: true, Breaker: true, }, MethodTimeouts: []MethodTimeoutConf{ { FullMethod: "/foo", Timeout: time.Second, }, }, }, func(server *grpc.Server) { }) svr.AddOptions(grpc.ConnectionTimeout(time.Hour)) svr.AddUnaryInterceptors(serverinterceptors.UnaryRecoverInterceptor) svr.AddStreamInterceptors(serverinterceptors.StreamRecoverInterceptor) go svr.Start() svr.Stop() } func TestServerError(t *testing.T) { _, err := NewServer(RpcServerConf{ ServiceConf: service.ServiceConf{ Log: logx.LogConf{ ServiceName: "foo", Mode: "console", }, }, ListenOn: "localhost:0", Etcd: discov.EtcdConf{ Hosts: []string{"localhost"}, }, Auth: true, Redis: redis.RedisKeyConf{}, Middlewares: ServerMiddlewaresConf{ Trace: true, Recover: true, Stat: true, Prometheus: true, Breaker: true, }, MethodTimeouts: []MethodTimeoutConf{}, }, func(server *grpc.Server) { }) assert.NotNil(t, err) } func TestServer_HasEtcd(t *testing.T) { svr := MustNewServer(RpcServerConf{ ServiceConf: service.ServiceConf{ Log: logx.LogConf{ ServiceName: "foo", Mode: "console", }, }, ListenOn: "localhost:0", Etcd: discov.EtcdConf{ Hosts: []string{"notexist"}, Key: "any", }, Redis: redis.RedisKeyConf{}, Middlewares: ServerMiddlewaresConf{ Trace: true, Recover: true, Stat: true, Prometheus: true, Breaker: true, }, MethodTimeouts: []MethodTimeoutConf{}, }, func(server *grpc.Server) { }) svr.AddOptions(grpc.ConnectionTimeout(time.Hour)) svr.AddUnaryInterceptors(serverinterceptors.UnaryRecoverInterceptor) svr.AddStreamInterceptors(serverinterceptors.StreamRecoverInterceptor) go svr.Start() svr.Stop() } func TestServer_StartFailed(t *testing.T) { svr := MustNewServer(RpcServerConf{ ServiceConf: service.ServiceConf{ Log: logx.LogConf{ ServiceName: "foo", Mode: "console", }, }, ListenOn: "localhost:aaa", Middlewares: ServerMiddlewaresConf{ Trace: true, Recover: true, Stat: true, Prometheus: true, Breaker: true, }, }, func(server *grpc.Server) { }) assert.Panics(t, svr.Start) } type mockedServer struct { unaryInterceptors []grpc.UnaryServerInterceptor streamInterceptors []grpc.StreamServerInterceptor } func (m *mockedServer) AddOptions(_ ...grpc.ServerOption) { } func (m *mockedServer) AddStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) { m.streamInterceptors = append(m.streamInterceptors, interceptors...) } func (m *mockedServer) AddUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) { m.unaryInterceptors = append(m.unaryInterceptors, interceptors...) } func (m *mockedServer) SetName(_ string) { } func (m *mockedServer) Start(_ internal.RegisterFn) error { return nil } func Test_setupUnaryInterceptors(t *testing.T) { tests := []struct { name string r *mockedServer conf RpcServerConf len int }{ { name: "empty", r: &mockedServer{}, len: 0, }, { name: "custom", r: &mockedServer{ unaryInterceptors: []grpc.UnaryServerInterceptor{ func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { return nil, nil }, }, }, len: 1, }, { name: "middleware", r: &mockedServer{}, conf: RpcServerConf{ Middlewares: ServerMiddlewaresConf{ Trace: true, Recover: true, Stat: true, Prometheus: true, Breaker: true, }, }, len: 5, }, { name: "internal middleware", r: &mockedServer{}, conf: RpcServerConf{ CpuThreshold: 900, Timeout: 100, Middlewares: ServerMiddlewaresConf{ Trace: true, Recover: true, Stat: true, Prometheus: true, Breaker: true, }, }, len: 7, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { metrics := stat.NewMetrics("abc") setupUnaryInterceptors(test.r, test.conf, metrics) assert.Equal(t, test.len, len(test.r.unaryInterceptors)) }) } } func Test_setupStreamInterceptors(t *testing.T) { tests := []struct { name string r *mockedServer conf RpcServerConf len int }{ { name: "empty", r: &mockedServer{}, len: 0, }, { name: "custom", r: &mockedServer{ streamInterceptors: []grpc.StreamServerInterceptor{ func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { return handler(srv, ss) }, }, }, len: 1, }, { name: "middleware", r: &mockedServer{}, conf: RpcServerConf{ Middlewares: ServerMiddlewaresConf{ Trace: true, Recover: true, Stat: true, Prometheus: true, Breaker: true, }, }, len: 3, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { setupStreamInterceptors(test.r, test.conf) assert.Equal(t, test.len, len(test.r.streamInterceptors)) }) } } func Test_setupAuthInterceptors(t *testing.T) { t.Run("no need set auth", func(t *testing.T) { s := &mockedServer{} err := setupAuthInterceptors(s, RpcServerConf{ Auth: false, Redis: redis.RedisKeyConf{}, }) assert.NoError(t, err) }) t.Run("redis error", func(t *testing.T) { s := &mockedServer{} err := setupAuthInterceptors(s, RpcServerConf{ Auth: true, Redis: redis.RedisKeyConf{}, }) assert.Error(t, err) }) t.Run("works", func(t *testing.T) { rds := miniredis.RunT(t) s := &mockedServer{} err := setupAuthInterceptors(s, RpcServerConf{ Auth: true, Redis: redis.RedisKeyConf{ RedisConf: redis.RedisConf{ Host: rds.Addr(), Type: redis.NodeType, }, Key: "foo", }, }) assert.NoError(t, err) assert.Equal(t, 1, len(s.unaryInterceptors)) assert.Equal(t, 1, len(s.streamInterceptors)) }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/config.go
zrpc/config.go
package zrpc import ( "time" "github.com/zeromicro/go-zero/core/discov" "github.com/zeromicro/go-zero/core/service" "github.com/zeromicro/go-zero/core/stores/redis" "github.com/zeromicro/go-zero/zrpc/internal" "github.com/zeromicro/go-zero/zrpc/resolver" ) type ( // ClientMiddlewaresConf defines whether to use client middlewares. ClientMiddlewaresConf = internal.ClientMiddlewaresConf // ServerMiddlewaresConf defines whether to use server middlewares. ServerMiddlewaresConf = internal.ServerMiddlewaresConf // StatConf defines the stat config. StatConf = internal.StatConf // MethodTimeoutConf defines specified timeout for gRPC method. MethodTimeoutConf = internal.MethodTimeoutConf // A RpcClientConf is a rpc client config. RpcClientConf struct { Etcd discov.EtcdConf `json:",optional,inherit"` Endpoints []string `json:",optional"` Target string `json:",optional"` App string `json:",optional"` Token string `json:",optional"` NonBlock bool `json:",default=true"` Timeout int64 `json:",default=2000"` KeepaliveTime time.Duration `json:",optional"` Middlewares ClientMiddlewaresConf BalancerName string `json:",default=p2c_ewma"` } // A RpcServerConf is a rpc server config. RpcServerConf struct { service.ServiceConf ListenOn string Etcd discov.EtcdConf `json:",optional,inherit"` Auth bool `json:",optional"` Redis redis.RedisKeyConf `json:",optional"` StrictControl bool `json:",optional"` // setting 0 means no timeout Timeout int64 `json:",default=2000"` CpuThreshold int64 `json:",default=900,range=[0:1000)"` // grpc health check switch Health bool `json:",default=true"` Middlewares ServerMiddlewaresConf // setting specified timeout for gRPC method MethodTimeouts []MethodTimeoutConf `json:",optional"` } ) // NewDirectClientConf returns a RpcClientConf. func NewDirectClientConf(endpoints []string, app, token string) RpcClientConf { return RpcClientConf{ Endpoints: endpoints, App: app, Token: token, } } // NewEtcdClientConf returns a RpcClientConf. func NewEtcdClientConf(hosts []string, key, app, token string) RpcClientConf { return RpcClientConf{ Etcd: discov.EtcdConf{ Hosts: hosts, Key: key, }, App: app, Token: token, } } // HasEtcd checks if there is etcd settings in config. func (sc RpcServerConf) HasEtcd() bool { return len(sc.Etcd.Hosts) > 0 && len(sc.Etcd.Key) > 0 } // Validate validates the config. func (sc RpcServerConf) Validate() error { if !sc.Auth { return nil } return sc.Redis.Validate() } // BuildTarget builds the rpc target from the given config. func (cc RpcClientConf) BuildTarget() (string, error) { if len(cc.Endpoints) > 0 { return resolver.BuildDirectTarget(cc.Endpoints), nil } else if len(cc.Target) > 0 { return cc.Target, nil } if err := cc.Etcd.Validate(); err != nil { return "", err } if cc.Etcd.HasAccount() { discov.RegisterAccount(cc.Etcd.Hosts, cc.Etcd.User, cc.Etcd.Pass) } if cc.Etcd.HasTLS() { if err := discov.RegisterTLS(cc.Etcd.Hosts, cc.Etcd.CertFile, cc.Etcd.CertKeyFile, cc.Etcd.CACertFile, cc.Etcd.InsecureSkipVerify); err != nil { return "", err } } return resolver.BuildDiscovTarget(cc.Etcd.Hosts, cc.Etcd.Key), nil } // HasCredential checks if there is a credential in config. func (cc RpcClientConf) HasCredential() bool { return len(cc.App) > 0 && len(cc.Token) > 0 }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/proxy_test.go
zrpc/proxy_test.go
package zrpc import ( "context" "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/internal/mock" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" ) func TestProxy(t *testing.T) { tests := []struct { name string amount float32 res *mock.DepositResponse errCode codes.Code errMsg string }{ { "invalid request with negative amount", -1.11, nil, codes.InvalidArgument, fmt.Sprintf("cannot deposit %v", -1.11), }, { "valid request with non negative amount", 0.00, &mock.DepositResponse{Ok: true}, codes.OK, "", }, } proxy := NewProxy("foo", WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())), WithDialOption(grpc.WithContextDialer(dialer()))) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { conn, err := proxy.TakeConn(context.Background()) assert.Nil(t, err) cli := mock.NewDepositServiceClient(conn) request := &mock.DepositRequest{Amount: tt.amount} response, err := cli.Deposit(context.Background(), request) if response != nil { assert.True(t, len(response.String()) > 0) if response.GetOk() != tt.res.GetOk() { t.Error("response: expected", tt.res.GetOk(), "received", response.GetOk()) } } if err != nil { if e, ok := status.FromError(err); ok { if e.Code() != tt.errCode { t.Error("error code: expected", codes.InvalidArgument, "received", e.Code()) } if e.Message() != tt.errMsg { t.Error("error message: expected", tt.errMsg, "received", e.Message()) } } } }) } } func TestRpcProxy_TakeConnNewClientFailed(t *testing.T) { proxy := NewProxy("foo", WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())), WithDialOption(grpc.WithBlock())) _, err := proxy.TakeConn(context.Background()) assert.NotNil(t, err) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/client_test.go
zrpc/client_test.go
package zrpc import ( "context" "fmt" "log" "net" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/discov" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/internal/mock" "github.com/zeromicro/go-zero/zrpc/internal/balancer/consistenthash" "github.com/zeromicro/go-zero/zrpc/internal/balancer/p2c" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" "google.golang.org/grpc/test/bufconn" ) func init() { logx.Disable() } func dialer() func(context.Context, string) (net.Conn, error) { listener := bufconn.Listen(1024 * 1024) server := grpc.NewServer() mock.RegisterDepositServiceServer(server, &mock.DepositServer{}) go func() { if err := server.Serve(listener); err != nil { log.Fatal(err) } }() return func(context.Context, string) (net.Conn, error) { return listener.Dial() } } func TestDepositServer_Deposit(t *testing.T) { tests := []struct { name string amount float32 timeout time.Duration res *mock.DepositResponse errCode codes.Code errMsg string }{ { name: "invalid request with negative amount", amount: -1.11, errCode: codes.InvalidArgument, errMsg: fmt.Sprintf("cannot deposit %v", -1.11), }, { name: "valid request with non negative amount", res: &mock.DepositResponse{Ok: true}, errCode: codes.OK, }, { name: "valid request with long handling time", amount: 2000.00, errCode: codes.DeadlineExceeded, errMsg: "context deadline exceeded", }, { name: "valid request with timeout call option", amount: 2000.00, timeout: time.Second * 3, res: &mock.DepositResponse{Ok: true}, errCode: codes.OK, errMsg: "", }, } directClient := MustNewClient( RpcClientConf{ Endpoints: []string{"foo"}, App: "foo", Token: "bar", Timeout: 1000, Middlewares: ClientMiddlewaresConf{ Trace: true, Duration: true, Prometheus: true, Breaker: true, Timeout: true, }, }, WithDialOption(grpc.WithContextDialer(dialer())), WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { return invoker(ctx, method, req, reply, cc, opts...) }), ) nonBlockClient := MustNewClient( RpcClientConf{ Endpoints: []string{"foo"}, App: "foo", Token: "bar", Timeout: 1000, NonBlock: true, Middlewares: ClientMiddlewaresConf{ Trace: true, Duration: true, Prometheus: true, Breaker: true, Timeout: true, }, }, WithDialOption(grpc.WithContextDialer(dialer())), WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { return invoker(ctx, method, req, reply, cc, opts...) }), ) tarConfClient := MustNewClient( RpcClientConf{ Target: "foo", App: "foo", Token: "bar", Timeout: 1000, KeepaliveTime: time.Second * 15, Middlewares: ClientMiddlewaresConf{ Trace: true, Duration: true, Prometheus: true, Breaker: true, Timeout: true, }, }, WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())), WithDialOption(grpc.WithContextDialer(dialer())), WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { return invoker(ctx, method, req, reply, cc, opts...) }), ) targetClient, err := NewClientWithTarget("foo", WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())), WithDialOption(grpc.WithContextDialer(dialer())), WithUnaryClientInterceptor( func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { return invoker(ctx, method, req, reply, cc, opts...) }), WithTimeout(1000*time.Millisecond)) assert.Nil(t, err) clients := []Client{ directClient, nonBlockClient, tarConfClient, targetClient, } DontLogClientContentForMethod("foo") SetClientSlowThreshold(time.Second) for _, tt := range tests { tt := tt for _, client := range clients { client := client t.Run(tt.name, func(t *testing.T) { t.Parallel() cli := mock.NewDepositServiceClient(client.Conn()) request := &mock.DepositRequest{Amount: tt.amount} var ( ctx = context.Background() response *mock.DepositResponse err error ) if tt.timeout > 0 { response, err = cli.Deposit(ctx, request, WithCallTimeout(tt.timeout)) } else { response, err = cli.Deposit(ctx, request) } if response != nil { assert.True(t, len(response.String()) > 0) if response.GetOk() != tt.res.GetOk() { t.Error("response: expected", tt.res.GetOk(), "received", response.GetOk()) } } if err != nil { if e, ok := status.FromError(err); ok { if e.Code() != tt.errCode { t.Error("error code: expected", codes.InvalidArgument, "received", e.Code()) } if e.Message() != tt.errMsg { t.Error("error message: expected", tt.errMsg, "received", e.Message()) } } } }) } } } func TestNewClientWithError(t *testing.T) { _, err := NewClient( RpcClientConf{ App: "foo", Token: "bar", Timeout: 1000, }, WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())), WithDialOption(grpc.WithContextDialer(dialer())), WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { return invoker(ctx, method, req, reply, cc, opts...) }), ) assert.NotNil(t, err) _, err = NewClient( RpcClientConf{ Etcd: discov.EtcdConf{ Hosts: []string{"localhost:2379"}, Key: "mock", }, App: "foo", Token: "bar", Timeout: 1, }, WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())), WithDialOption(grpc.WithContextDialer(dialer())), WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { return invoker(ctx, method, req, reply, cc, opts...) }), ) assert.NotNil(t, err) } func TestNewClientWithTarget(t *testing.T) { _, err := NewClientWithTarget("", WithDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())), WithDialOption(grpc.WithContextDialer(dialer())), WithUnaryClientInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { return invoker(ctx, method, req, reply, cc, opts...) })) assert.NotNil(t, err) } func TestMakeLBServiceConfig(t *testing.T) { tests := []struct { name string input string expected string }{ { name: "empty name uses default p2c", input: "", expected: fmt.Sprintf(`{"loadBalancingPolicy":"%s"}`, p2c.Name), }, { name: "custom balancer name", input: "consistent_hash", expected: `{"loadBalancingPolicy":"consistent_hash"}`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := makeLBServiceConfig(tt.input) if got != tt.expected { t.Errorf("expected %q, got %q", tt.expected, got) } }) } } func TestSetHashKey(t *testing.T) { ctx := context.Background() key := "abc123" ctx = SetHashKey(ctx, key) got := consistenthash.GetHashKey(ctx) assert.Equal(t, key, got) assert.Empty(t, consistenthash.GetHashKey(context.Background())) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/config_test.go
zrpc/config_test.go
package zrpc import ( "testing" "github.com/stretchr/testify/assert" zconf "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/core/discov" "github.com/zeromicro/go-zero/core/service" "github.com/zeromicro/go-zero/core/stores/redis" "github.com/zeromicro/go-zero/zrpc/internal/balancer/p2c" ) func TestRpcClientConf(t *testing.T) { t.Run("direct", func(t *testing.T) { conf := NewDirectClientConf([]string{"localhost:1234"}, "foo", "bar") assert.True(t, conf.HasCredential()) }) t.Run("etcd", func(t *testing.T) { conf := NewEtcdClientConf([]string{"localhost:1234", "localhost:5678"}, "key", "foo", "bar") assert.True(t, conf.HasCredential()) }) t.Run("etcd with account", func(t *testing.T) { conf := NewEtcdClientConf([]string{"localhost:1234", "localhost:5678"}, "key", "foo", "bar") conf.Etcd.User = "user" conf.Etcd.Pass = "pass" _, err := conf.BuildTarget() assert.NoError(t, err) }) t.Run("etcd with tls", func(t *testing.T) { conf := NewEtcdClientConf([]string{"localhost:1234", "localhost:5678"}, "key", "foo", "bar") conf.Etcd.CertFile = "cert" conf.Etcd.CertKeyFile = "key" conf.Etcd.CACertFile = "ca" _, err := conf.BuildTarget() assert.Error(t, err) }) t.Run("default balancer name", func(t *testing.T) { var conf RpcClientConf err := zconf.FillDefault(&conf) assert.NoError(t, err) assert.Equal(t, p2c.Name, conf.BalancerName) }) } func TestRpcServerConf(t *testing.T) { conf := RpcServerConf{ ServiceConf: service.ServiceConf{}, ListenOn: "", Etcd: discov.EtcdConf{ Hosts: []string{"localhost:1234"}, Key: "key", }, Auth: true, Redis: redis.RedisKeyConf{ RedisConf: redis.RedisConf{ Type: redis.NodeType, }, Key: "foo", }, StrictControl: false, Timeout: 0, CpuThreshold: 0, } assert.True(t, conf.HasEtcd()) assert.NotNil(t, conf.Validate()) conf.Redis.Host = "localhost:5678" assert.Nil(t, conf.Validate()) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/server.go
zrpc/server.go
package zrpc import ( "time" "github.com/zeromicro/go-zero/core/load" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/stat" "github.com/zeromicro/go-zero/core/stores/redis" "github.com/zeromicro/go-zero/zrpc/internal" "github.com/zeromicro/go-zero/zrpc/internal/auth" "github.com/zeromicro/go-zero/zrpc/internal/serverinterceptors" "google.golang.org/grpc" ) // A RpcServer is a rpc server. type RpcServer struct { server internal.Server register internal.RegisterFn } // MustNewServer returns a RpcSever, exits on any error. func MustNewServer(c RpcServerConf, register internal.RegisterFn) *RpcServer { server, err := NewServer(c, register) logx.Must(err) return server } // NewServer returns a RpcServer. func NewServer(c RpcServerConf, register internal.RegisterFn) (*RpcServer, error) { var err error if err = c.Validate(); err != nil { return nil, err } var server internal.Server metrics := stat.NewMetrics(c.ListenOn) serverOptions := []internal.ServerOption{ internal.WithRpcHealth(c.Health), } if c.HasEtcd() { server, err = internal.NewRpcPubServer(c.Etcd, c.ListenOn, serverOptions...) if err != nil { return nil, err } } else { server = internal.NewRpcServer(c.ListenOn, serverOptions...) } server.SetName(c.Name) metrics.SetName(c.Name) setupStreamInterceptors(server, c) setupUnaryInterceptors(server, c, metrics) if err = setupAuthInterceptors(server, c); err != nil { return nil, err } rpcServer := &RpcServer{ server: server, register: register, } if err = c.SetUp(); err != nil { return nil, err } return rpcServer, nil } // AddOptions adds given options. func (rs *RpcServer) AddOptions(options ...grpc.ServerOption) { rs.server.AddOptions(options...) } // AddStreamInterceptors adds given stream interceptors. func (rs *RpcServer) AddStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) { rs.server.AddStreamInterceptors(interceptors...) } // AddUnaryInterceptors adds given unary interceptors. func (rs *RpcServer) AddUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) { rs.server.AddUnaryInterceptors(interceptors...) } // Start starts the RpcServer. // Graceful shutdown is enabled by default. // Use proc.SetTimeToForceQuit to customize the graceful shutdown period. func (rs *RpcServer) Start() { if err := rs.server.Start(rs.register); err != nil { logx.Error(err) panic(err) } } // Stop stops the RpcServer. func (rs *RpcServer) Stop() { logx.Close() } // DontLogContentForMethod disable logging content for given method. // Deprecated: use ServerMiddlewaresConf.IgnoreContentMethods instead. func DontLogContentForMethod(method string) { serverinterceptors.DontLogContentForMethod(method) } // SetServerSlowThreshold sets the slow threshold on server side. // Deprecated: use ServerMiddlewaresConf.SlowThreshold instead. func SetServerSlowThreshold(threshold time.Duration) { serverinterceptors.SetSlowThreshold(threshold) } func setupAuthInterceptors(svr internal.Server, c RpcServerConf) error { if !c.Auth { return nil } rds, err := redis.NewRedis(c.Redis.RedisConf) if err != nil { return err } authenticator, err := auth.NewAuthenticator(rds, c.Redis.Key, c.StrictControl) if err != nil { return err } svr.AddStreamInterceptors(serverinterceptors.StreamAuthorizeInterceptor(authenticator)) svr.AddUnaryInterceptors(serverinterceptors.UnaryAuthorizeInterceptor(authenticator)) return nil } func setupStreamInterceptors(svr internal.Server, c RpcServerConf) { if c.Middlewares.Trace { svr.AddStreamInterceptors(serverinterceptors.StreamTracingInterceptor) } if c.Middlewares.Recover { svr.AddStreamInterceptors(serverinterceptors.StreamRecoverInterceptor) } if c.Middlewares.Breaker { svr.AddStreamInterceptors(serverinterceptors.StreamBreakerInterceptor) } } func setupUnaryInterceptors(svr internal.Server, c RpcServerConf, metrics *stat.Metrics) { if c.Middlewares.Trace { svr.AddUnaryInterceptors(serverinterceptors.UnaryTracingInterceptor) } if c.Middlewares.Recover { svr.AddUnaryInterceptors(serverinterceptors.UnaryRecoverInterceptor) } if c.Middlewares.Stat { svr.AddUnaryInterceptors(serverinterceptors.UnaryStatInterceptor(metrics, c.Middlewares.StatConf)) } if c.Middlewares.Prometheus { svr.AddUnaryInterceptors(serverinterceptors.UnaryPrometheusInterceptor) } if c.Middlewares.Breaker { svr.AddUnaryInterceptors(serverinterceptors.UnaryBreakerInterceptor) } if c.CpuThreshold > 0 { shedder := load.NewAdaptiveShedder(load.WithCpuThreshold(c.CpuThreshold)) svr.AddUnaryInterceptors(serverinterceptors.UnarySheddingInterceptor(shedder, metrics)) } if c.Timeout > 0 { svr.AddUnaryInterceptors(serverinterceptors.UnaryTimeoutInterceptor( time.Duration(c.Timeout)*time.Millisecond, c.MethodTimeouts...)) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/resolver/register.go
zrpc/resolver/register.go
package resolver import "github.com/zeromicro/go-zero/zrpc/resolver/internal" // Register registers schemes defined zrpc. // Keep it in a separated package to let third party register manually. func Register() { internal.RegisterResolver() }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/resolver/target_test.go
zrpc/resolver/target_test.go
package resolver import ( "testing" "github.com/stretchr/testify/assert" ) func TestBuildDirectTarget(t *testing.T) { target := BuildDirectTarget([]string{"localhost:123", "localhost:456"}) assert.Equal(t, "direct:///localhost:123,localhost:456", target) } func TestBuildDiscovTarget(t *testing.T) { target := BuildDiscovTarget([]string{"localhost:123", "localhost:456"}, "foo") assert.Equal(t, "etcd://localhost:123,localhost:456/foo", target) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/resolver/register_test.go
zrpc/resolver/register_test.go
package resolver import ( "testing" "github.com/stretchr/testify/assert" ) func TestRegister(t *testing.T) { assert.NotPanics(t, func() { Register() }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/resolver/target.go
zrpc/resolver/target.go
package resolver import ( "fmt" "strings" "github.com/zeromicro/go-zero/zrpc/resolver/internal" ) // BuildDirectTarget returns a string that represents the given endpoints with direct schema. func BuildDirectTarget(endpoints []string) string { return fmt.Sprintf("%s:///%s", internal.DirectScheme, strings.Join(endpoints, internal.EndpointSep)) } // BuildDiscovTarget returns a string that represents the given endpoints with discov schema. func BuildDiscovTarget(endpoints []string, key string) string { return fmt.Sprintf("%s://%s/%s", internal.EtcdScheme, strings.Join(endpoints, internal.EndpointSep), key) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/resolver/internal/discovbuilder.go
zrpc/resolver/internal/discovbuilder.go
package internal import ( "strings" "github.com/zeromicro/go-zero/core/discov" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/zrpc/resolver/internal/targets" "google.golang.org/grpc/resolver" ) type discovBuilder struct{} func (b *discovBuilder) Build(target resolver.Target, cc resolver.ClientConn, _ resolver.BuildOptions) ( resolver.Resolver, error) { hosts := strings.FieldsFunc(targets.GetAuthority(target), func(r rune) bool { return r == EndpointSepChar }) sub, err := discov.NewSubscriber(hosts, targets.GetEndpoints(target)) if err != nil { return nil, err } update := func() { vals := subset(sub.Values(), subsetSize) addrs := make([]resolver.Address, 0, len(vals)) for _, val := range vals { addrs = append(addrs, resolver.Address{ Addr: val, }) } if err := cc.UpdateState(resolver.State{ Addresses: addrs, }); err != nil { logx.Error(err) } } sub.AddListener(update) update() return &discovResolver{ cc: cc, sub: sub, }, nil } func (b *discovBuilder) Scheme() string { return DiscovScheme } type discovResolver struct { cc resolver.ClientConn sub *discov.Subscriber } func (r *discovResolver) Close() { r.sub.Close() } func (r *discovResolver) ResolveNow(_ resolver.ResolveNowOptions) { }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/resolver/internal/directbuilder_test.go
zrpc/resolver/internal/directbuilder_test.go
package internal import ( "errors" "fmt" "net/url" "strconv" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/lang" "google.golang.org/grpc/resolver" ) func TestDirectBuilder_Build(t *testing.T) { tests := []int{ 0, 1, 2, subsetSize / 2, subsetSize, subsetSize * 2, } for _, test := range tests { test := test t.Run(strconv.Itoa(test), func(t *testing.T) { var servers []string for i := 0; i < test; i++ { servers = append(servers, fmt.Sprintf("localhost:%d", i)) } var b directBuilder cc := new(mockedClientConn) target := fmt.Sprintf("%s:///%s", DirectScheme, strings.Join(servers, ",")) uri, err := url.Parse(target) assert.Nil(t, err) cc.err = errors.New("foo") _, err = b.Build(resolver.Target{ URL: *uri, }, cc, resolver.BuildOptions{}) assert.NotNil(t, err) cc.err = nil _, err = b.Build(resolver.Target{ URL: *uri, }, cc, resolver.BuildOptions{}) assert.NoError(t, err) size := min(test, subsetSize) assert.Equal(t, size, len(cc.state.Addresses)) m := make(map[string]lang.PlaceholderType) for _, each := range cc.state.Addresses { m[each.Addr] = lang.Placeholder } assert.Equal(t, size, len(m)) }) } } func TestDirectBuilder_Scheme(t *testing.T) { var b directBuilder assert.Equal(t, DirectScheme, b.Scheme()) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/zrpc/resolver/internal/kubebuilder_test.go
zrpc/resolver/internal/kubebuilder_test.go
package internal import ( "fmt" "net/url" "testing" "github.com/stretchr/testify/assert" "google.golang.org/grpc/resolver" ) func TestKubeBuilder_Scheme(t *testing.T) { var b kubeBuilder assert.Equal(t, KubernetesScheme, b.Scheme()) } func TestKubeBuilder_Build(t *testing.T) { var b kubeBuilder u, err := url.Parse(fmt.Sprintf("%s://%s", KubernetesScheme, "a,b")) assert.NoError(t, err) _, err = b.Build(resolver.Target{ URL: *u, }, nil, resolver.BuildOptions{}) assert.Error(t, err) u, err = url.Parse(fmt.Sprintf("%s://%s:9100/a:b:c", KubernetesScheme, "a,b,c,d")) assert.NoError(t, err) _, err = b.Build(resolver.Target{ URL: *u, }, nil, resolver.BuildOptions{}) assert.Error(t, err) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false