repo_name
stringlengths
8
38
pr_number
int64
3
47.1k
pr_title
stringlengths
8
175
pr_description
stringlengths
2
19.8k
author
null
date_created
stringlengths
25
25
date_merged
stringlengths
25
25
filepath
stringlengths
6
136
before_content
stringlengths
54
884k
after_content
stringlengths
56
884k
pr_author
stringlengths
3
21
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
comment
stringlengths
2
25.4k
comment_author
stringlengths
3
29
__index_level_0__
int64
0
5.1k
gohugoio/hugo
11,706
resources/resource: Fix GroupByParamDate with raw TOML dates
Closes #11563
null
2023-11-13 23:09:55+00:00
2023-11-22 11:09:48+00:00
resources/resource/resource_helpers.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 resource import ( "strings" "time" "github.com/gohugoio/hugo/helpers" "github.com/spf13/cast" ) // GetParam will return the param with the given key from the Resource, // nil if not found. func GetParam(r Resource, key string) any { return getParam(r, key, false) } // GetParamToLower is the same as GetParam but it will lower case any string // result, including string slices. func GetParamToLower(r Resource, key string) any { return getParam(r, key, true) } func getParam(r Resource, key string, stringToLower bool) any { v := r.Params()[strings.ToLower(key)] if v == nil { return nil } switch val := v.(type) { case bool: return val case string: if stringToLower { return strings.ToLower(val) } return val case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return val case []string: if stringToLower { return helpers.SliceToLower(val) } return v case map[string]any: return v case map[any]any: return v } return nil }
// 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 resource import ( "strings" "time" "github.com/gohugoio/hugo/helpers" "github.com/pelletier/go-toml/v2" "github.com/spf13/cast" ) // GetParam will return the param with the given key from the Resource, // nil if not found. func GetParam(r Resource, key string) any { return getParam(r, key, false) } // GetParamToLower is the same as GetParam but it will lower case any string // result, including string slices. func GetParamToLower(r Resource, key string) any { return getParam(r, key, true) } func getParam(r Resource, key string, stringToLower bool) any { v := r.Params()[strings.ToLower(key)] if v == nil { return nil } switch val := v.(type) { case bool: return val case string: if stringToLower { return strings.ToLower(val) } return val case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return val case toml.LocalDate: return val.AsTime(time.UTC) case toml.LocalDateTime: return val.AsTime(time.UTC) case []string: if stringToLower { return helpers.SliceToLower(val) } return v case map[string]any: return v case map[any]any: return v } return nil }
jmooring
27620daa20bfd951971f98c8177488fc46d7637c
dd6cd6268d2f73c5505077ff278c3e964d3a2e3b
This is nit picking, but but when you have a known type, converting it to another type (e.g. `interface{}` or `reflect.Value`) just so it can be converted back to the type you started with. I don't think it allocates any extra memory in this particular case, but I had to navigate into the ToTime... func to see what it does. I suggest you just call val.AsTime directly.
bep
2
gohugoio/hugo
11,706
resources/resource: Fix GroupByParamDate with raw TOML dates
Closes #11563
null
2023-11-13 23:09:55+00:00
2023-11-22 11:09:48+00:00
resources/resource/resource_helpers.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 resource import ( "strings" "time" "github.com/gohugoio/hugo/helpers" "github.com/spf13/cast" ) // GetParam will return the param with the given key from the Resource, // nil if not found. func GetParam(r Resource, key string) any { return getParam(r, key, false) } // GetParamToLower is the same as GetParam but it will lower case any string // result, including string slices. func GetParamToLower(r Resource, key string) any { return getParam(r, key, true) } func getParam(r Resource, key string, stringToLower bool) any { v := r.Params()[strings.ToLower(key)] if v == nil { return nil } switch val := v.(type) { case bool: return val case string: if stringToLower { return strings.ToLower(val) } return val case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return val case []string: if stringToLower { return helpers.SliceToLower(val) } return v case map[string]any: return v case map[any]any: return v } return nil }
// 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 resource import ( "strings" "time" "github.com/gohugoio/hugo/helpers" "github.com/pelletier/go-toml/v2" "github.com/spf13/cast" ) // GetParam will return the param with the given key from the Resource, // nil if not found. func GetParam(r Resource, key string) any { return getParam(r, key, false) } // GetParamToLower is the same as GetParam but it will lower case any string // result, including string slices. func GetParamToLower(r Resource, key string) any { return getParam(r, key, true) } func getParam(r Resource, key string, stringToLower bool) any { v := r.Params()[strings.ToLower(key)] if v == nil { return nil } switch val := v.(type) { case bool: return val case string: if stringToLower { return strings.ToLower(val) } return val case int64, int32, int16, int8, int: return cast.ToInt(v) case float64, float32: return cast.ToFloat64(v) case time.Time: return val case toml.LocalDate: return val.AsTime(time.UTC) case toml.LocalDateTime: return val.AsTime(time.UTC) case []string: if stringToLower { return helpers.SliceToLower(val) } return v case map[string]any: return v case map[any]any: return v } return nil }
jmooring
27620daa20bfd951971f98c8177488fc46d7637c
dd6cd6268d2f73c5505077ff278c3e964d3a2e3b
Sorry about the iterations here. This was the self-inflicted wound: ``` case toml.LocalDate, toml.LocalDateTime: ``` <https://go.dev/ref/spec#Type_switches> > In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard. Which meant I had type `any` instead of the toml.Whatever type, which meant AsTime() was not an option. Split the case; all is good.
jmooring
3
gohugoio/hugo
11,688
tpl: allow using page resources on the images page parameter for `opengraph`, `schema` and `twitter_cards` templates
Hi, I want to specify the page resources on `images` parameter other than renaming the files, the new image parsing order as follows. 1. If the image is external, leave it as it is. 2. Use page resource if there is matched one. 3. In other cases, use `absURL` to transform the image URL.
null
2023-11-09 04:17:47+00:00
2023-12-04 11:05:41+00:00
tpl/tplimpl/embedded/templates/schema.html
<meta itemprop="name" content="{{ .Title }}"> <meta itemprop="description" content="{{ with .Description }}{{ . }}{{ else }}{{if .IsPage}}{{ .Summary }}{{ else }}{{ with .Site.Params.description }}{{ . }}{{ end }}{{ end }}{{ end }}"> {{- if .IsPage -}} {{- $iso8601 := "2006-01-02T15:04:05-07:00" -}} {{ with .PublishDate }}<meta itemprop="datePublished" {{ .Format $iso8601 | printf "content=%q" | safeHTMLAttr }} />{{ end}} {{ with .Lastmod }}<meta itemprop="dateModified" {{ .Format $iso8601 | printf "content=%q" | safeHTMLAttr }} />{{ end}} <meta itemprop="wordCount" content="{{ .WordCount }}"> {{- with $.Params.images -}} {{- range first 6 . -}}<meta itemprop="image" content="{{ . | absURL }}">{{ end -}} {{- else -}} {{- $images := $.Resources.ByType "image" -}} {{- $featured := $images.GetMatch "*feature*" -}} {{- if not $featured }}{{ $featured = $images.GetMatch "{*cover*,*thumbnail*}" }}{{ end -}} {{- with $featured -}} <meta itemprop="image" content="{{ $featured.Permalink }}"> {{- else -}} {{- with $.Site.Params.images -}}<meta itemprop="image" content="{{ index . 0 | absURL }}"/>{{ end -}} {{- end -}} {{- end -}} <!-- Output all taxonomies as schema.org keywords --> <meta itemprop="keywords" content="{{ if .IsPage}}{{ range $index, $tag := .Params.tags }}{{ $tag }},{{ end }}{{ else }}{{ range $plural, $terms := .Site.Taxonomies }}{{ range $term, $val := $terms }}{{ printf "%s," $term }}{{ end }}{{ end }}{{ end }}" /> {{- end -}}
<meta itemprop="name" content="{{ .Title }}"> <meta itemprop="description" content="{{ with .Description }}{{ . }}{{ else }}{{if .IsPage}}{{ .Summary }}{{ else }}{{ with .Site.Params.description }}{{ . }}{{ end }}{{ end }}{{ end }}"> {{- if .IsPage -}} {{- $iso8601 := "2006-01-02T15:04:05-07:00" -}} {{ with .PublishDate }}<meta itemprop="datePublished" {{ .Format $iso8601 | printf "content=%q" | safeHTMLAttr }} />{{ end}} {{ with .Lastmod }}<meta itemprop="dateModified" {{ .Format $iso8601 | printf "content=%q" | safeHTMLAttr }} />{{ end}} <meta itemprop="wordCount" content="{{ .WordCount }}"> {{- $images := partial "_funcs/get-page-images" . -}} {{- range first 6 $images -}} <meta itemprop="image" content="{{ .Permalink }}" /> {{- end -}} <!-- Output all taxonomies as schema.org keywords --> <meta itemprop="keywords" content="{{ if .IsPage}}{{ range $index, $tag := .Params.tags }}{{ $tag }},{{ end }}{{ else }}{{ range $plural, $terms := .Site.Taxonomies }}{{ range $term, $val := $terms }}{{ printf "%s," $term }}{{ end }}{{ end }}{{ end }}" /> {{- end -}}
razonyang
171836cdfae7e9697fddafe262c46b9448bcb98e
14d85ec136413dcfc96ad8e4d31633f8f9cbf410
Remove cached here. I would guess that the potential value would be negative in this case (memory usage).
bep
4
gohugoio/hugo
11,622
markup/goldmark: update the CJK extension to allow specifying line break styles
This commit follows https://github.com/yuin/goldmark/pull/411
null
2023-10-29 05:55:03+00:00
2023-10-29 09:13:57+00:00
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 ( AutoHeadingIDTypeGitHub = "github" AutoHeadingIDTypeGitHubAscii = "github-ascii" AutoHeadingIDTypeBlackfriday = "blackfriday" ) // 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: true, DefinitionList: true, Table: true, Strikethrough: true, Linkify: true, LinkifyProtocol: "https", TaskList: true, CJK: CJK{ Enable: false, EastAsianLineBreaks: false, EscapedSpace: false, }, }, Renderer: Renderer{ Unsafe: false, }, Parser: Parser{ AutoHeadingID: true, AutoHeadingIDType: AutoHeadingIDTypeGitHub, WrapStandAloneImageWithinParagraph: true, Attribute: ParserAttribute{ Title: true, Block: false, }, }, } // Config configures Goldmark. type Config struct { Renderer Renderer Parser Parser Extensions Extensions } type Extensions struct { Typographer Typographer Footnote bool DefinitionList bool // GitHub flavored markdown Table bool Strikethrough bool Linkify bool LinkifyProtocol string TaskList bool CJK CJK } // 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 } type CJK struct { // Whether to enable CJK support. Enable bool // Whether softline breaks between east asian wide characters should be ignored. EastAsianLineBreaks bool // 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 // The strategy to use when generating heading IDs. // Available options are "github", "github-ascii". // Default is "github", which will create GitHub-compatible anchor names. AutoHeadingIDType string // Enables custom attributes. Attribute ParserAttribute // Whether to wrap stand-alone images within a paragraph or not. WrapStandAloneImageWithinParagraph bool } type ParserAttribute struct { // Enables custom attributes for titles. Title bool // Enables custom attributeds for blocks. Block bool }
// 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 ( AutoHeadingIDTypeGitHub = "github" AutoHeadingIDTypeGitHubAscii = "github-ascii" AutoHeadingIDTypeBlackfriday = "blackfriday" ) // 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: true, DefinitionList: true, Table: true, Strikethrough: true, Linkify: true, LinkifyProtocol: "https", TaskList: true, CJK: CJK{ Enable: false, EastAsianLineBreaks: false, EastAsianLineBreaksStyle: "simple", EscapedSpace: false, }, }, Renderer: Renderer{ Unsafe: false, }, Parser: Parser{ AutoHeadingID: true, AutoHeadingIDType: AutoHeadingIDTypeGitHub, WrapStandAloneImageWithinParagraph: true, Attribute: ParserAttribute{ Title: true, Block: false, }, }, } // Config configures Goldmark. type Config struct { Renderer Renderer Parser Parser Extensions Extensions } type Extensions struct { Typographer Typographer Footnote bool DefinitionList bool // GitHub flavored markdown Table bool Strikethrough bool Linkify bool LinkifyProtocol string TaskList bool CJK CJK } // 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 } 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 // The strategy to use when generating heading IDs. // Available options are "github", "github-ascii". // Default is "github", which will create GitHub-compatible anchor names. AutoHeadingIDType string // Enables custom attributes. Attribute ParserAttribute // Whether to wrap stand-alone images within a paragraph or not. WrapStandAloneImageWithinParagraph bool } type ParserAttribute struct { // Enables custom attributes for titles. Title bool // Enables custom attributeds for blocks. Block bool }
henry0312
3f64b5a3de5f097c4ee1b70505398f75feb391c4
db14238ba323279b28e7ad4cfff5aa10909ccd18
I placed the style specification settings at this level to maintain backward compatibility. `"simple"` is the current newline style. If not specified, it defaults to `"simple"`. Another option available is `"css3draft"`.
henry0312
5
gohugoio/hugo
11,621
resources/images: Create padding image filter
This addresses the primary use case described in https://github.com/gohugoio/hugo/issues/11599.
null
2023-10-28 17:24:03+00:00
2023-10-29 09:16:37+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "fmt" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct{} func (*Filters) Process(spec any) gift.Filter { return filter{ Options: newFilterOpts(spec), Filter: processFilter{ spec: cast.ToString(spec), }, } } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Opacity creates a filter that changes the opacity of an image. // The opacity parameter must be in range (0, 1). func (*Filters) Opacity(opacity any) gift.Filter { return filter{ Options: newFilterOpts(opacity), Filter: opacityFilter{opacity: cast.ToFloat32(opacity)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...any) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt maps.Params if len(options) > 0 { opt = maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) case "font": if err, ok := v.(error); ok { panic(fmt.Sprintf("invalid font source: %s", err)) } fontSource, ok1 := v.(hugio.ReadSeekCloserProvider) identifier, ok2 := v.(resource.Identifier) if !(ok1 && ok2) { panic(fmt.Sprintf("invalid text font source: %T", v)) } tf.fontSource = fontSource // The input value isn't hashable and will not make a stable key. // Replace it with a string in the map used as basis for the // hash string. opt["font"] = identifier.Key() } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma any) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma any) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift any) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size any) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor any) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals any } func newFilterOpts(vals ...any) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "fmt" "image/color" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct{} // Process creates a filter that processes an image using the given specification. func (*Filters) Process(spec any) gift.Filter { return filter{ Options: newFilterOpts(spec), Filter: processFilter{ spec: cast.ToString(spec), }, } } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Opacity creates a filter that changes the opacity of an image. // The opacity parameter must be in range (0, 1). func (*Filters) Opacity(opacity any) gift.Filter { return filter{ Options: newFilterOpts(opacity), Filter: opacityFilter{opacity: cast.ToFloat32(opacity)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...any) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt maps.Params if len(options) > 0 { opt = maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) case "font": if err, ok := v.(error); ok { panic(fmt.Sprintf("invalid font source: %s", err)) } fontSource, ok1 := v.(hugio.ReadSeekCloserProvider) identifier, ok2 := v.(resource.Identifier) if !(ok1 && ok2) { panic(fmt.Sprintf("invalid text font source: %T", v)) } tf.fontSource = fontSource // The input value isn't hashable and will not make a stable key. // Replace it with a string in the map used as basis for the // hash string. opt["font"] = identifier.Key() } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Padding creates a filter that resizes the image canvas without resizing the // image. The last argument is the canvas color, expressed as an RGB or RGBA // hexadecimal color. The default value is `ffffffff` (opaque white). The // preceding arguments are the padding values, in pixels, using the CSS // shorthand property syntax. Negative padding values will crop the image. The // signature is images.Padding V1 [V2] [V3] [V4] [COLOR]. func (*Filters) Padding(args ...any) gift.Filter { if len(args) < 1 || len(args) > 5 { panic("the padding filter requires between 1 and 5 arguments") } var top, right, bottom, left int var ccolor color.Color = color.White // canvas color var err error _args := args // preserve original args for most stable hash if vcs, ok := (args[len(args)-1]).(string); ok { ccolor, err = hexStringToColor(vcs) if err != nil { panic("invalid canvas color: specify RGB or RGBA using hex notation") } args = args[:len(args)-1] if len(args) == 0 { panic("not enough arguments: provide one or more padding values using the CSS shorthand property syntax") } } var vals []int for _, v := range args { vi := cast.ToInt(v) if vi > 5000 { panic("padding values must not exceed 5000 pixels") } vals = append(vals, vi) } switch len(args) { case 1: top, right, bottom, left = vals[0], vals[0], vals[0], vals[0] case 2: top, right, bottom, left = vals[0], vals[1], vals[0], vals[1] case 3: top, right, bottom, left = vals[0], vals[1], vals[2], vals[1] case 4: top, right, bottom, left = vals[0], vals[1], vals[2], vals[3] default: panic(fmt.Sprintf("too many padding values: received %d, expected maximum of 4", len(args))) } return filter{ Options: newFilterOpts(_args...), Filter: paddingFilter{ top: top, right: right, bottom: bottom, left: left, ccolor: ccolor, }, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma any) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma any) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift any) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size any) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor any) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals any } func newFilterOpts(vals ...any) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
jmooring
db14238ba323279b28e7ad4cfff5aa10909ccd18
3ed28e4bfe2d333fdf1ca2434b57cfc10c3d9791
I like the overall idea of the Padding func. But I think the variadic function setup becomes too complicated with 5 different arguments. I suggest * using a dict with top, right, bottom, left, color * create a struct with these and use mapstructure.WeakDecode * But make sure to pass the original dict (the one provided from the user) to newFilterOpts (this allows us to add fields to the options struct without breaking the hash)
bep
6
gohugoio/hugo
11,621
resources/images: Create padding image filter
This addresses the primary use case described in https://github.com/gohugoio/hugo/issues/11599.
null
2023-10-28 17:24:03+00:00
2023-10-29 09:16:37+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "fmt" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct{} func (*Filters) Process(spec any) gift.Filter { return filter{ Options: newFilterOpts(spec), Filter: processFilter{ spec: cast.ToString(spec), }, } } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Opacity creates a filter that changes the opacity of an image. // The opacity parameter must be in range (0, 1). func (*Filters) Opacity(opacity any) gift.Filter { return filter{ Options: newFilterOpts(opacity), Filter: opacityFilter{opacity: cast.ToFloat32(opacity)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...any) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt maps.Params if len(options) > 0 { opt = maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) case "font": if err, ok := v.(error); ok { panic(fmt.Sprintf("invalid font source: %s", err)) } fontSource, ok1 := v.(hugio.ReadSeekCloserProvider) identifier, ok2 := v.(resource.Identifier) if !(ok1 && ok2) { panic(fmt.Sprintf("invalid text font source: %T", v)) } tf.fontSource = fontSource // The input value isn't hashable and will not make a stable key. // Replace it with a string in the map used as basis for the // hash string. opt["font"] = identifier.Key() } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma any) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma any) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift any) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size any) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor any) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals any } func newFilterOpts(vals ...any) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "fmt" "image/color" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct{} // Process creates a filter that processes an image using the given specification. func (*Filters) Process(spec any) gift.Filter { return filter{ Options: newFilterOpts(spec), Filter: processFilter{ spec: cast.ToString(spec), }, } } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Opacity creates a filter that changes the opacity of an image. // The opacity parameter must be in range (0, 1). func (*Filters) Opacity(opacity any) gift.Filter { return filter{ Options: newFilterOpts(opacity), Filter: opacityFilter{opacity: cast.ToFloat32(opacity)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...any) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt maps.Params if len(options) > 0 { opt = maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) case "font": if err, ok := v.(error); ok { panic(fmt.Sprintf("invalid font source: %s", err)) } fontSource, ok1 := v.(hugio.ReadSeekCloserProvider) identifier, ok2 := v.(resource.Identifier) if !(ok1 && ok2) { panic(fmt.Sprintf("invalid text font source: %T", v)) } tf.fontSource = fontSource // The input value isn't hashable and will not make a stable key. // Replace it with a string in the map used as basis for the // hash string. opt["font"] = identifier.Key() } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Padding creates a filter that resizes the image canvas without resizing the // image. The last argument is the canvas color, expressed as an RGB or RGBA // hexadecimal color. The default value is `ffffffff` (opaque white). The // preceding arguments are the padding values, in pixels, using the CSS // shorthand property syntax. Negative padding values will crop the image. The // signature is images.Padding V1 [V2] [V3] [V4] [COLOR]. func (*Filters) Padding(args ...any) gift.Filter { if len(args) < 1 || len(args) > 5 { panic("the padding filter requires between 1 and 5 arguments") } var top, right, bottom, left int var ccolor color.Color = color.White // canvas color var err error _args := args // preserve original args for most stable hash if vcs, ok := (args[len(args)-1]).(string); ok { ccolor, err = hexStringToColor(vcs) if err != nil { panic("invalid canvas color: specify RGB or RGBA using hex notation") } args = args[:len(args)-1] if len(args) == 0 { panic("not enough arguments: provide one or more padding values using the CSS shorthand property syntax") } } var vals []int for _, v := range args { vi := cast.ToInt(v) if vi > 5000 { panic("padding values must not exceed 5000 pixels") } vals = append(vals, vi) } switch len(args) { case 1: top, right, bottom, left = vals[0], vals[0], vals[0], vals[0] case 2: top, right, bottom, left = vals[0], vals[1], vals[0], vals[1] case 3: top, right, bottom, left = vals[0], vals[1], vals[2], vals[1] case 4: top, right, bottom, left = vals[0], vals[1], vals[2], vals[3] default: panic(fmt.Sprintf("too many padding values: received %d, expected maximum of 4", len(args))) } return filter{ Options: newFilterOpts(_args...), Filter: paddingFilter{ top: top, right: right, bottom: bottom, left: left, ccolor: ccolor, }, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma any) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma any) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift any) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size any) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor any) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals any } func newFilterOpts(vals ...any) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
jmooring
db14238ba323279b28e7ad4cfff5aa10909ccd18
3ed28e4bfe2d333fdf1ca2434b57cfc10c3d9791
This is a polite request to reconsider. In my view the most common cases are: ```go-html-template {{ $filter := images.Padding 20 }} {{ $filter := images.Padding 20 40 }} ``` Also, the CSS padding shorthand should be familiar to most site and theme authors, and I can certainly add links to mozilla docs describing the notation. I'm fine with the options map; it just seems like a little more work compared to some of the other filters, excluding text and overlay.
jmooring
7
gohugoio/hugo
11,621
resources/images: Create padding image filter
This addresses the primary use case described in https://github.com/gohugoio/hugo/issues/11599.
null
2023-10-28 17:24:03+00:00
2023-10-29 09:16:37+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "fmt" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct{} func (*Filters) Process(spec any) gift.Filter { return filter{ Options: newFilterOpts(spec), Filter: processFilter{ spec: cast.ToString(spec), }, } } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Opacity creates a filter that changes the opacity of an image. // The opacity parameter must be in range (0, 1). func (*Filters) Opacity(opacity any) gift.Filter { return filter{ Options: newFilterOpts(opacity), Filter: opacityFilter{opacity: cast.ToFloat32(opacity)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...any) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt maps.Params if len(options) > 0 { opt = maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) case "font": if err, ok := v.(error); ok { panic(fmt.Sprintf("invalid font source: %s", err)) } fontSource, ok1 := v.(hugio.ReadSeekCloserProvider) identifier, ok2 := v.(resource.Identifier) if !(ok1 && ok2) { panic(fmt.Sprintf("invalid text font source: %T", v)) } tf.fontSource = fontSource // The input value isn't hashable and will not make a stable key. // Replace it with a string in the map used as basis for the // hash string. opt["font"] = identifier.Key() } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma any) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma any) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift any) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size any) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor any) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals any } func newFilterOpts(vals ...any) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "fmt" "image/color" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct{} // Process creates a filter that processes an image using the given specification. func (*Filters) Process(spec any) gift.Filter { return filter{ Options: newFilterOpts(spec), Filter: processFilter{ spec: cast.ToString(spec), }, } } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Opacity creates a filter that changes the opacity of an image. // The opacity parameter must be in range (0, 1). func (*Filters) Opacity(opacity any) gift.Filter { return filter{ Options: newFilterOpts(opacity), Filter: opacityFilter{opacity: cast.ToFloat32(opacity)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...any) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt maps.Params if len(options) > 0 { opt = maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) case "font": if err, ok := v.(error); ok { panic(fmt.Sprintf("invalid font source: %s", err)) } fontSource, ok1 := v.(hugio.ReadSeekCloserProvider) identifier, ok2 := v.(resource.Identifier) if !(ok1 && ok2) { panic(fmt.Sprintf("invalid text font source: %T", v)) } tf.fontSource = fontSource // The input value isn't hashable and will not make a stable key. // Replace it with a string in the map used as basis for the // hash string. opt["font"] = identifier.Key() } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Padding creates a filter that resizes the image canvas without resizing the // image. The last argument is the canvas color, expressed as an RGB or RGBA // hexadecimal color. The default value is `ffffffff` (opaque white). The // preceding arguments are the padding values, in pixels, using the CSS // shorthand property syntax. Negative padding values will crop the image. The // signature is images.Padding V1 [V2] [V3] [V4] [COLOR]. func (*Filters) Padding(args ...any) gift.Filter { if len(args) < 1 || len(args) > 5 { panic("the padding filter requires between 1 and 5 arguments") } var top, right, bottom, left int var ccolor color.Color = color.White // canvas color var err error _args := args // preserve original args for most stable hash if vcs, ok := (args[len(args)-1]).(string); ok { ccolor, err = hexStringToColor(vcs) if err != nil { panic("invalid canvas color: specify RGB or RGBA using hex notation") } args = args[:len(args)-1] if len(args) == 0 { panic("not enough arguments: provide one or more padding values using the CSS shorthand property syntax") } } var vals []int for _, v := range args { vi := cast.ToInt(v) if vi > 5000 { panic("padding values must not exceed 5000 pixels") } vals = append(vals, vi) } switch len(args) { case 1: top, right, bottom, left = vals[0], vals[0], vals[0], vals[0] case 2: top, right, bottom, left = vals[0], vals[1], vals[0], vals[1] case 3: top, right, bottom, left = vals[0], vals[1], vals[2], vals[1] case 4: top, right, bottom, left = vals[0], vals[1], vals[2], vals[3] default: panic(fmt.Sprintf("too many padding values: received %d, expected maximum of 4", len(args))) } return filter{ Options: newFilterOpts(_args...), Filter: paddingFilter{ top: top, right: right, bottom: bottom, left: left, ccolor: ccolor, }, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma any) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma any) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift any) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size any) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor any) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals any } func newFilterOpts(vals ...any) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
jmooring
db14238ba323279b28e7ad4cfff5aa10909ccd18
3ed28e4bfe2d333fdf1ca2434b57cfc10c3d9791
Yea, ok, we could introduce the dict if it gets more complicated.
bep
8
gohugoio/hugo
11,621
resources/images: Create padding image filter
This addresses the primary use case described in https://github.com/gohugoio/hugo/issues/11599.
null
2023-10-28 17:24:03+00:00
2023-10-29 09:16:37+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "fmt" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct{} func (*Filters) Process(spec any) gift.Filter { return filter{ Options: newFilterOpts(spec), Filter: processFilter{ spec: cast.ToString(spec), }, } } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Opacity creates a filter that changes the opacity of an image. // The opacity parameter must be in range (0, 1). func (*Filters) Opacity(opacity any) gift.Filter { return filter{ Options: newFilterOpts(opacity), Filter: opacityFilter{opacity: cast.ToFloat32(opacity)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...any) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt maps.Params if len(options) > 0 { opt = maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) case "font": if err, ok := v.(error); ok { panic(fmt.Sprintf("invalid font source: %s", err)) } fontSource, ok1 := v.(hugio.ReadSeekCloserProvider) identifier, ok2 := v.(resource.Identifier) if !(ok1 && ok2) { panic(fmt.Sprintf("invalid text font source: %T", v)) } tf.fontSource = fontSource // The input value isn't hashable and will not make a stable key. // Replace it with a string in the map used as basis for the // hash string. opt["font"] = identifier.Key() } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma any) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma any) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift any) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size any) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor any) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals any } func newFilterOpts(vals ...any) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "fmt" "image/color" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct{} // Process creates a filter that processes an image using the given specification. func (*Filters) Process(spec any) gift.Filter { return filter{ Options: newFilterOpts(spec), Filter: processFilter{ spec: cast.ToString(spec), }, } } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Opacity creates a filter that changes the opacity of an image. // The opacity parameter must be in range (0, 1). func (*Filters) Opacity(opacity any) gift.Filter { return filter{ Options: newFilterOpts(opacity), Filter: opacityFilter{opacity: cast.ToFloat32(opacity)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...any) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt maps.Params if len(options) > 0 { opt = maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) case "font": if err, ok := v.(error); ok { panic(fmt.Sprintf("invalid font source: %s", err)) } fontSource, ok1 := v.(hugio.ReadSeekCloserProvider) identifier, ok2 := v.(resource.Identifier) if !(ok1 && ok2) { panic(fmt.Sprintf("invalid text font source: %T", v)) } tf.fontSource = fontSource // The input value isn't hashable and will not make a stable key. // Replace it with a string in the map used as basis for the // hash string. opt["font"] = identifier.Key() } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Padding creates a filter that resizes the image canvas without resizing the // image. The last argument is the canvas color, expressed as an RGB or RGBA // hexadecimal color. The default value is `ffffffff` (opaque white). The // preceding arguments are the padding values, in pixels, using the CSS // shorthand property syntax. Negative padding values will crop the image. The // signature is images.Padding V1 [V2] [V3] [V4] [COLOR]. func (*Filters) Padding(args ...any) gift.Filter { if len(args) < 1 || len(args) > 5 { panic("the padding filter requires between 1 and 5 arguments") } var top, right, bottom, left int var ccolor color.Color = color.White // canvas color var err error _args := args // preserve original args for most stable hash if vcs, ok := (args[len(args)-1]).(string); ok { ccolor, err = hexStringToColor(vcs) if err != nil { panic("invalid canvas color: specify RGB or RGBA using hex notation") } args = args[:len(args)-1] if len(args) == 0 { panic("not enough arguments: provide one or more padding values using the CSS shorthand property syntax") } } var vals []int for _, v := range args { vi := cast.ToInt(v) if vi > 5000 { panic("padding values must not exceed 5000 pixels") } vals = append(vals, vi) } switch len(args) { case 1: top, right, bottom, left = vals[0], vals[0], vals[0], vals[0] case 2: top, right, bottom, left = vals[0], vals[1], vals[0], vals[1] case 3: top, right, bottom, left = vals[0], vals[1], vals[2], vals[1] case 4: top, right, bottom, left = vals[0], vals[1], vals[2], vals[3] default: panic(fmt.Sprintf("too many padding values: received %d, expected maximum of 4", len(args))) } return filter{ Options: newFilterOpts(_args...), Filter: paddingFilter{ top: top, right: right, bottom: bottom, left: left, ccolor: ccolor, }, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma any) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma any) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift any) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size any) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor any) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals any } func newFilterOpts(vals ...any) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
jmooring
db14238ba323279b28e7ad4cfff5aa10909ccd18
3ed28e4bfe2d333fdf1ca2434b57cfc10c3d9791
I don't see a need to use reflect here, do a "Go type cast".
bep
9
gohugoio/hugo
11,621
resources/images: Create padding image filter
This addresses the primary use case described in https://github.com/gohugoio/hugo/issues/11599.
null
2023-10-28 17:24:03+00:00
2023-10-29 09:16:37+00:00
resources/images/filters.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 images provides template functions for manipulating images. package images import ( "fmt" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct{} func (*Filters) Process(spec any) gift.Filter { return filter{ Options: newFilterOpts(spec), Filter: processFilter{ spec: cast.ToString(spec), }, } } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Opacity creates a filter that changes the opacity of an image. // The opacity parameter must be in range (0, 1). func (*Filters) Opacity(opacity any) gift.Filter { return filter{ Options: newFilterOpts(opacity), Filter: opacityFilter{opacity: cast.ToFloat32(opacity)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...any) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt maps.Params if len(options) > 0 { opt = maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) case "font": if err, ok := v.(error); ok { panic(fmt.Sprintf("invalid font source: %s", err)) } fontSource, ok1 := v.(hugio.ReadSeekCloserProvider) identifier, ok2 := v.(resource.Identifier) if !(ok1 && ok2) { panic(fmt.Sprintf("invalid text font source: %T", v)) } tf.fontSource = fontSource // The input value isn't hashable and will not make a stable key. // Replace it with a string in the map used as basis for the // hash string. opt["font"] = identifier.Key() } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma any) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma any) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift any) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size any) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor any) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals any } func newFilterOpts(vals ...any) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
// 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 images provides template functions for manipulating images. package images import ( "fmt" "image/color" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources/resource" "github.com/disintegration/gift" "github.com/spf13/cast" ) // Increment for re-generation of images using these filters. const filterAPIVersion = 0 type Filters struct{} // Process creates a filter that processes an image using the given specification. func (*Filters) Process(spec any) gift.Filter { return filter{ Options: newFilterOpts(spec), Filter: processFilter{ spec: cast.ToString(spec), }, } } // Overlay creates a filter that overlays src at position x y. func (*Filters) Overlay(src ImageSource, x, y any) gift.Filter { return filter{ Options: newFilterOpts(src.Key(), x, y), Filter: overlayFilter{src: src, x: cast.ToInt(x), y: cast.ToInt(y)}, } } // Opacity creates a filter that changes the opacity of an image. // The opacity parameter must be in range (0, 1). func (*Filters) Opacity(opacity any) gift.Filter { return filter{ Options: newFilterOpts(opacity), Filter: opacityFilter{opacity: cast.ToFloat32(opacity)}, } } // Text creates a filter that draws text with the given options. func (*Filters) Text(text string, options ...any) gift.Filter { tf := textFilter{ text: text, color: "#ffffff", size: 20, x: 10, y: 10, linespacing: 2, } var opt maps.Params if len(options) > 0 { opt = maps.MustToParamsAndPrepare(options[0]) for option, v := range opt { switch option { case "color": tf.color = cast.ToString(v) case "size": tf.size = cast.ToFloat64(v) case "x": tf.x = cast.ToInt(v) case "y": tf.y = cast.ToInt(v) case "linespacing": tf.linespacing = cast.ToInt(v) case "font": if err, ok := v.(error); ok { panic(fmt.Sprintf("invalid font source: %s", err)) } fontSource, ok1 := v.(hugio.ReadSeekCloserProvider) identifier, ok2 := v.(resource.Identifier) if !(ok1 && ok2) { panic(fmt.Sprintf("invalid text font source: %T", v)) } tf.fontSource = fontSource // The input value isn't hashable and will not make a stable key. // Replace it with a string in the map used as basis for the // hash string. opt["font"] = identifier.Key() } } } return filter{ Options: newFilterOpts(text, opt), Filter: tf, } } // Padding creates a filter that resizes the image canvas without resizing the // image. The last argument is the canvas color, expressed as an RGB or RGBA // hexadecimal color. The default value is `ffffffff` (opaque white). The // preceding arguments are the padding values, in pixels, using the CSS // shorthand property syntax. Negative padding values will crop the image. The // signature is images.Padding V1 [V2] [V3] [V4] [COLOR]. func (*Filters) Padding(args ...any) gift.Filter { if len(args) < 1 || len(args) > 5 { panic("the padding filter requires between 1 and 5 arguments") } var top, right, bottom, left int var ccolor color.Color = color.White // canvas color var err error _args := args // preserve original args for most stable hash if vcs, ok := (args[len(args)-1]).(string); ok { ccolor, err = hexStringToColor(vcs) if err != nil { panic("invalid canvas color: specify RGB or RGBA using hex notation") } args = args[:len(args)-1] if len(args) == 0 { panic("not enough arguments: provide one or more padding values using the CSS shorthand property syntax") } } var vals []int for _, v := range args { vi := cast.ToInt(v) if vi > 5000 { panic("padding values must not exceed 5000 pixels") } vals = append(vals, vi) } switch len(args) { case 1: top, right, bottom, left = vals[0], vals[0], vals[0], vals[0] case 2: top, right, bottom, left = vals[0], vals[1], vals[0], vals[1] case 3: top, right, bottom, left = vals[0], vals[1], vals[2], vals[1] case 4: top, right, bottom, left = vals[0], vals[1], vals[2], vals[3] default: panic(fmt.Sprintf("too many padding values: received %d, expected maximum of 4", len(args))) } return filter{ Options: newFilterOpts(_args...), Filter: paddingFilter{ top: top, right: right, bottom: bottom, left: left, ccolor: ccolor, }, } } // Brightness creates a filter that changes the brightness of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Brightness(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Brightness(cast.ToFloat32(percentage)), } } // ColorBalance creates a filter that changes the color balance of an image. // The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500). func (*Filters) ColorBalance(percentageRed, percentageGreen, percentageBlue any) gift.Filter { return filter{ Options: newFilterOpts(percentageRed, percentageGreen, percentageBlue), Filter: gift.ColorBalance(cast.ToFloat32(percentageRed), cast.ToFloat32(percentageGreen), cast.ToFloat32(percentageBlue)), } } // Colorize creates a filter that produces a colorized version of an image. // The hue parameter is the angle on the color wheel, typically in range (0, 360). // The saturation parameter must be in range (0, 100). // The percentage parameter specifies the strength of the effect, it must be in range (0, 100). func (*Filters) Colorize(hue, saturation, percentage any) gift.Filter { return filter{ Options: newFilterOpts(hue, saturation, percentage), Filter: gift.Colorize(cast.ToFloat32(hue), cast.ToFloat32(saturation), cast.ToFloat32(percentage)), } } // Contrast creates a filter that changes the contrast of an image. // The percentage parameter must be in range (-100, 100). func (*Filters) Contrast(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Contrast(cast.ToFloat32(percentage)), } } // Gamma creates a filter that performs a gamma correction on an image. // The gamma parameter must be positive. Gamma = 1 gives the original image. // Gamma less than 1 darkens the image and gamma greater than 1 lightens it. func (*Filters) Gamma(gamma any) gift.Filter { return filter{ Options: newFilterOpts(gamma), Filter: gift.Gamma(cast.ToFloat32(gamma)), } } // GaussianBlur creates a filter that applies a gaussian blur to an image. func (*Filters) GaussianBlur(sigma any) gift.Filter { return filter{ Options: newFilterOpts(sigma), Filter: gift.GaussianBlur(cast.ToFloat32(sigma)), } } // Grayscale creates a filter that produces a grayscale version of an image. func (*Filters) Grayscale() gift.Filter { return filter{ Filter: gift.Grayscale(), } } // Hue creates a filter that rotates the hue of an image. // The hue angle shift is typically in range -180 to 180. func (*Filters) Hue(shift any) gift.Filter { return filter{ Options: newFilterOpts(shift), Filter: gift.Hue(cast.ToFloat32(shift)), } } // Invert creates a filter that negates the colors of an image. func (*Filters) Invert() gift.Filter { return filter{ Filter: gift.Invert(), } } // Pixelate creates a filter that applies a pixelation effect to an image. func (*Filters) Pixelate(size any) gift.Filter { return filter{ Options: newFilterOpts(size), Filter: gift.Pixelate(cast.ToInt(size)), } } // Saturation creates a filter that changes the saturation of an image. func (*Filters) Saturation(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Saturation(cast.ToFloat32(percentage)), } } // Sepia creates a filter that produces a sepia-toned version of an image. func (*Filters) Sepia(percentage any) gift.Filter { return filter{ Options: newFilterOpts(percentage), Filter: gift.Sepia(cast.ToFloat32(percentage)), } } // Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. // It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. func (*Filters) Sigmoid(midpoint, factor any) gift.Filter { return filter{ Options: newFilterOpts(midpoint, factor), Filter: gift.Sigmoid(cast.ToFloat32(midpoint), cast.ToFloat32(factor)), } } // UnsharpMask creates a filter that sharpens an image. // The sigma parameter is used in a gaussian function and affects the radius of effect. // Sigma must be positive. Sharpen radius roughly equals 3 * sigma. // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05. func (*Filters) UnsharpMask(sigma, amount, threshold any) gift.Filter { return filter{ Options: newFilterOpts(sigma, amount, threshold), Filter: gift.UnsharpMask(cast.ToFloat32(sigma), cast.ToFloat32(amount), cast.ToFloat32(threshold)), } } type filter struct { Options filterOpts gift.Filter } // For cache-busting. type filterOpts struct { Version int Vals any } func newFilterOpts(vals ...any) filterOpts { return filterOpts{ Version: filterAPIVersion, Vals: vals, } }
jmooring
db14238ba323279b28e7ad4cfff5aa10909ccd18
3ed28e4bfe2d333fdf1ca2434b57cfc10c3d9791
Just pass `args...` in here, which would make the most stable hash.
bep
10
gohugoio/hugo
11,609
Revise the deprecation logging
This introduces a more automatic way of increasing the log levels for deprecation log statements based on the version it was deprecated. The thresholds are a little arbitrary, but * We log INFO for 6 releases * We log WARN for another 6 releases * THen ERROR (failing the build) This should give theme authors plenty of time to catch up without having the log filled with warnings.
null
2023-10-26 08:44:43+00:00
2023-10-26 18:41:19+00:00
common/hugo/hugo.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 hugo import ( "fmt" "html/template" "os" "path/filepath" "runtime/debug" "sort" "strings" "sync" godartsassv1 "github.com/bep/godartsass" "github.com/mitchellh/mapstructure" "time" "github.com/bep/godartsass/v2" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/hugofs/files" "github.com/spf13/afero" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugofs" ) const ( EnvironmentDevelopment = "development" EnvironmentProduction = "production" ) var ( // buildDate allows vendor-specified build date when .git/ is unavailable. buildDate string // vendorInfo contains vendor notes about the current build. vendorInfo string ) // HugoInfo contains information about the current Hugo environment type HugoInfo struct { CommitHash string BuildDate string // The build environment. // Defaults are "production" (hugo) and "development" (hugo server). // This can also be set by the user. // It can be any string, but it will be all lower case. Environment string // version of go that the Hugo binary was built with GoVersion string conf ConfigProvider deps []*Dependency } // Version returns the current version as a comparable version string. func (i HugoInfo) Version() VersionString { return CurrentVersion.Version() } // Generator a Hugo meta generator HTML tag. func (i HugoInfo) Generator() template.HTML { return template.HTML(fmt.Sprintf(`<meta name="generator" content="Hugo %s">`, CurrentVersion.String())) } // IsDevelopment reports whether the current running environment is "development". func (i HugoInfo) IsDevelopment() bool { return i.Environment == EnvironmentDevelopment } // IsProduction reports whether the current running environment is "production". func (i HugoInfo) IsProduction() bool { return i.Environment == EnvironmentProduction } // IsServer reports whether the built-in server is running. func (i HugoInfo) IsServer() bool { return i.conf.Running() } // IsExtended reports whether the Hugo binary is the extended version. func (i HugoInfo) IsExtended() bool { return IsExtended } // WorkingDir returns the project working directory. func (i HugoInfo) WorkingDir() string { return i.conf.WorkingDir() } // Deps gets a list of dependencies for this Hugo build. func (i HugoInfo) Deps() []*Dependency { return i.deps } // ConfigProvider represents the config options that are relevant for HugoInfo. type ConfigProvider interface { Environment() string Running() bool WorkingDir() string } // NewInfo creates a new Hugo Info object. func NewInfo(conf ConfigProvider, deps []*Dependency) HugoInfo { if conf.Environment() == "" { panic("environment not set") } var ( commitHash string buildDate string goVersion string ) bi := getBuildInfo() if bi != nil { commitHash = bi.Revision buildDate = bi.RevisionTime goVersion = bi.GoVersion } return HugoInfo{ CommitHash: commitHash, BuildDate: buildDate, Environment: conf.Environment(), conf: conf, deps: deps, GoVersion: goVersion, } } // GetExecEnviron creates and gets the common os/exec environment used in the // external programs we interact with via os/exec, e.g. postcss. func GetExecEnviron(workDir string, cfg config.AllProvider, fs afero.Fs) []string { var env []string nodepath := filepath.Join(workDir, "node_modules") if np := os.Getenv("NODE_PATH"); np != "" { nodepath = workDir + string(os.PathListSeparator) + np } config.SetEnvVars(&env, "NODE_PATH", nodepath) config.SetEnvVars(&env, "PWD", workDir) config.SetEnvVars(&env, "HUGO_ENVIRONMENT", cfg.Environment()) config.SetEnvVars(&env, "HUGO_ENV", cfg.Environment()) config.SetEnvVars(&env, "HUGO_PUBLISHDIR", filepath.Join(workDir, cfg.BaseConfig().PublishDir)) if fs != nil { fis, err := afero.ReadDir(fs, files.FolderJSConfig) if err == nil { for _, fi := range fis { key := fmt.Sprintf("HUGO_FILE_%s", strings.ReplaceAll(strings.ToUpper(fi.Name()), ".", "_")) value := fi.(hugofs.FileMetaInfo).Meta().Filename config.SetEnvVars(&env, key, value) } } } return env } type buildInfo struct { VersionControlSystem string Revision string RevisionTime string Modified bool GoOS string GoArch string *debug.BuildInfo } var bInfo *buildInfo var bInfoInit sync.Once func getBuildInfo() *buildInfo { bInfoInit.Do(func() { bi, ok := debug.ReadBuildInfo() if !ok { return } bInfo = &buildInfo{BuildInfo: bi} for _, s := range bInfo.Settings { switch s.Key { case "vcs": bInfo.VersionControlSystem = s.Value case "vcs.revision": bInfo.Revision = s.Value case "vcs.time": bInfo.RevisionTime = s.Value case "vcs.modified": bInfo.Modified = s.Value == "true" case "GOOS": bInfo.GoOS = s.Value case "GOARCH": bInfo.GoArch = s.Value } } }) return bInfo } func formatDep(path, version string) string { return fmt.Sprintf("%s=%q", path, version) } // GetDependencyList returns a sorted dependency list on the format package="version". // It includes both Go dependencies and (a manually maintained) list of C(++) dependencies. func GetDependencyList() []string { var deps []string bi := getBuildInfo() if bi == nil { return deps } for _, dep := range bi.Deps { deps = append(deps, formatDep(dep.Path, dep.Version)) } deps = append(deps, GetDependencyListNonGo()...) sort.Strings(deps) return deps } // GetDependencyListNonGo returns a list of non-Go dependencies. func GetDependencyListNonGo() []string { var deps []string if IsExtended { deps = append( deps, formatDep("github.com/sass/libsass", "3.6.5"), formatDep("github.com/webmproject/libwebp", "v1.2.4"), ) } if dartSass := dartSassVersion(); dartSass.ProtocolVersion != "" { var dartSassPath = "github.com/sass/dart-sass-embedded" if IsDartSassV2() { dartSassPath = "github.com/sass/dart-sass" } deps = append(deps, formatDep(dartSassPath+"/protocol", dartSass.ProtocolVersion), formatDep(dartSassPath+"/compiler", dartSass.CompilerVersion), formatDep(dartSassPath+"/implementation", dartSass.ImplementationVersion), ) } return deps } // IsRunningAsTest reports whether we are running as a test. func IsRunningAsTest() bool { for _, arg := range os.Args { if strings.HasPrefix(arg, "-test") { return true } } return false } // Dependency is a single dependency, which can be either a Hugo Module or a local theme. type Dependency struct { // Returns the path to this module. // This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", // or the path below your /theme folder, e.g. "mytheme". Path string // The module version. Version string // Whether this dependency is vendored. Vendor bool // Time version was created. Time time.Time // In the dependency tree, this is the first module that defines this module // as a dependency. Owner *Dependency // Replaced by this dependency. Replace *Dependency } func dartSassVersion() godartsass.DartSassVersion { if DartSassBinaryName == "" { return godartsass.DartSassVersion{} } if IsDartSassV2() { v, _ := godartsass.Version(DartSassBinaryName) return v } v, _ := godartsassv1.Version(DartSassBinaryName) var vv godartsass.DartSassVersion mapstructure.WeakDecode(v, &vv) return vv } // DartSassBinaryName is the name of the Dart Sass binary to use. // TODO(beop) find a better place for this. var DartSassBinaryName string func init() { DartSassBinaryName = os.Getenv("DART_SASS_BINARY") if DartSassBinaryName == "" { for _, name := range dartSassBinaryNamesV2 { if hexec.InPath(name) { DartSassBinaryName = name break } } if DartSassBinaryName == "" { if hexec.InPath(dartSassBinaryNameV1) { DartSassBinaryName = dartSassBinaryNameV1 } } } } var ( dartSassBinaryNameV1 = "dart-sass-embedded" dartSassBinaryNamesV2 = []string{"dart-sass", "sass"} ) func IsDartSassV2() bool { return !strings.Contains(DartSassBinaryName, "embedded") }
// 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 hugo import ( "fmt" "html/template" "os" "path/filepath" "runtime/debug" "sort" "strings" "sync" "time" godartsassv1 "github.com/bep/godartsass" "github.com/bep/logg" "github.com/mitchellh/mapstructure" "github.com/bep/godartsass/v2" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/hugofs/files" "github.com/spf13/afero" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugofs" ) const ( EnvironmentDevelopment = "development" EnvironmentProduction = "production" ) var ( // buildDate allows vendor-specified build date when .git/ is unavailable. buildDate string // vendorInfo contains vendor notes about the current build. vendorInfo string ) // HugoInfo contains information about the current Hugo environment type HugoInfo struct { CommitHash string BuildDate string // The build environment. // Defaults are "production" (hugo) and "development" (hugo server). // This can also be set by the user. // It can be any string, but it will be all lower case. Environment string // version of go that the Hugo binary was built with GoVersion string conf ConfigProvider deps []*Dependency } // Version returns the current version as a comparable version string. func (i HugoInfo) Version() VersionString { return CurrentVersion.Version() } // Generator a Hugo meta generator HTML tag. func (i HugoInfo) Generator() template.HTML { return template.HTML(fmt.Sprintf(`<meta name="generator" content="Hugo %s">`, CurrentVersion.String())) } // IsDevelopment reports whether the current running environment is "development". func (i HugoInfo) IsDevelopment() bool { return i.Environment == EnvironmentDevelopment } // IsProduction reports whether the current running environment is "production". func (i HugoInfo) IsProduction() bool { return i.Environment == EnvironmentProduction } // IsServer reports whether the built-in server is running. func (i HugoInfo) IsServer() bool { return i.conf.Running() } // IsExtended reports whether the Hugo binary is the extended version. func (i HugoInfo) IsExtended() bool { return IsExtended } // WorkingDir returns the project working directory. func (i HugoInfo) WorkingDir() string { return i.conf.WorkingDir() } // Deps gets a list of dependencies for this Hugo build. func (i HugoInfo) Deps() []*Dependency { return i.deps } // ConfigProvider represents the config options that are relevant for HugoInfo. type ConfigProvider interface { Environment() string Running() bool WorkingDir() string } // NewInfo creates a new Hugo Info object. func NewInfo(conf ConfigProvider, deps []*Dependency) HugoInfo { if conf.Environment() == "" { panic("environment not set") } var ( commitHash string buildDate string goVersion string ) bi := getBuildInfo() if bi != nil { commitHash = bi.Revision buildDate = bi.RevisionTime goVersion = bi.GoVersion } return HugoInfo{ CommitHash: commitHash, BuildDate: buildDate, Environment: conf.Environment(), conf: conf, deps: deps, GoVersion: goVersion, } } // GetExecEnviron creates and gets the common os/exec environment used in the // external programs we interact with via os/exec, e.g. postcss. func GetExecEnviron(workDir string, cfg config.AllProvider, fs afero.Fs) []string { var env []string nodepath := filepath.Join(workDir, "node_modules") if np := os.Getenv("NODE_PATH"); np != "" { nodepath = workDir + string(os.PathListSeparator) + np } config.SetEnvVars(&env, "NODE_PATH", nodepath) config.SetEnvVars(&env, "PWD", workDir) config.SetEnvVars(&env, "HUGO_ENVIRONMENT", cfg.Environment()) config.SetEnvVars(&env, "HUGO_ENV", cfg.Environment()) config.SetEnvVars(&env, "HUGO_PUBLISHDIR", filepath.Join(workDir, cfg.BaseConfig().PublishDir)) if fs != nil { fis, err := afero.ReadDir(fs, files.FolderJSConfig) if err == nil { for _, fi := range fis { key := fmt.Sprintf("HUGO_FILE_%s", strings.ReplaceAll(strings.ToUpper(fi.Name()), ".", "_")) value := fi.(hugofs.FileMetaInfo).Meta().Filename config.SetEnvVars(&env, key, value) } } } return env } type buildInfo struct { VersionControlSystem string Revision string RevisionTime string Modified bool GoOS string GoArch string *debug.BuildInfo } var ( bInfo *buildInfo bInfoInit sync.Once ) func getBuildInfo() *buildInfo { bInfoInit.Do(func() { bi, ok := debug.ReadBuildInfo() if !ok { return } bInfo = &buildInfo{BuildInfo: bi} for _, s := range bInfo.Settings { switch s.Key { case "vcs": bInfo.VersionControlSystem = s.Value case "vcs.revision": bInfo.Revision = s.Value case "vcs.time": bInfo.RevisionTime = s.Value case "vcs.modified": bInfo.Modified = s.Value == "true" case "GOOS": bInfo.GoOS = s.Value case "GOARCH": bInfo.GoArch = s.Value } } }) return bInfo } func formatDep(path, version string) string { return fmt.Sprintf("%s=%q", path, version) } // GetDependencyList returns a sorted dependency list on the format package="version". // It includes both Go dependencies and (a manually maintained) list of C(++) dependencies. func GetDependencyList() []string { var deps []string bi := getBuildInfo() if bi == nil { return deps } for _, dep := range bi.Deps { deps = append(deps, formatDep(dep.Path, dep.Version)) } deps = append(deps, GetDependencyListNonGo()...) sort.Strings(deps) return deps } // GetDependencyListNonGo returns a list of non-Go dependencies. func GetDependencyListNonGo() []string { var deps []string if IsExtended { deps = append( deps, formatDep("github.com/sass/libsass", "3.6.5"), formatDep("github.com/webmproject/libwebp", "v1.2.4"), ) } if dartSass := dartSassVersion(); dartSass.ProtocolVersion != "" { dartSassPath := "github.com/sass/dart-sass-embedded" if IsDartSassV2() { dartSassPath = "github.com/sass/dart-sass" } deps = append(deps, formatDep(dartSassPath+"/protocol", dartSass.ProtocolVersion), formatDep(dartSassPath+"/compiler", dartSass.CompilerVersion), formatDep(dartSassPath+"/implementation", dartSass.ImplementationVersion), ) } return deps } // IsRunningAsTest reports whether we are running as a test. func IsRunningAsTest() bool { for _, arg := range os.Args { if strings.HasPrefix(arg, "-test") { return true } } return false } // Dependency is a single dependency, which can be either a Hugo Module or a local theme. type Dependency struct { // Returns the path to this module. // This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", // or the path below your /theme folder, e.g. "mytheme". Path string // The module version. Version string // Whether this dependency is vendored. Vendor bool // Time version was created. Time time.Time // In the dependency tree, this is the first module that defines this module // as a dependency. Owner *Dependency // Replaced by this dependency. Replace *Dependency } func dartSassVersion() godartsass.DartSassVersion { if DartSassBinaryName == "" { return godartsass.DartSassVersion{} } if IsDartSassV2() { v, _ := godartsass.Version(DartSassBinaryName) return v } v, _ := godartsassv1.Version(DartSassBinaryName) var vv godartsass.DartSassVersion mapstructure.WeakDecode(v, &vv) return vv } // DartSassBinaryName is the name of the Dart Sass binary to use. // TODO(beop) find a better place for this. var DartSassBinaryName string func init() { DartSassBinaryName = os.Getenv("DART_SASS_BINARY") if DartSassBinaryName == "" { for _, name := range dartSassBinaryNamesV2 { if hexec.InPath(name) { DartSassBinaryName = name break } } if DartSassBinaryName == "" { if hexec.InPath(dartSassBinaryNameV1) { DartSassBinaryName = dartSassBinaryNameV1 } } } } var ( dartSassBinaryNameV1 = "dart-sass-embedded" dartSassBinaryNamesV2 = []string{"dart-sass", "sass"} ) func IsDartSassV2() bool { return !strings.Contains(DartSassBinaryName, "embedded") } // Deprecate informs about a deprecation starting at the given version. // // A deprecation typically needs a simple change in the template, but doing so will make the template incompatible with older versions. // Theme maintainers generally want // 1. No warnings or errors in the console when building a Hugo site. // 2. Their theme to work for at least the last few Hugo versions. func Deprecate(item, alternative string, version string) { level := deprecationLogLevelFromVersion(version) DeprecateLevel(item, alternative, version, level) } // DeprecateLevel informs about a deprecation logging at the given level. func DeprecateLevel(item, alternative, version string, level logg.Level) { var msg string if level == logg.LevelError { msg = fmt.Sprintf("%s was deprecated in Hugo %s and will be removed in Hugo %s. %s", item, version, CurrentVersion.Next().ReleaseVersion(), alternative) } else { msg = fmt.Sprintf("%s was deprecated in Hugo %s and will be removed in a future release. %s", item, version, alternative) } loggers.Log().Logger().WithLevel(level).Logf(msg) } // We ususally do about one minor version a month. // We want people to run at least the current and previous version without any warnings. // We want people who don't update Hugo that often to see the warnings and errors before we remove the feature. func deprecationLogLevelFromVersion(ver string) logg.Level { from := MustParseVersion(ver) to := CurrentVersion minorDiff := to.Minor - from.Minor switch { case minorDiff >= 12: // Start failing the build after about a year. return logg.LevelError case minorDiff >= 6: // Start printing warnings after about six months. return logg.LevelWarn default: return logg.LevelInfo } }
bep
c4a530f104f2b0d1dd82211b77b603a07db7c181
71fd79a3f44101ef515349a24527e6c0b566f368
```suggestion msg = fmt.Sprintf("%s was deprecated in Hugo %s and will be removed in Hugo %s. %s", item, version, CurrentVersion.Next().ReleaseVersion(), alternative) ```
jmooring
11
gohugoio/hugo
11,609
Revise the deprecation logging
This introduces a more automatic way of increasing the log levels for deprecation log statements based on the version it was deprecated. The thresholds are a little arbitrary, but * We log INFO for 6 releases * We log WARN for another 6 releases * THen ERROR (failing the build) This should give theme authors plenty of time to catch up without having the log filled with warnings.
null
2023-10-26 08:44:43+00:00
2023-10-26 18:41:19+00:00
common/hugo/hugo.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 hugo import ( "fmt" "html/template" "os" "path/filepath" "runtime/debug" "sort" "strings" "sync" godartsassv1 "github.com/bep/godartsass" "github.com/mitchellh/mapstructure" "time" "github.com/bep/godartsass/v2" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/hugofs/files" "github.com/spf13/afero" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugofs" ) const ( EnvironmentDevelopment = "development" EnvironmentProduction = "production" ) var ( // buildDate allows vendor-specified build date when .git/ is unavailable. buildDate string // vendorInfo contains vendor notes about the current build. vendorInfo string ) // HugoInfo contains information about the current Hugo environment type HugoInfo struct { CommitHash string BuildDate string // The build environment. // Defaults are "production" (hugo) and "development" (hugo server). // This can also be set by the user. // It can be any string, but it will be all lower case. Environment string // version of go that the Hugo binary was built with GoVersion string conf ConfigProvider deps []*Dependency } // Version returns the current version as a comparable version string. func (i HugoInfo) Version() VersionString { return CurrentVersion.Version() } // Generator a Hugo meta generator HTML tag. func (i HugoInfo) Generator() template.HTML { return template.HTML(fmt.Sprintf(`<meta name="generator" content="Hugo %s">`, CurrentVersion.String())) } // IsDevelopment reports whether the current running environment is "development". func (i HugoInfo) IsDevelopment() bool { return i.Environment == EnvironmentDevelopment } // IsProduction reports whether the current running environment is "production". func (i HugoInfo) IsProduction() bool { return i.Environment == EnvironmentProduction } // IsServer reports whether the built-in server is running. func (i HugoInfo) IsServer() bool { return i.conf.Running() } // IsExtended reports whether the Hugo binary is the extended version. func (i HugoInfo) IsExtended() bool { return IsExtended } // WorkingDir returns the project working directory. func (i HugoInfo) WorkingDir() string { return i.conf.WorkingDir() } // Deps gets a list of dependencies for this Hugo build. func (i HugoInfo) Deps() []*Dependency { return i.deps } // ConfigProvider represents the config options that are relevant for HugoInfo. type ConfigProvider interface { Environment() string Running() bool WorkingDir() string } // NewInfo creates a new Hugo Info object. func NewInfo(conf ConfigProvider, deps []*Dependency) HugoInfo { if conf.Environment() == "" { panic("environment not set") } var ( commitHash string buildDate string goVersion string ) bi := getBuildInfo() if bi != nil { commitHash = bi.Revision buildDate = bi.RevisionTime goVersion = bi.GoVersion } return HugoInfo{ CommitHash: commitHash, BuildDate: buildDate, Environment: conf.Environment(), conf: conf, deps: deps, GoVersion: goVersion, } } // GetExecEnviron creates and gets the common os/exec environment used in the // external programs we interact with via os/exec, e.g. postcss. func GetExecEnviron(workDir string, cfg config.AllProvider, fs afero.Fs) []string { var env []string nodepath := filepath.Join(workDir, "node_modules") if np := os.Getenv("NODE_PATH"); np != "" { nodepath = workDir + string(os.PathListSeparator) + np } config.SetEnvVars(&env, "NODE_PATH", nodepath) config.SetEnvVars(&env, "PWD", workDir) config.SetEnvVars(&env, "HUGO_ENVIRONMENT", cfg.Environment()) config.SetEnvVars(&env, "HUGO_ENV", cfg.Environment()) config.SetEnvVars(&env, "HUGO_PUBLISHDIR", filepath.Join(workDir, cfg.BaseConfig().PublishDir)) if fs != nil { fis, err := afero.ReadDir(fs, files.FolderJSConfig) if err == nil { for _, fi := range fis { key := fmt.Sprintf("HUGO_FILE_%s", strings.ReplaceAll(strings.ToUpper(fi.Name()), ".", "_")) value := fi.(hugofs.FileMetaInfo).Meta().Filename config.SetEnvVars(&env, key, value) } } } return env } type buildInfo struct { VersionControlSystem string Revision string RevisionTime string Modified bool GoOS string GoArch string *debug.BuildInfo } var bInfo *buildInfo var bInfoInit sync.Once func getBuildInfo() *buildInfo { bInfoInit.Do(func() { bi, ok := debug.ReadBuildInfo() if !ok { return } bInfo = &buildInfo{BuildInfo: bi} for _, s := range bInfo.Settings { switch s.Key { case "vcs": bInfo.VersionControlSystem = s.Value case "vcs.revision": bInfo.Revision = s.Value case "vcs.time": bInfo.RevisionTime = s.Value case "vcs.modified": bInfo.Modified = s.Value == "true" case "GOOS": bInfo.GoOS = s.Value case "GOARCH": bInfo.GoArch = s.Value } } }) return bInfo } func formatDep(path, version string) string { return fmt.Sprintf("%s=%q", path, version) } // GetDependencyList returns a sorted dependency list on the format package="version". // It includes both Go dependencies and (a manually maintained) list of C(++) dependencies. func GetDependencyList() []string { var deps []string bi := getBuildInfo() if bi == nil { return deps } for _, dep := range bi.Deps { deps = append(deps, formatDep(dep.Path, dep.Version)) } deps = append(deps, GetDependencyListNonGo()...) sort.Strings(deps) return deps } // GetDependencyListNonGo returns a list of non-Go dependencies. func GetDependencyListNonGo() []string { var deps []string if IsExtended { deps = append( deps, formatDep("github.com/sass/libsass", "3.6.5"), formatDep("github.com/webmproject/libwebp", "v1.2.4"), ) } if dartSass := dartSassVersion(); dartSass.ProtocolVersion != "" { var dartSassPath = "github.com/sass/dart-sass-embedded" if IsDartSassV2() { dartSassPath = "github.com/sass/dart-sass" } deps = append(deps, formatDep(dartSassPath+"/protocol", dartSass.ProtocolVersion), formatDep(dartSassPath+"/compiler", dartSass.CompilerVersion), formatDep(dartSassPath+"/implementation", dartSass.ImplementationVersion), ) } return deps } // IsRunningAsTest reports whether we are running as a test. func IsRunningAsTest() bool { for _, arg := range os.Args { if strings.HasPrefix(arg, "-test") { return true } } return false } // Dependency is a single dependency, which can be either a Hugo Module or a local theme. type Dependency struct { // Returns the path to this module. // This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", // or the path below your /theme folder, e.g. "mytheme". Path string // The module version. Version string // Whether this dependency is vendored. Vendor bool // Time version was created. Time time.Time // In the dependency tree, this is the first module that defines this module // as a dependency. Owner *Dependency // Replaced by this dependency. Replace *Dependency } func dartSassVersion() godartsass.DartSassVersion { if DartSassBinaryName == "" { return godartsass.DartSassVersion{} } if IsDartSassV2() { v, _ := godartsass.Version(DartSassBinaryName) return v } v, _ := godartsassv1.Version(DartSassBinaryName) var vv godartsass.DartSassVersion mapstructure.WeakDecode(v, &vv) return vv } // DartSassBinaryName is the name of the Dart Sass binary to use. // TODO(beop) find a better place for this. var DartSassBinaryName string func init() { DartSassBinaryName = os.Getenv("DART_SASS_BINARY") if DartSassBinaryName == "" { for _, name := range dartSassBinaryNamesV2 { if hexec.InPath(name) { DartSassBinaryName = name break } } if DartSassBinaryName == "" { if hexec.InPath(dartSassBinaryNameV1) { DartSassBinaryName = dartSassBinaryNameV1 } } } } var ( dartSassBinaryNameV1 = "dart-sass-embedded" dartSassBinaryNamesV2 = []string{"dart-sass", "sass"} ) func IsDartSassV2() bool { return !strings.Contains(DartSassBinaryName, "embedded") }
// 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 hugo import ( "fmt" "html/template" "os" "path/filepath" "runtime/debug" "sort" "strings" "sync" "time" godartsassv1 "github.com/bep/godartsass" "github.com/bep/logg" "github.com/mitchellh/mapstructure" "github.com/bep/godartsass/v2" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/hugofs/files" "github.com/spf13/afero" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/hugofs" ) const ( EnvironmentDevelopment = "development" EnvironmentProduction = "production" ) var ( // buildDate allows vendor-specified build date when .git/ is unavailable. buildDate string // vendorInfo contains vendor notes about the current build. vendorInfo string ) // HugoInfo contains information about the current Hugo environment type HugoInfo struct { CommitHash string BuildDate string // The build environment. // Defaults are "production" (hugo) and "development" (hugo server). // This can also be set by the user. // It can be any string, but it will be all lower case. Environment string // version of go that the Hugo binary was built with GoVersion string conf ConfigProvider deps []*Dependency } // Version returns the current version as a comparable version string. func (i HugoInfo) Version() VersionString { return CurrentVersion.Version() } // Generator a Hugo meta generator HTML tag. func (i HugoInfo) Generator() template.HTML { return template.HTML(fmt.Sprintf(`<meta name="generator" content="Hugo %s">`, CurrentVersion.String())) } // IsDevelopment reports whether the current running environment is "development". func (i HugoInfo) IsDevelopment() bool { return i.Environment == EnvironmentDevelopment } // IsProduction reports whether the current running environment is "production". func (i HugoInfo) IsProduction() bool { return i.Environment == EnvironmentProduction } // IsServer reports whether the built-in server is running. func (i HugoInfo) IsServer() bool { return i.conf.Running() } // IsExtended reports whether the Hugo binary is the extended version. func (i HugoInfo) IsExtended() bool { return IsExtended } // WorkingDir returns the project working directory. func (i HugoInfo) WorkingDir() string { return i.conf.WorkingDir() } // Deps gets a list of dependencies for this Hugo build. func (i HugoInfo) Deps() []*Dependency { return i.deps } // ConfigProvider represents the config options that are relevant for HugoInfo. type ConfigProvider interface { Environment() string Running() bool WorkingDir() string } // NewInfo creates a new Hugo Info object. func NewInfo(conf ConfigProvider, deps []*Dependency) HugoInfo { if conf.Environment() == "" { panic("environment not set") } var ( commitHash string buildDate string goVersion string ) bi := getBuildInfo() if bi != nil { commitHash = bi.Revision buildDate = bi.RevisionTime goVersion = bi.GoVersion } return HugoInfo{ CommitHash: commitHash, BuildDate: buildDate, Environment: conf.Environment(), conf: conf, deps: deps, GoVersion: goVersion, } } // GetExecEnviron creates and gets the common os/exec environment used in the // external programs we interact with via os/exec, e.g. postcss. func GetExecEnviron(workDir string, cfg config.AllProvider, fs afero.Fs) []string { var env []string nodepath := filepath.Join(workDir, "node_modules") if np := os.Getenv("NODE_PATH"); np != "" { nodepath = workDir + string(os.PathListSeparator) + np } config.SetEnvVars(&env, "NODE_PATH", nodepath) config.SetEnvVars(&env, "PWD", workDir) config.SetEnvVars(&env, "HUGO_ENVIRONMENT", cfg.Environment()) config.SetEnvVars(&env, "HUGO_ENV", cfg.Environment()) config.SetEnvVars(&env, "HUGO_PUBLISHDIR", filepath.Join(workDir, cfg.BaseConfig().PublishDir)) if fs != nil { fis, err := afero.ReadDir(fs, files.FolderJSConfig) if err == nil { for _, fi := range fis { key := fmt.Sprintf("HUGO_FILE_%s", strings.ReplaceAll(strings.ToUpper(fi.Name()), ".", "_")) value := fi.(hugofs.FileMetaInfo).Meta().Filename config.SetEnvVars(&env, key, value) } } } return env } type buildInfo struct { VersionControlSystem string Revision string RevisionTime string Modified bool GoOS string GoArch string *debug.BuildInfo } var ( bInfo *buildInfo bInfoInit sync.Once ) func getBuildInfo() *buildInfo { bInfoInit.Do(func() { bi, ok := debug.ReadBuildInfo() if !ok { return } bInfo = &buildInfo{BuildInfo: bi} for _, s := range bInfo.Settings { switch s.Key { case "vcs": bInfo.VersionControlSystem = s.Value case "vcs.revision": bInfo.Revision = s.Value case "vcs.time": bInfo.RevisionTime = s.Value case "vcs.modified": bInfo.Modified = s.Value == "true" case "GOOS": bInfo.GoOS = s.Value case "GOARCH": bInfo.GoArch = s.Value } } }) return bInfo } func formatDep(path, version string) string { return fmt.Sprintf("%s=%q", path, version) } // GetDependencyList returns a sorted dependency list on the format package="version". // It includes both Go dependencies and (a manually maintained) list of C(++) dependencies. func GetDependencyList() []string { var deps []string bi := getBuildInfo() if bi == nil { return deps } for _, dep := range bi.Deps { deps = append(deps, formatDep(dep.Path, dep.Version)) } deps = append(deps, GetDependencyListNonGo()...) sort.Strings(deps) return deps } // GetDependencyListNonGo returns a list of non-Go dependencies. func GetDependencyListNonGo() []string { var deps []string if IsExtended { deps = append( deps, formatDep("github.com/sass/libsass", "3.6.5"), formatDep("github.com/webmproject/libwebp", "v1.2.4"), ) } if dartSass := dartSassVersion(); dartSass.ProtocolVersion != "" { dartSassPath := "github.com/sass/dart-sass-embedded" if IsDartSassV2() { dartSassPath = "github.com/sass/dart-sass" } deps = append(deps, formatDep(dartSassPath+"/protocol", dartSass.ProtocolVersion), formatDep(dartSassPath+"/compiler", dartSass.CompilerVersion), formatDep(dartSassPath+"/implementation", dartSass.ImplementationVersion), ) } return deps } // IsRunningAsTest reports whether we are running as a test. func IsRunningAsTest() bool { for _, arg := range os.Args { if strings.HasPrefix(arg, "-test") { return true } } return false } // Dependency is a single dependency, which can be either a Hugo Module or a local theme. type Dependency struct { // Returns the path to this module. // This will either be the module path, e.g. "github.com/gohugoio/myshortcodes", // or the path below your /theme folder, e.g. "mytheme". Path string // The module version. Version string // Whether this dependency is vendored. Vendor bool // Time version was created. Time time.Time // In the dependency tree, this is the first module that defines this module // as a dependency. Owner *Dependency // Replaced by this dependency. Replace *Dependency } func dartSassVersion() godartsass.DartSassVersion { if DartSassBinaryName == "" { return godartsass.DartSassVersion{} } if IsDartSassV2() { v, _ := godartsass.Version(DartSassBinaryName) return v } v, _ := godartsassv1.Version(DartSassBinaryName) var vv godartsass.DartSassVersion mapstructure.WeakDecode(v, &vv) return vv } // DartSassBinaryName is the name of the Dart Sass binary to use. // TODO(beop) find a better place for this. var DartSassBinaryName string func init() { DartSassBinaryName = os.Getenv("DART_SASS_BINARY") if DartSassBinaryName == "" { for _, name := range dartSassBinaryNamesV2 { if hexec.InPath(name) { DartSassBinaryName = name break } } if DartSassBinaryName == "" { if hexec.InPath(dartSassBinaryNameV1) { DartSassBinaryName = dartSassBinaryNameV1 } } } } var ( dartSassBinaryNameV1 = "dart-sass-embedded" dartSassBinaryNamesV2 = []string{"dart-sass", "sass"} ) func IsDartSassV2() bool { return !strings.Contains(DartSassBinaryName, "embedded") } // Deprecate informs about a deprecation starting at the given version. // // A deprecation typically needs a simple change in the template, but doing so will make the template incompatible with older versions. // Theme maintainers generally want // 1. No warnings or errors in the console when building a Hugo site. // 2. Their theme to work for at least the last few Hugo versions. func Deprecate(item, alternative string, version string) { level := deprecationLogLevelFromVersion(version) DeprecateLevel(item, alternative, version, level) } // DeprecateLevel informs about a deprecation logging at the given level. func DeprecateLevel(item, alternative, version string, level logg.Level) { var msg string if level == logg.LevelError { msg = fmt.Sprintf("%s was deprecated in Hugo %s and will be removed in Hugo %s. %s", item, version, CurrentVersion.Next().ReleaseVersion(), alternative) } else { msg = fmt.Sprintf("%s was deprecated in Hugo %s and will be removed in a future release. %s", item, version, alternative) } loggers.Log().Logger().WithLevel(level).Logf(msg) } // We ususally do about one minor version a month. // We want people to run at least the current and previous version without any warnings. // We want people who don't update Hugo that often to see the warnings and errors before we remove the feature. func deprecationLogLevelFromVersion(ver string) logg.Level { from := MustParseVersion(ver) to := CurrentVersion minorDiff := to.Minor - from.Minor switch { case minorDiff >= 12: // Start failing the build after about a year. return logg.LevelError case minorDiff >= 6: // Start printing warnings after about six months. return logg.LevelWarn default: return logg.LevelInfo } }
bep
c4a530f104f2b0d1dd82211b77b603a07db7c181
71fd79a3f44101ef515349a24527e6c0b566f368
```suggestion msg = fmt.Sprintf("%s was deprecated in Hugo %s and will be removed a future release. %s", item, version, alternative) ```
jmooring
12
gohugoio/hugo
11,593
markdown: Pass emoji codes to yuin/goldmark-emoji
Fixes #7332 Fixes #11587
null
2023-10-22 16:27:19+00:00
2023-10-24 10:04:13+00:00
markup/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 := ` -- config.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/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.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/_default/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.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/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, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { filesTemplate := ` -- config.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/_default/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, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } b.Run("Default", func(b *testing.B) { runBenchmark(filesTemplate, b) }) b.Run("Hook no higlight", func(b *testing.B) { files := filesTemplate + ` -- layouts/_default/_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 := ` -- config.toml -- -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | RENDERFUNC }}</a> -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- https://example.org [email protected] ` 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 := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.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/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</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 := ` -- config.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/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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>", ) }
// 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 := ` -- config.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/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} {{- range $k, $v := .Attributes -}} {{- printf " %s=%q" $k $v | safeHTMLAttr -}} {{- end -}} >{{ .Text | safeHTML }}</h{{ .Level }}> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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/_default/_markup/render-heading.html -- plain: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v }}|{{ end }}| safeHTML: |{{- range $k, $v := .Attributes -}}{{ $k }}: {{ $v | safeHTML }}|{{ end }}| -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Hello [Test](https://example.com) -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "<h2 id=\"hello-testhttpsexamplecom\">\n Hello <a href=\"https://example.com\">Test</a>\n\n <a class=\"anchor\" href=\"#hello-testhttpsexamplecom\">#</a>\n</h2>", ) } func TestHighlight(t *testing.T) { t.Parallel() files := ` -- config.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/_default/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.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-heading.html -- <h{{ .Level }} id="{{ .Anchor | safeURL }}"> {{ .Text | safeHTML }} <a class="anchor" href="#{{ .Anchor | safeURL }}">#</a> </h{{ .Level }}> -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a> -- layouts/_default/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, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func BenchmarkCodeblocks(b *testing.B) { filesTemplate := ` -- config.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/_default/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, } builders := make([]*hugolib.IntegrationTestBuilder, b.N) for i := range builders { builders[i] = hugolib.NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } b.Run("Default", func(b *testing.B) { runBenchmark(filesTemplate, b) }) b.Run("Hook no higlight", func(b *testing.B) { files := filesTemplate + ` -- layouts/_default/_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 := ` -- config.toml -- -- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | RENDERFUNC }}</a> -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- https://example.org [email protected] ` 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 := ` -- config.toml -- [markup.goldmark.extensions] typographer = false -- content/p1.md -- --- title: "p1" --- !["a"](b.jpg) -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.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/_default/single.html -- {{ .Content }} ` files = strings.ReplaceAll(files, "PROTOCOL", protocol) if withHook { files += `-- layouts/_default/_markup/render-link.html -- <a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</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 := ` -- config.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/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 #7332 // Issue #11587 func TestGoldmarkEmojiExtension(t *testing.T) { t.Parallel() files := ` -- config.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/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.toml -- enableEmoji = false -- content/p1.md -- --- title: "p1" --- :x: -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContentExact("public/p1/index.html", "<p>:x:</p>") } func TestEmojiDefaultConfig(t *testing.T) { t.Parallel() files := ` -- content/p1.md -- --- title: "p1" --- :x: -- layouts/_default/single.html -- {{ .Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContentExact("public/p1/index.html", "<p>:x:</p>") }
jmooring
de4e466036026e9a5805155f00882b93267231b5
272484f8bfab97dbadad49a638a3e4b6af499f15
A tip: I found that I repeated the above construct so often, so I added 2 convenience funcs named `Test` and `TestRunning` which you could rewrite the above to: ```go b := hugolib.Test(t, files) ```
bep
13
gohugoio/hugo
11,578
livereloadinject: Use more robust injection method
This PR addresses all the concerns I raised in issue https://github.com/gohugoio/hugo/issues/11562 and then some. It changes the behavior of the livereloadinject transformer to read the HTML document from the start, consuming any comments and whitespace as well as the doctype, html start tag and head start tag in that order, stopping the moment another tag or text content is encountered, and injecting the livereload script there. Compared to the current code, it specifically: - Allows mixed casing in tag names. - Always injects at the start of the head even when tags are omitted, meaning the browser can download the script faster. - Always attempts to inject, and never with a warning. Browsers already warn the user if the HTML is malformed. - Requires whitespace before attributes, so `<header>` or `<head-foo>` are no longer mistaken for the head start tag. - Explicitly skips `<!--comments-->` that may contain tags. Also treats `<?xml instructions ?>` as comments. - Won't attempt to scan the document further if any other element or text is encountered. This should improve performance on pages without a head start tag, and prevent bugs due to scans inside `<title>`, `<script>` and `<template>` elements, or elements whose attribute values might contain `<` or `>`. This is a different approach compared to PR https://github.com/gohugoio/hugo/pull/11565 where I would search the whole document for each potential insertion point, which left some of the bugs unresolved.
null
2023-10-18 21:27:38+00:00
2023-10-29 17:37:05+00:00
transform/livereloadinject/livereloadinject.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 livereloadinject import ( "fmt" "html" "net/url" "regexp" "strings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/transform" ) var ignoredSyntax = regexp.MustCompile(`(?s)^(?:\s+|<!--.*?-->|<\?.*?\?>)*`) var tagsBeforeHead = []*regexp.Regexp{ regexp.MustCompile(`(?is)^<!doctype\s[^>]*>`), regexp.MustCompile(`(?is)^<html(?:\s[^>]*)?>`), regexp.MustCompile(`(?is)^<head(?:\s[^>]*)?>`), } // New creates a function that can be used to inject a script tag for // the livereload JavaScript at the start of an HTML document's head. func New(baseURL url.URL) transform.Transformer { return func(ft transform.FromTo) error { b := ft.From().Bytes() // We find the start of the head by reading past (in order) // the doctype declaration, HTML start tag and head start tag, // all of which are optional, and any whitespace, comments, or // XML instructions in-between. idx := 0 for _, tag := range tagsBeforeHead { idx += len(ignoredSyntax.Find(b[idx:])) idx += len(tag.Find(b[idx:])) } path := strings.TrimSuffix(baseURL.Path, "/") src := path + "/livereload.js?mindelay=10&v=2" src += "&port=" + baseURL.Port() src += "&path=" + strings.TrimPrefix(path+"/livereload", "/") c := make([]byte, len(b)) copy(c, b) script := []byte(fmt.Sprintf(`<script src="%s" data-no-instant defer></script>`, html.EscapeString(src))) c = append(c[:idx], append(script, c[idx:]...)...) if _, err := ft.To().Write(c); err != nil { loggers.Log().Warnf("Failed to inject LiveReload script:", err) } return nil } }
// 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 livereloadinject import ( "fmt" "html" "net/url" "regexp" "strings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/transform" ) var ( ignoredSyntax = regexp.MustCompile(`(?s)^(?:\s+|<!--.*?-->|<\?.*?\?>)*`) tagsBeforeHead = []*regexp.Regexp{ regexp.MustCompile(`(?is)^<!doctype\s[^>]*>`), regexp.MustCompile(`(?is)^<html(?:\s[^>]*)?>`), regexp.MustCompile(`(?is)^<head(?:\s[^>]*)?>`), } ) // New creates a function that can be used to inject a script tag for // the livereload JavaScript at the start of an HTML document's head. func New(baseURL url.URL) transform.Transformer { return func(ft transform.FromTo) error { b := ft.From().Bytes() // We find the start of the head by reading past (in order) // the doctype declaration, HTML start tag and head start tag, // all of which are optional, and any whitespace, comments, or // XML instructions in-between. idx := 0 for _, tag := range tagsBeforeHead { idx += len(ignoredSyntax.Find(b[idx:])) idx += len(tag.Find(b[idx:])) } path := strings.TrimSuffix(baseURL.Path, "/") src := path + "/livereload.js?mindelay=10&v=2" src += "&port=" + baseURL.Port() src += "&path=" + strings.TrimPrefix(path+"/livereload", "/") script := []byte(fmt.Sprintf(`<script src="%s" data-no-instant defer></script>`, html.EscapeString(src))) c := make([]byte, len(b)+len(script)) copy(c, b[:idx]) copy(c[idx:], script) copy(c[idx+len(script):], b[idx:]) if _, err := ft.To().Write(c); err != nil { loggers.Log().Warnf("Failed to inject LiveReload script:", err) } return nil } }
DominoPivot
9dc608084b73f04c146351cbe8d1b2f41058e8ba
8f60c0c1ec11c3c47ed7e3eff121ba1f1976f755
I didn't write those lines, but isn't this pointless? From my (limited) understanding of Go: - `make` wasn't passed a capacity, so future calls to `append(c, ...)` will need to reallocate - `copy` was given the entirety of `b` even though we're about to append to `c[:idx]`, overwriting most of it My intuition would be to write this lower in the function instead: c := make([]byte, idx, len(b)+len(script)) copy(c, b) Or alternatively: c := make([]byte, 0, len(b)+len(script)) c = append(c, b[:idx]...)
DominoPivot
14
gohugoio/hugo
11,578
livereloadinject: Use more robust injection method
This PR addresses all the concerns I raised in issue https://github.com/gohugoio/hugo/issues/11562 and then some. It changes the behavior of the livereloadinject transformer to read the HTML document from the start, consuming any comments and whitespace as well as the doctype, html start tag and head start tag in that order, stopping the moment another tag or text content is encountered, and injecting the livereload script there. Compared to the current code, it specifically: - Allows mixed casing in tag names. - Always injects at the start of the head even when tags are omitted, meaning the browser can download the script faster. - Always attempts to inject, and never with a warning. Browsers already warn the user if the HTML is malformed. - Requires whitespace before attributes, so `<header>` or `<head-foo>` are no longer mistaken for the head start tag. - Explicitly skips `<!--comments-->` that may contain tags. Also treats `<?xml instructions ?>` as comments. - Won't attempt to scan the document further if any other element or text is encountered. This should improve performance on pages without a head start tag, and prevent bugs due to scans inside `<title>`, `<script>` and `<template>` elements, or elements whose attribute values might contain `<` or `>`. This is a different approach compared to PR https://github.com/gohugoio/hugo/pull/11565 where I would search the whole document for each potential insertion point, which left some of the bugs unresolved.
null
2023-10-18 21:27:38+00:00
2023-10-29 17:37:05+00:00
transform/livereloadinject/livereloadinject.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 livereloadinject import ( "fmt" "html" "net/url" "regexp" "strings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/transform" ) var ignoredSyntax = regexp.MustCompile(`(?s)^(?:\s+|<!--.*?-->|<\?.*?\?>)*`) var tagsBeforeHead = []*regexp.Regexp{ regexp.MustCompile(`(?is)^<!doctype\s[^>]*>`), regexp.MustCompile(`(?is)^<html(?:\s[^>]*)?>`), regexp.MustCompile(`(?is)^<head(?:\s[^>]*)?>`), } // New creates a function that can be used to inject a script tag for // the livereload JavaScript at the start of an HTML document's head. func New(baseURL url.URL) transform.Transformer { return func(ft transform.FromTo) error { b := ft.From().Bytes() // We find the start of the head by reading past (in order) // the doctype declaration, HTML start tag and head start tag, // all of which are optional, and any whitespace, comments, or // XML instructions in-between. idx := 0 for _, tag := range tagsBeforeHead { idx += len(ignoredSyntax.Find(b[idx:])) idx += len(tag.Find(b[idx:])) } path := strings.TrimSuffix(baseURL.Path, "/") src := path + "/livereload.js?mindelay=10&v=2" src += "&port=" + baseURL.Port() src += "&path=" + strings.TrimPrefix(path+"/livereload", "/") c := make([]byte, len(b)) copy(c, b) script := []byte(fmt.Sprintf(`<script src="%s" data-no-instant defer></script>`, html.EscapeString(src))) c = append(c[:idx], append(script, c[idx:]...)...) if _, err := ft.To().Write(c); err != nil { loggers.Log().Warnf("Failed to inject LiveReload script:", err) } return nil } }
// 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 livereloadinject import ( "fmt" "html" "net/url" "regexp" "strings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/transform" ) var ( ignoredSyntax = regexp.MustCompile(`(?s)^(?:\s+|<!--.*?-->|<\?.*?\?>)*`) tagsBeforeHead = []*regexp.Regexp{ regexp.MustCompile(`(?is)^<!doctype\s[^>]*>`), regexp.MustCompile(`(?is)^<html(?:\s[^>]*)?>`), regexp.MustCompile(`(?is)^<head(?:\s[^>]*)?>`), } ) // New creates a function that can be used to inject a script tag for // the livereload JavaScript at the start of an HTML document's head. func New(baseURL url.URL) transform.Transformer { return func(ft transform.FromTo) error { b := ft.From().Bytes() // We find the start of the head by reading past (in order) // the doctype declaration, HTML start tag and head start tag, // all of which are optional, and any whitespace, comments, or // XML instructions in-between. idx := 0 for _, tag := range tagsBeforeHead { idx += len(ignoredSyntax.Find(b[idx:])) idx += len(tag.Find(b[idx:])) } path := strings.TrimSuffix(baseURL.Path, "/") src := path + "/livereload.js?mindelay=10&v=2" src += "&port=" + baseURL.Port() src += "&path=" + strings.TrimPrefix(path+"/livereload", "/") script := []byte(fmt.Sprintf(`<script src="%s" data-no-instant defer></script>`, html.EscapeString(src))) c := make([]byte, len(b)+len(script)) copy(c, b[:idx]) copy(c[idx:], script) copy(c[idx+len(script):], b[idx:]) if _, err := ft.To().Write(c); err != nil { loggers.Log().Warnf("Failed to inject LiveReload script:", err) } return nil } }
DominoPivot
9dc608084b73f04c146351cbe8d1b2f41058e8ba
8f60c0c1ec11c3c47ed7e3eff121ba1f1976f755
And again here, doesn't `append(script, c[i:]...)` cause another unnecessary reallocation? Wouldn't it be better to do: c := make([]byte, 0, len(b)+len(script)) c = append(c, b[:idx]...) c = append(c, script...) c = append(c, b[idx:]...)
DominoPivot
15
gohugoio/hugo
11,578
livereloadinject: Use more robust injection method
This PR addresses all the concerns I raised in issue https://github.com/gohugoio/hugo/issues/11562 and then some. It changes the behavior of the livereloadinject transformer to read the HTML document from the start, consuming any comments and whitespace as well as the doctype, html start tag and head start tag in that order, stopping the moment another tag or text content is encountered, and injecting the livereload script there. Compared to the current code, it specifically: - Allows mixed casing in tag names. - Always injects at the start of the head even when tags are omitted, meaning the browser can download the script faster. - Always attempts to inject, and never with a warning. Browsers already warn the user if the HTML is malformed. - Requires whitespace before attributes, so `<header>` or `<head-foo>` are no longer mistaken for the head start tag. - Explicitly skips `<!--comments-->` that may contain tags. Also treats `<?xml instructions ?>` as comments. - Won't attempt to scan the document further if any other element or text is encountered. This should improve performance on pages without a head start tag, and prevent bugs due to scans inside `<title>`, `<script>` and `<template>` elements, or elements whose attribute values might contain `<` or `>`. This is a different approach compared to PR https://github.com/gohugoio/hugo/pull/11565 where I would search the whole document for each potential insertion point, which left some of the bugs unresolved.
null
2023-10-18 21:27:38+00:00
2023-10-29 17:37:05+00:00
transform/livereloadinject/livereloadinject.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 livereloadinject import ( "fmt" "html" "net/url" "regexp" "strings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/transform" ) var ignoredSyntax = regexp.MustCompile(`(?s)^(?:\s+|<!--.*?-->|<\?.*?\?>)*`) var tagsBeforeHead = []*regexp.Regexp{ regexp.MustCompile(`(?is)^<!doctype\s[^>]*>`), regexp.MustCompile(`(?is)^<html(?:\s[^>]*)?>`), regexp.MustCompile(`(?is)^<head(?:\s[^>]*)?>`), } // New creates a function that can be used to inject a script tag for // the livereload JavaScript at the start of an HTML document's head. func New(baseURL url.URL) transform.Transformer { return func(ft transform.FromTo) error { b := ft.From().Bytes() // We find the start of the head by reading past (in order) // the doctype declaration, HTML start tag and head start tag, // all of which are optional, and any whitespace, comments, or // XML instructions in-between. idx := 0 for _, tag := range tagsBeforeHead { idx += len(ignoredSyntax.Find(b[idx:])) idx += len(tag.Find(b[idx:])) } path := strings.TrimSuffix(baseURL.Path, "/") src := path + "/livereload.js?mindelay=10&v=2" src += "&port=" + baseURL.Port() src += "&path=" + strings.TrimPrefix(path+"/livereload", "/") c := make([]byte, len(b)) copy(c, b) script := []byte(fmt.Sprintf(`<script src="%s" data-no-instant defer></script>`, html.EscapeString(src))) c = append(c[:idx], append(script, c[idx:]...)...) if _, err := ft.To().Write(c); err != nil { loggers.Log().Warnf("Failed to inject LiveReload script:", err) } return nil } }
// 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 livereloadinject import ( "fmt" "html" "net/url" "regexp" "strings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/transform" ) var ( ignoredSyntax = regexp.MustCompile(`(?s)^(?:\s+|<!--.*?-->|<\?.*?\?>)*`) tagsBeforeHead = []*regexp.Regexp{ regexp.MustCompile(`(?is)^<!doctype\s[^>]*>`), regexp.MustCompile(`(?is)^<html(?:\s[^>]*)?>`), regexp.MustCompile(`(?is)^<head(?:\s[^>]*)?>`), } ) // New creates a function that can be used to inject a script tag for // the livereload JavaScript at the start of an HTML document's head. func New(baseURL url.URL) transform.Transformer { return func(ft transform.FromTo) error { b := ft.From().Bytes() // We find the start of the head by reading past (in order) // the doctype declaration, HTML start tag and head start tag, // all of which are optional, and any whitespace, comments, or // XML instructions in-between. idx := 0 for _, tag := range tagsBeforeHead { idx += len(ignoredSyntax.Find(b[idx:])) idx += len(tag.Find(b[idx:])) } path := strings.TrimSuffix(baseURL.Path, "/") src := path + "/livereload.js?mindelay=10&v=2" src += "&port=" + baseURL.Port() src += "&path=" + strings.TrimPrefix(path+"/livereload", "/") script := []byte(fmt.Sprintf(`<script src="%s" data-no-instant defer></script>`, html.EscapeString(src))) c := make([]byte, len(b)+len(script)) copy(c, b[:idx]) copy(c[idx:], script) copy(c[idx+len(script):], b[idx:]) if _, err := ft.To().Write(c); err != nil { loggers.Log().Warnf("Failed to inject LiveReload script:", err) } return nil } }
DominoPivot
9dc608084b73f04c146351cbe8d1b2f41058e8ba
8f60c0c1ec11c3c47ed7e3eff121ba1f1976f755
You are right, this would be better: ```go c := make([]byte, idx, len(b)+len(script)) copy(c, b) ```
bep
16
gohugoio/hugo
11,578
livereloadinject: Use more robust injection method
This PR addresses all the concerns I raised in issue https://github.com/gohugoio/hugo/issues/11562 and then some. It changes the behavior of the livereloadinject transformer to read the HTML document from the start, consuming any comments and whitespace as well as the doctype, html start tag and head start tag in that order, stopping the moment another tag or text content is encountered, and injecting the livereload script there. Compared to the current code, it specifically: - Allows mixed casing in tag names. - Always injects at the start of the head even when tags are omitted, meaning the browser can download the script faster. - Always attempts to inject, and never with a warning. Browsers already warn the user if the HTML is malformed. - Requires whitespace before attributes, so `<header>` or `<head-foo>` are no longer mistaken for the head start tag. - Explicitly skips `<!--comments-->` that may contain tags. Also treats `<?xml instructions ?>` as comments. - Won't attempt to scan the document further if any other element or text is encountered. This should improve performance on pages without a head start tag, and prevent bugs due to scans inside `<title>`, `<script>` and `<template>` elements, or elements whose attribute values might contain `<` or `>`. This is a different approach compared to PR https://github.com/gohugoio/hugo/pull/11565 where I would search the whole document for each potential insertion point, which left some of the bugs unresolved.
null
2023-10-18 21:27:38+00:00
2023-10-29 17:37:05+00:00
transform/livereloadinject/livereloadinject.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 livereloadinject import ( "fmt" "html" "net/url" "regexp" "strings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/transform" ) var ignoredSyntax = regexp.MustCompile(`(?s)^(?:\s+|<!--.*?-->|<\?.*?\?>)*`) var tagsBeforeHead = []*regexp.Regexp{ regexp.MustCompile(`(?is)^<!doctype\s[^>]*>`), regexp.MustCompile(`(?is)^<html(?:\s[^>]*)?>`), regexp.MustCompile(`(?is)^<head(?:\s[^>]*)?>`), } // New creates a function that can be used to inject a script tag for // the livereload JavaScript at the start of an HTML document's head. func New(baseURL url.URL) transform.Transformer { return func(ft transform.FromTo) error { b := ft.From().Bytes() // We find the start of the head by reading past (in order) // the doctype declaration, HTML start tag and head start tag, // all of which are optional, and any whitespace, comments, or // XML instructions in-between. idx := 0 for _, tag := range tagsBeforeHead { idx += len(ignoredSyntax.Find(b[idx:])) idx += len(tag.Find(b[idx:])) } path := strings.TrimSuffix(baseURL.Path, "/") src := path + "/livereload.js?mindelay=10&v=2" src += "&port=" + baseURL.Port() src += "&path=" + strings.TrimPrefix(path+"/livereload", "/") c := make([]byte, len(b)) copy(c, b) script := []byte(fmt.Sprintf(`<script src="%s" data-no-instant defer></script>`, html.EscapeString(src))) c = append(c[:idx], append(script, c[idx:]...)...) if _, err := ft.To().Write(c); err != nil { loggers.Log().Warnf("Failed to inject LiveReload script:", err) } return nil } }
// 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 livereloadinject import ( "fmt" "html" "net/url" "regexp" "strings" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/transform" ) var ( ignoredSyntax = regexp.MustCompile(`(?s)^(?:\s+|<!--.*?-->|<\?.*?\?>)*`) tagsBeforeHead = []*regexp.Regexp{ regexp.MustCompile(`(?is)^<!doctype\s[^>]*>`), regexp.MustCompile(`(?is)^<html(?:\s[^>]*)?>`), regexp.MustCompile(`(?is)^<head(?:\s[^>]*)?>`), } ) // New creates a function that can be used to inject a script tag for // the livereload JavaScript at the start of an HTML document's head. func New(baseURL url.URL) transform.Transformer { return func(ft transform.FromTo) error { b := ft.From().Bytes() // We find the start of the head by reading past (in order) // the doctype declaration, HTML start tag and head start tag, // all of which are optional, and any whitespace, comments, or // XML instructions in-between. idx := 0 for _, tag := range tagsBeforeHead { idx += len(ignoredSyntax.Find(b[idx:])) idx += len(tag.Find(b[idx:])) } path := strings.TrimSuffix(baseURL.Path, "/") src := path + "/livereload.js?mindelay=10&v=2" src += "&port=" + baseURL.Port() src += "&path=" + strings.TrimPrefix(path+"/livereload", "/") script := []byte(fmt.Sprintf(`<script src="%s" data-no-instant defer></script>`, html.EscapeString(src))) c := make([]byte, len(b)+len(script)) copy(c, b[:idx]) copy(c[idx:], script) copy(c[idx+len(script):], b[idx:]) if _, err := ft.To().Write(c); err != nil { loggers.Log().Warnf("Failed to inject LiveReload script:", err) } return nil } }
DominoPivot
9dc608084b73f04c146351cbe8d1b2f41058e8ba
8f60c0c1ec11c3c47ed7e3eff121ba1f1976f755
From my quick glance, I don't think you're right here, but it would be trivial to write a quick benchmark.
bep
17
gohugoio/hugo
11,442
Print language code after web server address info
With dozens of different languages, it is nice to see which port maps to which language in local development.
null
2023-09-10 17:11:46+00:00
2023-09-11 09:38:24+00:00
commands/server.go
// Copyright 2023 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 commands import ( "bytes" "context" "crypto/tls" "crypto/x509" "encoding/json" "encoding/pem" "errors" "fmt" "io" "net" "net/http" "net/url" "os" "sync" "sync/atomic" "github.com/bep/mclib" "os/signal" "path" "path/filepath" "regexp" "strconv" "strings" "syscall" "time" "github.com/bep/debounce" "github.com/bep/simplecobra" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/common/urls" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/livereload" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/transform" "github.com/gohugoio/hugo/transform/livereloadinject" "github.com/spf13/afero" "github.com/spf13/cobra" "github.com/spf13/fsync" "golang.org/x/sync/errgroup" "golang.org/x/sync/semaphore" ) var ( logDuplicateTemplateExecuteRe = regexp.MustCompile(`: template: .*?:\d+:\d+: executing ".*?"`) logDuplicateTemplateParseRe = regexp.MustCompile(`: template: .*?:\d+:\d*`) ) var logReplacer = strings.NewReplacer( "can't", "can’t", // Chroma lexer doesn't do well with "can't" "*hugolib.pageState", "page.Page", // Page is the public interface. "Rebuild failed:", "", ) const ( configChangeConfig = "config file" configChangeGoMod = "go.mod file" configChangeGoWork = "go work file" ) func newHugoBuilder(r *rootCommand, s *serverCommand, onConfigLoaded ...func(reloaded bool) error) *hugoBuilder { return &hugoBuilder{ r: r, s: s, visitedURLs: types.NewEvictingStringQueue(100), fullRebuildSem: semaphore.NewWeighted(1), debounce: debounce.New(4 * time.Second), onConfigLoaded: func(reloaded bool) error { for _, wc := range onConfigLoaded { if err := wc(reloaded); err != nil { return err } } return nil }, } } func newServerCommand() *serverCommand { // Flags. var uninstall bool c := &serverCommand{ quit: make(chan bool), commands: []simplecobra.Commander{ &simpleCommand{ name: "trust", short: "Install the local CA in the system trust store.", run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { action := "-install" if uninstall { action = "-uninstall" } os.Args = []string{action} return mclib.RunMain() }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVar(&uninstall, "uninstall", false, "Uninstall the local CA (but do not delete it).") }, }, }, } return c } func (c *serverCommand) Commands() []simplecobra.Commander { return c.commands } type countingStatFs struct { afero.Fs statCounter uint64 } func (fs *countingStatFs) Stat(name string) (os.FileInfo, error) { f, err := fs.Fs.Stat(name) if err == nil { if !f.IsDir() { atomic.AddUint64(&fs.statCounter, 1) } } return f, err } // dynamicEvents contains events that is considered dynamic, as in "not static". // Both of these categories will trigger a new build, but the asset events // does not fit into the "navigate to changed" logic. type dynamicEvents struct { ContentEvents []fsnotify.Event AssetEvents []fsnotify.Event } type fileChangeDetector struct { sync.Mutex current map[string]string prev map[string]string irrelevantRe *regexp.Regexp } func (f *fileChangeDetector) OnFileClose(name, md5sum string) { f.Lock() defer f.Unlock() f.current[name] = md5sum } func (f *fileChangeDetector) PrepareNew() { if f == nil { return } f.Lock() defer f.Unlock() if f.current == nil { f.current = make(map[string]string) f.prev = make(map[string]string) return } f.prev = make(map[string]string) for k, v := range f.current { f.prev[k] = v } f.current = make(map[string]string) } func (f *fileChangeDetector) changed() []string { if f == nil { return nil } f.Lock() defer f.Unlock() var c []string for k, v := range f.current { vv, found := f.prev[k] if !found || v != vv { c = append(c, k) } } return f.filterIrrelevant(c) } func (f *fileChangeDetector) filterIrrelevant(in []string) []string { var filtered []string for _, v := range in { if !f.irrelevantRe.MatchString(v) { filtered = append(filtered, v) } } return filtered } type fileServer struct { baseURLs []string roots []string errorTemplate func(err any) (io.Reader, error) c *serverCommand } func (f *fileServer) createEndpoint(i int) (*http.ServeMux, net.Listener, string, string, error) { r := f.c.r baseURL := f.baseURLs[i] root := f.roots[i] port := f.c.serverPorts[i].p listener := f.c.serverPorts[i].ln logger := f.c.r.logger r.Printf("Environment: %q\n", f.c.hugoTry().Deps.Site.Hugo().Environment) if i == 0 { if f.c.renderToDisk { r.Println("Serving pages from disk") } else if f.c.renderStaticToDisk { r.Println("Serving pages from memory and static files from disk") } else { r.Println("Serving pages from memory") } } var httpFs *afero.HttpFs f.c.withConf(func(conf *commonConfig) { httpFs = afero.NewHttpFs(conf.fs.PublishDirServer) }) fs := filesOnlyFs{httpFs.Dir(path.Join("/", root))} if i == 0 && f.c.fastRenderMode { r.Println("Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender") } // We're only interested in the path u, err := url.Parse(baseURL) if err != nil { return nil, nil, "", "", fmt.Errorf("invalid baseURL: %w", err) } decorate := func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if f.c.showErrorInBrowser { // First check the error state err := f.c.getErrorWithContext() if err != nil { f.c.errState.setWasErr(true) w.WriteHeader(500) r, err := f.errorTemplate(err) if err != nil { logger.Errorln(err) } port = 1313 f.c.withConf(func(conf *commonConfig) { if lrport := conf.configs.GetFirstLanguageConfig().BaseURLLiveReload().Port(); lrport != 0 { port = lrport } }) lr := *u lr.Host = fmt.Sprintf("%s:%d", lr.Hostname(), port) fmt.Fprint(w, injectLiveReloadScript(r, lr)) return } } if f.c.noHTTPCache { w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0") w.Header().Set("Pragma", "no-cache") } var serverConfig config.Server f.c.withConf(func(conf *commonConfig) { serverConfig = conf.configs.Base.Server }) // Ignore any query params for the operations below. requestURI, _ := url.PathUnescape(strings.TrimSuffix(r.RequestURI, "?"+r.URL.RawQuery)) for _, header := range serverConfig.MatchHeaders(requestURI) { w.Header().Set(header.Key, header.Value) } if redirect := serverConfig.MatchRedirect(requestURI); !redirect.IsZero() { // fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))) doRedirect := true // This matches Netlify's behaviour and is needed for SPA behaviour. // See https://docs.netlify.com/routing/redirects/rewrites-proxies/ if !redirect.Force { path := filepath.Clean(strings.TrimPrefix(requestURI, u.Path)) if root != "" { path = filepath.Join(root, path) } var fs afero.Fs f.c.withConf(func(conf *commonConfig) { fs = conf.fs.PublishDirServer }) fi, err := fs.Stat(path) if err == nil { if fi.IsDir() { // There will be overlapping directories, so we // need to check for a file. _, err = fs.Stat(filepath.Join(path, "index.html")) doRedirect = err != nil } else { doRedirect = false } } } if doRedirect { switch redirect.Status { case 404: w.WriteHeader(404) file, err := fs.Open(strings.TrimPrefix(redirect.To, u.Path)) if err == nil { defer file.Close() io.Copy(w, file) } else { fmt.Fprintln(w, "<h1>Page Not Found</h1>") } return case 200: if r2 := f.rewriteRequest(r, strings.TrimPrefix(redirect.To, u.Path)); r2 != nil { requestURI = redirect.To r = r2 } default: w.Header().Set("Content-Type", "") http.Redirect(w, r, redirect.To, redirect.Status) return } } } if f.c.fastRenderMode && f.c.errState.buildErr() == nil { if strings.HasSuffix(requestURI, "/") || strings.HasSuffix(requestURI, "html") || strings.HasSuffix(requestURI, "htm") { if !f.c.visitedURLs.Contains(requestURI) { // If not already on stack, re-render that single page. if err := f.c.partialReRender(requestURI); err != nil { f.c.handleBuildErr(err, fmt.Sprintf("Failed to render %q", requestURI)) if f.c.showErrorInBrowser { http.Redirect(w, r, requestURI, http.StatusMovedPermanently) return } } } f.c.visitedURLs.Add(requestURI) } } h.ServeHTTP(w, r) }) } fileserver := decorate(http.FileServer(fs)) mu := http.NewServeMux() if u.Path == "" || u.Path == "/" { mu.Handle("/", fileserver) } else { mu.Handle(u.Path, http.StripPrefix(u.Path, fileserver)) } if r.IsTestRun() { var shutDownOnce sync.Once mu.HandleFunc("/__stop", func(w http.ResponseWriter, r *http.Request) { shutDownOnce.Do(func() { close(f.c.quit) }) }) } endpoint := net.JoinHostPort(f.c.serverInterface, strconv.Itoa(port)) return mu, listener, u.String(), endpoint, nil } func (f *fileServer) rewriteRequest(r *http.Request, toPath string) *http.Request { r2 := new(http.Request) *r2 = *r r2.URL = new(url.URL) *r2.URL = *r.URL r2.URL.Path = toPath r2.Header.Set("X-Rewrite-Original-URI", r.URL.RequestURI()) return r2 } type filesOnlyFs struct { fs http.FileSystem } func (fs filesOnlyFs) Open(name string) (http.File, error) { f, err := fs.fs.Open(name) if err != nil { return nil, err } return noDirFile{f}, nil } type noDirFile struct { http.File } func (f noDirFile) Readdir(count int) ([]os.FileInfo, error) { return nil, nil } type serverCommand struct { r *rootCommand commands []simplecobra.Commander *hugoBuilder quit chan bool // Closed when the server should shut down. Used in tests only. serverPorts []serverPortListener doLiveReload bool // Flags. renderToDisk bool renderStaticToDisk bool navigateToChanged bool serverAppend bool serverInterface string tlsCertFile string tlsKeyFile string tlsAuto bool serverPort int liveReloadPort int serverWatch bool noHTTPCache bool disableLiveReload bool disableFastRender bool disableBrowserError bool } func (c *serverCommand) Name() string { return "server" } func (c *serverCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { // Watch runs its own server as part of the routine if c.serverWatch { watchDirs, err := c.getDirList() if err != nil { return err } watchGroups := helpers.ExtractAndGroupRootPaths(watchDirs) for _, group := range watchGroups { c.r.Printf("Watching for changes in %s\n", group) } watcher, err := c.newWatcher(c.r.poll, watchDirs...) if err != nil { return err } defer watcher.Close() } err := func() error { defer c.r.timeTrack(time.Now(), "Built") err := c.build() return err }() if err != nil { return err } return c.serve() } func (c *serverCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "A high performance webserver" cmd.Long = `Hugo provides its own webserver which builds and serves the site. While hugo server is high performance, it is a webserver with limited options. 'hugo server' will avoid writing the rendered and served content to disk, preferring to store it in memory. By default hugo will also watch your files for any changes you make and automatically rebuild the site. It will then live reload any open browser pages and push the latest content to them. As most Hugo sites are built in a fraction of a second, you will be able to save and see your changes nearly instantly.` cmd.Aliases = []string{"serve"} cmd.Flags().IntVarP(&c.serverPort, "port", "p", 1313, "port on which the server will listen") cmd.Flags().IntVar(&c.liveReloadPort, "liveReloadPort", -1, "port for live reloading (i.e. 443 in HTTPS proxy situations)") cmd.Flags().StringVarP(&c.serverInterface, "bind", "", "127.0.0.1", "interface to which the server will bind") cmd.Flags().StringVarP(&c.tlsCertFile, "tlsCertFile", "", "", "path to TLS certificate file") cmd.Flags().StringVarP(&c.tlsKeyFile, "tlsKeyFile", "", "", "path to TLS key file") cmd.Flags().BoolVar(&c.tlsAuto, "tlsAuto", false, "generate and use locally-trusted certificates.") cmd.Flags().BoolVarP(&c.serverWatch, "watch", "w", true, "watch filesystem for changes and recreate as needed") cmd.Flags().BoolVar(&c.noHTTPCache, "noHTTPCache", false, "prevent HTTP caching") cmd.Flags().BoolVarP(&c.serverAppend, "appendPort", "", true, "append port to baseURL") cmd.Flags().BoolVar(&c.disableLiveReload, "disableLiveReload", false, "watch without enabling live browser reload on rebuild") cmd.Flags().BoolVar(&c.navigateToChanged, "navigateToChanged", false, "navigate to changed content file on live browser reload") cmd.Flags().BoolVar(&c.renderToDisk, "renderToDisk", false, "serve all files from disk (default is from memory)") cmd.Flags().BoolVar(&c.renderStaticToDisk, "renderStaticToDisk", false, "serve static files from disk and dynamic files from memory") cmd.Flags().BoolVar(&c.disableFastRender, "disableFastRender", false, "enables full re-renders on changes") cmd.Flags().BoolVar(&c.disableBrowserError, "disableBrowserError", false, "do not show build errors in the browser") cmd.Flags().String("memstats", "", "log memory usage to this file") cmd.Flags().String("meminterval", "100ms", "interval to poll memory usage (requires --memstats), valid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\".") cmd.Flags().SetAnnotation("tlsCertFile", cobra.BashCompSubdirsInDir, []string{}) cmd.Flags().SetAnnotation("tlsKeyFile", cobra.BashCompSubdirsInDir, []string{}) r := cd.Root.Command.(*rootCommand) applyLocalFlagsBuild(cmd, r) return nil } func (c *serverCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.r = cd.Root.Command.(*rootCommand) c.hugoBuilder = newHugoBuilder( c.r, c, func(reloaded bool) error { if !reloaded { if err := c.createServerPorts(cd); err != nil { return err } if (c.tlsCertFile == "" || c.tlsKeyFile == "") && c.tlsAuto { c.withConfE(func(conf *commonConfig) error { return c.createCertificates(conf) }) } } if err := c.setBaseURLsInConfig(); err != nil { return err } if !reloaded && c.fastRenderMode { c.withConf(func(conf *commonConfig) { conf.fs.PublishDir = hugofs.NewHashingFs(conf.fs.PublishDir, c.changeDetector) conf.fs.PublishDirStatic = hugofs.NewHashingFs(conf.fs.PublishDirStatic, c.changeDetector) }) } return nil }, ) destinationFlag := cd.CobraCommand.Flags().Lookup("destination") c.renderToDisk = c.renderToDisk || (destinationFlag != nil && destinationFlag.Changed) c.doLiveReload = !c.disableLiveReload c.fastRenderMode = !c.disableFastRender c.showErrorInBrowser = c.doLiveReload && !c.disableBrowserError if c.fastRenderMode { // For now, fast render mode only. It should, however, be fast enough // for the full variant, too. c.changeDetector = &fileChangeDetector{ // We use this detector to decide to do a Hot reload of a single path or not. // We need to filter out source maps and possibly some other to be able // to make that decision. irrelevantRe: regexp.MustCompile(`\.map$`), } c.changeDetector.PrepareNew() } err := c.loadConfig(cd, true) if err != nil { return err } return nil } func (c *serverCommand) setBaseURLsInConfig() error { if len(c.serverPorts) == 0 { panic("no server ports set") } return c.withConfE(func(conf *commonConfig) error { for i, language := range conf.configs.Languages { isMultiHost := conf.configs.IsMultihost var serverPort int if isMultiHost { serverPort = c.serverPorts[i].p } else { serverPort = c.serverPorts[0].p } langConfig := conf.configs.LanguageConfigMap[language.Lang] baseURLStr, err := c.fixURL(langConfig.BaseURL, c.r.baseURL, serverPort) if err != nil { return err } baseURL, err := urls.NewBaseURLFromString(baseURLStr) if err != nil { return fmt.Errorf("failed to create baseURL from %q: %s", baseURLStr, err) } baseURLLiveReload := baseURL if c.liveReloadPort != -1 { baseURLLiveReload, _ = baseURLLiveReload.WithPort(c.liveReloadPort) } langConfig.C.SetBaseURL(baseURL, baseURLLiveReload) } return nil }) } func (c *serverCommand) getErrorWithContext() any { errCount := c.errCount() if errCount == 0 { return nil } m := make(map[string]any) m["Error"] = cleanErrorLog(c.r.logger.Errors()) m["Version"] = hugo.BuildVersionString() ferrors := herrors.UnwrapFileErrorsWithErrorContext(c.errState.buildErr()) m["Files"] = ferrors return m } func (c *serverCommand) createCertificates(conf *commonConfig) error { hostname := "localhost" if c.r.baseURL != "" { u, err := url.Parse(c.r.baseURL) if err != nil { return err } hostname = u.Hostname() } // For now, store these in the Hugo cache dir. // Hugo should probably introduce some concept of a less temporary application directory. keyDir := filepath.Join(conf.configs.LoadingInfo.BaseConfig.CacheDir, "_mkcerts") // Create the directory if it doesn't exist. if _, err := os.Stat(keyDir); os.IsNotExist(err) { if err := os.MkdirAll(keyDir, 0777); err != nil { return err } } c.tlsCertFile = filepath.Join(keyDir, fmt.Sprintf("%s.pem", hostname)) c.tlsKeyFile = filepath.Join(keyDir, fmt.Sprintf("%s-key.pem", hostname)) // Check if the certificate already exists and is valid. certPEM, err := os.ReadFile(c.tlsCertFile) if err == nil { rootPem, err := os.ReadFile(filepath.Join(mclib.GetCAROOT(), "rootCA.pem")) if err == nil { if err := c.verifyCert(rootPem, certPEM, hostname); err == nil { c.r.Println("Using existing", c.tlsCertFile, "and", c.tlsKeyFile) return nil } } } c.r.Println("Creating TLS certificates in", keyDir) // Yes, this is unfortunate, but it's currently the only way to use Mkcert as a library. os.Args = []string{"-cert-file", c.tlsCertFile, "-key-file", c.tlsKeyFile, hostname} return mclib.RunMain() } func (c *serverCommand) verifyCert(rootPEM, certPEM []byte, name string) error { roots := x509.NewCertPool() ok := roots.AppendCertsFromPEM(rootPEM) if !ok { return fmt.Errorf("failed to parse root certificate") } block, _ := pem.Decode(certPEM) if block == nil { return fmt.Errorf("failed to parse certificate PEM") } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return fmt.Errorf("failed to parse certificate: %v", err.Error()) } opts := x509.VerifyOptions{ DNSName: name, Roots: roots, } if _, err := cert.Verify(opts); err != nil { return fmt.Errorf("failed to verify certificate: %v", err.Error()) } return nil } func (c *serverCommand) createServerPorts(cd *simplecobra.Commandeer) error { flags := cd.CobraCommand.Flags() var cerr error c.withConf(func(conf *commonConfig) { isMultiHost := conf.configs.IsMultihost c.serverPorts = make([]serverPortListener, 1) if isMultiHost { if !c.serverAppend { cerr = errors.New("--appendPort=false not supported when in multihost mode") return } c.serverPorts = make([]serverPortListener, len(conf.configs.Languages)) } currentServerPort := c.serverPort for i := 0; i < len(c.serverPorts); i++ { l, err := net.Listen("tcp", net.JoinHostPort(c.serverInterface, strconv.Itoa(currentServerPort))) if err == nil { c.serverPorts[i] = serverPortListener{ln: l, p: currentServerPort} } else { if i == 0 && flags.Changed("port") { // port set explicitly by user -- he/she probably meant it! cerr = fmt.Errorf("server startup failed: %s", err) return } c.r.Println("port", currentServerPort, "already in use, attempting to use an available port") l, sp, err := helpers.TCPListen() if err != nil { cerr = fmt.Errorf("unable to find alternative port to use: %s", err) return } c.serverPorts[i] = serverPortListener{ln: l, p: sp.Port} } currentServerPort = c.serverPorts[i].p + 1 } }) return cerr } // fixURL massages the baseURL into a form needed for serving // all pages correctly. func (c *serverCommand) fixURL(baseURLFromConfig, baseURLFromFlag string, port int) (string, error) { certsSet := (c.tlsCertFile != "" && c.tlsKeyFile != "") || c.tlsAuto useLocalhost := false baseURL := baseURLFromFlag if baseURL == "" { baseURL = baseURLFromConfig useLocalhost = true } if !strings.HasSuffix(baseURL, "/") { baseURL = baseURL + "/" } // do an initial parse of the input string u, err := url.Parse(baseURL) if err != nil { return "", err } // if no Host is defined, then assume that no schema or double-slash were // present in the url. Add a double-slash and make a best effort attempt. if u.Host == "" && baseURL != "/" { baseURL = "//" + baseURL u, err = url.Parse(baseURL) if err != nil { return "", err } } if useLocalhost { if certsSet { u.Scheme = "https" } else if u.Scheme == "https" { u.Scheme = "http" } u.Host = "localhost" } if c.serverAppend { if strings.Contains(u.Host, ":") { u.Host, _, err = net.SplitHostPort(u.Host) if err != nil { return "", fmt.Errorf("failed to split baseURL hostport: %w", err) } } u.Host += fmt.Sprintf(":%d", port) } return u.String(), nil } func (c *serverCommand) partialReRender(urls ...string) error { defer func() { c.errState.setWasErr(false) }() c.errState.setBuildErr(nil) visited := make(map[string]bool) for _, url := range urls { visited[url] = true } h, err := c.hugo() if err != nil { return err } // Note: We do not set NoBuildLock as the file lock is not acquired at this stage. return h.Build(hugolib.BuildCfg{NoBuildLock: false, RecentlyVisited: visited, PartialReRender: true, ErrRecovery: c.errState.wasErr()}) } func (c *serverCommand) serve() error { var ( baseURLs []string roots []string h *hugolib.HugoSites ) err := c.withConfE(func(conf *commonConfig) error { isMultiHost := conf.configs.IsMultihost var err error h, err = c.r.HugFromConfig(conf) if err != nil { return err } // We need the server to share the same logger as the Hugo build (for error counts etc.) c.r.logger = h.Log if isMultiHost { for _, l := range conf.configs.ConfigLangs() { baseURLs = append(baseURLs, l.BaseURL().String()) roots = append(roots, l.Language().Lang) } } else { l := conf.configs.GetFirstLanguageConfig() baseURLs = []string{l.BaseURL().String()} roots = []string{""} } return nil }) if err != nil { return err } // Cache it here. The HugoSites object may be unavailable later on due to intermittent configuration errors. // To allow the en user to change the error template while the server is running, we use // the freshest template we can provide. var ( errTempl tpl.Template templHandler tpl.TemplateHandler ) getErrorTemplateAndHandler := func(h *hugolib.HugoSites) (tpl.Template, tpl.TemplateHandler) { if h == nil { return errTempl, templHandler } templHandler := h.Tmpl() errTempl, found := templHandler.Lookup("_server/error.html") if !found { panic("template server/error.html not found") } return errTempl, templHandler } errTempl, templHandler = getErrorTemplateAndHandler(h) srv := &fileServer{ baseURLs: baseURLs, roots: roots, c: c, errorTemplate: func(ctx any) (io.Reader, error) { // hugoTry does not block, getErrorTemplateAndHandler will fall back // to cached values if nil. templ, handler := getErrorTemplateAndHandler(c.hugoTry()) b := &bytes.Buffer{} err := handler.ExecuteWithContext(context.Background(), templ, b, ctx) return b, err }, } doLiveReload := !c.disableLiveReload if doLiveReload { livereload.Initialize() } sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) var servers []*http.Server wg1, ctx := errgroup.WithContext(context.Background()) for i := range baseURLs { mu, listener, serverURL, endpoint, err := srv.createEndpoint(i) var srv *http.Server if c.tlsCertFile != "" && c.tlsKeyFile != "" { srv = &http.Server{ Addr: endpoint, Handler: mu, TLSConfig: &tls.Config{ MinVersion: tls.VersionTLS12, }, } } else { srv = &http.Server{ Addr: endpoint, Handler: mu, } } servers = append(servers, srv) if doLiveReload { u, err := url.Parse(helpers.SanitizeURL(baseURLs[i])) if err != nil { return err } mu.HandleFunc(u.Path+"/livereload.js", livereload.ServeJS) mu.HandleFunc(u.Path+"/livereload", livereload.Handler) } c.r.Printf("Web Server is available at %s (bind address %s)\n", serverURL, c.serverInterface) wg1.Go(func() error { if c.tlsCertFile != "" && c.tlsKeyFile != "" { err = srv.ServeTLS(listener, c.tlsCertFile, c.tlsKeyFile) } else { err = srv.Serve(listener) } if err != nil && err != http.ErrServerClosed { return err } return nil }) } if c.r.IsTestRun() { // Write a .ready file to disk to signal ready status. // This is where the test is run from. testInfo := map[string]any{ "baseURLs": srv.baseURLs, } dir := os.Getenv("WORK") if dir != "" { readyFile := filepath.Join(dir, ".ready") // encode the test info as JSON into the .ready file. b, err := json.Marshal(testInfo) if err != nil { return err } err = os.WriteFile(readyFile, b, 0777) if err != nil { return err } } } c.r.Println("Press Ctrl+C to stop") err = func() error { for { select { case <-c.quit: return nil case <-sigs: return nil case <-ctx.Done(): return ctx.Err() } } }() if err != nil { c.r.Println("Error:", err) } if h := c.hugoTry(); h != nil { h.Close() } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() wg2, ctx := errgroup.WithContext(ctx) for _, srv := range servers { srv := srv wg2.Go(func() error { return srv.Shutdown(ctx) }) } err1, err2 := wg1.Wait(), wg2.Wait() if err1 != nil { return err1 } return err2 } type serverPortListener struct { p int ln net.Listener } type staticSyncer struct { c *hugoBuilder } func (s *staticSyncer) isStatic(h *hugolib.HugoSites, filename string) bool { return h.BaseFs.SourceFilesystems.IsStatic(filename) } func (s *staticSyncer) syncsStaticEvents(staticEvents []fsnotify.Event) error { c := s.c syncFn := func(sourceFs *filesystems.SourceFilesystem) (uint64, error) { publishDir := helpers.FilePathSeparator if sourceFs.PublishFolder != "" { publishDir = filepath.Join(publishDir, sourceFs.PublishFolder) } syncer := fsync.NewSyncer() c.withConf(func(conf *commonConfig) { syncer.NoTimes = conf.configs.Base.NoTimes syncer.NoChmod = conf.configs.Base.NoChmod syncer.ChmodFilter = chmodFilter syncer.SrcFs = sourceFs.Fs syncer.DestFs = conf.fs.PublishDir if c.s != nil && c.s.renderStaticToDisk { syncer.DestFs = conf.fs.PublishDirStatic } }) logger := s.c.r.logger for _, ev := range staticEvents { // Due to our approach of layering both directories and the content's rendered output // into one we can't accurately remove a file not in one of the source directories. // If a file is in the local static dir and also in the theme static dir and we remove // it from one of those locations we expect it to still exist in the destination // // If Hugo generates a file (from the content dir) over a static file // the content generated file should take precedence. // // Because we are now watching and handling individual events it is possible that a static // event that occupies the same path as a content generated file will take precedence // until a regeneration of the content takes places. // // Hugo assumes that these cases are very rare and will permit this bad behavior // The alternative is to track every single file and which pipeline rendered it // and then to handle conflict resolution on every event. fromPath := ev.Name relPath, found := sourceFs.MakePathRelative(fromPath) if !found { // Not member of this virtual host. continue } // Remove || rename is harder and will require an assumption. // Hugo takes the following approach: // If the static file exists in any of the static source directories after this event // Hugo will re-sync it. // If it does not exist in all of the static directories Hugo will remove it. // // This assumes that Hugo has not generated content on top of a static file and then removed // the source of that static file. In this case Hugo will incorrectly remove that file // from the published directory. if ev.Op&fsnotify.Rename == fsnotify.Rename || ev.Op&fsnotify.Remove == fsnotify.Remove { if _, err := sourceFs.Fs.Stat(relPath); herrors.IsNotExist(err) { // If file doesn't exist in any static dir, remove it logger.Println("File no longer exists in static dir, removing", relPath) c.withConf(func(conf *commonConfig) { _ = conf.fs.PublishDirStatic.RemoveAll(relPath) }) } else if err == nil { // If file still exists, sync it logger.Println("Syncing", relPath, "to", publishDir) if err := syncer.Sync(relPath, relPath); err != nil { c.r.logger.Errorln(err) } } else { c.r.logger.Errorln(err) } continue } // For all other event operations Hugo will sync static. logger.Println("Syncing", relPath, "to", publishDir) if err := syncer.Sync(filepath.Join(publishDir, relPath), relPath); err != nil { c.r.logger.Errorln(err) } } return 0, nil } _, err := c.doWithPublishDirs(syncFn) return err } func chmodFilter(dst, src os.FileInfo) bool { // Hugo publishes data from multiple sources, potentially // with overlapping directory structures. We cannot sync permissions // for directories as that would mean that we might end up with write-protected // directories inside /public. // One example of this would be syncing from the Go Module cache, // which have 0555 directories. return src.IsDir() } func cleanErrorLog(content string) string { content = strings.ReplaceAll(content, "\n", " ") content = logReplacer.Replace(content) content = logDuplicateTemplateExecuteRe.ReplaceAllString(content, "") content = logDuplicateTemplateParseRe.ReplaceAllString(content, "") seen := make(map[string]bool) parts := strings.Split(content, ": ") keep := make([]string, 0, len(parts)) for _, part := range parts { if seen[part] { continue } seen[part] = true keep = append(keep, part) } return strings.Join(keep, ": ") } func injectLiveReloadScript(src io.Reader, baseURL url.URL) string { var b bytes.Buffer chain := transform.Chain{livereloadinject.New(baseURL)} chain.Apply(&b, src) return b.String() } func partitionDynamicEvents(sourceFs *filesystems.SourceFilesystems, events []fsnotify.Event) (de dynamicEvents) { for _, e := range events { if !sourceFs.IsContent(e.Name) { de.AssetEvents = append(de.AssetEvents, e) } else { de.ContentEvents = append(de.ContentEvents, e) } } return } func pickOneWriteOrCreatePath(events []fsnotify.Event) string { name := "" for _, ev := range events { if ev.Op&fsnotify.Write == fsnotify.Write || ev.Op&fsnotify.Create == fsnotify.Create { if files.IsIndexContentFile(ev.Name) { return ev.Name } if files.IsContentFile(ev.Name) { name = ev.Name } } } return name } func formatByteCount(b uint64) string { const unit = 1000 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := int64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) }
// Copyright 2023 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 commands import ( "bytes" "context" "crypto/tls" "crypto/x509" "encoding/json" "encoding/pem" "errors" "fmt" "io" "net" "net/http" "net/url" "os" "sync" "sync/atomic" "github.com/bep/mclib" "os/signal" "path" "path/filepath" "regexp" "strconv" "strings" "syscall" "time" "github.com/bep/debounce" "github.com/bep/simplecobra" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/common/urls" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/livereload" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/transform" "github.com/gohugoio/hugo/transform/livereloadinject" "github.com/spf13/afero" "github.com/spf13/cobra" "github.com/spf13/fsync" "golang.org/x/sync/errgroup" "golang.org/x/sync/semaphore" ) var ( logDuplicateTemplateExecuteRe = regexp.MustCompile(`: template: .*?:\d+:\d+: executing ".*?"`) logDuplicateTemplateParseRe = regexp.MustCompile(`: template: .*?:\d+:\d*`) ) var logReplacer = strings.NewReplacer( "can't", "can’t", // Chroma lexer doesn't do well with "can't" "*hugolib.pageState", "page.Page", // Page is the public interface. "Rebuild failed:", "", ) const ( configChangeConfig = "config file" configChangeGoMod = "go.mod file" configChangeGoWork = "go work file" ) func newHugoBuilder(r *rootCommand, s *serverCommand, onConfigLoaded ...func(reloaded bool) error) *hugoBuilder { return &hugoBuilder{ r: r, s: s, visitedURLs: types.NewEvictingStringQueue(100), fullRebuildSem: semaphore.NewWeighted(1), debounce: debounce.New(4 * time.Second), onConfigLoaded: func(reloaded bool) error { for _, wc := range onConfigLoaded { if err := wc(reloaded); err != nil { return err } } return nil }, } } func newServerCommand() *serverCommand { // Flags. var uninstall bool c := &serverCommand{ quit: make(chan bool), commands: []simplecobra.Commander{ &simpleCommand{ name: "trust", short: "Install the local CA in the system trust store.", run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { action := "-install" if uninstall { action = "-uninstall" } os.Args = []string{action} return mclib.RunMain() }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVar(&uninstall, "uninstall", false, "Uninstall the local CA (but do not delete it).") }, }, }, } return c } func (c *serverCommand) Commands() []simplecobra.Commander { return c.commands } type countingStatFs struct { afero.Fs statCounter uint64 } func (fs *countingStatFs) Stat(name string) (os.FileInfo, error) { f, err := fs.Fs.Stat(name) if err == nil { if !f.IsDir() { atomic.AddUint64(&fs.statCounter, 1) } } return f, err } // dynamicEvents contains events that is considered dynamic, as in "not static". // Both of these categories will trigger a new build, but the asset events // does not fit into the "navigate to changed" logic. type dynamicEvents struct { ContentEvents []fsnotify.Event AssetEvents []fsnotify.Event } type fileChangeDetector struct { sync.Mutex current map[string]string prev map[string]string irrelevantRe *regexp.Regexp } func (f *fileChangeDetector) OnFileClose(name, md5sum string) { f.Lock() defer f.Unlock() f.current[name] = md5sum } func (f *fileChangeDetector) PrepareNew() { if f == nil { return } f.Lock() defer f.Unlock() if f.current == nil { f.current = make(map[string]string) f.prev = make(map[string]string) return } f.prev = make(map[string]string) for k, v := range f.current { f.prev[k] = v } f.current = make(map[string]string) } func (f *fileChangeDetector) changed() []string { if f == nil { return nil } f.Lock() defer f.Unlock() var c []string for k, v := range f.current { vv, found := f.prev[k] if !found || v != vv { c = append(c, k) } } return f.filterIrrelevant(c) } func (f *fileChangeDetector) filterIrrelevant(in []string) []string { var filtered []string for _, v := range in { if !f.irrelevantRe.MatchString(v) { filtered = append(filtered, v) } } return filtered } type fileServer struct { baseURLs []string roots []string errorTemplate func(err any) (io.Reader, error) c *serverCommand } func (f *fileServer) createEndpoint(i int) (*http.ServeMux, net.Listener, string, string, error) { r := f.c.r baseURL := f.baseURLs[i] root := f.roots[i] port := f.c.serverPorts[i].p listener := f.c.serverPorts[i].ln logger := f.c.r.logger r.Printf("Environment: %q\n", f.c.hugoTry().Deps.Site.Hugo().Environment) if i == 0 { if f.c.renderToDisk { r.Println("Serving pages from disk") } else if f.c.renderStaticToDisk { r.Println("Serving pages from memory and static files from disk") } else { r.Println("Serving pages from memory") } } var httpFs *afero.HttpFs f.c.withConf(func(conf *commonConfig) { httpFs = afero.NewHttpFs(conf.fs.PublishDirServer) }) fs := filesOnlyFs{httpFs.Dir(path.Join("/", root))} if i == 0 && f.c.fastRenderMode { r.Println("Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender") } // We're only interested in the path u, err := url.Parse(baseURL) if err != nil { return nil, nil, "", "", fmt.Errorf("invalid baseURL: %w", err) } decorate := func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if f.c.showErrorInBrowser { // First check the error state err := f.c.getErrorWithContext() if err != nil { f.c.errState.setWasErr(true) w.WriteHeader(500) r, err := f.errorTemplate(err) if err != nil { logger.Errorln(err) } port = 1313 f.c.withConf(func(conf *commonConfig) { if lrport := conf.configs.GetFirstLanguageConfig().BaseURLLiveReload().Port(); lrport != 0 { port = lrport } }) lr := *u lr.Host = fmt.Sprintf("%s:%d", lr.Hostname(), port) fmt.Fprint(w, injectLiveReloadScript(r, lr)) return } } if f.c.noHTTPCache { w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0") w.Header().Set("Pragma", "no-cache") } var serverConfig config.Server f.c.withConf(func(conf *commonConfig) { serverConfig = conf.configs.Base.Server }) // Ignore any query params for the operations below. requestURI, _ := url.PathUnescape(strings.TrimSuffix(r.RequestURI, "?"+r.URL.RawQuery)) for _, header := range serverConfig.MatchHeaders(requestURI) { w.Header().Set(header.Key, header.Value) } if redirect := serverConfig.MatchRedirect(requestURI); !redirect.IsZero() { // fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))) doRedirect := true // This matches Netlify's behaviour and is needed for SPA behaviour. // See https://docs.netlify.com/routing/redirects/rewrites-proxies/ if !redirect.Force { path := filepath.Clean(strings.TrimPrefix(requestURI, u.Path)) if root != "" { path = filepath.Join(root, path) } var fs afero.Fs f.c.withConf(func(conf *commonConfig) { fs = conf.fs.PublishDirServer }) fi, err := fs.Stat(path) if err == nil { if fi.IsDir() { // There will be overlapping directories, so we // need to check for a file. _, err = fs.Stat(filepath.Join(path, "index.html")) doRedirect = err != nil } else { doRedirect = false } } } if doRedirect { switch redirect.Status { case 404: w.WriteHeader(404) file, err := fs.Open(strings.TrimPrefix(redirect.To, u.Path)) if err == nil { defer file.Close() io.Copy(w, file) } else { fmt.Fprintln(w, "<h1>Page Not Found</h1>") } return case 200: if r2 := f.rewriteRequest(r, strings.TrimPrefix(redirect.To, u.Path)); r2 != nil { requestURI = redirect.To r = r2 } default: w.Header().Set("Content-Type", "") http.Redirect(w, r, redirect.To, redirect.Status) return } } } if f.c.fastRenderMode && f.c.errState.buildErr() == nil { if strings.HasSuffix(requestURI, "/") || strings.HasSuffix(requestURI, "html") || strings.HasSuffix(requestURI, "htm") { if !f.c.visitedURLs.Contains(requestURI) { // If not already on stack, re-render that single page. if err := f.c.partialReRender(requestURI); err != nil { f.c.handleBuildErr(err, fmt.Sprintf("Failed to render %q", requestURI)) if f.c.showErrorInBrowser { http.Redirect(w, r, requestURI, http.StatusMovedPermanently) return } } } f.c.visitedURLs.Add(requestURI) } } h.ServeHTTP(w, r) }) } fileserver := decorate(http.FileServer(fs)) mu := http.NewServeMux() if u.Path == "" || u.Path == "/" { mu.Handle("/", fileserver) } else { mu.Handle(u.Path, http.StripPrefix(u.Path, fileserver)) } if r.IsTestRun() { var shutDownOnce sync.Once mu.HandleFunc("/__stop", func(w http.ResponseWriter, r *http.Request) { shutDownOnce.Do(func() { close(f.c.quit) }) }) } endpoint := net.JoinHostPort(f.c.serverInterface, strconv.Itoa(port)) return mu, listener, u.String(), endpoint, nil } func (f *fileServer) rewriteRequest(r *http.Request, toPath string) *http.Request { r2 := new(http.Request) *r2 = *r r2.URL = new(url.URL) *r2.URL = *r.URL r2.URL.Path = toPath r2.Header.Set("X-Rewrite-Original-URI", r.URL.RequestURI()) return r2 } type filesOnlyFs struct { fs http.FileSystem } func (fs filesOnlyFs) Open(name string) (http.File, error) { f, err := fs.fs.Open(name) if err != nil { return nil, err } return noDirFile{f}, nil } type noDirFile struct { http.File } func (f noDirFile) Readdir(count int) ([]os.FileInfo, error) { return nil, nil } type serverCommand struct { r *rootCommand commands []simplecobra.Commander *hugoBuilder quit chan bool // Closed when the server should shut down. Used in tests only. serverPorts []serverPortListener doLiveReload bool // Flags. renderToDisk bool renderStaticToDisk bool navigateToChanged bool serverAppend bool serverInterface string tlsCertFile string tlsKeyFile string tlsAuto bool serverPort int liveReloadPort int serverWatch bool noHTTPCache bool disableLiveReload bool disableFastRender bool disableBrowserError bool } func (c *serverCommand) Name() string { return "server" } func (c *serverCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { // Watch runs its own server as part of the routine if c.serverWatch { watchDirs, err := c.getDirList() if err != nil { return err } watchGroups := helpers.ExtractAndGroupRootPaths(watchDirs) for _, group := range watchGroups { c.r.Printf("Watching for changes in %s\n", group) } watcher, err := c.newWatcher(c.r.poll, watchDirs...) if err != nil { return err } defer watcher.Close() } err := func() error { defer c.r.timeTrack(time.Now(), "Built") err := c.build() return err }() if err != nil { return err } return c.serve() } func (c *serverCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "A high performance webserver" cmd.Long = `Hugo provides its own webserver which builds and serves the site. While hugo server is high performance, it is a webserver with limited options. 'hugo server' will avoid writing the rendered and served content to disk, preferring to store it in memory. By default hugo will also watch your files for any changes you make and automatically rebuild the site. It will then live reload any open browser pages and push the latest content to them. As most Hugo sites are built in a fraction of a second, you will be able to save and see your changes nearly instantly.` cmd.Aliases = []string{"serve"} cmd.Flags().IntVarP(&c.serverPort, "port", "p", 1313, "port on which the server will listen") cmd.Flags().IntVar(&c.liveReloadPort, "liveReloadPort", -1, "port for live reloading (i.e. 443 in HTTPS proxy situations)") cmd.Flags().StringVarP(&c.serverInterface, "bind", "", "127.0.0.1", "interface to which the server will bind") cmd.Flags().StringVarP(&c.tlsCertFile, "tlsCertFile", "", "", "path to TLS certificate file") cmd.Flags().StringVarP(&c.tlsKeyFile, "tlsKeyFile", "", "", "path to TLS key file") cmd.Flags().BoolVar(&c.tlsAuto, "tlsAuto", false, "generate and use locally-trusted certificates.") cmd.Flags().BoolVarP(&c.serverWatch, "watch", "w", true, "watch filesystem for changes and recreate as needed") cmd.Flags().BoolVar(&c.noHTTPCache, "noHTTPCache", false, "prevent HTTP caching") cmd.Flags().BoolVarP(&c.serverAppend, "appendPort", "", true, "append port to baseURL") cmd.Flags().BoolVar(&c.disableLiveReload, "disableLiveReload", false, "watch without enabling live browser reload on rebuild") cmd.Flags().BoolVar(&c.navigateToChanged, "navigateToChanged", false, "navigate to changed content file on live browser reload") cmd.Flags().BoolVar(&c.renderToDisk, "renderToDisk", false, "serve all files from disk (default is from memory)") cmd.Flags().BoolVar(&c.renderStaticToDisk, "renderStaticToDisk", false, "serve static files from disk and dynamic files from memory") cmd.Flags().BoolVar(&c.disableFastRender, "disableFastRender", false, "enables full re-renders on changes") cmd.Flags().BoolVar(&c.disableBrowserError, "disableBrowserError", false, "do not show build errors in the browser") cmd.Flags().String("memstats", "", "log memory usage to this file") cmd.Flags().String("meminterval", "100ms", "interval to poll memory usage (requires --memstats), valid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\".") cmd.Flags().SetAnnotation("tlsCertFile", cobra.BashCompSubdirsInDir, []string{}) cmd.Flags().SetAnnotation("tlsKeyFile", cobra.BashCompSubdirsInDir, []string{}) r := cd.Root.Command.(*rootCommand) applyLocalFlagsBuild(cmd, r) return nil } func (c *serverCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.r = cd.Root.Command.(*rootCommand) c.hugoBuilder = newHugoBuilder( c.r, c, func(reloaded bool) error { if !reloaded { if err := c.createServerPorts(cd); err != nil { return err } if (c.tlsCertFile == "" || c.tlsKeyFile == "") && c.tlsAuto { c.withConfE(func(conf *commonConfig) error { return c.createCertificates(conf) }) } } if err := c.setBaseURLsInConfig(); err != nil { return err } if !reloaded && c.fastRenderMode { c.withConf(func(conf *commonConfig) { conf.fs.PublishDir = hugofs.NewHashingFs(conf.fs.PublishDir, c.changeDetector) conf.fs.PublishDirStatic = hugofs.NewHashingFs(conf.fs.PublishDirStatic, c.changeDetector) }) } return nil }, ) destinationFlag := cd.CobraCommand.Flags().Lookup("destination") c.renderToDisk = c.renderToDisk || (destinationFlag != nil && destinationFlag.Changed) c.doLiveReload = !c.disableLiveReload c.fastRenderMode = !c.disableFastRender c.showErrorInBrowser = c.doLiveReload && !c.disableBrowserError if c.fastRenderMode { // For now, fast render mode only. It should, however, be fast enough // for the full variant, too. c.changeDetector = &fileChangeDetector{ // We use this detector to decide to do a Hot reload of a single path or not. // We need to filter out source maps and possibly some other to be able // to make that decision. irrelevantRe: regexp.MustCompile(`\.map$`), } c.changeDetector.PrepareNew() } err := c.loadConfig(cd, true) if err != nil { return err } return nil } func (c *serverCommand) setBaseURLsInConfig() error { if len(c.serverPorts) == 0 { panic("no server ports set") } return c.withConfE(func(conf *commonConfig) error { for i, language := range conf.configs.Languages { isMultiHost := conf.configs.IsMultihost var serverPort int if isMultiHost { serverPort = c.serverPorts[i].p } else { serverPort = c.serverPorts[0].p } langConfig := conf.configs.LanguageConfigMap[language.Lang] baseURLStr, err := c.fixURL(langConfig.BaseURL, c.r.baseURL, serverPort) if err != nil { return err } baseURL, err := urls.NewBaseURLFromString(baseURLStr) if err != nil { return fmt.Errorf("failed to create baseURL from %q: %s", baseURLStr, err) } baseURLLiveReload := baseURL if c.liveReloadPort != -1 { baseURLLiveReload, _ = baseURLLiveReload.WithPort(c.liveReloadPort) } langConfig.C.SetBaseURL(baseURL, baseURLLiveReload) } return nil }) } func (c *serverCommand) getErrorWithContext() any { errCount := c.errCount() if errCount == 0 { return nil } m := make(map[string]any) m["Error"] = cleanErrorLog(c.r.logger.Errors()) m["Version"] = hugo.BuildVersionString() ferrors := herrors.UnwrapFileErrorsWithErrorContext(c.errState.buildErr()) m["Files"] = ferrors return m } func (c *serverCommand) createCertificates(conf *commonConfig) error { hostname := "localhost" if c.r.baseURL != "" { u, err := url.Parse(c.r.baseURL) if err != nil { return err } hostname = u.Hostname() } // For now, store these in the Hugo cache dir. // Hugo should probably introduce some concept of a less temporary application directory. keyDir := filepath.Join(conf.configs.LoadingInfo.BaseConfig.CacheDir, "_mkcerts") // Create the directory if it doesn't exist. if _, err := os.Stat(keyDir); os.IsNotExist(err) { if err := os.MkdirAll(keyDir, 0777); err != nil { return err } } c.tlsCertFile = filepath.Join(keyDir, fmt.Sprintf("%s.pem", hostname)) c.tlsKeyFile = filepath.Join(keyDir, fmt.Sprintf("%s-key.pem", hostname)) // Check if the certificate already exists and is valid. certPEM, err := os.ReadFile(c.tlsCertFile) if err == nil { rootPem, err := os.ReadFile(filepath.Join(mclib.GetCAROOT(), "rootCA.pem")) if err == nil { if err := c.verifyCert(rootPem, certPEM, hostname); err == nil { c.r.Println("Using existing", c.tlsCertFile, "and", c.tlsKeyFile) return nil } } } c.r.Println("Creating TLS certificates in", keyDir) // Yes, this is unfortunate, but it's currently the only way to use Mkcert as a library. os.Args = []string{"-cert-file", c.tlsCertFile, "-key-file", c.tlsKeyFile, hostname} return mclib.RunMain() } func (c *serverCommand) verifyCert(rootPEM, certPEM []byte, name string) error { roots := x509.NewCertPool() ok := roots.AppendCertsFromPEM(rootPEM) if !ok { return fmt.Errorf("failed to parse root certificate") } block, _ := pem.Decode(certPEM) if block == nil { return fmt.Errorf("failed to parse certificate PEM") } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return fmt.Errorf("failed to parse certificate: %v", err.Error()) } opts := x509.VerifyOptions{ DNSName: name, Roots: roots, } if _, err := cert.Verify(opts); err != nil { return fmt.Errorf("failed to verify certificate: %v", err.Error()) } return nil } func (c *serverCommand) createServerPorts(cd *simplecobra.Commandeer) error { flags := cd.CobraCommand.Flags() var cerr error c.withConf(func(conf *commonConfig) { isMultiHost := conf.configs.IsMultihost c.serverPorts = make([]serverPortListener, 1) if isMultiHost { if !c.serverAppend { cerr = errors.New("--appendPort=false not supported when in multihost mode") return } c.serverPorts = make([]serverPortListener, len(conf.configs.Languages)) } currentServerPort := c.serverPort for i := 0; i < len(c.serverPorts); i++ { l, err := net.Listen("tcp", net.JoinHostPort(c.serverInterface, strconv.Itoa(currentServerPort))) if err == nil { c.serverPorts[i] = serverPortListener{ln: l, p: currentServerPort} } else { if i == 0 && flags.Changed("port") { // port set explicitly by user -- he/she probably meant it! cerr = fmt.Errorf("server startup failed: %s", err) return } c.r.Println("port", currentServerPort, "already in use, attempting to use an available port") l, sp, err := helpers.TCPListen() if err != nil { cerr = fmt.Errorf("unable to find alternative port to use: %s", err) return } c.serverPorts[i] = serverPortListener{ln: l, p: sp.Port} } currentServerPort = c.serverPorts[i].p + 1 } }) return cerr } // fixURL massages the baseURL into a form needed for serving // all pages correctly. func (c *serverCommand) fixURL(baseURLFromConfig, baseURLFromFlag string, port int) (string, error) { certsSet := (c.tlsCertFile != "" && c.tlsKeyFile != "") || c.tlsAuto useLocalhost := false baseURL := baseURLFromFlag if baseURL == "" { baseURL = baseURLFromConfig useLocalhost = true } if !strings.HasSuffix(baseURL, "/") { baseURL = baseURL + "/" } // do an initial parse of the input string u, err := url.Parse(baseURL) if err != nil { return "", err } // if no Host is defined, then assume that no schema or double-slash were // present in the url. Add a double-slash and make a best effort attempt. if u.Host == "" && baseURL != "/" { baseURL = "//" + baseURL u, err = url.Parse(baseURL) if err != nil { return "", err } } if useLocalhost { if certsSet { u.Scheme = "https" } else if u.Scheme == "https" { u.Scheme = "http" } u.Host = "localhost" } if c.serverAppend { if strings.Contains(u.Host, ":") { u.Host, _, err = net.SplitHostPort(u.Host) if err != nil { return "", fmt.Errorf("failed to split baseURL hostport: %w", err) } } u.Host += fmt.Sprintf(":%d", port) } return u.String(), nil } func (c *serverCommand) partialReRender(urls ...string) error { defer func() { c.errState.setWasErr(false) }() c.errState.setBuildErr(nil) visited := make(map[string]bool) for _, url := range urls { visited[url] = true } h, err := c.hugo() if err != nil { return err } // Note: We do not set NoBuildLock as the file lock is not acquired at this stage. return h.Build(hugolib.BuildCfg{NoBuildLock: false, RecentlyVisited: visited, PartialReRender: true, ErrRecovery: c.errState.wasErr()}) } func (c *serverCommand) serve() error { var ( baseURLs []string roots []string h *hugolib.HugoSites ) err := c.withConfE(func(conf *commonConfig) error { isMultiHost := conf.configs.IsMultihost var err error h, err = c.r.HugFromConfig(conf) if err != nil { return err } // We need the server to share the same logger as the Hugo build (for error counts etc.) c.r.logger = h.Log if isMultiHost { for _, l := range conf.configs.ConfigLangs() { baseURLs = append(baseURLs, l.BaseURL().String()) roots = append(roots, l.Language().Lang) } } else { l := conf.configs.GetFirstLanguageConfig() baseURLs = []string{l.BaseURL().String()} roots = []string{""} } return nil }) if err != nil { return err } // Cache it here. The HugoSites object may be unavailable later on due to intermittent configuration errors. // To allow the en user to change the error template while the server is running, we use // the freshest template we can provide. var ( errTempl tpl.Template templHandler tpl.TemplateHandler ) getErrorTemplateAndHandler := func(h *hugolib.HugoSites) (tpl.Template, tpl.TemplateHandler) { if h == nil { return errTempl, templHandler } templHandler := h.Tmpl() errTempl, found := templHandler.Lookup("_server/error.html") if !found { panic("template server/error.html not found") } return errTempl, templHandler } errTempl, templHandler = getErrorTemplateAndHandler(h) srv := &fileServer{ baseURLs: baseURLs, roots: roots, c: c, errorTemplate: func(ctx any) (io.Reader, error) { // hugoTry does not block, getErrorTemplateAndHandler will fall back // to cached values if nil. templ, handler := getErrorTemplateAndHandler(c.hugoTry()) b := &bytes.Buffer{} err := handler.ExecuteWithContext(context.Background(), templ, b, ctx) return b, err }, } doLiveReload := !c.disableLiveReload if doLiveReload { livereload.Initialize() } sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) var servers []*http.Server wg1, ctx := errgroup.WithContext(context.Background()) for i := range baseURLs { mu, listener, serverURL, endpoint, err := srv.createEndpoint(i) var srv *http.Server if c.tlsCertFile != "" && c.tlsKeyFile != "" { srv = &http.Server{ Addr: endpoint, Handler: mu, TLSConfig: &tls.Config{ MinVersion: tls.VersionTLS12, }, } } else { srv = &http.Server{ Addr: endpoint, Handler: mu, } } servers = append(servers, srv) if doLiveReload { u, err := url.Parse(helpers.SanitizeURL(baseURLs[i])) if err != nil { return err } mu.HandleFunc(u.Path+"/livereload.js", livereload.ServeJS) mu.HandleFunc(u.Path+"/livereload", livereload.Handler) } c.r.Printf("Web Server is available at %s (bind address %s) %s\n", serverURL, c.serverInterface, roots[i]) wg1.Go(func() error { if c.tlsCertFile != "" && c.tlsKeyFile != "" { err = srv.ServeTLS(listener, c.tlsCertFile, c.tlsKeyFile) } else { err = srv.Serve(listener) } if err != nil && err != http.ErrServerClosed { return err } return nil }) } if c.r.IsTestRun() { // Write a .ready file to disk to signal ready status. // This is where the test is run from. testInfo := map[string]any{ "baseURLs": srv.baseURLs, } dir := os.Getenv("WORK") if dir != "" { readyFile := filepath.Join(dir, ".ready") // encode the test info as JSON into the .ready file. b, err := json.Marshal(testInfo) if err != nil { return err } err = os.WriteFile(readyFile, b, 0777) if err != nil { return err } } } c.r.Println("Press Ctrl+C to stop") err = func() error { for { select { case <-c.quit: return nil case <-sigs: return nil case <-ctx.Done(): return ctx.Err() } } }() if err != nil { c.r.Println("Error:", err) } if h := c.hugoTry(); h != nil { h.Close() } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() wg2, ctx := errgroup.WithContext(ctx) for _, srv := range servers { srv := srv wg2.Go(func() error { return srv.Shutdown(ctx) }) } err1, err2 := wg1.Wait(), wg2.Wait() if err1 != nil { return err1 } return err2 } type serverPortListener struct { p int ln net.Listener } type staticSyncer struct { c *hugoBuilder } func (s *staticSyncer) isStatic(h *hugolib.HugoSites, filename string) bool { return h.BaseFs.SourceFilesystems.IsStatic(filename) } func (s *staticSyncer) syncsStaticEvents(staticEvents []fsnotify.Event) error { c := s.c syncFn := func(sourceFs *filesystems.SourceFilesystem) (uint64, error) { publishDir := helpers.FilePathSeparator if sourceFs.PublishFolder != "" { publishDir = filepath.Join(publishDir, sourceFs.PublishFolder) } syncer := fsync.NewSyncer() c.withConf(func(conf *commonConfig) { syncer.NoTimes = conf.configs.Base.NoTimes syncer.NoChmod = conf.configs.Base.NoChmod syncer.ChmodFilter = chmodFilter syncer.SrcFs = sourceFs.Fs syncer.DestFs = conf.fs.PublishDir if c.s != nil && c.s.renderStaticToDisk { syncer.DestFs = conf.fs.PublishDirStatic } }) logger := s.c.r.logger for _, ev := range staticEvents { // Due to our approach of layering both directories and the content's rendered output // into one we can't accurately remove a file not in one of the source directories. // If a file is in the local static dir and also in the theme static dir and we remove // it from one of those locations we expect it to still exist in the destination // // If Hugo generates a file (from the content dir) over a static file // the content generated file should take precedence. // // Because we are now watching and handling individual events it is possible that a static // event that occupies the same path as a content generated file will take precedence // until a regeneration of the content takes places. // // Hugo assumes that these cases are very rare and will permit this bad behavior // The alternative is to track every single file and which pipeline rendered it // and then to handle conflict resolution on every event. fromPath := ev.Name relPath, found := sourceFs.MakePathRelative(fromPath) if !found { // Not member of this virtual host. continue } // Remove || rename is harder and will require an assumption. // Hugo takes the following approach: // If the static file exists in any of the static source directories after this event // Hugo will re-sync it. // If it does not exist in all of the static directories Hugo will remove it. // // This assumes that Hugo has not generated content on top of a static file and then removed // the source of that static file. In this case Hugo will incorrectly remove that file // from the published directory. if ev.Op&fsnotify.Rename == fsnotify.Rename || ev.Op&fsnotify.Remove == fsnotify.Remove { if _, err := sourceFs.Fs.Stat(relPath); herrors.IsNotExist(err) { // If file doesn't exist in any static dir, remove it logger.Println("File no longer exists in static dir, removing", relPath) c.withConf(func(conf *commonConfig) { _ = conf.fs.PublishDirStatic.RemoveAll(relPath) }) } else if err == nil { // If file still exists, sync it logger.Println("Syncing", relPath, "to", publishDir) if err := syncer.Sync(relPath, relPath); err != nil { c.r.logger.Errorln(err) } } else { c.r.logger.Errorln(err) } continue } // For all other event operations Hugo will sync static. logger.Println("Syncing", relPath, "to", publishDir) if err := syncer.Sync(filepath.Join(publishDir, relPath), relPath); err != nil { c.r.logger.Errorln(err) } } return 0, nil } _, err := c.doWithPublishDirs(syncFn) return err } func chmodFilter(dst, src os.FileInfo) bool { // Hugo publishes data from multiple sources, potentially // with overlapping directory structures. We cannot sync permissions // for directories as that would mean that we might end up with write-protected // directories inside /public. // One example of this would be syncing from the Go Module cache, // which have 0555 directories. return src.IsDir() } func cleanErrorLog(content string) string { content = strings.ReplaceAll(content, "\n", " ") content = logReplacer.Replace(content) content = logDuplicateTemplateExecuteRe.ReplaceAllString(content, "") content = logDuplicateTemplateParseRe.ReplaceAllString(content, "") seen := make(map[string]bool) parts := strings.Split(content, ": ") keep := make([]string, 0, len(parts)) for _, part := range parts { if seen[part] { continue } seen[part] = true keep = append(keep, part) } return strings.Join(keep, ": ") } func injectLiveReloadScript(src io.Reader, baseURL url.URL) string { var b bytes.Buffer chain := transform.Chain{livereloadinject.New(baseURL)} chain.Apply(&b, src) return b.String() } func partitionDynamicEvents(sourceFs *filesystems.SourceFilesystems, events []fsnotify.Event) (de dynamicEvents) { for _, e := range events { if !sourceFs.IsContent(e.Name) { de.AssetEvents = append(de.AssetEvents, e) } else { de.ContentEvents = append(de.ContentEvents, e) } } return } func pickOneWriteOrCreatePath(events []fsnotify.Event) string { name := "" for _, ev := range events { if ev.Op&fsnotify.Write == fsnotify.Write || ev.Op&fsnotify.Create == fsnotify.Create { if files.IsIndexContentFile(ev.Name) { return ev.Name } if files.IsContentFile(ev.Name) { name = ev.Name } } } return name } func formatByteCount(b uint64) string { const unit = 1000 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := int64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) }
ilmari-lauhakangas
2ae4786ca1e4b912fabc8a6be503772374fed5d6
525bed99190b2f90946e7010c6094feb3884af6a
```suggestion ```
jmooring
18
gohugoio/hugo
11,442
Print language code after web server address info
With dozens of different languages, it is nice to see which port maps to which language in local development.
null
2023-09-10 17:11:46+00:00
2023-09-11 09:38:24+00:00
commands/server.go
// Copyright 2023 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 commands import ( "bytes" "context" "crypto/tls" "crypto/x509" "encoding/json" "encoding/pem" "errors" "fmt" "io" "net" "net/http" "net/url" "os" "sync" "sync/atomic" "github.com/bep/mclib" "os/signal" "path" "path/filepath" "regexp" "strconv" "strings" "syscall" "time" "github.com/bep/debounce" "github.com/bep/simplecobra" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/common/urls" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/livereload" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/transform" "github.com/gohugoio/hugo/transform/livereloadinject" "github.com/spf13/afero" "github.com/spf13/cobra" "github.com/spf13/fsync" "golang.org/x/sync/errgroup" "golang.org/x/sync/semaphore" ) var ( logDuplicateTemplateExecuteRe = regexp.MustCompile(`: template: .*?:\d+:\d+: executing ".*?"`) logDuplicateTemplateParseRe = regexp.MustCompile(`: template: .*?:\d+:\d*`) ) var logReplacer = strings.NewReplacer( "can't", "can’t", // Chroma lexer doesn't do well with "can't" "*hugolib.pageState", "page.Page", // Page is the public interface. "Rebuild failed:", "", ) const ( configChangeConfig = "config file" configChangeGoMod = "go.mod file" configChangeGoWork = "go work file" ) func newHugoBuilder(r *rootCommand, s *serverCommand, onConfigLoaded ...func(reloaded bool) error) *hugoBuilder { return &hugoBuilder{ r: r, s: s, visitedURLs: types.NewEvictingStringQueue(100), fullRebuildSem: semaphore.NewWeighted(1), debounce: debounce.New(4 * time.Second), onConfigLoaded: func(reloaded bool) error { for _, wc := range onConfigLoaded { if err := wc(reloaded); err != nil { return err } } return nil }, } } func newServerCommand() *serverCommand { // Flags. var uninstall bool c := &serverCommand{ quit: make(chan bool), commands: []simplecobra.Commander{ &simpleCommand{ name: "trust", short: "Install the local CA in the system trust store.", run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { action := "-install" if uninstall { action = "-uninstall" } os.Args = []string{action} return mclib.RunMain() }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVar(&uninstall, "uninstall", false, "Uninstall the local CA (but do not delete it).") }, }, }, } return c } func (c *serverCommand) Commands() []simplecobra.Commander { return c.commands } type countingStatFs struct { afero.Fs statCounter uint64 } func (fs *countingStatFs) Stat(name string) (os.FileInfo, error) { f, err := fs.Fs.Stat(name) if err == nil { if !f.IsDir() { atomic.AddUint64(&fs.statCounter, 1) } } return f, err } // dynamicEvents contains events that is considered dynamic, as in "not static". // Both of these categories will trigger a new build, but the asset events // does not fit into the "navigate to changed" logic. type dynamicEvents struct { ContentEvents []fsnotify.Event AssetEvents []fsnotify.Event } type fileChangeDetector struct { sync.Mutex current map[string]string prev map[string]string irrelevantRe *regexp.Regexp } func (f *fileChangeDetector) OnFileClose(name, md5sum string) { f.Lock() defer f.Unlock() f.current[name] = md5sum } func (f *fileChangeDetector) PrepareNew() { if f == nil { return } f.Lock() defer f.Unlock() if f.current == nil { f.current = make(map[string]string) f.prev = make(map[string]string) return } f.prev = make(map[string]string) for k, v := range f.current { f.prev[k] = v } f.current = make(map[string]string) } func (f *fileChangeDetector) changed() []string { if f == nil { return nil } f.Lock() defer f.Unlock() var c []string for k, v := range f.current { vv, found := f.prev[k] if !found || v != vv { c = append(c, k) } } return f.filterIrrelevant(c) } func (f *fileChangeDetector) filterIrrelevant(in []string) []string { var filtered []string for _, v := range in { if !f.irrelevantRe.MatchString(v) { filtered = append(filtered, v) } } return filtered } type fileServer struct { baseURLs []string roots []string errorTemplate func(err any) (io.Reader, error) c *serverCommand } func (f *fileServer) createEndpoint(i int) (*http.ServeMux, net.Listener, string, string, error) { r := f.c.r baseURL := f.baseURLs[i] root := f.roots[i] port := f.c.serverPorts[i].p listener := f.c.serverPorts[i].ln logger := f.c.r.logger r.Printf("Environment: %q\n", f.c.hugoTry().Deps.Site.Hugo().Environment) if i == 0 { if f.c.renderToDisk { r.Println("Serving pages from disk") } else if f.c.renderStaticToDisk { r.Println("Serving pages from memory and static files from disk") } else { r.Println("Serving pages from memory") } } var httpFs *afero.HttpFs f.c.withConf(func(conf *commonConfig) { httpFs = afero.NewHttpFs(conf.fs.PublishDirServer) }) fs := filesOnlyFs{httpFs.Dir(path.Join("/", root))} if i == 0 && f.c.fastRenderMode { r.Println("Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender") } // We're only interested in the path u, err := url.Parse(baseURL) if err != nil { return nil, nil, "", "", fmt.Errorf("invalid baseURL: %w", err) } decorate := func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if f.c.showErrorInBrowser { // First check the error state err := f.c.getErrorWithContext() if err != nil { f.c.errState.setWasErr(true) w.WriteHeader(500) r, err := f.errorTemplate(err) if err != nil { logger.Errorln(err) } port = 1313 f.c.withConf(func(conf *commonConfig) { if lrport := conf.configs.GetFirstLanguageConfig().BaseURLLiveReload().Port(); lrport != 0 { port = lrport } }) lr := *u lr.Host = fmt.Sprintf("%s:%d", lr.Hostname(), port) fmt.Fprint(w, injectLiveReloadScript(r, lr)) return } } if f.c.noHTTPCache { w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0") w.Header().Set("Pragma", "no-cache") } var serverConfig config.Server f.c.withConf(func(conf *commonConfig) { serverConfig = conf.configs.Base.Server }) // Ignore any query params for the operations below. requestURI, _ := url.PathUnescape(strings.TrimSuffix(r.RequestURI, "?"+r.URL.RawQuery)) for _, header := range serverConfig.MatchHeaders(requestURI) { w.Header().Set(header.Key, header.Value) } if redirect := serverConfig.MatchRedirect(requestURI); !redirect.IsZero() { // fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))) doRedirect := true // This matches Netlify's behaviour and is needed for SPA behaviour. // See https://docs.netlify.com/routing/redirects/rewrites-proxies/ if !redirect.Force { path := filepath.Clean(strings.TrimPrefix(requestURI, u.Path)) if root != "" { path = filepath.Join(root, path) } var fs afero.Fs f.c.withConf(func(conf *commonConfig) { fs = conf.fs.PublishDirServer }) fi, err := fs.Stat(path) if err == nil { if fi.IsDir() { // There will be overlapping directories, so we // need to check for a file. _, err = fs.Stat(filepath.Join(path, "index.html")) doRedirect = err != nil } else { doRedirect = false } } } if doRedirect { switch redirect.Status { case 404: w.WriteHeader(404) file, err := fs.Open(strings.TrimPrefix(redirect.To, u.Path)) if err == nil { defer file.Close() io.Copy(w, file) } else { fmt.Fprintln(w, "<h1>Page Not Found</h1>") } return case 200: if r2 := f.rewriteRequest(r, strings.TrimPrefix(redirect.To, u.Path)); r2 != nil { requestURI = redirect.To r = r2 } default: w.Header().Set("Content-Type", "") http.Redirect(w, r, redirect.To, redirect.Status) return } } } if f.c.fastRenderMode && f.c.errState.buildErr() == nil { if strings.HasSuffix(requestURI, "/") || strings.HasSuffix(requestURI, "html") || strings.HasSuffix(requestURI, "htm") { if !f.c.visitedURLs.Contains(requestURI) { // If not already on stack, re-render that single page. if err := f.c.partialReRender(requestURI); err != nil { f.c.handleBuildErr(err, fmt.Sprintf("Failed to render %q", requestURI)) if f.c.showErrorInBrowser { http.Redirect(w, r, requestURI, http.StatusMovedPermanently) return } } } f.c.visitedURLs.Add(requestURI) } } h.ServeHTTP(w, r) }) } fileserver := decorate(http.FileServer(fs)) mu := http.NewServeMux() if u.Path == "" || u.Path == "/" { mu.Handle("/", fileserver) } else { mu.Handle(u.Path, http.StripPrefix(u.Path, fileserver)) } if r.IsTestRun() { var shutDownOnce sync.Once mu.HandleFunc("/__stop", func(w http.ResponseWriter, r *http.Request) { shutDownOnce.Do(func() { close(f.c.quit) }) }) } endpoint := net.JoinHostPort(f.c.serverInterface, strconv.Itoa(port)) return mu, listener, u.String(), endpoint, nil } func (f *fileServer) rewriteRequest(r *http.Request, toPath string) *http.Request { r2 := new(http.Request) *r2 = *r r2.URL = new(url.URL) *r2.URL = *r.URL r2.URL.Path = toPath r2.Header.Set("X-Rewrite-Original-URI", r.URL.RequestURI()) return r2 } type filesOnlyFs struct { fs http.FileSystem } func (fs filesOnlyFs) Open(name string) (http.File, error) { f, err := fs.fs.Open(name) if err != nil { return nil, err } return noDirFile{f}, nil } type noDirFile struct { http.File } func (f noDirFile) Readdir(count int) ([]os.FileInfo, error) { return nil, nil } type serverCommand struct { r *rootCommand commands []simplecobra.Commander *hugoBuilder quit chan bool // Closed when the server should shut down. Used in tests only. serverPorts []serverPortListener doLiveReload bool // Flags. renderToDisk bool renderStaticToDisk bool navigateToChanged bool serverAppend bool serverInterface string tlsCertFile string tlsKeyFile string tlsAuto bool serverPort int liveReloadPort int serverWatch bool noHTTPCache bool disableLiveReload bool disableFastRender bool disableBrowserError bool } func (c *serverCommand) Name() string { return "server" } func (c *serverCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { // Watch runs its own server as part of the routine if c.serverWatch { watchDirs, err := c.getDirList() if err != nil { return err } watchGroups := helpers.ExtractAndGroupRootPaths(watchDirs) for _, group := range watchGroups { c.r.Printf("Watching for changes in %s\n", group) } watcher, err := c.newWatcher(c.r.poll, watchDirs...) if err != nil { return err } defer watcher.Close() } err := func() error { defer c.r.timeTrack(time.Now(), "Built") err := c.build() return err }() if err != nil { return err } return c.serve() } func (c *serverCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "A high performance webserver" cmd.Long = `Hugo provides its own webserver which builds and serves the site. While hugo server is high performance, it is a webserver with limited options. 'hugo server' will avoid writing the rendered and served content to disk, preferring to store it in memory. By default hugo will also watch your files for any changes you make and automatically rebuild the site. It will then live reload any open browser pages and push the latest content to them. As most Hugo sites are built in a fraction of a second, you will be able to save and see your changes nearly instantly.` cmd.Aliases = []string{"serve"} cmd.Flags().IntVarP(&c.serverPort, "port", "p", 1313, "port on which the server will listen") cmd.Flags().IntVar(&c.liveReloadPort, "liveReloadPort", -1, "port for live reloading (i.e. 443 in HTTPS proxy situations)") cmd.Flags().StringVarP(&c.serverInterface, "bind", "", "127.0.0.1", "interface to which the server will bind") cmd.Flags().StringVarP(&c.tlsCertFile, "tlsCertFile", "", "", "path to TLS certificate file") cmd.Flags().StringVarP(&c.tlsKeyFile, "tlsKeyFile", "", "", "path to TLS key file") cmd.Flags().BoolVar(&c.tlsAuto, "tlsAuto", false, "generate and use locally-trusted certificates.") cmd.Flags().BoolVarP(&c.serverWatch, "watch", "w", true, "watch filesystem for changes and recreate as needed") cmd.Flags().BoolVar(&c.noHTTPCache, "noHTTPCache", false, "prevent HTTP caching") cmd.Flags().BoolVarP(&c.serverAppend, "appendPort", "", true, "append port to baseURL") cmd.Flags().BoolVar(&c.disableLiveReload, "disableLiveReload", false, "watch without enabling live browser reload on rebuild") cmd.Flags().BoolVar(&c.navigateToChanged, "navigateToChanged", false, "navigate to changed content file on live browser reload") cmd.Flags().BoolVar(&c.renderToDisk, "renderToDisk", false, "serve all files from disk (default is from memory)") cmd.Flags().BoolVar(&c.renderStaticToDisk, "renderStaticToDisk", false, "serve static files from disk and dynamic files from memory") cmd.Flags().BoolVar(&c.disableFastRender, "disableFastRender", false, "enables full re-renders on changes") cmd.Flags().BoolVar(&c.disableBrowserError, "disableBrowserError", false, "do not show build errors in the browser") cmd.Flags().String("memstats", "", "log memory usage to this file") cmd.Flags().String("meminterval", "100ms", "interval to poll memory usage (requires --memstats), valid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\".") cmd.Flags().SetAnnotation("tlsCertFile", cobra.BashCompSubdirsInDir, []string{}) cmd.Flags().SetAnnotation("tlsKeyFile", cobra.BashCompSubdirsInDir, []string{}) r := cd.Root.Command.(*rootCommand) applyLocalFlagsBuild(cmd, r) return nil } func (c *serverCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.r = cd.Root.Command.(*rootCommand) c.hugoBuilder = newHugoBuilder( c.r, c, func(reloaded bool) error { if !reloaded { if err := c.createServerPorts(cd); err != nil { return err } if (c.tlsCertFile == "" || c.tlsKeyFile == "") && c.tlsAuto { c.withConfE(func(conf *commonConfig) error { return c.createCertificates(conf) }) } } if err := c.setBaseURLsInConfig(); err != nil { return err } if !reloaded && c.fastRenderMode { c.withConf(func(conf *commonConfig) { conf.fs.PublishDir = hugofs.NewHashingFs(conf.fs.PublishDir, c.changeDetector) conf.fs.PublishDirStatic = hugofs.NewHashingFs(conf.fs.PublishDirStatic, c.changeDetector) }) } return nil }, ) destinationFlag := cd.CobraCommand.Flags().Lookup("destination") c.renderToDisk = c.renderToDisk || (destinationFlag != nil && destinationFlag.Changed) c.doLiveReload = !c.disableLiveReload c.fastRenderMode = !c.disableFastRender c.showErrorInBrowser = c.doLiveReload && !c.disableBrowserError if c.fastRenderMode { // For now, fast render mode only. It should, however, be fast enough // for the full variant, too. c.changeDetector = &fileChangeDetector{ // We use this detector to decide to do a Hot reload of a single path or not. // We need to filter out source maps and possibly some other to be able // to make that decision. irrelevantRe: regexp.MustCompile(`\.map$`), } c.changeDetector.PrepareNew() } err := c.loadConfig(cd, true) if err != nil { return err } return nil } func (c *serverCommand) setBaseURLsInConfig() error { if len(c.serverPorts) == 0 { panic("no server ports set") } return c.withConfE(func(conf *commonConfig) error { for i, language := range conf.configs.Languages { isMultiHost := conf.configs.IsMultihost var serverPort int if isMultiHost { serverPort = c.serverPorts[i].p } else { serverPort = c.serverPorts[0].p } langConfig := conf.configs.LanguageConfigMap[language.Lang] baseURLStr, err := c.fixURL(langConfig.BaseURL, c.r.baseURL, serverPort) if err != nil { return err } baseURL, err := urls.NewBaseURLFromString(baseURLStr) if err != nil { return fmt.Errorf("failed to create baseURL from %q: %s", baseURLStr, err) } baseURLLiveReload := baseURL if c.liveReloadPort != -1 { baseURLLiveReload, _ = baseURLLiveReload.WithPort(c.liveReloadPort) } langConfig.C.SetBaseURL(baseURL, baseURLLiveReload) } return nil }) } func (c *serverCommand) getErrorWithContext() any { errCount := c.errCount() if errCount == 0 { return nil } m := make(map[string]any) m["Error"] = cleanErrorLog(c.r.logger.Errors()) m["Version"] = hugo.BuildVersionString() ferrors := herrors.UnwrapFileErrorsWithErrorContext(c.errState.buildErr()) m["Files"] = ferrors return m } func (c *serverCommand) createCertificates(conf *commonConfig) error { hostname := "localhost" if c.r.baseURL != "" { u, err := url.Parse(c.r.baseURL) if err != nil { return err } hostname = u.Hostname() } // For now, store these in the Hugo cache dir. // Hugo should probably introduce some concept of a less temporary application directory. keyDir := filepath.Join(conf.configs.LoadingInfo.BaseConfig.CacheDir, "_mkcerts") // Create the directory if it doesn't exist. if _, err := os.Stat(keyDir); os.IsNotExist(err) { if err := os.MkdirAll(keyDir, 0777); err != nil { return err } } c.tlsCertFile = filepath.Join(keyDir, fmt.Sprintf("%s.pem", hostname)) c.tlsKeyFile = filepath.Join(keyDir, fmt.Sprintf("%s-key.pem", hostname)) // Check if the certificate already exists and is valid. certPEM, err := os.ReadFile(c.tlsCertFile) if err == nil { rootPem, err := os.ReadFile(filepath.Join(mclib.GetCAROOT(), "rootCA.pem")) if err == nil { if err := c.verifyCert(rootPem, certPEM, hostname); err == nil { c.r.Println("Using existing", c.tlsCertFile, "and", c.tlsKeyFile) return nil } } } c.r.Println("Creating TLS certificates in", keyDir) // Yes, this is unfortunate, but it's currently the only way to use Mkcert as a library. os.Args = []string{"-cert-file", c.tlsCertFile, "-key-file", c.tlsKeyFile, hostname} return mclib.RunMain() } func (c *serverCommand) verifyCert(rootPEM, certPEM []byte, name string) error { roots := x509.NewCertPool() ok := roots.AppendCertsFromPEM(rootPEM) if !ok { return fmt.Errorf("failed to parse root certificate") } block, _ := pem.Decode(certPEM) if block == nil { return fmt.Errorf("failed to parse certificate PEM") } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return fmt.Errorf("failed to parse certificate: %v", err.Error()) } opts := x509.VerifyOptions{ DNSName: name, Roots: roots, } if _, err := cert.Verify(opts); err != nil { return fmt.Errorf("failed to verify certificate: %v", err.Error()) } return nil } func (c *serverCommand) createServerPorts(cd *simplecobra.Commandeer) error { flags := cd.CobraCommand.Flags() var cerr error c.withConf(func(conf *commonConfig) { isMultiHost := conf.configs.IsMultihost c.serverPorts = make([]serverPortListener, 1) if isMultiHost { if !c.serverAppend { cerr = errors.New("--appendPort=false not supported when in multihost mode") return } c.serverPorts = make([]serverPortListener, len(conf.configs.Languages)) } currentServerPort := c.serverPort for i := 0; i < len(c.serverPorts); i++ { l, err := net.Listen("tcp", net.JoinHostPort(c.serverInterface, strconv.Itoa(currentServerPort))) if err == nil { c.serverPorts[i] = serverPortListener{ln: l, p: currentServerPort} } else { if i == 0 && flags.Changed("port") { // port set explicitly by user -- he/she probably meant it! cerr = fmt.Errorf("server startup failed: %s", err) return } c.r.Println("port", currentServerPort, "already in use, attempting to use an available port") l, sp, err := helpers.TCPListen() if err != nil { cerr = fmt.Errorf("unable to find alternative port to use: %s", err) return } c.serverPorts[i] = serverPortListener{ln: l, p: sp.Port} } currentServerPort = c.serverPorts[i].p + 1 } }) return cerr } // fixURL massages the baseURL into a form needed for serving // all pages correctly. func (c *serverCommand) fixURL(baseURLFromConfig, baseURLFromFlag string, port int) (string, error) { certsSet := (c.tlsCertFile != "" && c.tlsKeyFile != "") || c.tlsAuto useLocalhost := false baseURL := baseURLFromFlag if baseURL == "" { baseURL = baseURLFromConfig useLocalhost = true } if !strings.HasSuffix(baseURL, "/") { baseURL = baseURL + "/" } // do an initial parse of the input string u, err := url.Parse(baseURL) if err != nil { return "", err } // if no Host is defined, then assume that no schema or double-slash were // present in the url. Add a double-slash and make a best effort attempt. if u.Host == "" && baseURL != "/" { baseURL = "//" + baseURL u, err = url.Parse(baseURL) if err != nil { return "", err } } if useLocalhost { if certsSet { u.Scheme = "https" } else if u.Scheme == "https" { u.Scheme = "http" } u.Host = "localhost" } if c.serverAppend { if strings.Contains(u.Host, ":") { u.Host, _, err = net.SplitHostPort(u.Host) if err != nil { return "", fmt.Errorf("failed to split baseURL hostport: %w", err) } } u.Host += fmt.Sprintf(":%d", port) } return u.String(), nil } func (c *serverCommand) partialReRender(urls ...string) error { defer func() { c.errState.setWasErr(false) }() c.errState.setBuildErr(nil) visited := make(map[string]bool) for _, url := range urls { visited[url] = true } h, err := c.hugo() if err != nil { return err } // Note: We do not set NoBuildLock as the file lock is not acquired at this stage. return h.Build(hugolib.BuildCfg{NoBuildLock: false, RecentlyVisited: visited, PartialReRender: true, ErrRecovery: c.errState.wasErr()}) } func (c *serverCommand) serve() error { var ( baseURLs []string roots []string h *hugolib.HugoSites ) err := c.withConfE(func(conf *commonConfig) error { isMultiHost := conf.configs.IsMultihost var err error h, err = c.r.HugFromConfig(conf) if err != nil { return err } // We need the server to share the same logger as the Hugo build (for error counts etc.) c.r.logger = h.Log if isMultiHost { for _, l := range conf.configs.ConfigLangs() { baseURLs = append(baseURLs, l.BaseURL().String()) roots = append(roots, l.Language().Lang) } } else { l := conf.configs.GetFirstLanguageConfig() baseURLs = []string{l.BaseURL().String()} roots = []string{""} } return nil }) if err != nil { return err } // Cache it here. The HugoSites object may be unavailable later on due to intermittent configuration errors. // To allow the en user to change the error template while the server is running, we use // the freshest template we can provide. var ( errTempl tpl.Template templHandler tpl.TemplateHandler ) getErrorTemplateAndHandler := func(h *hugolib.HugoSites) (tpl.Template, tpl.TemplateHandler) { if h == nil { return errTempl, templHandler } templHandler := h.Tmpl() errTempl, found := templHandler.Lookup("_server/error.html") if !found { panic("template server/error.html not found") } return errTempl, templHandler } errTempl, templHandler = getErrorTemplateAndHandler(h) srv := &fileServer{ baseURLs: baseURLs, roots: roots, c: c, errorTemplate: func(ctx any) (io.Reader, error) { // hugoTry does not block, getErrorTemplateAndHandler will fall back // to cached values if nil. templ, handler := getErrorTemplateAndHandler(c.hugoTry()) b := &bytes.Buffer{} err := handler.ExecuteWithContext(context.Background(), templ, b, ctx) return b, err }, } doLiveReload := !c.disableLiveReload if doLiveReload { livereload.Initialize() } sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) var servers []*http.Server wg1, ctx := errgroup.WithContext(context.Background()) for i := range baseURLs { mu, listener, serverURL, endpoint, err := srv.createEndpoint(i) var srv *http.Server if c.tlsCertFile != "" && c.tlsKeyFile != "" { srv = &http.Server{ Addr: endpoint, Handler: mu, TLSConfig: &tls.Config{ MinVersion: tls.VersionTLS12, }, } } else { srv = &http.Server{ Addr: endpoint, Handler: mu, } } servers = append(servers, srv) if doLiveReload { u, err := url.Parse(helpers.SanitizeURL(baseURLs[i])) if err != nil { return err } mu.HandleFunc(u.Path+"/livereload.js", livereload.ServeJS) mu.HandleFunc(u.Path+"/livereload", livereload.Handler) } c.r.Printf("Web Server is available at %s (bind address %s)\n", serverURL, c.serverInterface) wg1.Go(func() error { if c.tlsCertFile != "" && c.tlsKeyFile != "" { err = srv.ServeTLS(listener, c.tlsCertFile, c.tlsKeyFile) } else { err = srv.Serve(listener) } if err != nil && err != http.ErrServerClosed { return err } return nil }) } if c.r.IsTestRun() { // Write a .ready file to disk to signal ready status. // This is where the test is run from. testInfo := map[string]any{ "baseURLs": srv.baseURLs, } dir := os.Getenv("WORK") if dir != "" { readyFile := filepath.Join(dir, ".ready") // encode the test info as JSON into the .ready file. b, err := json.Marshal(testInfo) if err != nil { return err } err = os.WriteFile(readyFile, b, 0777) if err != nil { return err } } } c.r.Println("Press Ctrl+C to stop") err = func() error { for { select { case <-c.quit: return nil case <-sigs: return nil case <-ctx.Done(): return ctx.Err() } } }() if err != nil { c.r.Println("Error:", err) } if h := c.hugoTry(); h != nil { h.Close() } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() wg2, ctx := errgroup.WithContext(ctx) for _, srv := range servers { srv := srv wg2.Go(func() error { return srv.Shutdown(ctx) }) } err1, err2 := wg1.Wait(), wg2.Wait() if err1 != nil { return err1 } return err2 } type serverPortListener struct { p int ln net.Listener } type staticSyncer struct { c *hugoBuilder } func (s *staticSyncer) isStatic(h *hugolib.HugoSites, filename string) bool { return h.BaseFs.SourceFilesystems.IsStatic(filename) } func (s *staticSyncer) syncsStaticEvents(staticEvents []fsnotify.Event) error { c := s.c syncFn := func(sourceFs *filesystems.SourceFilesystem) (uint64, error) { publishDir := helpers.FilePathSeparator if sourceFs.PublishFolder != "" { publishDir = filepath.Join(publishDir, sourceFs.PublishFolder) } syncer := fsync.NewSyncer() c.withConf(func(conf *commonConfig) { syncer.NoTimes = conf.configs.Base.NoTimes syncer.NoChmod = conf.configs.Base.NoChmod syncer.ChmodFilter = chmodFilter syncer.SrcFs = sourceFs.Fs syncer.DestFs = conf.fs.PublishDir if c.s != nil && c.s.renderStaticToDisk { syncer.DestFs = conf.fs.PublishDirStatic } }) logger := s.c.r.logger for _, ev := range staticEvents { // Due to our approach of layering both directories and the content's rendered output // into one we can't accurately remove a file not in one of the source directories. // If a file is in the local static dir and also in the theme static dir and we remove // it from one of those locations we expect it to still exist in the destination // // If Hugo generates a file (from the content dir) over a static file // the content generated file should take precedence. // // Because we are now watching and handling individual events it is possible that a static // event that occupies the same path as a content generated file will take precedence // until a regeneration of the content takes places. // // Hugo assumes that these cases are very rare and will permit this bad behavior // The alternative is to track every single file and which pipeline rendered it // and then to handle conflict resolution on every event. fromPath := ev.Name relPath, found := sourceFs.MakePathRelative(fromPath) if !found { // Not member of this virtual host. continue } // Remove || rename is harder and will require an assumption. // Hugo takes the following approach: // If the static file exists in any of the static source directories after this event // Hugo will re-sync it. // If it does not exist in all of the static directories Hugo will remove it. // // This assumes that Hugo has not generated content on top of a static file and then removed // the source of that static file. In this case Hugo will incorrectly remove that file // from the published directory. if ev.Op&fsnotify.Rename == fsnotify.Rename || ev.Op&fsnotify.Remove == fsnotify.Remove { if _, err := sourceFs.Fs.Stat(relPath); herrors.IsNotExist(err) { // If file doesn't exist in any static dir, remove it logger.Println("File no longer exists in static dir, removing", relPath) c.withConf(func(conf *commonConfig) { _ = conf.fs.PublishDirStatic.RemoveAll(relPath) }) } else if err == nil { // If file still exists, sync it logger.Println("Syncing", relPath, "to", publishDir) if err := syncer.Sync(relPath, relPath); err != nil { c.r.logger.Errorln(err) } } else { c.r.logger.Errorln(err) } continue } // For all other event operations Hugo will sync static. logger.Println("Syncing", relPath, "to", publishDir) if err := syncer.Sync(filepath.Join(publishDir, relPath), relPath); err != nil { c.r.logger.Errorln(err) } } return 0, nil } _, err := c.doWithPublishDirs(syncFn) return err } func chmodFilter(dst, src os.FileInfo) bool { // Hugo publishes data from multiple sources, potentially // with overlapping directory structures. We cannot sync permissions // for directories as that would mean that we might end up with write-protected // directories inside /public. // One example of this would be syncing from the Go Module cache, // which have 0555 directories. return src.IsDir() } func cleanErrorLog(content string) string { content = strings.ReplaceAll(content, "\n", " ") content = logReplacer.Replace(content) content = logDuplicateTemplateExecuteRe.ReplaceAllString(content, "") content = logDuplicateTemplateParseRe.ReplaceAllString(content, "") seen := make(map[string]bool) parts := strings.Split(content, ": ") keep := make([]string, 0, len(parts)) for _, part := range parts { if seen[part] { continue } seen[part] = true keep = append(keep, part) } return strings.Join(keep, ": ") } func injectLiveReloadScript(src io.Reader, baseURL url.URL) string { var b bytes.Buffer chain := transform.Chain{livereloadinject.New(baseURL)} chain.Apply(&b, src) return b.String() } func partitionDynamicEvents(sourceFs *filesystems.SourceFilesystems, events []fsnotify.Event) (de dynamicEvents) { for _, e := range events { if !sourceFs.IsContent(e.Name) { de.AssetEvents = append(de.AssetEvents, e) } else { de.ContentEvents = append(de.ContentEvents, e) } } return } func pickOneWriteOrCreatePath(events []fsnotify.Event) string { name := "" for _, ev := range events { if ev.Op&fsnotify.Write == fsnotify.Write || ev.Op&fsnotify.Create == fsnotify.Create { if files.IsIndexContentFile(ev.Name) { return ev.Name } if files.IsContentFile(ev.Name) { name = ev.Name } } } return name } func formatByteCount(b uint64) string { const unit = 1000 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := int64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) }
// Copyright 2023 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 commands import ( "bytes" "context" "crypto/tls" "crypto/x509" "encoding/json" "encoding/pem" "errors" "fmt" "io" "net" "net/http" "net/url" "os" "sync" "sync/atomic" "github.com/bep/mclib" "os/signal" "path" "path/filepath" "regexp" "strconv" "strings" "syscall" "time" "github.com/bep/debounce" "github.com/bep/simplecobra" "github.com/fsnotify/fsnotify" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/common/urls" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/livereload" "github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/transform" "github.com/gohugoio/hugo/transform/livereloadinject" "github.com/spf13/afero" "github.com/spf13/cobra" "github.com/spf13/fsync" "golang.org/x/sync/errgroup" "golang.org/x/sync/semaphore" ) var ( logDuplicateTemplateExecuteRe = regexp.MustCompile(`: template: .*?:\d+:\d+: executing ".*?"`) logDuplicateTemplateParseRe = regexp.MustCompile(`: template: .*?:\d+:\d*`) ) var logReplacer = strings.NewReplacer( "can't", "can’t", // Chroma lexer doesn't do well with "can't" "*hugolib.pageState", "page.Page", // Page is the public interface. "Rebuild failed:", "", ) const ( configChangeConfig = "config file" configChangeGoMod = "go.mod file" configChangeGoWork = "go work file" ) func newHugoBuilder(r *rootCommand, s *serverCommand, onConfigLoaded ...func(reloaded bool) error) *hugoBuilder { return &hugoBuilder{ r: r, s: s, visitedURLs: types.NewEvictingStringQueue(100), fullRebuildSem: semaphore.NewWeighted(1), debounce: debounce.New(4 * time.Second), onConfigLoaded: func(reloaded bool) error { for _, wc := range onConfigLoaded { if err := wc(reloaded); err != nil { return err } } return nil }, } } func newServerCommand() *serverCommand { // Flags. var uninstall bool c := &serverCommand{ quit: make(chan bool), commands: []simplecobra.Commander{ &simpleCommand{ name: "trust", short: "Install the local CA in the system trust store.", run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { action := "-install" if uninstall { action = "-uninstall" } os.Args = []string{action} return mclib.RunMain() }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVar(&uninstall, "uninstall", false, "Uninstall the local CA (but do not delete it).") }, }, }, } return c } func (c *serverCommand) Commands() []simplecobra.Commander { return c.commands } type countingStatFs struct { afero.Fs statCounter uint64 } func (fs *countingStatFs) Stat(name string) (os.FileInfo, error) { f, err := fs.Fs.Stat(name) if err == nil { if !f.IsDir() { atomic.AddUint64(&fs.statCounter, 1) } } return f, err } // dynamicEvents contains events that is considered dynamic, as in "not static". // Both of these categories will trigger a new build, but the asset events // does not fit into the "navigate to changed" logic. type dynamicEvents struct { ContentEvents []fsnotify.Event AssetEvents []fsnotify.Event } type fileChangeDetector struct { sync.Mutex current map[string]string prev map[string]string irrelevantRe *regexp.Regexp } func (f *fileChangeDetector) OnFileClose(name, md5sum string) { f.Lock() defer f.Unlock() f.current[name] = md5sum } func (f *fileChangeDetector) PrepareNew() { if f == nil { return } f.Lock() defer f.Unlock() if f.current == nil { f.current = make(map[string]string) f.prev = make(map[string]string) return } f.prev = make(map[string]string) for k, v := range f.current { f.prev[k] = v } f.current = make(map[string]string) } func (f *fileChangeDetector) changed() []string { if f == nil { return nil } f.Lock() defer f.Unlock() var c []string for k, v := range f.current { vv, found := f.prev[k] if !found || v != vv { c = append(c, k) } } return f.filterIrrelevant(c) } func (f *fileChangeDetector) filterIrrelevant(in []string) []string { var filtered []string for _, v := range in { if !f.irrelevantRe.MatchString(v) { filtered = append(filtered, v) } } return filtered } type fileServer struct { baseURLs []string roots []string errorTemplate func(err any) (io.Reader, error) c *serverCommand } func (f *fileServer) createEndpoint(i int) (*http.ServeMux, net.Listener, string, string, error) { r := f.c.r baseURL := f.baseURLs[i] root := f.roots[i] port := f.c.serverPorts[i].p listener := f.c.serverPorts[i].ln logger := f.c.r.logger r.Printf("Environment: %q\n", f.c.hugoTry().Deps.Site.Hugo().Environment) if i == 0 { if f.c.renderToDisk { r.Println("Serving pages from disk") } else if f.c.renderStaticToDisk { r.Println("Serving pages from memory and static files from disk") } else { r.Println("Serving pages from memory") } } var httpFs *afero.HttpFs f.c.withConf(func(conf *commonConfig) { httpFs = afero.NewHttpFs(conf.fs.PublishDirServer) }) fs := filesOnlyFs{httpFs.Dir(path.Join("/", root))} if i == 0 && f.c.fastRenderMode { r.Println("Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender") } // We're only interested in the path u, err := url.Parse(baseURL) if err != nil { return nil, nil, "", "", fmt.Errorf("invalid baseURL: %w", err) } decorate := func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if f.c.showErrorInBrowser { // First check the error state err := f.c.getErrorWithContext() if err != nil { f.c.errState.setWasErr(true) w.WriteHeader(500) r, err := f.errorTemplate(err) if err != nil { logger.Errorln(err) } port = 1313 f.c.withConf(func(conf *commonConfig) { if lrport := conf.configs.GetFirstLanguageConfig().BaseURLLiveReload().Port(); lrport != 0 { port = lrport } }) lr := *u lr.Host = fmt.Sprintf("%s:%d", lr.Hostname(), port) fmt.Fprint(w, injectLiveReloadScript(r, lr)) return } } if f.c.noHTTPCache { w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0") w.Header().Set("Pragma", "no-cache") } var serverConfig config.Server f.c.withConf(func(conf *commonConfig) { serverConfig = conf.configs.Base.Server }) // Ignore any query params for the operations below. requestURI, _ := url.PathUnescape(strings.TrimSuffix(r.RequestURI, "?"+r.URL.RawQuery)) for _, header := range serverConfig.MatchHeaders(requestURI) { w.Header().Set(header.Key, header.Value) } if redirect := serverConfig.MatchRedirect(requestURI); !redirect.IsZero() { // fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))) doRedirect := true // This matches Netlify's behaviour and is needed for SPA behaviour. // See https://docs.netlify.com/routing/redirects/rewrites-proxies/ if !redirect.Force { path := filepath.Clean(strings.TrimPrefix(requestURI, u.Path)) if root != "" { path = filepath.Join(root, path) } var fs afero.Fs f.c.withConf(func(conf *commonConfig) { fs = conf.fs.PublishDirServer }) fi, err := fs.Stat(path) if err == nil { if fi.IsDir() { // There will be overlapping directories, so we // need to check for a file. _, err = fs.Stat(filepath.Join(path, "index.html")) doRedirect = err != nil } else { doRedirect = false } } } if doRedirect { switch redirect.Status { case 404: w.WriteHeader(404) file, err := fs.Open(strings.TrimPrefix(redirect.To, u.Path)) if err == nil { defer file.Close() io.Copy(w, file) } else { fmt.Fprintln(w, "<h1>Page Not Found</h1>") } return case 200: if r2 := f.rewriteRequest(r, strings.TrimPrefix(redirect.To, u.Path)); r2 != nil { requestURI = redirect.To r = r2 } default: w.Header().Set("Content-Type", "") http.Redirect(w, r, redirect.To, redirect.Status) return } } } if f.c.fastRenderMode && f.c.errState.buildErr() == nil { if strings.HasSuffix(requestURI, "/") || strings.HasSuffix(requestURI, "html") || strings.HasSuffix(requestURI, "htm") { if !f.c.visitedURLs.Contains(requestURI) { // If not already on stack, re-render that single page. if err := f.c.partialReRender(requestURI); err != nil { f.c.handleBuildErr(err, fmt.Sprintf("Failed to render %q", requestURI)) if f.c.showErrorInBrowser { http.Redirect(w, r, requestURI, http.StatusMovedPermanently) return } } } f.c.visitedURLs.Add(requestURI) } } h.ServeHTTP(w, r) }) } fileserver := decorate(http.FileServer(fs)) mu := http.NewServeMux() if u.Path == "" || u.Path == "/" { mu.Handle("/", fileserver) } else { mu.Handle(u.Path, http.StripPrefix(u.Path, fileserver)) } if r.IsTestRun() { var shutDownOnce sync.Once mu.HandleFunc("/__stop", func(w http.ResponseWriter, r *http.Request) { shutDownOnce.Do(func() { close(f.c.quit) }) }) } endpoint := net.JoinHostPort(f.c.serverInterface, strconv.Itoa(port)) return mu, listener, u.String(), endpoint, nil } func (f *fileServer) rewriteRequest(r *http.Request, toPath string) *http.Request { r2 := new(http.Request) *r2 = *r r2.URL = new(url.URL) *r2.URL = *r.URL r2.URL.Path = toPath r2.Header.Set("X-Rewrite-Original-URI", r.URL.RequestURI()) return r2 } type filesOnlyFs struct { fs http.FileSystem } func (fs filesOnlyFs) Open(name string) (http.File, error) { f, err := fs.fs.Open(name) if err != nil { return nil, err } return noDirFile{f}, nil } type noDirFile struct { http.File } func (f noDirFile) Readdir(count int) ([]os.FileInfo, error) { return nil, nil } type serverCommand struct { r *rootCommand commands []simplecobra.Commander *hugoBuilder quit chan bool // Closed when the server should shut down. Used in tests only. serverPorts []serverPortListener doLiveReload bool // Flags. renderToDisk bool renderStaticToDisk bool navigateToChanged bool serverAppend bool serverInterface string tlsCertFile string tlsKeyFile string tlsAuto bool serverPort int liveReloadPort int serverWatch bool noHTTPCache bool disableLiveReload bool disableFastRender bool disableBrowserError bool } func (c *serverCommand) Name() string { return "server" } func (c *serverCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { // Watch runs its own server as part of the routine if c.serverWatch { watchDirs, err := c.getDirList() if err != nil { return err } watchGroups := helpers.ExtractAndGroupRootPaths(watchDirs) for _, group := range watchGroups { c.r.Printf("Watching for changes in %s\n", group) } watcher, err := c.newWatcher(c.r.poll, watchDirs...) if err != nil { return err } defer watcher.Close() } err := func() error { defer c.r.timeTrack(time.Now(), "Built") err := c.build() return err }() if err != nil { return err } return c.serve() } func (c *serverCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "A high performance webserver" cmd.Long = `Hugo provides its own webserver which builds and serves the site. While hugo server is high performance, it is a webserver with limited options. 'hugo server' will avoid writing the rendered and served content to disk, preferring to store it in memory. By default hugo will also watch your files for any changes you make and automatically rebuild the site. It will then live reload any open browser pages and push the latest content to them. As most Hugo sites are built in a fraction of a second, you will be able to save and see your changes nearly instantly.` cmd.Aliases = []string{"serve"} cmd.Flags().IntVarP(&c.serverPort, "port", "p", 1313, "port on which the server will listen") cmd.Flags().IntVar(&c.liveReloadPort, "liveReloadPort", -1, "port for live reloading (i.e. 443 in HTTPS proxy situations)") cmd.Flags().StringVarP(&c.serverInterface, "bind", "", "127.0.0.1", "interface to which the server will bind") cmd.Flags().StringVarP(&c.tlsCertFile, "tlsCertFile", "", "", "path to TLS certificate file") cmd.Flags().StringVarP(&c.tlsKeyFile, "tlsKeyFile", "", "", "path to TLS key file") cmd.Flags().BoolVar(&c.tlsAuto, "tlsAuto", false, "generate and use locally-trusted certificates.") cmd.Flags().BoolVarP(&c.serverWatch, "watch", "w", true, "watch filesystem for changes and recreate as needed") cmd.Flags().BoolVar(&c.noHTTPCache, "noHTTPCache", false, "prevent HTTP caching") cmd.Flags().BoolVarP(&c.serverAppend, "appendPort", "", true, "append port to baseURL") cmd.Flags().BoolVar(&c.disableLiveReload, "disableLiveReload", false, "watch without enabling live browser reload on rebuild") cmd.Flags().BoolVar(&c.navigateToChanged, "navigateToChanged", false, "navigate to changed content file on live browser reload") cmd.Flags().BoolVar(&c.renderToDisk, "renderToDisk", false, "serve all files from disk (default is from memory)") cmd.Flags().BoolVar(&c.renderStaticToDisk, "renderStaticToDisk", false, "serve static files from disk and dynamic files from memory") cmd.Flags().BoolVar(&c.disableFastRender, "disableFastRender", false, "enables full re-renders on changes") cmd.Flags().BoolVar(&c.disableBrowserError, "disableBrowserError", false, "do not show build errors in the browser") cmd.Flags().String("memstats", "", "log memory usage to this file") cmd.Flags().String("meminterval", "100ms", "interval to poll memory usage (requires --memstats), valid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\".") cmd.Flags().SetAnnotation("tlsCertFile", cobra.BashCompSubdirsInDir, []string{}) cmd.Flags().SetAnnotation("tlsKeyFile", cobra.BashCompSubdirsInDir, []string{}) r := cd.Root.Command.(*rootCommand) applyLocalFlagsBuild(cmd, r) return nil } func (c *serverCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.r = cd.Root.Command.(*rootCommand) c.hugoBuilder = newHugoBuilder( c.r, c, func(reloaded bool) error { if !reloaded { if err := c.createServerPorts(cd); err != nil { return err } if (c.tlsCertFile == "" || c.tlsKeyFile == "") && c.tlsAuto { c.withConfE(func(conf *commonConfig) error { return c.createCertificates(conf) }) } } if err := c.setBaseURLsInConfig(); err != nil { return err } if !reloaded && c.fastRenderMode { c.withConf(func(conf *commonConfig) { conf.fs.PublishDir = hugofs.NewHashingFs(conf.fs.PublishDir, c.changeDetector) conf.fs.PublishDirStatic = hugofs.NewHashingFs(conf.fs.PublishDirStatic, c.changeDetector) }) } return nil }, ) destinationFlag := cd.CobraCommand.Flags().Lookup("destination") c.renderToDisk = c.renderToDisk || (destinationFlag != nil && destinationFlag.Changed) c.doLiveReload = !c.disableLiveReload c.fastRenderMode = !c.disableFastRender c.showErrorInBrowser = c.doLiveReload && !c.disableBrowserError if c.fastRenderMode { // For now, fast render mode only. It should, however, be fast enough // for the full variant, too. c.changeDetector = &fileChangeDetector{ // We use this detector to decide to do a Hot reload of a single path or not. // We need to filter out source maps and possibly some other to be able // to make that decision. irrelevantRe: regexp.MustCompile(`\.map$`), } c.changeDetector.PrepareNew() } err := c.loadConfig(cd, true) if err != nil { return err } return nil } func (c *serverCommand) setBaseURLsInConfig() error { if len(c.serverPorts) == 0 { panic("no server ports set") } return c.withConfE(func(conf *commonConfig) error { for i, language := range conf.configs.Languages { isMultiHost := conf.configs.IsMultihost var serverPort int if isMultiHost { serverPort = c.serverPorts[i].p } else { serverPort = c.serverPorts[0].p } langConfig := conf.configs.LanguageConfigMap[language.Lang] baseURLStr, err := c.fixURL(langConfig.BaseURL, c.r.baseURL, serverPort) if err != nil { return err } baseURL, err := urls.NewBaseURLFromString(baseURLStr) if err != nil { return fmt.Errorf("failed to create baseURL from %q: %s", baseURLStr, err) } baseURLLiveReload := baseURL if c.liveReloadPort != -1 { baseURLLiveReload, _ = baseURLLiveReload.WithPort(c.liveReloadPort) } langConfig.C.SetBaseURL(baseURL, baseURLLiveReload) } return nil }) } func (c *serverCommand) getErrorWithContext() any { errCount := c.errCount() if errCount == 0 { return nil } m := make(map[string]any) m["Error"] = cleanErrorLog(c.r.logger.Errors()) m["Version"] = hugo.BuildVersionString() ferrors := herrors.UnwrapFileErrorsWithErrorContext(c.errState.buildErr()) m["Files"] = ferrors return m } func (c *serverCommand) createCertificates(conf *commonConfig) error { hostname := "localhost" if c.r.baseURL != "" { u, err := url.Parse(c.r.baseURL) if err != nil { return err } hostname = u.Hostname() } // For now, store these in the Hugo cache dir. // Hugo should probably introduce some concept of a less temporary application directory. keyDir := filepath.Join(conf.configs.LoadingInfo.BaseConfig.CacheDir, "_mkcerts") // Create the directory if it doesn't exist. if _, err := os.Stat(keyDir); os.IsNotExist(err) { if err := os.MkdirAll(keyDir, 0777); err != nil { return err } } c.tlsCertFile = filepath.Join(keyDir, fmt.Sprintf("%s.pem", hostname)) c.tlsKeyFile = filepath.Join(keyDir, fmt.Sprintf("%s-key.pem", hostname)) // Check if the certificate already exists and is valid. certPEM, err := os.ReadFile(c.tlsCertFile) if err == nil { rootPem, err := os.ReadFile(filepath.Join(mclib.GetCAROOT(), "rootCA.pem")) if err == nil { if err := c.verifyCert(rootPem, certPEM, hostname); err == nil { c.r.Println("Using existing", c.tlsCertFile, "and", c.tlsKeyFile) return nil } } } c.r.Println("Creating TLS certificates in", keyDir) // Yes, this is unfortunate, but it's currently the only way to use Mkcert as a library. os.Args = []string{"-cert-file", c.tlsCertFile, "-key-file", c.tlsKeyFile, hostname} return mclib.RunMain() } func (c *serverCommand) verifyCert(rootPEM, certPEM []byte, name string) error { roots := x509.NewCertPool() ok := roots.AppendCertsFromPEM(rootPEM) if !ok { return fmt.Errorf("failed to parse root certificate") } block, _ := pem.Decode(certPEM) if block == nil { return fmt.Errorf("failed to parse certificate PEM") } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return fmt.Errorf("failed to parse certificate: %v", err.Error()) } opts := x509.VerifyOptions{ DNSName: name, Roots: roots, } if _, err := cert.Verify(opts); err != nil { return fmt.Errorf("failed to verify certificate: %v", err.Error()) } return nil } func (c *serverCommand) createServerPorts(cd *simplecobra.Commandeer) error { flags := cd.CobraCommand.Flags() var cerr error c.withConf(func(conf *commonConfig) { isMultiHost := conf.configs.IsMultihost c.serverPorts = make([]serverPortListener, 1) if isMultiHost { if !c.serverAppend { cerr = errors.New("--appendPort=false not supported when in multihost mode") return } c.serverPorts = make([]serverPortListener, len(conf.configs.Languages)) } currentServerPort := c.serverPort for i := 0; i < len(c.serverPorts); i++ { l, err := net.Listen("tcp", net.JoinHostPort(c.serverInterface, strconv.Itoa(currentServerPort))) if err == nil { c.serverPorts[i] = serverPortListener{ln: l, p: currentServerPort} } else { if i == 0 && flags.Changed("port") { // port set explicitly by user -- he/she probably meant it! cerr = fmt.Errorf("server startup failed: %s", err) return } c.r.Println("port", currentServerPort, "already in use, attempting to use an available port") l, sp, err := helpers.TCPListen() if err != nil { cerr = fmt.Errorf("unable to find alternative port to use: %s", err) return } c.serverPorts[i] = serverPortListener{ln: l, p: sp.Port} } currentServerPort = c.serverPorts[i].p + 1 } }) return cerr } // fixURL massages the baseURL into a form needed for serving // all pages correctly. func (c *serverCommand) fixURL(baseURLFromConfig, baseURLFromFlag string, port int) (string, error) { certsSet := (c.tlsCertFile != "" && c.tlsKeyFile != "") || c.tlsAuto useLocalhost := false baseURL := baseURLFromFlag if baseURL == "" { baseURL = baseURLFromConfig useLocalhost = true } if !strings.HasSuffix(baseURL, "/") { baseURL = baseURL + "/" } // do an initial parse of the input string u, err := url.Parse(baseURL) if err != nil { return "", err } // if no Host is defined, then assume that no schema or double-slash were // present in the url. Add a double-slash and make a best effort attempt. if u.Host == "" && baseURL != "/" { baseURL = "//" + baseURL u, err = url.Parse(baseURL) if err != nil { return "", err } } if useLocalhost { if certsSet { u.Scheme = "https" } else if u.Scheme == "https" { u.Scheme = "http" } u.Host = "localhost" } if c.serverAppend { if strings.Contains(u.Host, ":") { u.Host, _, err = net.SplitHostPort(u.Host) if err != nil { return "", fmt.Errorf("failed to split baseURL hostport: %w", err) } } u.Host += fmt.Sprintf(":%d", port) } return u.String(), nil } func (c *serverCommand) partialReRender(urls ...string) error { defer func() { c.errState.setWasErr(false) }() c.errState.setBuildErr(nil) visited := make(map[string]bool) for _, url := range urls { visited[url] = true } h, err := c.hugo() if err != nil { return err } // Note: We do not set NoBuildLock as the file lock is not acquired at this stage. return h.Build(hugolib.BuildCfg{NoBuildLock: false, RecentlyVisited: visited, PartialReRender: true, ErrRecovery: c.errState.wasErr()}) } func (c *serverCommand) serve() error { var ( baseURLs []string roots []string h *hugolib.HugoSites ) err := c.withConfE(func(conf *commonConfig) error { isMultiHost := conf.configs.IsMultihost var err error h, err = c.r.HugFromConfig(conf) if err != nil { return err } // We need the server to share the same logger as the Hugo build (for error counts etc.) c.r.logger = h.Log if isMultiHost { for _, l := range conf.configs.ConfigLangs() { baseURLs = append(baseURLs, l.BaseURL().String()) roots = append(roots, l.Language().Lang) } } else { l := conf.configs.GetFirstLanguageConfig() baseURLs = []string{l.BaseURL().String()} roots = []string{""} } return nil }) if err != nil { return err } // Cache it here. The HugoSites object may be unavailable later on due to intermittent configuration errors. // To allow the en user to change the error template while the server is running, we use // the freshest template we can provide. var ( errTempl tpl.Template templHandler tpl.TemplateHandler ) getErrorTemplateAndHandler := func(h *hugolib.HugoSites) (tpl.Template, tpl.TemplateHandler) { if h == nil { return errTempl, templHandler } templHandler := h.Tmpl() errTempl, found := templHandler.Lookup("_server/error.html") if !found { panic("template server/error.html not found") } return errTempl, templHandler } errTempl, templHandler = getErrorTemplateAndHandler(h) srv := &fileServer{ baseURLs: baseURLs, roots: roots, c: c, errorTemplate: func(ctx any) (io.Reader, error) { // hugoTry does not block, getErrorTemplateAndHandler will fall back // to cached values if nil. templ, handler := getErrorTemplateAndHandler(c.hugoTry()) b := &bytes.Buffer{} err := handler.ExecuteWithContext(context.Background(), templ, b, ctx) return b, err }, } doLiveReload := !c.disableLiveReload if doLiveReload { livereload.Initialize() } sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) var servers []*http.Server wg1, ctx := errgroup.WithContext(context.Background()) for i := range baseURLs { mu, listener, serverURL, endpoint, err := srv.createEndpoint(i) var srv *http.Server if c.tlsCertFile != "" && c.tlsKeyFile != "" { srv = &http.Server{ Addr: endpoint, Handler: mu, TLSConfig: &tls.Config{ MinVersion: tls.VersionTLS12, }, } } else { srv = &http.Server{ Addr: endpoint, Handler: mu, } } servers = append(servers, srv) if doLiveReload { u, err := url.Parse(helpers.SanitizeURL(baseURLs[i])) if err != nil { return err } mu.HandleFunc(u.Path+"/livereload.js", livereload.ServeJS) mu.HandleFunc(u.Path+"/livereload", livereload.Handler) } c.r.Printf("Web Server is available at %s (bind address %s) %s\n", serverURL, c.serverInterface, roots[i]) wg1.Go(func() error { if c.tlsCertFile != "" && c.tlsKeyFile != "" { err = srv.ServeTLS(listener, c.tlsCertFile, c.tlsKeyFile) } else { err = srv.Serve(listener) } if err != nil && err != http.ErrServerClosed { return err } return nil }) } if c.r.IsTestRun() { // Write a .ready file to disk to signal ready status. // This is where the test is run from. testInfo := map[string]any{ "baseURLs": srv.baseURLs, } dir := os.Getenv("WORK") if dir != "" { readyFile := filepath.Join(dir, ".ready") // encode the test info as JSON into the .ready file. b, err := json.Marshal(testInfo) if err != nil { return err } err = os.WriteFile(readyFile, b, 0777) if err != nil { return err } } } c.r.Println("Press Ctrl+C to stop") err = func() error { for { select { case <-c.quit: return nil case <-sigs: return nil case <-ctx.Done(): return ctx.Err() } } }() if err != nil { c.r.Println("Error:", err) } if h := c.hugoTry(); h != nil { h.Close() } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() wg2, ctx := errgroup.WithContext(ctx) for _, srv := range servers { srv := srv wg2.Go(func() error { return srv.Shutdown(ctx) }) } err1, err2 := wg1.Wait(), wg2.Wait() if err1 != nil { return err1 } return err2 } type serverPortListener struct { p int ln net.Listener } type staticSyncer struct { c *hugoBuilder } func (s *staticSyncer) isStatic(h *hugolib.HugoSites, filename string) bool { return h.BaseFs.SourceFilesystems.IsStatic(filename) } func (s *staticSyncer) syncsStaticEvents(staticEvents []fsnotify.Event) error { c := s.c syncFn := func(sourceFs *filesystems.SourceFilesystem) (uint64, error) { publishDir := helpers.FilePathSeparator if sourceFs.PublishFolder != "" { publishDir = filepath.Join(publishDir, sourceFs.PublishFolder) } syncer := fsync.NewSyncer() c.withConf(func(conf *commonConfig) { syncer.NoTimes = conf.configs.Base.NoTimes syncer.NoChmod = conf.configs.Base.NoChmod syncer.ChmodFilter = chmodFilter syncer.SrcFs = sourceFs.Fs syncer.DestFs = conf.fs.PublishDir if c.s != nil && c.s.renderStaticToDisk { syncer.DestFs = conf.fs.PublishDirStatic } }) logger := s.c.r.logger for _, ev := range staticEvents { // Due to our approach of layering both directories and the content's rendered output // into one we can't accurately remove a file not in one of the source directories. // If a file is in the local static dir and also in the theme static dir and we remove // it from one of those locations we expect it to still exist in the destination // // If Hugo generates a file (from the content dir) over a static file // the content generated file should take precedence. // // Because we are now watching and handling individual events it is possible that a static // event that occupies the same path as a content generated file will take precedence // until a regeneration of the content takes places. // // Hugo assumes that these cases are very rare and will permit this bad behavior // The alternative is to track every single file and which pipeline rendered it // and then to handle conflict resolution on every event. fromPath := ev.Name relPath, found := sourceFs.MakePathRelative(fromPath) if !found { // Not member of this virtual host. continue } // Remove || rename is harder and will require an assumption. // Hugo takes the following approach: // If the static file exists in any of the static source directories after this event // Hugo will re-sync it. // If it does not exist in all of the static directories Hugo will remove it. // // This assumes that Hugo has not generated content on top of a static file and then removed // the source of that static file. In this case Hugo will incorrectly remove that file // from the published directory. if ev.Op&fsnotify.Rename == fsnotify.Rename || ev.Op&fsnotify.Remove == fsnotify.Remove { if _, err := sourceFs.Fs.Stat(relPath); herrors.IsNotExist(err) { // If file doesn't exist in any static dir, remove it logger.Println("File no longer exists in static dir, removing", relPath) c.withConf(func(conf *commonConfig) { _ = conf.fs.PublishDirStatic.RemoveAll(relPath) }) } else if err == nil { // If file still exists, sync it logger.Println("Syncing", relPath, "to", publishDir) if err := syncer.Sync(relPath, relPath); err != nil { c.r.logger.Errorln(err) } } else { c.r.logger.Errorln(err) } continue } // For all other event operations Hugo will sync static. logger.Println("Syncing", relPath, "to", publishDir) if err := syncer.Sync(filepath.Join(publishDir, relPath), relPath); err != nil { c.r.logger.Errorln(err) } } return 0, nil } _, err := c.doWithPublishDirs(syncFn) return err } func chmodFilter(dst, src os.FileInfo) bool { // Hugo publishes data from multiple sources, potentially // with overlapping directory structures. We cannot sync permissions // for directories as that would mean that we might end up with write-protected // directories inside /public. // One example of this would be syncing from the Go Module cache, // which have 0555 directories. return src.IsDir() } func cleanErrorLog(content string) string { content = strings.ReplaceAll(content, "\n", " ") content = logReplacer.Replace(content) content = logDuplicateTemplateExecuteRe.ReplaceAllString(content, "") content = logDuplicateTemplateParseRe.ReplaceAllString(content, "") seen := make(map[string]bool) parts := strings.Split(content, ": ") keep := make([]string, 0, len(parts)) for _, part := range parts { if seen[part] { continue } seen[part] = true keep = append(keep, part) } return strings.Join(keep, ": ") } func injectLiveReloadScript(src io.Reader, baseURL url.URL) string { var b bytes.Buffer chain := transform.Chain{livereloadinject.New(baseURL)} chain.Apply(&b, src) return b.String() } func partitionDynamicEvents(sourceFs *filesystems.SourceFilesystems, events []fsnotify.Event) (de dynamicEvents) { for _, e := range events { if !sourceFs.IsContent(e.Name) { de.AssetEvents = append(de.AssetEvents, e) } else { de.ContentEvents = append(de.ContentEvents, e) } } return } func pickOneWriteOrCreatePath(events []fsnotify.Event) string { name := "" for _, ev := range events { if ev.Op&fsnotify.Write == fsnotify.Write || ev.Op&fsnotify.Create == fsnotify.Create { if files.IsIndexContentFile(ev.Name) { return ev.Name } if files.IsContentFile(ev.Name) { name = ev.Name } } } return name } func formatByteCount(b uint64) string { const unit = 1000 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := int64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) }
ilmari-lauhakangas
2ae4786ca1e4b912fabc8a6be503772374fed5d6
525bed99190b2f90946e7010c6094feb3884af6a
```suggestion c.r.Printf("Web Server is available at %s (bind address %s) %s\n", serverURL, c.serverInterface, roots[i]) ```
jmooring
19
gohugoio/hugo
11,385
Go 1.21 Upgrade
Fixes #11351
null
2023-08-23 16:58:49+00:00
2023-08-23 19:49:27+00:00
snap/snapcraft.yaml
name: hugo base: core20 confinement: strict adopt-info: hugo title: Hugo icon: snap/local/logo.png summary: Fast and Flexible Static Site Generator description: | Hugo is a static site generator written in Go, optimized for speed and designed for flexibility. With its advanced templating system and fast asset pipelines, Hugo renders a complete site in seconds, often less. Due to its flexible framework, multilingual support, and powerful taxonomy system, Hugo is widely used to create: * Corporate, government, nonprofit, education, news, event, and project sites * Documentation sites * Image portfolios * Landing pages * Business, professional, and personal blogs * Resumes and CVs Use Hugo's embedded web server during development to instantly see changes to content, structure, behavior, and presentation. Then deploy the site to your host, or push changes to your Git provider for automated builds and deployment. issues: https://github.com/gohugoio/hugo/issues license: "Apache-2.0" source-code: https://github.com/gohugoio/hugo.git website: https://gohugo.io/ package-repositories: - type: apt components: [main] suites: [focal] key-id: 9FD3B784BC1C6FC31A8A0A1C1655A0AB68576280 url: https://deb.nodesource.com/node_16.x plugs: etc-gitconfig: interface: system-files read: - /etc/gitconfig gitconfig: interface: personal-files read: - $HOME/.gitconfig - $HOME/.config/git - $HOME/.gitconfig.local dot-aws: interface: personal-files read: - $HOME/.aws dot-azure: interface: personal-files read: - $HOME/.azure dot-config-gcloud: interface: personal-files read: - $HOME/.config/gcloud dot-cache-hugo: interface: personal-files write: - $HOME/.cache/hugo_cache ssh-keys: interface: ssh-keys environment: HOME: $SNAP_REAL_HOME GIT_EXEC_PATH: $SNAP/usr/lib/git-core GOCACHE: $SNAP_USER_DATA/.cache/go-build npm_config_cache: $SNAP_USER_DATA/.npm npm_config_init_module: $SNAP_USER_DATA/.npm-init.js npm_config_userconfig: $SNAP_USER_DATA/.npmrc pandoc_datadir: $SNAP/usr/share/pandoc PYTHONHOME: /usr:$SNAP/usr RUBYLIB: $SNAP/usr/lib/ruby/vendor_ruby/2.7.0:$SNAP/usr/lib/$SNAPCRAFT_ARCH_TRIPLET/ruby/vendor_ruby/2.7.0:$SNAP/usr/lib/ruby/vendor_ruby:$SNAP/usr/lib/ruby/2.7.0:$SNAP/usr/lib/$SNAPCRAFT_ARCH_TRIPLET/ruby/2.7.0 # HUGO_SECURITY_EXEC_OSENV # # Default value: # (?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG)$ # Bundled applications require additional access: # git: GIT_EXEC_PATH and LD_LIBRARY_PATH # npx: npm_config_{cache,init_module,userconfig} # pandoc: pandoc_datadir # rst2html: PYTHONHOME and SNAP # asciidoctor: RUBYLIB HUGO_SECURITY_EXEC_OSENV: (?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|GIT_EXEC_PATH|LD_LIBRARY_PATH|npm_config_(cache|init_module|userconfig)|pandoc_datadir|PYTHONHOME|SNAP|RUBYLIB)$ apps: hugo: command: bin/hugo completer: hugo-completion plugs: - home - network-bind - removable-media - etc-gitconfig - gitconfig - dot-aws - dot-azure - dot-config-gcloud - dot-cache-hugo - ssh-keys parts: git: plugin: nil stage-packages: - git prime: - usr/bin/git - usr/lib go: plugin: nil stage-snaps: - go/1.19/stable prime: - bin/go - pkg/tool - -pkg/tool/* hugo: plugin: nil source: . after: - git - go override-pull: | snapcraftctl pull snapcraftctl set-version "$(git describe --tags --always --match 'v[0-9]*' | sed 's/^v//; s/-/+git/; s/-g/./')" if grep -q 'Suffix:\s*""' common/hugo/version_current.go; then snapcraftctl set-grade "stable" else snapcraftctl set-grade "devel" fi override-build: | echo "\nStarting override-build:" set -ex export GOPATH=$(realpath ../go) export PATH=$GOPATH/bin:$PATH HUGO_BUILD_TAGS="extended" echo " * Building hugo (HUGO_BUILD_TAGS=\"$HUGO_BUILD_TAGS\")..." go build -v -ldflags "-X github.com/gohugoio/hugo/common/hugo.vendorInfo=snap:$(git describe --tags --always --match 'v[0-9]*' | sed 's/^v//; s/-/+git/; s/-g/./')" -tags "$HUGO_BUILD_TAGS" ./hugo version ldd hugo || : echo " * Building shell completion..." ./hugo completion bash > hugo-completion echo " * Installing to ${SNAPCRAFT_PART_INSTALL}..." install -d $SNAPCRAFT_PART_INSTALL/bin cp -av hugo $SNAPCRAFT_PART_INSTALL/bin/ mv -v hugo-completion $SNAPCRAFT_PART_INSTALL/ echo " * Stripping binary..." ls -l $SNAPCRAFT_PART_INSTALL/bin/hugo strip --remove-section=.comment --remove-section=.note $SNAPCRAFT_PART_INSTALL/bin/hugo ls -l $SNAPCRAFT_PART_INSTALL/bin/hugo asciidoctor: plugin: nil stage-packages: - asciidoctor override-build: | set -ex snapcraftctl build sed -i '1s|#!/usr/bin/ruby|#!/usr/bin/env ruby|' $SNAPCRAFT_PART_INSTALL/usr/bin/asciidoctor dart-sass-embedded: plugin: nil build-packages: - curl override-build: | set -ex snapcraftctl build case "$SNAPCRAFT_TARGET_ARCH" in amd64) arch=x64 ;; arm64) arch=arm64 ;; armhf) arch=arm ;; i386) arch=ia32 ;; *) arch="" ;; esac if [[ -n $arch ]]; then url=$(curl -s https://api.github.com/repos/sass/dart-sass/releases/latest | awk -F\" "/browser_download_url.*-linux-${arch}.tar.gz/{print \$(NF-1)}") curl -LO --retry-connrefused --retry 10 "${url}" tar xf dart-sass-*-linux-${arch}.tar.gz install -d $SNAPCRAFT_PART_INSTALL/bin cp -av dart-sass/* $SNAPCRAFT_PART_INSTALL/bin/ fi node: plugin: nil stage-packages: - nodejs pandoc: plugin: nil stage-packages: - pandoc rst2html: plugin: nil stage-packages: - python3-docutils override-build: | set -ex snapcraftctl build sed -i "s|'/usr/share/docutils/'|os.path.expandvars('\$SNAP/usr/share/docutils/')|" $SNAPCRAFT_PART_INSTALL/usr/lib/python3/dist-packages/docutils/__init__.py organize: usr/share/docutils/scripts/python3: usr/bin
name: hugo base: core20 confinement: strict adopt-info: hugo title: Hugo icon: snap/local/logo.png summary: Fast and Flexible Static Site Generator description: | Hugo is a static site generator written in Go, optimized for speed and designed for flexibility. With its advanced templating system and fast asset pipelines, Hugo renders a complete site in seconds, often less. Due to its flexible framework, multilingual support, and powerful taxonomy system, Hugo is widely used to create: * Corporate, government, nonprofit, education, news, event, and project sites * Documentation sites * Image portfolios * Landing pages * Business, professional, and personal blogs * Resumes and CVs Use Hugo's embedded web server during development to instantly see changes to content, structure, behavior, and presentation. Then deploy the site to your host, or push changes to your Git provider for automated builds and deployment. issues: https://github.com/gohugoio/hugo/issues license: "Apache-2.0" source-code: https://github.com/gohugoio/hugo.git website: https://gohugo.io/ package-repositories: - type: apt components: [main] suites: [focal] key-id: 9FD3B784BC1C6FC31A8A0A1C1655A0AB68576280 url: https://deb.nodesource.com/node_16.x plugs: etc-gitconfig: interface: system-files read: - /etc/gitconfig gitconfig: interface: personal-files read: - $HOME/.gitconfig - $HOME/.config/git - $HOME/.gitconfig.local dot-aws: interface: personal-files read: - $HOME/.aws dot-azure: interface: personal-files read: - $HOME/.azure dot-config-gcloud: interface: personal-files read: - $HOME/.config/gcloud dot-cache-hugo: interface: personal-files write: - $HOME/.cache/hugo_cache ssh-keys: interface: ssh-keys environment: HOME: $SNAP_REAL_HOME GIT_EXEC_PATH: $SNAP/usr/lib/git-core GOCACHE: $SNAP_USER_DATA/.cache/go-build npm_config_cache: $SNAP_USER_DATA/.npm npm_config_init_module: $SNAP_USER_DATA/.npm-init.js npm_config_userconfig: $SNAP_USER_DATA/.npmrc pandoc_datadir: $SNAP/usr/share/pandoc PYTHONHOME: /usr:$SNAP/usr RUBYLIB: $SNAP/usr/lib/ruby/vendor_ruby/2.7.0:$SNAP/usr/lib/$SNAPCRAFT_ARCH_TRIPLET/ruby/vendor_ruby/2.7.0:$SNAP/usr/lib/ruby/vendor_ruby:$SNAP/usr/lib/ruby/2.7.0:$SNAP/usr/lib/$SNAPCRAFT_ARCH_TRIPLET/ruby/2.7.0 # HUGO_SECURITY_EXEC_OSENV # # Default value: # (?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG)$ # Bundled applications require additional access: # git: GIT_EXEC_PATH and LD_LIBRARY_PATH # npx: npm_config_{cache,init_module,userconfig} # pandoc: pandoc_datadir # rst2html: PYTHONHOME and SNAP # asciidoctor: RUBYLIB HUGO_SECURITY_EXEC_OSENV: (?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|GIT_EXEC_PATH|LD_LIBRARY_PATH|npm_config_(cache|init_module|userconfig)|pandoc_datadir|PYTHONHOME|SNAP|RUBYLIB)$ apps: hugo: command: bin/hugo completer: hugo-completion plugs: - home - network-bind - removable-media - etc-gitconfig - gitconfig - dot-aws - dot-azure - dot-config-gcloud - dot-cache-hugo - ssh-keys parts: git: plugin: nil stage-packages: - git prime: - usr/bin/git - usr/lib go: plugin: nil stage-snaps: - go/1.21/stable prime: - bin/go - pkg/tool - -pkg/tool/* hugo: plugin: nil source: . after: - git - go override-pull: | snapcraftctl pull snapcraftctl set-version "$(git describe --tags --always --match 'v[0-9]*' | sed 's/^v//; s/-/+git/; s/-g/./')" if grep -q 'Suffix:\s*""' common/hugo/version_current.go; then snapcraftctl set-grade "stable" else snapcraftctl set-grade "devel" fi override-build: | echo "\nStarting override-build:" set -ex export GOPATH=$(realpath ../go) export PATH=$GOPATH/bin:$PATH HUGO_BUILD_TAGS="extended" echo " * Building hugo (HUGO_BUILD_TAGS=\"$HUGO_BUILD_TAGS\")..." go build -v -ldflags "-X github.com/gohugoio/hugo/common/hugo.vendorInfo=snap:$(git describe --tags --always --match 'v[0-9]*' | sed 's/^v//; s/-/+git/; s/-g/./')" -tags "$HUGO_BUILD_TAGS" ./hugo version ldd hugo || : echo " * Building shell completion..." ./hugo completion bash > hugo-completion echo " * Installing to ${SNAPCRAFT_PART_INSTALL}..." install -d $SNAPCRAFT_PART_INSTALL/bin cp -av hugo $SNAPCRAFT_PART_INSTALL/bin/ mv -v hugo-completion $SNAPCRAFT_PART_INSTALL/ echo " * Stripping binary..." ls -l $SNAPCRAFT_PART_INSTALL/bin/hugo strip --remove-section=.comment --remove-section=.note $SNAPCRAFT_PART_INSTALL/bin/hugo ls -l $SNAPCRAFT_PART_INSTALL/bin/hugo asciidoctor: plugin: nil stage-packages: - asciidoctor override-build: | set -ex snapcraftctl build sed -i '1s|#!/usr/bin/ruby|#!/usr/bin/env ruby|' $SNAPCRAFT_PART_INSTALL/usr/bin/asciidoctor dart-sass-embedded: plugin: nil build-packages: - curl override-build: | set -ex snapcraftctl build case "$SNAPCRAFT_TARGET_ARCH" in amd64) arch=x64 ;; arm64) arch=arm64 ;; armhf) arch=arm ;; i386) arch=ia32 ;; *) arch="" ;; esac if [[ -n $arch ]]; then url=$(curl -s https://api.github.com/repos/sass/dart-sass/releases/latest | awk -F\" "/browser_download_url.*-linux-${arch}.tar.gz/{print \$(NF-1)}") curl -LO --retry-connrefused --retry 10 "${url}" tar xf dart-sass-*-linux-${arch}.tar.gz install -d $SNAPCRAFT_PART_INSTALL/bin cp -av dart-sass/* $SNAPCRAFT_PART_INSTALL/bin/ fi node: plugin: nil stage-packages: - nodejs pandoc: plugin: nil stage-packages: - pandoc rst2html: plugin: nil stage-packages: - python3-docutils override-build: | set -ex snapcraftctl build sed -i "s|'/usr/share/docutils/'|os.path.expandvars('\$SNAP/usr/share/docutils/')|" $SNAPCRAFT_PART_INSTALL/usr/lib/python3/dist-packages/docutils/__init__.py organize: usr/share/docutils/scripts/python3: usr/bin
bep
111f02db2a2cb139a19e4643dd73fa637e40ad6e
24b1be45c17d68c67bab61b2fbb568f53a3d8202
@jmooring quick question: Does the above work?
bep
20
gohugoio/hugo
11,385
Go 1.21 Upgrade
Fixes #11351
null
2023-08-23 16:58:49+00:00
2023-08-23 19:49:27+00:00
snap/snapcraft.yaml
name: hugo base: core20 confinement: strict adopt-info: hugo title: Hugo icon: snap/local/logo.png summary: Fast and Flexible Static Site Generator description: | Hugo is a static site generator written in Go, optimized for speed and designed for flexibility. With its advanced templating system and fast asset pipelines, Hugo renders a complete site in seconds, often less. Due to its flexible framework, multilingual support, and powerful taxonomy system, Hugo is widely used to create: * Corporate, government, nonprofit, education, news, event, and project sites * Documentation sites * Image portfolios * Landing pages * Business, professional, and personal blogs * Resumes and CVs Use Hugo's embedded web server during development to instantly see changes to content, structure, behavior, and presentation. Then deploy the site to your host, or push changes to your Git provider for automated builds and deployment. issues: https://github.com/gohugoio/hugo/issues license: "Apache-2.0" source-code: https://github.com/gohugoio/hugo.git website: https://gohugo.io/ package-repositories: - type: apt components: [main] suites: [focal] key-id: 9FD3B784BC1C6FC31A8A0A1C1655A0AB68576280 url: https://deb.nodesource.com/node_16.x plugs: etc-gitconfig: interface: system-files read: - /etc/gitconfig gitconfig: interface: personal-files read: - $HOME/.gitconfig - $HOME/.config/git - $HOME/.gitconfig.local dot-aws: interface: personal-files read: - $HOME/.aws dot-azure: interface: personal-files read: - $HOME/.azure dot-config-gcloud: interface: personal-files read: - $HOME/.config/gcloud dot-cache-hugo: interface: personal-files write: - $HOME/.cache/hugo_cache ssh-keys: interface: ssh-keys environment: HOME: $SNAP_REAL_HOME GIT_EXEC_PATH: $SNAP/usr/lib/git-core GOCACHE: $SNAP_USER_DATA/.cache/go-build npm_config_cache: $SNAP_USER_DATA/.npm npm_config_init_module: $SNAP_USER_DATA/.npm-init.js npm_config_userconfig: $SNAP_USER_DATA/.npmrc pandoc_datadir: $SNAP/usr/share/pandoc PYTHONHOME: /usr:$SNAP/usr RUBYLIB: $SNAP/usr/lib/ruby/vendor_ruby/2.7.0:$SNAP/usr/lib/$SNAPCRAFT_ARCH_TRIPLET/ruby/vendor_ruby/2.7.0:$SNAP/usr/lib/ruby/vendor_ruby:$SNAP/usr/lib/ruby/2.7.0:$SNAP/usr/lib/$SNAPCRAFT_ARCH_TRIPLET/ruby/2.7.0 # HUGO_SECURITY_EXEC_OSENV # # Default value: # (?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG)$ # Bundled applications require additional access: # git: GIT_EXEC_PATH and LD_LIBRARY_PATH # npx: npm_config_{cache,init_module,userconfig} # pandoc: pandoc_datadir # rst2html: PYTHONHOME and SNAP # asciidoctor: RUBYLIB HUGO_SECURITY_EXEC_OSENV: (?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|GIT_EXEC_PATH|LD_LIBRARY_PATH|npm_config_(cache|init_module|userconfig)|pandoc_datadir|PYTHONHOME|SNAP|RUBYLIB)$ apps: hugo: command: bin/hugo completer: hugo-completion plugs: - home - network-bind - removable-media - etc-gitconfig - gitconfig - dot-aws - dot-azure - dot-config-gcloud - dot-cache-hugo - ssh-keys parts: git: plugin: nil stage-packages: - git prime: - usr/bin/git - usr/lib go: plugin: nil stage-snaps: - go/1.19/stable prime: - bin/go - pkg/tool - -pkg/tool/* hugo: plugin: nil source: . after: - git - go override-pull: | snapcraftctl pull snapcraftctl set-version "$(git describe --tags --always --match 'v[0-9]*' | sed 's/^v//; s/-/+git/; s/-g/./')" if grep -q 'Suffix:\s*""' common/hugo/version_current.go; then snapcraftctl set-grade "stable" else snapcraftctl set-grade "devel" fi override-build: | echo "\nStarting override-build:" set -ex export GOPATH=$(realpath ../go) export PATH=$GOPATH/bin:$PATH HUGO_BUILD_TAGS="extended" echo " * Building hugo (HUGO_BUILD_TAGS=\"$HUGO_BUILD_TAGS\")..." go build -v -ldflags "-X github.com/gohugoio/hugo/common/hugo.vendorInfo=snap:$(git describe --tags --always --match 'v[0-9]*' | sed 's/^v//; s/-/+git/; s/-g/./')" -tags "$HUGO_BUILD_TAGS" ./hugo version ldd hugo || : echo " * Building shell completion..." ./hugo completion bash > hugo-completion echo " * Installing to ${SNAPCRAFT_PART_INSTALL}..." install -d $SNAPCRAFT_PART_INSTALL/bin cp -av hugo $SNAPCRAFT_PART_INSTALL/bin/ mv -v hugo-completion $SNAPCRAFT_PART_INSTALL/ echo " * Stripping binary..." ls -l $SNAPCRAFT_PART_INSTALL/bin/hugo strip --remove-section=.comment --remove-section=.note $SNAPCRAFT_PART_INSTALL/bin/hugo ls -l $SNAPCRAFT_PART_INSTALL/bin/hugo asciidoctor: plugin: nil stage-packages: - asciidoctor override-build: | set -ex snapcraftctl build sed -i '1s|#!/usr/bin/ruby|#!/usr/bin/env ruby|' $SNAPCRAFT_PART_INSTALL/usr/bin/asciidoctor dart-sass-embedded: plugin: nil build-packages: - curl override-build: | set -ex snapcraftctl build case "$SNAPCRAFT_TARGET_ARCH" in amd64) arch=x64 ;; arm64) arch=arm64 ;; armhf) arch=arm ;; i386) arch=ia32 ;; *) arch="" ;; esac if [[ -n $arch ]]; then url=$(curl -s https://api.github.com/repos/sass/dart-sass/releases/latest | awk -F\" "/browser_download_url.*-linux-${arch}.tar.gz/{print \$(NF-1)}") curl -LO --retry-connrefused --retry 10 "${url}" tar xf dart-sass-*-linux-${arch}.tar.gz install -d $SNAPCRAFT_PART_INSTALL/bin cp -av dart-sass/* $SNAPCRAFT_PART_INSTALL/bin/ fi node: plugin: nil stage-packages: - nodejs pandoc: plugin: nil stage-packages: - pandoc rst2html: plugin: nil stage-packages: - python3-docutils override-build: | set -ex snapcraftctl build sed -i "s|'/usr/share/docutils/'|os.path.expandvars('\$SNAP/usr/share/docutils/')|" $SNAPCRAFT_PART_INSTALL/usr/lib/python3/dist-packages/docutils/__init__.py organize: usr/share/docutils/scripts/python3: usr/bin
name: hugo base: core20 confinement: strict adopt-info: hugo title: Hugo icon: snap/local/logo.png summary: Fast and Flexible Static Site Generator description: | Hugo is a static site generator written in Go, optimized for speed and designed for flexibility. With its advanced templating system and fast asset pipelines, Hugo renders a complete site in seconds, often less. Due to its flexible framework, multilingual support, and powerful taxonomy system, Hugo is widely used to create: * Corporate, government, nonprofit, education, news, event, and project sites * Documentation sites * Image portfolios * Landing pages * Business, professional, and personal blogs * Resumes and CVs Use Hugo's embedded web server during development to instantly see changes to content, structure, behavior, and presentation. Then deploy the site to your host, or push changes to your Git provider for automated builds and deployment. issues: https://github.com/gohugoio/hugo/issues license: "Apache-2.0" source-code: https://github.com/gohugoio/hugo.git website: https://gohugo.io/ package-repositories: - type: apt components: [main] suites: [focal] key-id: 9FD3B784BC1C6FC31A8A0A1C1655A0AB68576280 url: https://deb.nodesource.com/node_16.x plugs: etc-gitconfig: interface: system-files read: - /etc/gitconfig gitconfig: interface: personal-files read: - $HOME/.gitconfig - $HOME/.config/git - $HOME/.gitconfig.local dot-aws: interface: personal-files read: - $HOME/.aws dot-azure: interface: personal-files read: - $HOME/.azure dot-config-gcloud: interface: personal-files read: - $HOME/.config/gcloud dot-cache-hugo: interface: personal-files write: - $HOME/.cache/hugo_cache ssh-keys: interface: ssh-keys environment: HOME: $SNAP_REAL_HOME GIT_EXEC_PATH: $SNAP/usr/lib/git-core GOCACHE: $SNAP_USER_DATA/.cache/go-build npm_config_cache: $SNAP_USER_DATA/.npm npm_config_init_module: $SNAP_USER_DATA/.npm-init.js npm_config_userconfig: $SNAP_USER_DATA/.npmrc pandoc_datadir: $SNAP/usr/share/pandoc PYTHONHOME: /usr:$SNAP/usr RUBYLIB: $SNAP/usr/lib/ruby/vendor_ruby/2.7.0:$SNAP/usr/lib/$SNAPCRAFT_ARCH_TRIPLET/ruby/vendor_ruby/2.7.0:$SNAP/usr/lib/ruby/vendor_ruby:$SNAP/usr/lib/ruby/2.7.0:$SNAP/usr/lib/$SNAPCRAFT_ARCH_TRIPLET/ruby/2.7.0 # HUGO_SECURITY_EXEC_OSENV # # Default value: # (?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG)$ # Bundled applications require additional access: # git: GIT_EXEC_PATH and LD_LIBRARY_PATH # npx: npm_config_{cache,init_module,userconfig} # pandoc: pandoc_datadir # rst2html: PYTHONHOME and SNAP # asciidoctor: RUBYLIB HUGO_SECURITY_EXEC_OSENV: (?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|GIT_EXEC_PATH|LD_LIBRARY_PATH|npm_config_(cache|init_module|userconfig)|pandoc_datadir|PYTHONHOME|SNAP|RUBYLIB)$ apps: hugo: command: bin/hugo completer: hugo-completion plugs: - home - network-bind - removable-media - etc-gitconfig - gitconfig - dot-aws - dot-azure - dot-config-gcloud - dot-cache-hugo - ssh-keys parts: git: plugin: nil stage-packages: - git prime: - usr/bin/git - usr/lib go: plugin: nil stage-snaps: - go/1.21/stable prime: - bin/go - pkg/tool - -pkg/tool/* hugo: plugin: nil source: . after: - git - go override-pull: | snapcraftctl pull snapcraftctl set-version "$(git describe --tags --always --match 'v[0-9]*' | sed 's/^v//; s/-/+git/; s/-g/./')" if grep -q 'Suffix:\s*""' common/hugo/version_current.go; then snapcraftctl set-grade "stable" else snapcraftctl set-grade "devel" fi override-build: | echo "\nStarting override-build:" set -ex export GOPATH=$(realpath ../go) export PATH=$GOPATH/bin:$PATH HUGO_BUILD_TAGS="extended" echo " * Building hugo (HUGO_BUILD_TAGS=\"$HUGO_BUILD_TAGS\")..." go build -v -ldflags "-X github.com/gohugoio/hugo/common/hugo.vendorInfo=snap:$(git describe --tags --always --match 'v[0-9]*' | sed 's/^v//; s/-/+git/; s/-g/./')" -tags "$HUGO_BUILD_TAGS" ./hugo version ldd hugo || : echo " * Building shell completion..." ./hugo completion bash > hugo-completion echo " * Installing to ${SNAPCRAFT_PART_INSTALL}..." install -d $SNAPCRAFT_PART_INSTALL/bin cp -av hugo $SNAPCRAFT_PART_INSTALL/bin/ mv -v hugo-completion $SNAPCRAFT_PART_INSTALL/ echo " * Stripping binary..." ls -l $SNAPCRAFT_PART_INSTALL/bin/hugo strip --remove-section=.comment --remove-section=.note $SNAPCRAFT_PART_INSTALL/bin/hugo ls -l $SNAPCRAFT_PART_INSTALL/bin/hugo asciidoctor: plugin: nil stage-packages: - asciidoctor override-build: | set -ex snapcraftctl build sed -i '1s|#!/usr/bin/ruby|#!/usr/bin/env ruby|' $SNAPCRAFT_PART_INSTALL/usr/bin/asciidoctor dart-sass-embedded: plugin: nil build-packages: - curl override-build: | set -ex snapcraftctl build case "$SNAPCRAFT_TARGET_ARCH" in amd64) arch=x64 ;; arm64) arch=arm64 ;; armhf) arch=arm ;; i386) arch=ia32 ;; *) arch="" ;; esac if [[ -n $arch ]]; then url=$(curl -s https://api.github.com/repos/sass/dart-sass/releases/latest | awk -F\" "/browser_download_url.*-linux-${arch}.tar.gz/{print \$(NF-1)}") curl -LO --retry-connrefused --retry 10 "${url}" tar xf dart-sass-*-linux-${arch}.tar.gz install -d $SNAPCRAFT_PART_INSTALL/bin cp -av dart-sass/* $SNAPCRAFT_PART_INSTALL/bin/ fi node: plugin: nil stage-packages: - nodejs pandoc: plugin: nil stage-packages: - pandoc rst2html: plugin: nil stage-packages: - python3-docutils override-build: | set -ex snapcraftctl build sed -i "s|'/usr/share/docutils/'|os.path.expandvars('\$SNAP/usr/share/docutils/')|" $SNAPCRAFT_PART_INSTALL/usr/lib/python3/dist-packages/docutils/__init__.py organize: usr/share/docutils/scripts/python3: usr/bin
bep
111f02db2a2cb139a19e4643dd73fa637e40ad6e
24b1be45c17d68c67bab61b2fbb568f53a3d8202
Yes. I rebuilt the snap locally and tested.
jmooring
21
gohugoio/hugo
11,281
tpl/collections: Add like operator to where function
Enables constructs such as: ```text {{ range where site.RegularPages "Params.foo" "like" "^ab" }} <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> {{ end }} ``` Will submit documentation change to the documentation repository is this is merged. Closes #11279
null
2023-07-23 19:55:24+00:00
2023-07-28 07:53:01+00:00
tpl/collections/where.go
// Copyright 2017 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 collections import ( "context" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" ) // Where returns a filtered subset of collection c. func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) { seqv, isNil := indirect(reflect.ValueOf(c)) if isNil { return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String()) } mv, op, err := parseWhereArgs(args...) if err != nil { return nil, err } ctxv := reflect.ValueOf(ctx) var path []string kv := reflect.ValueOf(key) if kv.Kind() == reflect.String { path = strings.Split(strings.Trim(kv.String(), "."), ".") } switch seqv.Kind() { case reflect.Array, reflect.Slice: return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op) case reflect.Map: return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op) default: return nil, fmt.Errorf("can't iterate over %v", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := indirect(mv) if !mv.IsValid() { mvIsNil = true } if vIsNil || mvIsNil { switch op { case "", "=", "==", "eq": return vIsNil == mvIsNil, nil case "!=", "<>", "ne": return vIsNil != mvIsNil, nil } return false, nil } if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool { switch op { case "", "=", "==", "eq": return v.Bool() == mv.Bool(), nil case "!=", "<>", "ne": return v.Bool() != mv.Bool(), nil } return false, nil } var ivp, imvp *int64 var fvp, fmvp *float64 var svp, smvp *string var slv, slmv any var ima []int64 var fma []float64 var sma []string if mv.Kind() == v.Kind() { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv imv := mv.Int() imvp = &imv case reflect.String: sv := v.String() svp = &sv smv := mv.String() smvp = &smv case reflect.Float64: fv := v.Float() fvp = &fv fmv := mv.Float() fmvp = &fmv case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv imv := ns.toTimeUnix(mv) imvp = &imv } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } else if isNumber(v.Kind()) && isNumber(mv.Kind()) { fv, err := toFloat(v) if err != nil { return false, err } fvp = &fv fmv, err := toFloat(mv) if err != nil { return false, err } fmvp = &fmv } else { if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice { return false, nil } if mv.Len() == 0 { return false, nil } if v.Kind() != reflect.Interface && mv.Type().Elem().Kind() != reflect.Interface && mv.Type().Elem() != v.Type() && v.Kind() != reflect.Array && v.Kind() != reflect.Slice { return false, nil } switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv for i := 0; i < mv.Len(); i++ { if anInt, err := toInt(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := 0; i < mv.Len(); i++ { if aString, err := toString(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := 0; i < mv.Len(); i++ { if aFloat, err := toFloat(mv.Index(i)); err == nil { fma = append(fma, aFloat) } } case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv for i := 0; i < mv.Len(); i++ { ima = append(ima, ns.toTimeUnix(mv.Index(i))) } } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } switch op { case "", "=", "==", "eq": switch { case ivp != nil && imvp != nil: return *ivp == *imvp, nil case svp != nil && smvp != nil: return *svp == *smvp, nil case fvp != nil && fmvp != nil: return *fvp == *fmvp, nil } case "!=", "<>", "ne": switch { case ivp != nil && imvp != nil: return *ivp != *imvp, nil case svp != nil && smvp != nil: return *svp != *smvp, nil case fvp != nil && fmvp != nil: return *fvp != *fmvp, nil } case ">=", "ge": switch { case ivp != nil && imvp != nil: return *ivp >= *imvp, nil case svp != nil && smvp != nil: return *svp >= *smvp, nil case fvp != nil && fmvp != nil: return *fvp >= *fmvp, nil } case ">", "gt": switch { case ivp != nil && imvp != nil: return *ivp > *imvp, nil case svp != nil && smvp != nil: return *svp > *smvp, nil case fvp != nil && fmvp != nil: return *fvp > *fmvp, nil } case "<=", "le": switch { case ivp != nil && imvp != nil: return *ivp <= *imvp, nil case svp != nil && smvp != nil: return *svp <= *smvp, nil case fvp != nil && fmvp != nil: return *fvp <= *fmvp, nil } case "<", "lt": switch { case ivp != nil && imvp != nil: return *ivp < *imvp, nil case svp != nil && smvp != nil: return *svp < *smvp, nil case fvp != nil && fmvp != nil: return *fvp < *fmvp, nil } case "in", "not in": var r bool switch { case ivp != nil && len(ima) > 0: r, _ = ns.In(ima, *ivp) case fvp != nil && len(fma) > 0: r, _ = ns.In(fma, *fvp) case svp != nil: if len(sma) > 0 { r, _ = ns.In(sma, *svp) } else if smvp != nil { r, _ = ns.In(*smvp, *svp) } default: return false, nil } if op == "not in" { return !r, nil } return r, nil case "intersect": r, err := ns.Intersect(slv, slmv) if err != nil { return false, err } if reflect.TypeOf(r).Kind() == reflect.Slice { s := reflect.ValueOf(r) if s.Len() > 0 { return true, nil } return false, nil } return false, errors.New("invalid intersect values") default: return false, errors.New("no such operator") } return false, nil } func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) { if !obj.IsValid() { return zero, errors.New("can't evaluate an invalid value") } typ := obj.Type() obj, isNil := indirect(obj) if obj.Kind() == reflect.Interface { // If obj is an interface, we need to inspect the value it contains // to see the full set of methods and fields. // Indirect returns the value that it points to, which is what's needed // below to be able to reflect on its fields. obj = reflect.Indirect(obj.Elem()) } // first, check whether obj has a method. In this case, obj is // a struct or its pointer. If obj is a struct, // to check all T and *T method, use obj pointer type Value objPtr := obj if objPtr.Kind() != reflect.Interface && objPtr.CanAddr() { objPtr = objPtr.Addr() } index := hreflect.GetMethodIndexByName(objPtr.Type(), elemName) if index != -1 { var args []reflect.Value mt := objPtr.Type().Method(index) num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && mt.Type.In(1).Implements(hreflect.ContextInterface) { args = []reflect.Value{ctx} maxNumIn = 2 } switch { case mt.PkgPath != "": return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ) case mt.Type.NumIn() > maxNumIn: return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn) case mt.Type.NumOut() == 0: return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ) case mt.Type.NumOut() > 2: return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ) case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ) case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ) } res := objPtr.Method(mt.Index).Call(args) if len(res) == 2 && !res[1].IsNil() { return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error)) } return res[0], nil } // elemName isn't a method so next start to check whether it is // a struct field or a map value. In both cases, it mustn't be // a nil value if isNil { return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName) } switch obj.Kind() { case reflect.Struct: ft, ok := obj.Type().FieldByName(elemName) if ok { if ft.PkgPath != "" && !ft.Anonymous { return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ) } return obj.FieldByIndex(ft.Index), nil } return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ) case reflect.Map: kv := reflect.ValueOf(elemName) if kv.Type().AssignableTo(obj.Type().Key()) { return obj.MapIndex(kv), nil } return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ) } return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ) } // parseWhereArgs parses the end arguments to the where function. Return a // match value and an operator, if one is defined. func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) { switch len(args) { case 1: mv = reflect.ValueOf(args[0]) case 2: var ok bool if op, ok = args[0].(string); !ok { err = errors.New("operator argument must be string type") return } op = strings.TrimSpace(strings.ToLower(op)) mv = reflect.ValueOf(args[1]) default: err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments") } return } // checkWhereArray handles the where-matching logic when the seqv value is an // Array or Slice. func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeSlice(seqv.Type(), 0, 0) for i := 0; i < seqv.Len(); i++ { var vvv reflect.Value rvv := seqv.Index(i) if kv.Kind() == reflect.String { if params, ok := rvv.Interface().(maps.Params); ok { vvv = reflect.ValueOf(params.GetNested(path...)) } else { vvv = rvv for i, elemName := range path { var err error vvv, err = evaluateSubElem(ctxv, vvv, elemName) if err != nil { continue } if i < len(path)-1 && vvv.IsValid() { if params, ok := vvv.Interface().(maps.Params); ok { // The current path element is the map itself, .Params. vvv = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } } } } else { vv, _ := indirect(rvv) if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) { vvv = vv.MapIndex(kv) } } if ok, err := ns.checkCondition(vvv, mv, op); ok { rv = reflect.Append(rv, rvv) } else if err != nil { return nil, err } } return rv.Interface(), nil } // checkWhereMap handles the where-matching logic when the seqv value is a Map. func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeMap(seqv.Type()) keys := seqv.MapKeys() for _, k := range keys { elemv := seqv.MapIndex(k) switch elemv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } case reflect.Interface: elemvv, isNil := indirect(elemv) if isNil { continue } switch elemvv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } } } } return rv.Interface(), nil } // toFloat returns the float value if possible. func toFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Convert(reflect.TypeOf(float64(0))).Float(), nil case reflect.Interface: return toFloat(v.Elem()) } return -1, errors.New("unable to convert value to float") } // toInt returns the int value if possible, -1 if not. // TODO(bep) consolidate all these reflect funcs. func toInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil case reflect.Interface: return toInt(v.Elem()) } return -1, errors.New("unable to convert value to int") } func toUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil case reflect.Interface: return toUint(v.Elem()) } return 0, errors.New("unable to convert value to uint") } // toString returns the string value if possible, "" if not. func toString(v reflect.Value) (string, error) { switch v.Kind() { case reflect.String: return v.String(), nil case reflect.Interface: return toString(v.Elem()) } return "", errors.New("unable to convert value to string") } func (ns *Namespace) toTimeUnix(v reflect.Value) int64 { t, ok := hreflect.AsTime(v, ns.loc) if !ok { panic("coding error: argument must be time.Time type reflect Value") } return t.Unix() }
// Copyright 2017 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 collections import ( "context" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/maps" ) // Where returns a filtered subset of collection c. func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) { seqv, isNil := indirect(reflect.ValueOf(c)) if isNil { return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String()) } mv, op, err := parseWhereArgs(args...) if err != nil { return nil, err } ctxv := reflect.ValueOf(ctx) var path []string kv := reflect.ValueOf(key) if kv.Kind() == reflect.String { path = strings.Split(strings.Trim(kv.String(), "."), ".") } switch seqv.Kind() { case reflect.Array, reflect.Slice: return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op) case reflect.Map: return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op) default: return nil, fmt.Errorf("can't iterate over %v", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := indirect(mv) if !mv.IsValid() { mvIsNil = true } if vIsNil || mvIsNil { switch op { case "", "=", "==", "eq": return vIsNil == mvIsNil, nil case "!=", "<>", "ne": return vIsNil != mvIsNil, nil } return false, nil } if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool { switch op { case "", "=", "==", "eq": return v.Bool() == mv.Bool(), nil case "!=", "<>", "ne": return v.Bool() != mv.Bool(), nil } return false, nil } var ivp, imvp *int64 var fvp, fmvp *float64 var svp, smvp *string var slv, slmv any var ima []int64 var fma []float64 var sma []string if mv.Kind() == v.Kind() { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv imv := mv.Int() imvp = &imv case reflect.String: sv := v.String() svp = &sv smv := mv.String() smvp = &smv case reflect.Float64: fv := v.Float() fvp = &fv fmv := mv.Float() fmvp = &fmv case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv imv := ns.toTimeUnix(mv) imvp = &imv } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } else if isNumber(v.Kind()) && isNumber(mv.Kind()) { fv, err := toFloat(v) if err != nil { return false, err } fvp = &fv fmv, err := toFloat(mv) if err != nil { return false, err } fmvp = &fmv } else { if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice { return false, nil } if mv.Len() == 0 { return false, nil } if v.Kind() != reflect.Interface && mv.Type().Elem().Kind() != reflect.Interface && mv.Type().Elem() != v.Type() && v.Kind() != reflect.Array && v.Kind() != reflect.Slice { return false, nil } switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv for i := 0; i < mv.Len(); i++ { if anInt, err := toInt(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := 0; i < mv.Len(); i++ { if aString, err := toString(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := 0; i < mv.Len(); i++ { if aFloat, err := toFloat(mv.Index(i)); err == nil { fma = append(fma, aFloat) } } case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv for i := 0; i < mv.Len(); i++ { ima = append(ima, ns.toTimeUnix(mv.Index(i))) } } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } switch op { case "", "=", "==", "eq": switch { case ivp != nil && imvp != nil: return *ivp == *imvp, nil case svp != nil && smvp != nil: return *svp == *smvp, nil case fvp != nil && fmvp != nil: return *fvp == *fmvp, nil } case "!=", "<>", "ne": switch { case ivp != nil && imvp != nil: return *ivp != *imvp, nil case svp != nil && smvp != nil: return *svp != *smvp, nil case fvp != nil && fmvp != nil: return *fvp != *fmvp, nil } case ">=", "ge": switch { case ivp != nil && imvp != nil: return *ivp >= *imvp, nil case svp != nil && smvp != nil: return *svp >= *smvp, nil case fvp != nil && fmvp != nil: return *fvp >= *fmvp, nil } case ">", "gt": switch { case ivp != nil && imvp != nil: return *ivp > *imvp, nil case svp != nil && smvp != nil: return *svp > *smvp, nil case fvp != nil && fmvp != nil: return *fvp > *fmvp, nil } case "<=", "le": switch { case ivp != nil && imvp != nil: return *ivp <= *imvp, nil case svp != nil && smvp != nil: return *svp <= *smvp, nil case fvp != nil && fmvp != nil: return *fvp <= *fmvp, nil } case "<", "lt": switch { case ivp != nil && imvp != nil: return *ivp < *imvp, nil case svp != nil && smvp != nil: return *svp < *smvp, nil case fvp != nil && fmvp != nil: return *fvp < *fmvp, nil } case "in", "not in": var r bool switch { case ivp != nil && len(ima) > 0: r, _ = ns.In(ima, *ivp) case fvp != nil && len(fma) > 0: r, _ = ns.In(fma, *fvp) case svp != nil: if len(sma) > 0 { r, _ = ns.In(sma, *svp) } else if smvp != nil { r, _ = ns.In(*smvp, *svp) } default: return false, nil } if op == "not in" { return !r, nil } return r, nil case "intersect": r, err := ns.Intersect(slv, slmv) if err != nil { return false, err } if reflect.TypeOf(r).Kind() == reflect.Slice { s := reflect.ValueOf(r) if s.Len() > 0 { return true, nil } return false, nil } return false, errors.New("invalid intersect values") case "like": if svp != nil && smvp != nil { re, err := hstrings.GetOrCompileRegexp(*smvp) if err != nil { return false, err } if re.MatchString(*svp) { return true, nil } return false, nil } default: return false, errors.New("no such operator") } return false, nil } func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) { if !obj.IsValid() { return zero, errors.New("can't evaluate an invalid value") } typ := obj.Type() obj, isNil := indirect(obj) if obj.Kind() == reflect.Interface { // If obj is an interface, we need to inspect the value it contains // to see the full set of methods and fields. // Indirect returns the value that it points to, which is what's needed // below to be able to reflect on its fields. obj = reflect.Indirect(obj.Elem()) } // first, check whether obj has a method. In this case, obj is // a struct or its pointer. If obj is a struct, // to check all T and *T method, use obj pointer type Value objPtr := obj if objPtr.Kind() != reflect.Interface && objPtr.CanAddr() { objPtr = objPtr.Addr() } index := hreflect.GetMethodIndexByName(objPtr.Type(), elemName) if index != -1 { var args []reflect.Value mt := objPtr.Type().Method(index) num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && mt.Type.In(1).Implements(hreflect.ContextInterface) { args = []reflect.Value{ctx} maxNumIn = 2 } switch { case mt.PkgPath != "": return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ) case mt.Type.NumIn() > maxNumIn: return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn) case mt.Type.NumOut() == 0: return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ) case mt.Type.NumOut() > 2: return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ) case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ) case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ) } res := objPtr.Method(mt.Index).Call(args) if len(res) == 2 && !res[1].IsNil() { return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error)) } return res[0], nil } // elemName isn't a method so next start to check whether it is // a struct field or a map value. In both cases, it mustn't be // a nil value if isNil { return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName) } switch obj.Kind() { case reflect.Struct: ft, ok := obj.Type().FieldByName(elemName) if ok { if ft.PkgPath != "" && !ft.Anonymous { return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ) } return obj.FieldByIndex(ft.Index), nil } return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ) case reflect.Map: kv := reflect.ValueOf(elemName) if kv.Type().AssignableTo(obj.Type().Key()) { return obj.MapIndex(kv), nil } return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ) } return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ) } // parseWhereArgs parses the end arguments to the where function. Return a // match value and an operator, if one is defined. func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) { switch len(args) { case 1: mv = reflect.ValueOf(args[0]) case 2: var ok bool if op, ok = args[0].(string); !ok { err = errors.New("operator argument must be string type") return } op = strings.TrimSpace(strings.ToLower(op)) mv = reflect.ValueOf(args[1]) default: err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments") } return } // checkWhereArray handles the where-matching logic when the seqv value is an // Array or Slice. func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeSlice(seqv.Type(), 0, 0) for i := 0; i < seqv.Len(); i++ { var vvv reflect.Value rvv := seqv.Index(i) if kv.Kind() == reflect.String { if params, ok := rvv.Interface().(maps.Params); ok { vvv = reflect.ValueOf(params.GetNested(path...)) } else { vvv = rvv for i, elemName := range path { var err error vvv, err = evaluateSubElem(ctxv, vvv, elemName) if err != nil { continue } if i < len(path)-1 && vvv.IsValid() { if params, ok := vvv.Interface().(maps.Params); ok { // The current path element is the map itself, .Params. vvv = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } } } } else { vv, _ := indirect(rvv) if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) { vvv = vv.MapIndex(kv) } } if ok, err := ns.checkCondition(vvv, mv, op); ok { rv = reflect.Append(rv, rvv) } else if err != nil { return nil, err } } return rv.Interface(), nil } // checkWhereMap handles the where-matching logic when the seqv value is a Map. func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeMap(seqv.Type()) keys := seqv.MapKeys() for _, k := range keys { elemv := seqv.MapIndex(k) switch elemv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } case reflect.Interface: elemvv, isNil := indirect(elemv) if isNil { continue } switch elemvv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } } } } return rv.Interface(), nil } // toFloat returns the float value if possible. func toFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Convert(reflect.TypeOf(float64(0))).Float(), nil case reflect.Interface: return toFloat(v.Elem()) } return -1, errors.New("unable to convert value to float") } // toInt returns the int value if possible, -1 if not. // TODO(bep) consolidate all these reflect funcs. func toInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil case reflect.Interface: return toInt(v.Elem()) } return -1, errors.New("unable to convert value to int") } func toUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil case reflect.Interface: return toUint(v.Elem()) } return 0, errors.New("unable to convert value to uint") } // toString returns the string value if possible, "" if not. func toString(v reflect.Value) (string, error) { switch v.Kind() { case reflect.String: return v.String(), nil case reflect.Interface: return toString(v.Elem()) } return "", errors.New("unable to convert value to string") } func (ns *Namespace) toTimeUnix(v reflect.Value) int64 { t, ok := hreflect.AsTime(v, ns.loc) if !ok { panic("coding error: argument must be time.Time type reflect Value") } return t.Unix() }
jmooring
dc2a544fac7a3f9cb8bff70d5cbe92b37dee98d1
f4598a09864bee2689a7630dda83a71a9b9cf55b
I guess this both makes sense/would be useful, but: 1. Compile is slowish, so do it once and reuse the `*regexp.Regexp` somehow. 2. Also use `regexp.Compile` and return any error.
bep
22
gohugoio/hugo
11,281
tpl/collections: Add like operator to where function
Enables constructs such as: ```text {{ range where site.RegularPages "Params.foo" "like" "^ab" }} <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> {{ end }} ``` Will submit documentation change to the documentation repository is this is merged. Closes #11279
null
2023-07-23 19:55:24+00:00
2023-07-28 07:53:01+00:00
tpl/collections/where.go
// Copyright 2017 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 collections import ( "context" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" ) // Where returns a filtered subset of collection c. func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) { seqv, isNil := indirect(reflect.ValueOf(c)) if isNil { return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String()) } mv, op, err := parseWhereArgs(args...) if err != nil { return nil, err } ctxv := reflect.ValueOf(ctx) var path []string kv := reflect.ValueOf(key) if kv.Kind() == reflect.String { path = strings.Split(strings.Trim(kv.String(), "."), ".") } switch seqv.Kind() { case reflect.Array, reflect.Slice: return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op) case reflect.Map: return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op) default: return nil, fmt.Errorf("can't iterate over %v", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := indirect(mv) if !mv.IsValid() { mvIsNil = true } if vIsNil || mvIsNil { switch op { case "", "=", "==", "eq": return vIsNil == mvIsNil, nil case "!=", "<>", "ne": return vIsNil != mvIsNil, nil } return false, nil } if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool { switch op { case "", "=", "==", "eq": return v.Bool() == mv.Bool(), nil case "!=", "<>", "ne": return v.Bool() != mv.Bool(), nil } return false, nil } var ivp, imvp *int64 var fvp, fmvp *float64 var svp, smvp *string var slv, slmv any var ima []int64 var fma []float64 var sma []string if mv.Kind() == v.Kind() { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv imv := mv.Int() imvp = &imv case reflect.String: sv := v.String() svp = &sv smv := mv.String() smvp = &smv case reflect.Float64: fv := v.Float() fvp = &fv fmv := mv.Float() fmvp = &fmv case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv imv := ns.toTimeUnix(mv) imvp = &imv } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } else if isNumber(v.Kind()) && isNumber(mv.Kind()) { fv, err := toFloat(v) if err != nil { return false, err } fvp = &fv fmv, err := toFloat(mv) if err != nil { return false, err } fmvp = &fmv } else { if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice { return false, nil } if mv.Len() == 0 { return false, nil } if v.Kind() != reflect.Interface && mv.Type().Elem().Kind() != reflect.Interface && mv.Type().Elem() != v.Type() && v.Kind() != reflect.Array && v.Kind() != reflect.Slice { return false, nil } switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv for i := 0; i < mv.Len(); i++ { if anInt, err := toInt(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := 0; i < mv.Len(); i++ { if aString, err := toString(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := 0; i < mv.Len(); i++ { if aFloat, err := toFloat(mv.Index(i)); err == nil { fma = append(fma, aFloat) } } case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv for i := 0; i < mv.Len(); i++ { ima = append(ima, ns.toTimeUnix(mv.Index(i))) } } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } switch op { case "", "=", "==", "eq": switch { case ivp != nil && imvp != nil: return *ivp == *imvp, nil case svp != nil && smvp != nil: return *svp == *smvp, nil case fvp != nil && fmvp != nil: return *fvp == *fmvp, nil } case "!=", "<>", "ne": switch { case ivp != nil && imvp != nil: return *ivp != *imvp, nil case svp != nil && smvp != nil: return *svp != *smvp, nil case fvp != nil && fmvp != nil: return *fvp != *fmvp, nil } case ">=", "ge": switch { case ivp != nil && imvp != nil: return *ivp >= *imvp, nil case svp != nil && smvp != nil: return *svp >= *smvp, nil case fvp != nil && fmvp != nil: return *fvp >= *fmvp, nil } case ">", "gt": switch { case ivp != nil && imvp != nil: return *ivp > *imvp, nil case svp != nil && smvp != nil: return *svp > *smvp, nil case fvp != nil && fmvp != nil: return *fvp > *fmvp, nil } case "<=", "le": switch { case ivp != nil && imvp != nil: return *ivp <= *imvp, nil case svp != nil && smvp != nil: return *svp <= *smvp, nil case fvp != nil && fmvp != nil: return *fvp <= *fmvp, nil } case "<", "lt": switch { case ivp != nil && imvp != nil: return *ivp < *imvp, nil case svp != nil && smvp != nil: return *svp < *smvp, nil case fvp != nil && fmvp != nil: return *fvp < *fmvp, nil } case "in", "not in": var r bool switch { case ivp != nil && len(ima) > 0: r, _ = ns.In(ima, *ivp) case fvp != nil && len(fma) > 0: r, _ = ns.In(fma, *fvp) case svp != nil: if len(sma) > 0 { r, _ = ns.In(sma, *svp) } else if smvp != nil { r, _ = ns.In(*smvp, *svp) } default: return false, nil } if op == "not in" { return !r, nil } return r, nil case "intersect": r, err := ns.Intersect(slv, slmv) if err != nil { return false, err } if reflect.TypeOf(r).Kind() == reflect.Slice { s := reflect.ValueOf(r) if s.Len() > 0 { return true, nil } return false, nil } return false, errors.New("invalid intersect values") default: return false, errors.New("no such operator") } return false, nil } func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) { if !obj.IsValid() { return zero, errors.New("can't evaluate an invalid value") } typ := obj.Type() obj, isNil := indirect(obj) if obj.Kind() == reflect.Interface { // If obj is an interface, we need to inspect the value it contains // to see the full set of methods and fields. // Indirect returns the value that it points to, which is what's needed // below to be able to reflect on its fields. obj = reflect.Indirect(obj.Elem()) } // first, check whether obj has a method. In this case, obj is // a struct or its pointer. If obj is a struct, // to check all T and *T method, use obj pointer type Value objPtr := obj if objPtr.Kind() != reflect.Interface && objPtr.CanAddr() { objPtr = objPtr.Addr() } index := hreflect.GetMethodIndexByName(objPtr.Type(), elemName) if index != -1 { var args []reflect.Value mt := objPtr.Type().Method(index) num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && mt.Type.In(1).Implements(hreflect.ContextInterface) { args = []reflect.Value{ctx} maxNumIn = 2 } switch { case mt.PkgPath != "": return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ) case mt.Type.NumIn() > maxNumIn: return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn) case mt.Type.NumOut() == 0: return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ) case mt.Type.NumOut() > 2: return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ) case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ) case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ) } res := objPtr.Method(mt.Index).Call(args) if len(res) == 2 && !res[1].IsNil() { return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error)) } return res[0], nil } // elemName isn't a method so next start to check whether it is // a struct field or a map value. In both cases, it mustn't be // a nil value if isNil { return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName) } switch obj.Kind() { case reflect.Struct: ft, ok := obj.Type().FieldByName(elemName) if ok { if ft.PkgPath != "" && !ft.Anonymous { return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ) } return obj.FieldByIndex(ft.Index), nil } return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ) case reflect.Map: kv := reflect.ValueOf(elemName) if kv.Type().AssignableTo(obj.Type().Key()) { return obj.MapIndex(kv), nil } return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ) } return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ) } // parseWhereArgs parses the end arguments to the where function. Return a // match value and an operator, if one is defined. func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) { switch len(args) { case 1: mv = reflect.ValueOf(args[0]) case 2: var ok bool if op, ok = args[0].(string); !ok { err = errors.New("operator argument must be string type") return } op = strings.TrimSpace(strings.ToLower(op)) mv = reflect.ValueOf(args[1]) default: err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments") } return } // checkWhereArray handles the where-matching logic when the seqv value is an // Array or Slice. func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeSlice(seqv.Type(), 0, 0) for i := 0; i < seqv.Len(); i++ { var vvv reflect.Value rvv := seqv.Index(i) if kv.Kind() == reflect.String { if params, ok := rvv.Interface().(maps.Params); ok { vvv = reflect.ValueOf(params.GetNested(path...)) } else { vvv = rvv for i, elemName := range path { var err error vvv, err = evaluateSubElem(ctxv, vvv, elemName) if err != nil { continue } if i < len(path)-1 && vvv.IsValid() { if params, ok := vvv.Interface().(maps.Params); ok { // The current path element is the map itself, .Params. vvv = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } } } } else { vv, _ := indirect(rvv) if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) { vvv = vv.MapIndex(kv) } } if ok, err := ns.checkCondition(vvv, mv, op); ok { rv = reflect.Append(rv, rvv) } else if err != nil { return nil, err } } return rv.Interface(), nil } // checkWhereMap handles the where-matching logic when the seqv value is a Map. func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeMap(seqv.Type()) keys := seqv.MapKeys() for _, k := range keys { elemv := seqv.MapIndex(k) switch elemv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } case reflect.Interface: elemvv, isNil := indirect(elemv) if isNil { continue } switch elemvv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } } } } return rv.Interface(), nil } // toFloat returns the float value if possible. func toFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Convert(reflect.TypeOf(float64(0))).Float(), nil case reflect.Interface: return toFloat(v.Elem()) } return -1, errors.New("unable to convert value to float") } // toInt returns the int value if possible, -1 if not. // TODO(bep) consolidate all these reflect funcs. func toInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil case reflect.Interface: return toInt(v.Elem()) } return -1, errors.New("unable to convert value to int") } func toUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil case reflect.Interface: return toUint(v.Elem()) } return 0, errors.New("unable to convert value to uint") } // toString returns the string value if possible, "" if not. func toString(v reflect.Value) (string, error) { switch v.Kind() { case reflect.String: return v.String(), nil case reflect.Interface: return toString(v.Elem()) } return "", errors.New("unable to convert value to string") } func (ns *Namespace) toTimeUnix(v reflect.Value) int64 { t, ok := hreflect.AsTime(v, ns.loc) if !ok { panic("coding error: argument must be time.Time type reflect Value") } return t.Unix() }
// Copyright 2017 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 collections import ( "context" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/maps" ) // Where returns a filtered subset of collection c. func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) { seqv, isNil := indirect(reflect.ValueOf(c)) if isNil { return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String()) } mv, op, err := parseWhereArgs(args...) if err != nil { return nil, err } ctxv := reflect.ValueOf(ctx) var path []string kv := reflect.ValueOf(key) if kv.Kind() == reflect.String { path = strings.Split(strings.Trim(kv.String(), "."), ".") } switch seqv.Kind() { case reflect.Array, reflect.Slice: return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op) case reflect.Map: return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op) default: return nil, fmt.Errorf("can't iterate over %v", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := indirect(mv) if !mv.IsValid() { mvIsNil = true } if vIsNil || mvIsNil { switch op { case "", "=", "==", "eq": return vIsNil == mvIsNil, nil case "!=", "<>", "ne": return vIsNil != mvIsNil, nil } return false, nil } if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool { switch op { case "", "=", "==", "eq": return v.Bool() == mv.Bool(), nil case "!=", "<>", "ne": return v.Bool() != mv.Bool(), nil } return false, nil } var ivp, imvp *int64 var fvp, fmvp *float64 var svp, smvp *string var slv, slmv any var ima []int64 var fma []float64 var sma []string if mv.Kind() == v.Kind() { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv imv := mv.Int() imvp = &imv case reflect.String: sv := v.String() svp = &sv smv := mv.String() smvp = &smv case reflect.Float64: fv := v.Float() fvp = &fv fmv := mv.Float() fmvp = &fmv case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv imv := ns.toTimeUnix(mv) imvp = &imv } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } else if isNumber(v.Kind()) && isNumber(mv.Kind()) { fv, err := toFloat(v) if err != nil { return false, err } fvp = &fv fmv, err := toFloat(mv) if err != nil { return false, err } fmvp = &fmv } else { if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice { return false, nil } if mv.Len() == 0 { return false, nil } if v.Kind() != reflect.Interface && mv.Type().Elem().Kind() != reflect.Interface && mv.Type().Elem() != v.Type() && v.Kind() != reflect.Array && v.Kind() != reflect.Slice { return false, nil } switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv for i := 0; i < mv.Len(); i++ { if anInt, err := toInt(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := 0; i < mv.Len(); i++ { if aString, err := toString(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := 0; i < mv.Len(); i++ { if aFloat, err := toFloat(mv.Index(i)); err == nil { fma = append(fma, aFloat) } } case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv for i := 0; i < mv.Len(); i++ { ima = append(ima, ns.toTimeUnix(mv.Index(i))) } } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } switch op { case "", "=", "==", "eq": switch { case ivp != nil && imvp != nil: return *ivp == *imvp, nil case svp != nil && smvp != nil: return *svp == *smvp, nil case fvp != nil && fmvp != nil: return *fvp == *fmvp, nil } case "!=", "<>", "ne": switch { case ivp != nil && imvp != nil: return *ivp != *imvp, nil case svp != nil && smvp != nil: return *svp != *smvp, nil case fvp != nil && fmvp != nil: return *fvp != *fmvp, nil } case ">=", "ge": switch { case ivp != nil && imvp != nil: return *ivp >= *imvp, nil case svp != nil && smvp != nil: return *svp >= *smvp, nil case fvp != nil && fmvp != nil: return *fvp >= *fmvp, nil } case ">", "gt": switch { case ivp != nil && imvp != nil: return *ivp > *imvp, nil case svp != nil && smvp != nil: return *svp > *smvp, nil case fvp != nil && fmvp != nil: return *fvp > *fmvp, nil } case "<=", "le": switch { case ivp != nil && imvp != nil: return *ivp <= *imvp, nil case svp != nil && smvp != nil: return *svp <= *smvp, nil case fvp != nil && fmvp != nil: return *fvp <= *fmvp, nil } case "<", "lt": switch { case ivp != nil && imvp != nil: return *ivp < *imvp, nil case svp != nil && smvp != nil: return *svp < *smvp, nil case fvp != nil && fmvp != nil: return *fvp < *fmvp, nil } case "in", "not in": var r bool switch { case ivp != nil && len(ima) > 0: r, _ = ns.In(ima, *ivp) case fvp != nil && len(fma) > 0: r, _ = ns.In(fma, *fvp) case svp != nil: if len(sma) > 0 { r, _ = ns.In(sma, *svp) } else if smvp != nil { r, _ = ns.In(*smvp, *svp) } default: return false, nil } if op == "not in" { return !r, nil } return r, nil case "intersect": r, err := ns.Intersect(slv, slmv) if err != nil { return false, err } if reflect.TypeOf(r).Kind() == reflect.Slice { s := reflect.ValueOf(r) if s.Len() > 0 { return true, nil } return false, nil } return false, errors.New("invalid intersect values") case "like": if svp != nil && smvp != nil { re, err := hstrings.GetOrCompileRegexp(*smvp) if err != nil { return false, err } if re.MatchString(*svp) { return true, nil } return false, nil } default: return false, errors.New("no such operator") } return false, nil } func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) { if !obj.IsValid() { return zero, errors.New("can't evaluate an invalid value") } typ := obj.Type() obj, isNil := indirect(obj) if obj.Kind() == reflect.Interface { // If obj is an interface, we need to inspect the value it contains // to see the full set of methods and fields. // Indirect returns the value that it points to, which is what's needed // below to be able to reflect on its fields. obj = reflect.Indirect(obj.Elem()) } // first, check whether obj has a method. In this case, obj is // a struct or its pointer. If obj is a struct, // to check all T and *T method, use obj pointer type Value objPtr := obj if objPtr.Kind() != reflect.Interface && objPtr.CanAddr() { objPtr = objPtr.Addr() } index := hreflect.GetMethodIndexByName(objPtr.Type(), elemName) if index != -1 { var args []reflect.Value mt := objPtr.Type().Method(index) num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && mt.Type.In(1).Implements(hreflect.ContextInterface) { args = []reflect.Value{ctx} maxNumIn = 2 } switch { case mt.PkgPath != "": return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ) case mt.Type.NumIn() > maxNumIn: return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn) case mt.Type.NumOut() == 0: return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ) case mt.Type.NumOut() > 2: return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ) case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ) case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ) } res := objPtr.Method(mt.Index).Call(args) if len(res) == 2 && !res[1].IsNil() { return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error)) } return res[0], nil } // elemName isn't a method so next start to check whether it is // a struct field or a map value. In both cases, it mustn't be // a nil value if isNil { return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName) } switch obj.Kind() { case reflect.Struct: ft, ok := obj.Type().FieldByName(elemName) if ok { if ft.PkgPath != "" && !ft.Anonymous { return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ) } return obj.FieldByIndex(ft.Index), nil } return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ) case reflect.Map: kv := reflect.ValueOf(elemName) if kv.Type().AssignableTo(obj.Type().Key()) { return obj.MapIndex(kv), nil } return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ) } return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ) } // parseWhereArgs parses the end arguments to the where function. Return a // match value and an operator, if one is defined. func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) { switch len(args) { case 1: mv = reflect.ValueOf(args[0]) case 2: var ok bool if op, ok = args[0].(string); !ok { err = errors.New("operator argument must be string type") return } op = strings.TrimSpace(strings.ToLower(op)) mv = reflect.ValueOf(args[1]) default: err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments") } return } // checkWhereArray handles the where-matching logic when the seqv value is an // Array or Slice. func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeSlice(seqv.Type(), 0, 0) for i := 0; i < seqv.Len(); i++ { var vvv reflect.Value rvv := seqv.Index(i) if kv.Kind() == reflect.String { if params, ok := rvv.Interface().(maps.Params); ok { vvv = reflect.ValueOf(params.GetNested(path...)) } else { vvv = rvv for i, elemName := range path { var err error vvv, err = evaluateSubElem(ctxv, vvv, elemName) if err != nil { continue } if i < len(path)-1 && vvv.IsValid() { if params, ok := vvv.Interface().(maps.Params); ok { // The current path element is the map itself, .Params. vvv = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } } } } else { vv, _ := indirect(rvv) if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) { vvv = vv.MapIndex(kv) } } if ok, err := ns.checkCondition(vvv, mv, op); ok { rv = reflect.Append(rv, rvv) } else if err != nil { return nil, err } } return rv.Interface(), nil } // checkWhereMap handles the where-matching logic when the seqv value is a Map. func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeMap(seqv.Type()) keys := seqv.MapKeys() for _, k := range keys { elemv := seqv.MapIndex(k) switch elemv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } case reflect.Interface: elemvv, isNil := indirect(elemv) if isNil { continue } switch elemvv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } } } } return rv.Interface(), nil } // toFloat returns the float value if possible. func toFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Convert(reflect.TypeOf(float64(0))).Float(), nil case reflect.Interface: return toFloat(v.Elem()) } return -1, errors.New("unable to convert value to float") } // toInt returns the int value if possible, -1 if not. // TODO(bep) consolidate all these reflect funcs. func toInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil case reflect.Interface: return toInt(v.Elem()) } return -1, errors.New("unable to convert value to int") } func toUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil case reflect.Interface: return toUint(v.Elem()) } return 0, errors.New("unable to convert value to uint") } // toString returns the string value if possible, "" if not. func toString(v reflect.Value) (string, error) { switch v.Kind() { case reflect.String: return v.String(), nil case reflect.Interface: return toString(v.Elem()) } return "", errors.New("unable to convert value to string") } func (ns *Namespace) toTimeUnix(v reflect.Value) int64 { t, ok := hreflect.AsTime(v, ns.loc) if !ok { panic("coding error: argument must be time.Time type reflect Value") } return t.Unix() }
jmooring
dc2a544fac7a3f9cb8bff70d5cbe92b37dee98d1
f4598a09864bee2689a7630dda83a71a9b9cf55b
As to 1) Above, it's fine to create one `*regexp.Regexp` per `where` invocation, we just need to avoid repeating it for every element in the collection.
bep
23
gohugoio/hugo
11,281
tpl/collections: Add like operator to where function
Enables constructs such as: ```text {{ range where site.RegularPages "Params.foo" "like" "^ab" }} <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> {{ end }} ``` Will submit documentation change to the documentation repository is this is merged. Closes #11279
null
2023-07-23 19:55:24+00:00
2023-07-28 07:53:01+00:00
tpl/collections/where.go
// Copyright 2017 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 collections import ( "context" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" ) // Where returns a filtered subset of collection c. func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) { seqv, isNil := indirect(reflect.ValueOf(c)) if isNil { return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String()) } mv, op, err := parseWhereArgs(args...) if err != nil { return nil, err } ctxv := reflect.ValueOf(ctx) var path []string kv := reflect.ValueOf(key) if kv.Kind() == reflect.String { path = strings.Split(strings.Trim(kv.String(), "."), ".") } switch seqv.Kind() { case reflect.Array, reflect.Slice: return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op) case reflect.Map: return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op) default: return nil, fmt.Errorf("can't iterate over %v", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := indirect(mv) if !mv.IsValid() { mvIsNil = true } if vIsNil || mvIsNil { switch op { case "", "=", "==", "eq": return vIsNil == mvIsNil, nil case "!=", "<>", "ne": return vIsNil != mvIsNil, nil } return false, nil } if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool { switch op { case "", "=", "==", "eq": return v.Bool() == mv.Bool(), nil case "!=", "<>", "ne": return v.Bool() != mv.Bool(), nil } return false, nil } var ivp, imvp *int64 var fvp, fmvp *float64 var svp, smvp *string var slv, slmv any var ima []int64 var fma []float64 var sma []string if mv.Kind() == v.Kind() { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv imv := mv.Int() imvp = &imv case reflect.String: sv := v.String() svp = &sv smv := mv.String() smvp = &smv case reflect.Float64: fv := v.Float() fvp = &fv fmv := mv.Float() fmvp = &fmv case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv imv := ns.toTimeUnix(mv) imvp = &imv } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } else if isNumber(v.Kind()) && isNumber(mv.Kind()) { fv, err := toFloat(v) if err != nil { return false, err } fvp = &fv fmv, err := toFloat(mv) if err != nil { return false, err } fmvp = &fmv } else { if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice { return false, nil } if mv.Len() == 0 { return false, nil } if v.Kind() != reflect.Interface && mv.Type().Elem().Kind() != reflect.Interface && mv.Type().Elem() != v.Type() && v.Kind() != reflect.Array && v.Kind() != reflect.Slice { return false, nil } switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv for i := 0; i < mv.Len(); i++ { if anInt, err := toInt(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := 0; i < mv.Len(); i++ { if aString, err := toString(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := 0; i < mv.Len(); i++ { if aFloat, err := toFloat(mv.Index(i)); err == nil { fma = append(fma, aFloat) } } case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv for i := 0; i < mv.Len(); i++ { ima = append(ima, ns.toTimeUnix(mv.Index(i))) } } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } switch op { case "", "=", "==", "eq": switch { case ivp != nil && imvp != nil: return *ivp == *imvp, nil case svp != nil && smvp != nil: return *svp == *smvp, nil case fvp != nil && fmvp != nil: return *fvp == *fmvp, nil } case "!=", "<>", "ne": switch { case ivp != nil && imvp != nil: return *ivp != *imvp, nil case svp != nil && smvp != nil: return *svp != *smvp, nil case fvp != nil && fmvp != nil: return *fvp != *fmvp, nil } case ">=", "ge": switch { case ivp != nil && imvp != nil: return *ivp >= *imvp, nil case svp != nil && smvp != nil: return *svp >= *smvp, nil case fvp != nil && fmvp != nil: return *fvp >= *fmvp, nil } case ">", "gt": switch { case ivp != nil && imvp != nil: return *ivp > *imvp, nil case svp != nil && smvp != nil: return *svp > *smvp, nil case fvp != nil && fmvp != nil: return *fvp > *fmvp, nil } case "<=", "le": switch { case ivp != nil && imvp != nil: return *ivp <= *imvp, nil case svp != nil && smvp != nil: return *svp <= *smvp, nil case fvp != nil && fmvp != nil: return *fvp <= *fmvp, nil } case "<", "lt": switch { case ivp != nil && imvp != nil: return *ivp < *imvp, nil case svp != nil && smvp != nil: return *svp < *smvp, nil case fvp != nil && fmvp != nil: return *fvp < *fmvp, nil } case "in", "not in": var r bool switch { case ivp != nil && len(ima) > 0: r, _ = ns.In(ima, *ivp) case fvp != nil && len(fma) > 0: r, _ = ns.In(fma, *fvp) case svp != nil: if len(sma) > 0 { r, _ = ns.In(sma, *svp) } else if smvp != nil { r, _ = ns.In(*smvp, *svp) } default: return false, nil } if op == "not in" { return !r, nil } return r, nil case "intersect": r, err := ns.Intersect(slv, slmv) if err != nil { return false, err } if reflect.TypeOf(r).Kind() == reflect.Slice { s := reflect.ValueOf(r) if s.Len() > 0 { return true, nil } return false, nil } return false, errors.New("invalid intersect values") default: return false, errors.New("no such operator") } return false, nil } func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) { if !obj.IsValid() { return zero, errors.New("can't evaluate an invalid value") } typ := obj.Type() obj, isNil := indirect(obj) if obj.Kind() == reflect.Interface { // If obj is an interface, we need to inspect the value it contains // to see the full set of methods and fields. // Indirect returns the value that it points to, which is what's needed // below to be able to reflect on its fields. obj = reflect.Indirect(obj.Elem()) } // first, check whether obj has a method. In this case, obj is // a struct or its pointer. If obj is a struct, // to check all T and *T method, use obj pointer type Value objPtr := obj if objPtr.Kind() != reflect.Interface && objPtr.CanAddr() { objPtr = objPtr.Addr() } index := hreflect.GetMethodIndexByName(objPtr.Type(), elemName) if index != -1 { var args []reflect.Value mt := objPtr.Type().Method(index) num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && mt.Type.In(1).Implements(hreflect.ContextInterface) { args = []reflect.Value{ctx} maxNumIn = 2 } switch { case mt.PkgPath != "": return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ) case mt.Type.NumIn() > maxNumIn: return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn) case mt.Type.NumOut() == 0: return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ) case mt.Type.NumOut() > 2: return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ) case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ) case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ) } res := objPtr.Method(mt.Index).Call(args) if len(res) == 2 && !res[1].IsNil() { return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error)) } return res[0], nil } // elemName isn't a method so next start to check whether it is // a struct field or a map value. In both cases, it mustn't be // a nil value if isNil { return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName) } switch obj.Kind() { case reflect.Struct: ft, ok := obj.Type().FieldByName(elemName) if ok { if ft.PkgPath != "" && !ft.Anonymous { return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ) } return obj.FieldByIndex(ft.Index), nil } return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ) case reflect.Map: kv := reflect.ValueOf(elemName) if kv.Type().AssignableTo(obj.Type().Key()) { return obj.MapIndex(kv), nil } return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ) } return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ) } // parseWhereArgs parses the end arguments to the where function. Return a // match value and an operator, if one is defined. func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) { switch len(args) { case 1: mv = reflect.ValueOf(args[0]) case 2: var ok bool if op, ok = args[0].(string); !ok { err = errors.New("operator argument must be string type") return } op = strings.TrimSpace(strings.ToLower(op)) mv = reflect.ValueOf(args[1]) default: err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments") } return } // checkWhereArray handles the where-matching logic when the seqv value is an // Array or Slice. func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeSlice(seqv.Type(), 0, 0) for i := 0; i < seqv.Len(); i++ { var vvv reflect.Value rvv := seqv.Index(i) if kv.Kind() == reflect.String { if params, ok := rvv.Interface().(maps.Params); ok { vvv = reflect.ValueOf(params.GetNested(path...)) } else { vvv = rvv for i, elemName := range path { var err error vvv, err = evaluateSubElem(ctxv, vvv, elemName) if err != nil { continue } if i < len(path)-1 && vvv.IsValid() { if params, ok := vvv.Interface().(maps.Params); ok { // The current path element is the map itself, .Params. vvv = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } } } } else { vv, _ := indirect(rvv) if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) { vvv = vv.MapIndex(kv) } } if ok, err := ns.checkCondition(vvv, mv, op); ok { rv = reflect.Append(rv, rvv) } else if err != nil { return nil, err } } return rv.Interface(), nil } // checkWhereMap handles the where-matching logic when the seqv value is a Map. func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeMap(seqv.Type()) keys := seqv.MapKeys() for _, k := range keys { elemv := seqv.MapIndex(k) switch elemv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } case reflect.Interface: elemvv, isNil := indirect(elemv) if isNil { continue } switch elemvv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } } } } return rv.Interface(), nil } // toFloat returns the float value if possible. func toFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Convert(reflect.TypeOf(float64(0))).Float(), nil case reflect.Interface: return toFloat(v.Elem()) } return -1, errors.New("unable to convert value to float") } // toInt returns the int value if possible, -1 if not. // TODO(bep) consolidate all these reflect funcs. func toInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil case reflect.Interface: return toInt(v.Elem()) } return -1, errors.New("unable to convert value to int") } func toUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil case reflect.Interface: return toUint(v.Elem()) } return 0, errors.New("unable to convert value to uint") } // toString returns the string value if possible, "" if not. func toString(v reflect.Value) (string, error) { switch v.Kind() { case reflect.String: return v.String(), nil case reflect.Interface: return toString(v.Elem()) } return "", errors.New("unable to convert value to string") } func (ns *Namespace) toTimeUnix(v reflect.Value) int64 { t, ok := hreflect.AsTime(v, ns.loc) if !ok { panic("coding error: argument must be time.Time type reflect Value") } return t.Unix() }
// Copyright 2017 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 collections import ( "context" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/maps" ) // Where returns a filtered subset of collection c. func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) { seqv, isNil := indirect(reflect.ValueOf(c)) if isNil { return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String()) } mv, op, err := parseWhereArgs(args...) if err != nil { return nil, err } ctxv := reflect.ValueOf(ctx) var path []string kv := reflect.ValueOf(key) if kv.Kind() == reflect.String { path = strings.Split(strings.Trim(kv.String(), "."), ".") } switch seqv.Kind() { case reflect.Array, reflect.Slice: return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op) case reflect.Map: return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op) default: return nil, fmt.Errorf("can't iterate over %v", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := indirect(mv) if !mv.IsValid() { mvIsNil = true } if vIsNil || mvIsNil { switch op { case "", "=", "==", "eq": return vIsNil == mvIsNil, nil case "!=", "<>", "ne": return vIsNil != mvIsNil, nil } return false, nil } if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool { switch op { case "", "=", "==", "eq": return v.Bool() == mv.Bool(), nil case "!=", "<>", "ne": return v.Bool() != mv.Bool(), nil } return false, nil } var ivp, imvp *int64 var fvp, fmvp *float64 var svp, smvp *string var slv, slmv any var ima []int64 var fma []float64 var sma []string if mv.Kind() == v.Kind() { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv imv := mv.Int() imvp = &imv case reflect.String: sv := v.String() svp = &sv smv := mv.String() smvp = &smv case reflect.Float64: fv := v.Float() fvp = &fv fmv := mv.Float() fmvp = &fmv case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv imv := ns.toTimeUnix(mv) imvp = &imv } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } else if isNumber(v.Kind()) && isNumber(mv.Kind()) { fv, err := toFloat(v) if err != nil { return false, err } fvp = &fv fmv, err := toFloat(mv) if err != nil { return false, err } fmvp = &fmv } else { if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice { return false, nil } if mv.Len() == 0 { return false, nil } if v.Kind() != reflect.Interface && mv.Type().Elem().Kind() != reflect.Interface && mv.Type().Elem() != v.Type() && v.Kind() != reflect.Array && v.Kind() != reflect.Slice { return false, nil } switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv for i := 0; i < mv.Len(); i++ { if anInt, err := toInt(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := 0; i < mv.Len(); i++ { if aString, err := toString(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := 0; i < mv.Len(); i++ { if aFloat, err := toFloat(mv.Index(i)); err == nil { fma = append(fma, aFloat) } } case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv for i := 0; i < mv.Len(); i++ { ima = append(ima, ns.toTimeUnix(mv.Index(i))) } } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } switch op { case "", "=", "==", "eq": switch { case ivp != nil && imvp != nil: return *ivp == *imvp, nil case svp != nil && smvp != nil: return *svp == *smvp, nil case fvp != nil && fmvp != nil: return *fvp == *fmvp, nil } case "!=", "<>", "ne": switch { case ivp != nil && imvp != nil: return *ivp != *imvp, nil case svp != nil && smvp != nil: return *svp != *smvp, nil case fvp != nil && fmvp != nil: return *fvp != *fmvp, nil } case ">=", "ge": switch { case ivp != nil && imvp != nil: return *ivp >= *imvp, nil case svp != nil && smvp != nil: return *svp >= *smvp, nil case fvp != nil && fmvp != nil: return *fvp >= *fmvp, nil } case ">", "gt": switch { case ivp != nil && imvp != nil: return *ivp > *imvp, nil case svp != nil && smvp != nil: return *svp > *smvp, nil case fvp != nil && fmvp != nil: return *fvp > *fmvp, nil } case "<=", "le": switch { case ivp != nil && imvp != nil: return *ivp <= *imvp, nil case svp != nil && smvp != nil: return *svp <= *smvp, nil case fvp != nil && fmvp != nil: return *fvp <= *fmvp, nil } case "<", "lt": switch { case ivp != nil && imvp != nil: return *ivp < *imvp, nil case svp != nil && smvp != nil: return *svp < *smvp, nil case fvp != nil && fmvp != nil: return *fvp < *fmvp, nil } case "in", "not in": var r bool switch { case ivp != nil && len(ima) > 0: r, _ = ns.In(ima, *ivp) case fvp != nil && len(fma) > 0: r, _ = ns.In(fma, *fvp) case svp != nil: if len(sma) > 0 { r, _ = ns.In(sma, *svp) } else if smvp != nil { r, _ = ns.In(*smvp, *svp) } default: return false, nil } if op == "not in" { return !r, nil } return r, nil case "intersect": r, err := ns.Intersect(slv, slmv) if err != nil { return false, err } if reflect.TypeOf(r).Kind() == reflect.Slice { s := reflect.ValueOf(r) if s.Len() > 0 { return true, nil } return false, nil } return false, errors.New("invalid intersect values") case "like": if svp != nil && smvp != nil { re, err := hstrings.GetOrCompileRegexp(*smvp) if err != nil { return false, err } if re.MatchString(*svp) { return true, nil } return false, nil } default: return false, errors.New("no such operator") } return false, nil } func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) { if !obj.IsValid() { return zero, errors.New("can't evaluate an invalid value") } typ := obj.Type() obj, isNil := indirect(obj) if obj.Kind() == reflect.Interface { // If obj is an interface, we need to inspect the value it contains // to see the full set of methods and fields. // Indirect returns the value that it points to, which is what's needed // below to be able to reflect on its fields. obj = reflect.Indirect(obj.Elem()) } // first, check whether obj has a method. In this case, obj is // a struct or its pointer. If obj is a struct, // to check all T and *T method, use obj pointer type Value objPtr := obj if objPtr.Kind() != reflect.Interface && objPtr.CanAddr() { objPtr = objPtr.Addr() } index := hreflect.GetMethodIndexByName(objPtr.Type(), elemName) if index != -1 { var args []reflect.Value mt := objPtr.Type().Method(index) num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && mt.Type.In(1).Implements(hreflect.ContextInterface) { args = []reflect.Value{ctx} maxNumIn = 2 } switch { case mt.PkgPath != "": return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ) case mt.Type.NumIn() > maxNumIn: return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn) case mt.Type.NumOut() == 0: return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ) case mt.Type.NumOut() > 2: return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ) case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ) case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ) } res := objPtr.Method(mt.Index).Call(args) if len(res) == 2 && !res[1].IsNil() { return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error)) } return res[0], nil } // elemName isn't a method so next start to check whether it is // a struct field or a map value. In both cases, it mustn't be // a nil value if isNil { return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName) } switch obj.Kind() { case reflect.Struct: ft, ok := obj.Type().FieldByName(elemName) if ok { if ft.PkgPath != "" && !ft.Anonymous { return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ) } return obj.FieldByIndex(ft.Index), nil } return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ) case reflect.Map: kv := reflect.ValueOf(elemName) if kv.Type().AssignableTo(obj.Type().Key()) { return obj.MapIndex(kv), nil } return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ) } return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ) } // parseWhereArgs parses the end arguments to the where function. Return a // match value and an operator, if one is defined. func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) { switch len(args) { case 1: mv = reflect.ValueOf(args[0]) case 2: var ok bool if op, ok = args[0].(string); !ok { err = errors.New("operator argument must be string type") return } op = strings.TrimSpace(strings.ToLower(op)) mv = reflect.ValueOf(args[1]) default: err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments") } return } // checkWhereArray handles the where-matching logic when the seqv value is an // Array or Slice. func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeSlice(seqv.Type(), 0, 0) for i := 0; i < seqv.Len(); i++ { var vvv reflect.Value rvv := seqv.Index(i) if kv.Kind() == reflect.String { if params, ok := rvv.Interface().(maps.Params); ok { vvv = reflect.ValueOf(params.GetNested(path...)) } else { vvv = rvv for i, elemName := range path { var err error vvv, err = evaluateSubElem(ctxv, vvv, elemName) if err != nil { continue } if i < len(path)-1 && vvv.IsValid() { if params, ok := vvv.Interface().(maps.Params); ok { // The current path element is the map itself, .Params. vvv = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } } } } else { vv, _ := indirect(rvv) if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) { vvv = vv.MapIndex(kv) } } if ok, err := ns.checkCondition(vvv, mv, op); ok { rv = reflect.Append(rv, rvv) } else if err != nil { return nil, err } } return rv.Interface(), nil } // checkWhereMap handles the where-matching logic when the seqv value is a Map. func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeMap(seqv.Type()) keys := seqv.MapKeys() for _, k := range keys { elemv := seqv.MapIndex(k) switch elemv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } case reflect.Interface: elemvv, isNil := indirect(elemv) if isNil { continue } switch elemvv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } } } } return rv.Interface(), nil } // toFloat returns the float value if possible. func toFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Convert(reflect.TypeOf(float64(0))).Float(), nil case reflect.Interface: return toFloat(v.Elem()) } return -1, errors.New("unable to convert value to float") } // toInt returns the int value if possible, -1 if not. // TODO(bep) consolidate all these reflect funcs. func toInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil case reflect.Interface: return toInt(v.Elem()) } return -1, errors.New("unable to convert value to int") } func toUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil case reflect.Interface: return toUint(v.Elem()) } return 0, errors.New("unable to convert value to uint") } // toString returns the string value if possible, "" if not. func toString(v reflect.Value) (string, error) { switch v.Kind() { case reflect.String: return v.String(), nil case reflect.Interface: return toString(v.Elem()) } return "", errors.New("unable to convert value to string") } func (ns *Namespace) toTimeUnix(v reflect.Value) int64 { t, ok := hreflect.AsTime(v, ns.loc) if !ok { panic("coding error: argument must be time.Time type reflect Value") } return t.Unix() }
jmooring
dc2a544fac7a3f9cb8bff70d5cbe92b37dee98d1
f4598a09864bee2689a7630dda83a71a9b9cf55b
The strings regex functions (`findRE`, etc.). use a caching mechanism: <https://github.com/gohugoio/hugo/blob/master/tpl/strings/regexp.go#L120> I would need guidance to figure out to how share that between the two namespaces.
jmooring
24
gohugoio/hugo
11,281
tpl/collections: Add like operator to where function
Enables constructs such as: ```text {{ range where site.RegularPages "Params.foo" "like" "^ab" }} <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> {{ end }} ``` Will submit documentation change to the documentation repository is this is merged. Closes #11279
null
2023-07-23 19:55:24+00:00
2023-07-28 07:53:01+00:00
tpl/collections/where.go
// Copyright 2017 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 collections import ( "context" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" ) // Where returns a filtered subset of collection c. func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) { seqv, isNil := indirect(reflect.ValueOf(c)) if isNil { return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String()) } mv, op, err := parseWhereArgs(args...) if err != nil { return nil, err } ctxv := reflect.ValueOf(ctx) var path []string kv := reflect.ValueOf(key) if kv.Kind() == reflect.String { path = strings.Split(strings.Trim(kv.String(), "."), ".") } switch seqv.Kind() { case reflect.Array, reflect.Slice: return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op) case reflect.Map: return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op) default: return nil, fmt.Errorf("can't iterate over %v", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := indirect(mv) if !mv.IsValid() { mvIsNil = true } if vIsNil || mvIsNil { switch op { case "", "=", "==", "eq": return vIsNil == mvIsNil, nil case "!=", "<>", "ne": return vIsNil != mvIsNil, nil } return false, nil } if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool { switch op { case "", "=", "==", "eq": return v.Bool() == mv.Bool(), nil case "!=", "<>", "ne": return v.Bool() != mv.Bool(), nil } return false, nil } var ivp, imvp *int64 var fvp, fmvp *float64 var svp, smvp *string var slv, slmv any var ima []int64 var fma []float64 var sma []string if mv.Kind() == v.Kind() { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv imv := mv.Int() imvp = &imv case reflect.String: sv := v.String() svp = &sv smv := mv.String() smvp = &smv case reflect.Float64: fv := v.Float() fvp = &fv fmv := mv.Float() fmvp = &fmv case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv imv := ns.toTimeUnix(mv) imvp = &imv } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } else if isNumber(v.Kind()) && isNumber(mv.Kind()) { fv, err := toFloat(v) if err != nil { return false, err } fvp = &fv fmv, err := toFloat(mv) if err != nil { return false, err } fmvp = &fmv } else { if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice { return false, nil } if mv.Len() == 0 { return false, nil } if v.Kind() != reflect.Interface && mv.Type().Elem().Kind() != reflect.Interface && mv.Type().Elem() != v.Type() && v.Kind() != reflect.Array && v.Kind() != reflect.Slice { return false, nil } switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv for i := 0; i < mv.Len(); i++ { if anInt, err := toInt(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := 0; i < mv.Len(); i++ { if aString, err := toString(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := 0; i < mv.Len(); i++ { if aFloat, err := toFloat(mv.Index(i)); err == nil { fma = append(fma, aFloat) } } case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv for i := 0; i < mv.Len(); i++ { ima = append(ima, ns.toTimeUnix(mv.Index(i))) } } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } switch op { case "", "=", "==", "eq": switch { case ivp != nil && imvp != nil: return *ivp == *imvp, nil case svp != nil && smvp != nil: return *svp == *smvp, nil case fvp != nil && fmvp != nil: return *fvp == *fmvp, nil } case "!=", "<>", "ne": switch { case ivp != nil && imvp != nil: return *ivp != *imvp, nil case svp != nil && smvp != nil: return *svp != *smvp, nil case fvp != nil && fmvp != nil: return *fvp != *fmvp, nil } case ">=", "ge": switch { case ivp != nil && imvp != nil: return *ivp >= *imvp, nil case svp != nil && smvp != nil: return *svp >= *smvp, nil case fvp != nil && fmvp != nil: return *fvp >= *fmvp, nil } case ">", "gt": switch { case ivp != nil && imvp != nil: return *ivp > *imvp, nil case svp != nil && smvp != nil: return *svp > *smvp, nil case fvp != nil && fmvp != nil: return *fvp > *fmvp, nil } case "<=", "le": switch { case ivp != nil && imvp != nil: return *ivp <= *imvp, nil case svp != nil && smvp != nil: return *svp <= *smvp, nil case fvp != nil && fmvp != nil: return *fvp <= *fmvp, nil } case "<", "lt": switch { case ivp != nil && imvp != nil: return *ivp < *imvp, nil case svp != nil && smvp != nil: return *svp < *smvp, nil case fvp != nil && fmvp != nil: return *fvp < *fmvp, nil } case "in", "not in": var r bool switch { case ivp != nil && len(ima) > 0: r, _ = ns.In(ima, *ivp) case fvp != nil && len(fma) > 0: r, _ = ns.In(fma, *fvp) case svp != nil: if len(sma) > 0 { r, _ = ns.In(sma, *svp) } else if smvp != nil { r, _ = ns.In(*smvp, *svp) } default: return false, nil } if op == "not in" { return !r, nil } return r, nil case "intersect": r, err := ns.Intersect(slv, slmv) if err != nil { return false, err } if reflect.TypeOf(r).Kind() == reflect.Slice { s := reflect.ValueOf(r) if s.Len() > 0 { return true, nil } return false, nil } return false, errors.New("invalid intersect values") default: return false, errors.New("no such operator") } return false, nil } func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) { if !obj.IsValid() { return zero, errors.New("can't evaluate an invalid value") } typ := obj.Type() obj, isNil := indirect(obj) if obj.Kind() == reflect.Interface { // If obj is an interface, we need to inspect the value it contains // to see the full set of methods and fields. // Indirect returns the value that it points to, which is what's needed // below to be able to reflect on its fields. obj = reflect.Indirect(obj.Elem()) } // first, check whether obj has a method. In this case, obj is // a struct or its pointer. If obj is a struct, // to check all T and *T method, use obj pointer type Value objPtr := obj if objPtr.Kind() != reflect.Interface && objPtr.CanAddr() { objPtr = objPtr.Addr() } index := hreflect.GetMethodIndexByName(objPtr.Type(), elemName) if index != -1 { var args []reflect.Value mt := objPtr.Type().Method(index) num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && mt.Type.In(1).Implements(hreflect.ContextInterface) { args = []reflect.Value{ctx} maxNumIn = 2 } switch { case mt.PkgPath != "": return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ) case mt.Type.NumIn() > maxNumIn: return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn) case mt.Type.NumOut() == 0: return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ) case mt.Type.NumOut() > 2: return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ) case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ) case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ) } res := objPtr.Method(mt.Index).Call(args) if len(res) == 2 && !res[1].IsNil() { return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error)) } return res[0], nil } // elemName isn't a method so next start to check whether it is // a struct field or a map value. In both cases, it mustn't be // a nil value if isNil { return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName) } switch obj.Kind() { case reflect.Struct: ft, ok := obj.Type().FieldByName(elemName) if ok { if ft.PkgPath != "" && !ft.Anonymous { return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ) } return obj.FieldByIndex(ft.Index), nil } return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ) case reflect.Map: kv := reflect.ValueOf(elemName) if kv.Type().AssignableTo(obj.Type().Key()) { return obj.MapIndex(kv), nil } return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ) } return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ) } // parseWhereArgs parses the end arguments to the where function. Return a // match value and an operator, if one is defined. func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) { switch len(args) { case 1: mv = reflect.ValueOf(args[0]) case 2: var ok bool if op, ok = args[0].(string); !ok { err = errors.New("operator argument must be string type") return } op = strings.TrimSpace(strings.ToLower(op)) mv = reflect.ValueOf(args[1]) default: err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments") } return } // checkWhereArray handles the where-matching logic when the seqv value is an // Array or Slice. func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeSlice(seqv.Type(), 0, 0) for i := 0; i < seqv.Len(); i++ { var vvv reflect.Value rvv := seqv.Index(i) if kv.Kind() == reflect.String { if params, ok := rvv.Interface().(maps.Params); ok { vvv = reflect.ValueOf(params.GetNested(path...)) } else { vvv = rvv for i, elemName := range path { var err error vvv, err = evaluateSubElem(ctxv, vvv, elemName) if err != nil { continue } if i < len(path)-1 && vvv.IsValid() { if params, ok := vvv.Interface().(maps.Params); ok { // The current path element is the map itself, .Params. vvv = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } } } } else { vv, _ := indirect(rvv) if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) { vvv = vv.MapIndex(kv) } } if ok, err := ns.checkCondition(vvv, mv, op); ok { rv = reflect.Append(rv, rvv) } else if err != nil { return nil, err } } return rv.Interface(), nil } // checkWhereMap handles the where-matching logic when the seqv value is a Map. func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeMap(seqv.Type()) keys := seqv.MapKeys() for _, k := range keys { elemv := seqv.MapIndex(k) switch elemv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } case reflect.Interface: elemvv, isNil := indirect(elemv) if isNil { continue } switch elemvv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } } } } return rv.Interface(), nil } // toFloat returns the float value if possible. func toFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Convert(reflect.TypeOf(float64(0))).Float(), nil case reflect.Interface: return toFloat(v.Elem()) } return -1, errors.New("unable to convert value to float") } // toInt returns the int value if possible, -1 if not. // TODO(bep) consolidate all these reflect funcs. func toInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil case reflect.Interface: return toInt(v.Elem()) } return -1, errors.New("unable to convert value to int") } func toUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil case reflect.Interface: return toUint(v.Elem()) } return 0, errors.New("unable to convert value to uint") } // toString returns the string value if possible, "" if not. func toString(v reflect.Value) (string, error) { switch v.Kind() { case reflect.String: return v.String(), nil case reflect.Interface: return toString(v.Elem()) } return "", errors.New("unable to convert value to string") } func (ns *Namespace) toTimeUnix(v reflect.Value) int64 { t, ok := hreflect.AsTime(v, ns.loc) if !ok { panic("coding error: argument must be time.Time type reflect Value") } return t.Unix() }
// Copyright 2017 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 collections import ( "context" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/maps" ) // Where returns a filtered subset of collection c. func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) { seqv, isNil := indirect(reflect.ValueOf(c)) if isNil { return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String()) } mv, op, err := parseWhereArgs(args...) if err != nil { return nil, err } ctxv := reflect.ValueOf(ctx) var path []string kv := reflect.ValueOf(key) if kv.Kind() == reflect.String { path = strings.Split(strings.Trim(kv.String(), "."), ".") } switch seqv.Kind() { case reflect.Array, reflect.Slice: return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op) case reflect.Map: return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op) default: return nil, fmt.Errorf("can't iterate over %v", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := indirect(mv) if !mv.IsValid() { mvIsNil = true } if vIsNil || mvIsNil { switch op { case "", "=", "==", "eq": return vIsNil == mvIsNil, nil case "!=", "<>", "ne": return vIsNil != mvIsNil, nil } return false, nil } if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool { switch op { case "", "=", "==", "eq": return v.Bool() == mv.Bool(), nil case "!=", "<>", "ne": return v.Bool() != mv.Bool(), nil } return false, nil } var ivp, imvp *int64 var fvp, fmvp *float64 var svp, smvp *string var slv, slmv any var ima []int64 var fma []float64 var sma []string if mv.Kind() == v.Kind() { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv imv := mv.Int() imvp = &imv case reflect.String: sv := v.String() svp = &sv smv := mv.String() smvp = &smv case reflect.Float64: fv := v.Float() fvp = &fv fmv := mv.Float() fmvp = &fmv case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv imv := ns.toTimeUnix(mv) imvp = &imv } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } else if isNumber(v.Kind()) && isNumber(mv.Kind()) { fv, err := toFloat(v) if err != nil { return false, err } fvp = &fv fmv, err := toFloat(mv) if err != nil { return false, err } fmvp = &fmv } else { if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice { return false, nil } if mv.Len() == 0 { return false, nil } if v.Kind() != reflect.Interface && mv.Type().Elem().Kind() != reflect.Interface && mv.Type().Elem() != v.Type() && v.Kind() != reflect.Array && v.Kind() != reflect.Slice { return false, nil } switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv for i := 0; i < mv.Len(); i++ { if anInt, err := toInt(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := 0; i < mv.Len(); i++ { if aString, err := toString(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := 0; i < mv.Len(); i++ { if aFloat, err := toFloat(mv.Index(i)); err == nil { fma = append(fma, aFloat) } } case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv for i := 0; i < mv.Len(); i++ { ima = append(ima, ns.toTimeUnix(mv.Index(i))) } } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } switch op { case "", "=", "==", "eq": switch { case ivp != nil && imvp != nil: return *ivp == *imvp, nil case svp != nil && smvp != nil: return *svp == *smvp, nil case fvp != nil && fmvp != nil: return *fvp == *fmvp, nil } case "!=", "<>", "ne": switch { case ivp != nil && imvp != nil: return *ivp != *imvp, nil case svp != nil && smvp != nil: return *svp != *smvp, nil case fvp != nil && fmvp != nil: return *fvp != *fmvp, nil } case ">=", "ge": switch { case ivp != nil && imvp != nil: return *ivp >= *imvp, nil case svp != nil && smvp != nil: return *svp >= *smvp, nil case fvp != nil && fmvp != nil: return *fvp >= *fmvp, nil } case ">", "gt": switch { case ivp != nil && imvp != nil: return *ivp > *imvp, nil case svp != nil && smvp != nil: return *svp > *smvp, nil case fvp != nil && fmvp != nil: return *fvp > *fmvp, nil } case "<=", "le": switch { case ivp != nil && imvp != nil: return *ivp <= *imvp, nil case svp != nil && smvp != nil: return *svp <= *smvp, nil case fvp != nil && fmvp != nil: return *fvp <= *fmvp, nil } case "<", "lt": switch { case ivp != nil && imvp != nil: return *ivp < *imvp, nil case svp != nil && smvp != nil: return *svp < *smvp, nil case fvp != nil && fmvp != nil: return *fvp < *fmvp, nil } case "in", "not in": var r bool switch { case ivp != nil && len(ima) > 0: r, _ = ns.In(ima, *ivp) case fvp != nil && len(fma) > 0: r, _ = ns.In(fma, *fvp) case svp != nil: if len(sma) > 0 { r, _ = ns.In(sma, *svp) } else if smvp != nil { r, _ = ns.In(*smvp, *svp) } default: return false, nil } if op == "not in" { return !r, nil } return r, nil case "intersect": r, err := ns.Intersect(slv, slmv) if err != nil { return false, err } if reflect.TypeOf(r).Kind() == reflect.Slice { s := reflect.ValueOf(r) if s.Len() > 0 { return true, nil } return false, nil } return false, errors.New("invalid intersect values") case "like": if svp != nil && smvp != nil { re, err := hstrings.GetOrCompileRegexp(*smvp) if err != nil { return false, err } if re.MatchString(*svp) { return true, nil } return false, nil } default: return false, errors.New("no such operator") } return false, nil } func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) { if !obj.IsValid() { return zero, errors.New("can't evaluate an invalid value") } typ := obj.Type() obj, isNil := indirect(obj) if obj.Kind() == reflect.Interface { // If obj is an interface, we need to inspect the value it contains // to see the full set of methods and fields. // Indirect returns the value that it points to, which is what's needed // below to be able to reflect on its fields. obj = reflect.Indirect(obj.Elem()) } // first, check whether obj has a method. In this case, obj is // a struct or its pointer. If obj is a struct, // to check all T and *T method, use obj pointer type Value objPtr := obj if objPtr.Kind() != reflect.Interface && objPtr.CanAddr() { objPtr = objPtr.Addr() } index := hreflect.GetMethodIndexByName(objPtr.Type(), elemName) if index != -1 { var args []reflect.Value mt := objPtr.Type().Method(index) num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && mt.Type.In(1).Implements(hreflect.ContextInterface) { args = []reflect.Value{ctx} maxNumIn = 2 } switch { case mt.PkgPath != "": return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ) case mt.Type.NumIn() > maxNumIn: return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn) case mt.Type.NumOut() == 0: return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ) case mt.Type.NumOut() > 2: return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ) case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ) case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ) } res := objPtr.Method(mt.Index).Call(args) if len(res) == 2 && !res[1].IsNil() { return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error)) } return res[0], nil } // elemName isn't a method so next start to check whether it is // a struct field or a map value. In both cases, it mustn't be // a nil value if isNil { return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName) } switch obj.Kind() { case reflect.Struct: ft, ok := obj.Type().FieldByName(elemName) if ok { if ft.PkgPath != "" && !ft.Anonymous { return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ) } return obj.FieldByIndex(ft.Index), nil } return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ) case reflect.Map: kv := reflect.ValueOf(elemName) if kv.Type().AssignableTo(obj.Type().Key()) { return obj.MapIndex(kv), nil } return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ) } return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ) } // parseWhereArgs parses the end arguments to the where function. Return a // match value and an operator, if one is defined. func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) { switch len(args) { case 1: mv = reflect.ValueOf(args[0]) case 2: var ok bool if op, ok = args[0].(string); !ok { err = errors.New("operator argument must be string type") return } op = strings.TrimSpace(strings.ToLower(op)) mv = reflect.ValueOf(args[1]) default: err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments") } return } // checkWhereArray handles the where-matching logic when the seqv value is an // Array or Slice. func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeSlice(seqv.Type(), 0, 0) for i := 0; i < seqv.Len(); i++ { var vvv reflect.Value rvv := seqv.Index(i) if kv.Kind() == reflect.String { if params, ok := rvv.Interface().(maps.Params); ok { vvv = reflect.ValueOf(params.GetNested(path...)) } else { vvv = rvv for i, elemName := range path { var err error vvv, err = evaluateSubElem(ctxv, vvv, elemName) if err != nil { continue } if i < len(path)-1 && vvv.IsValid() { if params, ok := vvv.Interface().(maps.Params); ok { // The current path element is the map itself, .Params. vvv = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } } } } else { vv, _ := indirect(rvv) if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) { vvv = vv.MapIndex(kv) } } if ok, err := ns.checkCondition(vvv, mv, op); ok { rv = reflect.Append(rv, rvv) } else if err != nil { return nil, err } } return rv.Interface(), nil } // checkWhereMap handles the where-matching logic when the seqv value is a Map. func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeMap(seqv.Type()) keys := seqv.MapKeys() for _, k := range keys { elemv := seqv.MapIndex(k) switch elemv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } case reflect.Interface: elemvv, isNil := indirect(elemv) if isNil { continue } switch elemvv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } } } } return rv.Interface(), nil } // toFloat returns the float value if possible. func toFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Convert(reflect.TypeOf(float64(0))).Float(), nil case reflect.Interface: return toFloat(v.Elem()) } return -1, errors.New("unable to convert value to float") } // toInt returns the int value if possible, -1 if not. // TODO(bep) consolidate all these reflect funcs. func toInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil case reflect.Interface: return toInt(v.Elem()) } return -1, errors.New("unable to convert value to int") } func toUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil case reflect.Interface: return toUint(v.Elem()) } return 0, errors.New("unable to convert value to uint") } // toString returns the string value if possible, "" if not. func toString(v reflect.Value) (string, error) { switch v.Kind() { case reflect.String: return v.String(), nil case reflect.Interface: return toString(v.Elem()) } return "", errors.New("unable to convert value to string") } func (ns *Namespace) toTimeUnix(v reflect.Value) int64 { t, ok := hreflect.AsTime(v, ns.loc) if !ok { panic("coding error: argument must be time.Time type reflect Value") } return t.Unix() }
jmooring
dc2a544fac7a3f9cb8bff70d5cbe92b37dee98d1
f4598a09864bee2689a7630dda83a71a9b9cf55b
Yea, a common regexp cache would probably be a good idea. Give me 5 minutes and I'll be back.
bep
25
gohugoio/hugo
11,281
tpl/collections: Add like operator to where function
Enables constructs such as: ```text {{ range where site.RegularPages "Params.foo" "like" "^ab" }} <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2> {{ end }} ``` Will submit documentation change to the documentation repository is this is merged. Closes #11279
null
2023-07-23 19:55:24+00:00
2023-07-28 07:53:01+00:00
tpl/collections/where.go
// Copyright 2017 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 collections import ( "context" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" ) // Where returns a filtered subset of collection c. func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) { seqv, isNil := indirect(reflect.ValueOf(c)) if isNil { return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String()) } mv, op, err := parseWhereArgs(args...) if err != nil { return nil, err } ctxv := reflect.ValueOf(ctx) var path []string kv := reflect.ValueOf(key) if kv.Kind() == reflect.String { path = strings.Split(strings.Trim(kv.String(), "."), ".") } switch seqv.Kind() { case reflect.Array, reflect.Slice: return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op) case reflect.Map: return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op) default: return nil, fmt.Errorf("can't iterate over %v", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := indirect(mv) if !mv.IsValid() { mvIsNil = true } if vIsNil || mvIsNil { switch op { case "", "=", "==", "eq": return vIsNil == mvIsNil, nil case "!=", "<>", "ne": return vIsNil != mvIsNil, nil } return false, nil } if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool { switch op { case "", "=", "==", "eq": return v.Bool() == mv.Bool(), nil case "!=", "<>", "ne": return v.Bool() != mv.Bool(), nil } return false, nil } var ivp, imvp *int64 var fvp, fmvp *float64 var svp, smvp *string var slv, slmv any var ima []int64 var fma []float64 var sma []string if mv.Kind() == v.Kind() { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv imv := mv.Int() imvp = &imv case reflect.String: sv := v.String() svp = &sv smv := mv.String() smvp = &smv case reflect.Float64: fv := v.Float() fvp = &fv fmv := mv.Float() fmvp = &fmv case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv imv := ns.toTimeUnix(mv) imvp = &imv } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } else if isNumber(v.Kind()) && isNumber(mv.Kind()) { fv, err := toFloat(v) if err != nil { return false, err } fvp = &fv fmv, err := toFloat(mv) if err != nil { return false, err } fmvp = &fmv } else { if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice { return false, nil } if mv.Len() == 0 { return false, nil } if v.Kind() != reflect.Interface && mv.Type().Elem().Kind() != reflect.Interface && mv.Type().Elem() != v.Type() && v.Kind() != reflect.Array && v.Kind() != reflect.Slice { return false, nil } switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv for i := 0; i < mv.Len(); i++ { if anInt, err := toInt(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := 0; i < mv.Len(); i++ { if aString, err := toString(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := 0; i < mv.Len(); i++ { if aFloat, err := toFloat(mv.Index(i)); err == nil { fma = append(fma, aFloat) } } case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv for i := 0; i < mv.Len(); i++ { ima = append(ima, ns.toTimeUnix(mv.Index(i))) } } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } switch op { case "", "=", "==", "eq": switch { case ivp != nil && imvp != nil: return *ivp == *imvp, nil case svp != nil && smvp != nil: return *svp == *smvp, nil case fvp != nil && fmvp != nil: return *fvp == *fmvp, nil } case "!=", "<>", "ne": switch { case ivp != nil && imvp != nil: return *ivp != *imvp, nil case svp != nil && smvp != nil: return *svp != *smvp, nil case fvp != nil && fmvp != nil: return *fvp != *fmvp, nil } case ">=", "ge": switch { case ivp != nil && imvp != nil: return *ivp >= *imvp, nil case svp != nil && smvp != nil: return *svp >= *smvp, nil case fvp != nil && fmvp != nil: return *fvp >= *fmvp, nil } case ">", "gt": switch { case ivp != nil && imvp != nil: return *ivp > *imvp, nil case svp != nil && smvp != nil: return *svp > *smvp, nil case fvp != nil && fmvp != nil: return *fvp > *fmvp, nil } case "<=", "le": switch { case ivp != nil && imvp != nil: return *ivp <= *imvp, nil case svp != nil && smvp != nil: return *svp <= *smvp, nil case fvp != nil && fmvp != nil: return *fvp <= *fmvp, nil } case "<", "lt": switch { case ivp != nil && imvp != nil: return *ivp < *imvp, nil case svp != nil && smvp != nil: return *svp < *smvp, nil case fvp != nil && fmvp != nil: return *fvp < *fmvp, nil } case "in", "not in": var r bool switch { case ivp != nil && len(ima) > 0: r, _ = ns.In(ima, *ivp) case fvp != nil && len(fma) > 0: r, _ = ns.In(fma, *fvp) case svp != nil: if len(sma) > 0 { r, _ = ns.In(sma, *svp) } else if smvp != nil { r, _ = ns.In(*smvp, *svp) } default: return false, nil } if op == "not in" { return !r, nil } return r, nil case "intersect": r, err := ns.Intersect(slv, slmv) if err != nil { return false, err } if reflect.TypeOf(r).Kind() == reflect.Slice { s := reflect.ValueOf(r) if s.Len() > 0 { return true, nil } return false, nil } return false, errors.New("invalid intersect values") default: return false, errors.New("no such operator") } return false, nil } func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) { if !obj.IsValid() { return zero, errors.New("can't evaluate an invalid value") } typ := obj.Type() obj, isNil := indirect(obj) if obj.Kind() == reflect.Interface { // If obj is an interface, we need to inspect the value it contains // to see the full set of methods and fields. // Indirect returns the value that it points to, which is what's needed // below to be able to reflect on its fields. obj = reflect.Indirect(obj.Elem()) } // first, check whether obj has a method. In this case, obj is // a struct or its pointer. If obj is a struct, // to check all T and *T method, use obj pointer type Value objPtr := obj if objPtr.Kind() != reflect.Interface && objPtr.CanAddr() { objPtr = objPtr.Addr() } index := hreflect.GetMethodIndexByName(objPtr.Type(), elemName) if index != -1 { var args []reflect.Value mt := objPtr.Type().Method(index) num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && mt.Type.In(1).Implements(hreflect.ContextInterface) { args = []reflect.Value{ctx} maxNumIn = 2 } switch { case mt.PkgPath != "": return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ) case mt.Type.NumIn() > maxNumIn: return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn) case mt.Type.NumOut() == 0: return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ) case mt.Type.NumOut() > 2: return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ) case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ) case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ) } res := objPtr.Method(mt.Index).Call(args) if len(res) == 2 && !res[1].IsNil() { return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error)) } return res[0], nil } // elemName isn't a method so next start to check whether it is // a struct field or a map value. In both cases, it mustn't be // a nil value if isNil { return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName) } switch obj.Kind() { case reflect.Struct: ft, ok := obj.Type().FieldByName(elemName) if ok { if ft.PkgPath != "" && !ft.Anonymous { return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ) } return obj.FieldByIndex(ft.Index), nil } return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ) case reflect.Map: kv := reflect.ValueOf(elemName) if kv.Type().AssignableTo(obj.Type().Key()) { return obj.MapIndex(kv), nil } return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ) } return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ) } // parseWhereArgs parses the end arguments to the where function. Return a // match value and an operator, if one is defined. func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) { switch len(args) { case 1: mv = reflect.ValueOf(args[0]) case 2: var ok bool if op, ok = args[0].(string); !ok { err = errors.New("operator argument must be string type") return } op = strings.TrimSpace(strings.ToLower(op)) mv = reflect.ValueOf(args[1]) default: err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments") } return } // checkWhereArray handles the where-matching logic when the seqv value is an // Array or Slice. func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeSlice(seqv.Type(), 0, 0) for i := 0; i < seqv.Len(); i++ { var vvv reflect.Value rvv := seqv.Index(i) if kv.Kind() == reflect.String { if params, ok := rvv.Interface().(maps.Params); ok { vvv = reflect.ValueOf(params.GetNested(path...)) } else { vvv = rvv for i, elemName := range path { var err error vvv, err = evaluateSubElem(ctxv, vvv, elemName) if err != nil { continue } if i < len(path)-1 && vvv.IsValid() { if params, ok := vvv.Interface().(maps.Params); ok { // The current path element is the map itself, .Params. vvv = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } } } } else { vv, _ := indirect(rvv) if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) { vvv = vv.MapIndex(kv) } } if ok, err := ns.checkCondition(vvv, mv, op); ok { rv = reflect.Append(rv, rvv) } else if err != nil { return nil, err } } return rv.Interface(), nil } // checkWhereMap handles the where-matching logic when the seqv value is a Map. func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeMap(seqv.Type()) keys := seqv.MapKeys() for _, k := range keys { elemv := seqv.MapIndex(k) switch elemv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } case reflect.Interface: elemvv, isNil := indirect(elemv) if isNil { continue } switch elemvv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } } } } return rv.Interface(), nil } // toFloat returns the float value if possible. func toFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Convert(reflect.TypeOf(float64(0))).Float(), nil case reflect.Interface: return toFloat(v.Elem()) } return -1, errors.New("unable to convert value to float") } // toInt returns the int value if possible, -1 if not. // TODO(bep) consolidate all these reflect funcs. func toInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil case reflect.Interface: return toInt(v.Elem()) } return -1, errors.New("unable to convert value to int") } func toUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil case reflect.Interface: return toUint(v.Elem()) } return 0, errors.New("unable to convert value to uint") } // toString returns the string value if possible, "" if not. func toString(v reflect.Value) (string, error) { switch v.Kind() { case reflect.String: return v.String(), nil case reflect.Interface: return toString(v.Elem()) } return "", errors.New("unable to convert value to string") } func (ns *Namespace) toTimeUnix(v reflect.Value) int64 { t, ok := hreflect.AsTime(v, ns.loc) if !ok { panic("coding error: argument must be time.Time type reflect Value") } return t.Unix() }
// Copyright 2017 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 collections import ( "context" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/maps" ) // Where returns a filtered subset of collection c. func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) { seqv, isNil := indirect(reflect.ValueOf(c)) if isNil { return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String()) } mv, op, err := parseWhereArgs(args...) if err != nil { return nil, err } ctxv := reflect.ValueOf(ctx) var path []string kv := reflect.ValueOf(key) if kv.Kind() == reflect.String { path = strings.Split(strings.Trim(kv.String(), "."), ".") } switch seqv.Kind() { case reflect.Array, reflect.Slice: return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op) case reflect.Map: return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op) default: return nil, fmt.Errorf("can't iterate over %v", c) } } func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) { v, vIsNil := indirect(v) if !v.IsValid() { vIsNil = true } mv, mvIsNil := indirect(mv) if !mv.IsValid() { mvIsNil = true } if vIsNil || mvIsNil { switch op { case "", "=", "==", "eq": return vIsNil == mvIsNil, nil case "!=", "<>", "ne": return vIsNil != mvIsNil, nil } return false, nil } if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool { switch op { case "", "=", "==", "eq": return v.Bool() == mv.Bool(), nil case "!=", "<>", "ne": return v.Bool() != mv.Bool(), nil } return false, nil } var ivp, imvp *int64 var fvp, fmvp *float64 var svp, smvp *string var slv, slmv any var ima []int64 var fma []float64 var sma []string if mv.Kind() == v.Kind() { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv imv := mv.Int() imvp = &imv case reflect.String: sv := v.String() svp = &sv smv := mv.String() smvp = &smv case reflect.Float64: fv := v.Float() fvp = &fv fmv := mv.Float() fmvp = &fmv case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv imv := ns.toTimeUnix(mv) imvp = &imv } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } else if isNumber(v.Kind()) && isNumber(mv.Kind()) { fv, err := toFloat(v) if err != nil { return false, err } fvp = &fv fmv, err := toFloat(mv) if err != nil { return false, err } fmvp = &fmv } else { if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice { return false, nil } if mv.Len() == 0 { return false, nil } if v.Kind() != reflect.Interface && mv.Type().Elem().Kind() != reflect.Interface && mv.Type().Elem() != v.Type() && v.Kind() != reflect.Array && v.Kind() != reflect.Slice { return false, nil } switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: iv := v.Int() ivp = &iv for i := 0; i < mv.Len(); i++ { if anInt, err := toInt(mv.Index(i)); err == nil { ima = append(ima, anInt) } } case reflect.String: sv := v.String() svp = &sv for i := 0; i < mv.Len(); i++ { if aString, err := toString(mv.Index(i)); err == nil { sma = append(sma, aString) } } case reflect.Float64: fv := v.Float() fvp = &fv for i := 0; i < mv.Len(); i++ { if aFloat, err := toFloat(mv.Index(i)); err == nil { fma = append(fma, aFloat) } } case reflect.Struct: if hreflect.IsTime(v.Type()) { iv := ns.toTimeUnix(v) ivp = &iv for i := 0; i < mv.Len(); i++ { ima = append(ima, ns.toTimeUnix(mv.Index(i))) } } case reflect.Array, reflect.Slice: slv = v.Interface() slmv = mv.Interface() } } switch op { case "", "=", "==", "eq": switch { case ivp != nil && imvp != nil: return *ivp == *imvp, nil case svp != nil && smvp != nil: return *svp == *smvp, nil case fvp != nil && fmvp != nil: return *fvp == *fmvp, nil } case "!=", "<>", "ne": switch { case ivp != nil && imvp != nil: return *ivp != *imvp, nil case svp != nil && smvp != nil: return *svp != *smvp, nil case fvp != nil && fmvp != nil: return *fvp != *fmvp, nil } case ">=", "ge": switch { case ivp != nil && imvp != nil: return *ivp >= *imvp, nil case svp != nil && smvp != nil: return *svp >= *smvp, nil case fvp != nil && fmvp != nil: return *fvp >= *fmvp, nil } case ">", "gt": switch { case ivp != nil && imvp != nil: return *ivp > *imvp, nil case svp != nil && smvp != nil: return *svp > *smvp, nil case fvp != nil && fmvp != nil: return *fvp > *fmvp, nil } case "<=", "le": switch { case ivp != nil && imvp != nil: return *ivp <= *imvp, nil case svp != nil && smvp != nil: return *svp <= *smvp, nil case fvp != nil && fmvp != nil: return *fvp <= *fmvp, nil } case "<", "lt": switch { case ivp != nil && imvp != nil: return *ivp < *imvp, nil case svp != nil && smvp != nil: return *svp < *smvp, nil case fvp != nil && fmvp != nil: return *fvp < *fmvp, nil } case "in", "not in": var r bool switch { case ivp != nil && len(ima) > 0: r, _ = ns.In(ima, *ivp) case fvp != nil && len(fma) > 0: r, _ = ns.In(fma, *fvp) case svp != nil: if len(sma) > 0 { r, _ = ns.In(sma, *svp) } else if smvp != nil { r, _ = ns.In(*smvp, *svp) } default: return false, nil } if op == "not in" { return !r, nil } return r, nil case "intersect": r, err := ns.Intersect(slv, slmv) if err != nil { return false, err } if reflect.TypeOf(r).Kind() == reflect.Slice { s := reflect.ValueOf(r) if s.Len() > 0 { return true, nil } return false, nil } return false, errors.New("invalid intersect values") case "like": if svp != nil && smvp != nil { re, err := hstrings.GetOrCompileRegexp(*smvp) if err != nil { return false, err } if re.MatchString(*svp) { return true, nil } return false, nil } default: return false, errors.New("no such operator") } return false, nil } func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) { if !obj.IsValid() { return zero, errors.New("can't evaluate an invalid value") } typ := obj.Type() obj, isNil := indirect(obj) if obj.Kind() == reflect.Interface { // If obj is an interface, we need to inspect the value it contains // to see the full set of methods and fields. // Indirect returns the value that it points to, which is what's needed // below to be able to reflect on its fields. obj = reflect.Indirect(obj.Elem()) } // first, check whether obj has a method. In this case, obj is // a struct or its pointer. If obj is a struct, // to check all T and *T method, use obj pointer type Value objPtr := obj if objPtr.Kind() != reflect.Interface && objPtr.CanAddr() { objPtr = objPtr.Addr() } index := hreflect.GetMethodIndexByName(objPtr.Type(), elemName) if index != -1 { var args []reflect.Value mt := objPtr.Type().Method(index) num := mt.Type.NumIn() maxNumIn := 1 if num > 1 && mt.Type.In(1).Implements(hreflect.ContextInterface) { args = []reflect.Value{ctx} maxNumIn = 2 } switch { case mt.PkgPath != "": return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ) case mt.Type.NumIn() > maxNumIn: return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn) case mt.Type.NumOut() == 0: return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ) case mt.Type.NumOut() > 2: return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ) case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ) case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType): return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ) } res := objPtr.Method(mt.Index).Call(args) if len(res) == 2 && !res[1].IsNil() { return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error)) } return res[0], nil } // elemName isn't a method so next start to check whether it is // a struct field or a map value. In both cases, it mustn't be // a nil value if isNil { return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName) } switch obj.Kind() { case reflect.Struct: ft, ok := obj.Type().FieldByName(elemName) if ok { if ft.PkgPath != "" && !ft.Anonymous { return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ) } return obj.FieldByIndex(ft.Index), nil } return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ) case reflect.Map: kv := reflect.ValueOf(elemName) if kv.Type().AssignableTo(obj.Type().Key()) { return obj.MapIndex(kv), nil } return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ) } return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ) } // parseWhereArgs parses the end arguments to the where function. Return a // match value and an operator, if one is defined. func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) { switch len(args) { case 1: mv = reflect.ValueOf(args[0]) case 2: var ok bool if op, ok = args[0].(string); !ok { err = errors.New("operator argument must be string type") return } op = strings.TrimSpace(strings.ToLower(op)) mv = reflect.ValueOf(args[1]) default: err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments") } return } // checkWhereArray handles the where-matching logic when the seqv value is an // Array or Slice. func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeSlice(seqv.Type(), 0, 0) for i := 0; i < seqv.Len(); i++ { var vvv reflect.Value rvv := seqv.Index(i) if kv.Kind() == reflect.String { if params, ok := rvv.Interface().(maps.Params); ok { vvv = reflect.ValueOf(params.GetNested(path...)) } else { vvv = rvv for i, elemName := range path { var err error vvv, err = evaluateSubElem(ctxv, vvv, elemName) if err != nil { continue } if i < len(path)-1 && vvv.IsValid() { if params, ok := vvv.Interface().(maps.Params); ok { // The current path element is the map itself, .Params. vvv = reflect.ValueOf(params.GetNested(path[i+1:]...)) break } } } } } else { vv, _ := indirect(rvv) if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) { vvv = vv.MapIndex(kv) } } if ok, err := ns.checkCondition(vvv, mv, op); ok { rv = reflect.Append(rv, rvv) } else if err != nil { return nil, err } } return rv.Interface(), nil } // checkWhereMap handles the where-matching logic when the seqv value is a Map. func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) { rv := reflect.MakeMap(seqv.Type()) keys := seqv.MapKeys() for _, k := range keys { elemv := seqv.MapIndex(k) switch elemv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } case reflect.Interface: elemvv, isNil := indirect(elemv) if isNil { continue } switch elemvv.Kind() { case reflect.Array, reflect.Slice: r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op) if err != nil { return nil, err } switch rr := reflect.ValueOf(r); rr.Kind() { case reflect.Slice: if rr.Len() > 0 { rv.SetMapIndex(k, elemv) } } } } } return rv.Interface(), nil } // toFloat returns the float value if possible. func toFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Convert(reflect.TypeOf(float64(0))).Float(), nil case reflect.Interface: return toFloat(v.Elem()) } return -1, errors.New("unable to convert value to float") } // toInt returns the int value if possible, -1 if not. // TODO(bep) consolidate all these reflect funcs. func toInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil case reflect.Interface: return toInt(v.Elem()) } return -1, errors.New("unable to convert value to int") } func toUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil case reflect.Interface: return toUint(v.Elem()) } return 0, errors.New("unable to convert value to uint") } // toString returns the string value if possible, "" if not. func toString(v reflect.Value) (string, error) { switch v.Kind() { case reflect.String: return v.String(), nil case reflect.Interface: return toString(v.Elem()) } return "", errors.New("unable to convert value to string") } func (ns *Namespace) toTimeUnix(v reflect.Value) int64 { t, ok := hreflect.AsTime(v, ns.loc) if !ok { panic("coding error: argument must be time.Time type reflect Value") } return t.Unix() }
jmooring
dc2a544fac7a3f9cb8bff70d5cbe92b37dee98d1
f4598a09864bee2689a7630dda83a71a9b9cf55b
I have pushed a commit that adds `hstrings.GetOrCompileRegexp`.
bep
26
gohugoio/hugo
11,220
fix: dotpath for Hugo modules mounted as data
Fixes #10681 Before this change, data files from Hugo modules were always mounted at the root of the `data` directory. The File and FileMetaInfo structs for modules are different from 'native' data directories. This changes how the keyParts for data files are generated so that data from modules or native directories are treated the same. > **Note** > > This might not be the best way of solving this issue. Perhaps it's preferred > to change how file metadata gets created, so that the properties for native > and module data directories are the same. I just couldn't figure out how to > do that. Signed-off-by: David Karlsson <[email protected]>
null
2023-07-07 15:39:22+00:00
2023-07-15 09:13:08+00:00
hugolib/hugo_modules_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 hugolib import ( "fmt" "math/rand" "os" "path/filepath" "strings" "testing" "time" "github.com/bep/logg" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/modules/npm" "github.com/spf13/afero" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugofs" qt "github.com/frankban/quicktest" "github.com/gohugoio/testmodBuilder/mods" ) func TestHugoModulesVariants(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } tomlConfig := ` baseURL="https://example.org" workingDir = %q [module] [[module.imports]] path="github.com/gohugoio/hugoTestModule2" %s ` createConfig := func(workingDir, moduleOpts string) string { return fmt.Sprintf(tomlConfig, workingDir, moduleOpts) } newTestBuilder := func(t testing.TB, moduleOpts string) *sitesBuilder { b := newTestSitesBuilder(t) tempDir := t.TempDir() workingDir := filepath.Join(tempDir, "myhugosite") b.Assert(os.MkdirAll(workingDir, 0777), qt.IsNil) cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) b.WithWorkingDir(workingDir).WithConfigFile("toml", createConfig(workingDir, moduleOpts)) b.WithTemplates( "index.html", ` Param from module: {{ site.Params.Hugo }}| {{ $js := resources.Get "jslibs/alpinejs/alpine.js" }} JS imported in module: {{ with $js }}{{ .RelPermalink }}{{ end }}| `, "_default/single.html", `{{ .Content }}`) b.WithContent("p1.md", `--- title: "Page" --- [A link](https://bep.is) `) b.WithSourceFile("go.mod", ` module github.com/gohugoio/tests/testHugoModules `) b.WithSourceFile("go.sum", ` github.com/gohugoio/hugoTestModule2 v0.0.0-20200131160637-9657d7697877 h1:WLM2bQCKIWo04T6NsIWsX/Vtirhf0TnpY66xyqGlgVY= github.com/gohugoio/hugoTestModule2 v0.0.0-20200131160637-9657d7697877/go.mod h1:CBFZS3khIAXKxReMwq0le8sEl/D8hcXmixlOHVv+Gd0= `) return b } t.Run("Target in subfolder", func(t *testing.T) { b := newTestBuilder(t, "ignoreImports=true") b.Build(BuildCfg{}) b.AssertFileContent("public/p1/index.html", `<p>Page|https://bep.is|Title: |Text: A link|END</p>`) }) t.Run("Ignore config", func(t *testing.T) { b := newTestBuilder(t, "ignoreConfig=true") b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Param from module: | JS imported in module: | `) }) t.Run("Ignore imports", func(t *testing.T) { b := newTestBuilder(t, "ignoreImports=true") b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Param from module: Rocks| JS imported in module: | `) }) t.Run("Create package.json", func(t *testing.T) { b := newTestBuilder(t, "") b.WithSourceFile("package.json", `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "nonon": "error" } }`) b.WithSourceFile("package.hugo.json", `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "foo": "1.2.3" }, "devDependencies": { "postcss-cli": "7.8.0", "tailwindcss": "1.8.0" } }`) b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "foo": "project", "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "project", "tailwindcss": "project" } }, "dependencies": { "foo": "1.2.3", "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.8.0", "tailwindcss": "1.8.0" }, "name": "mypack", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "version": "1.2.3" } ` }) }) t.Run("Create package.json, no default", func(t *testing.T) { b := newTestBuilder(t, "") const origPackageJSON = `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "moo": "1.2.3" } }` b.WithSourceFile("package.json", origPackageJSON) b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "moo": "project", "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "github.com/gohugoio/hugoTestModule2", "tailwindcss": "github.com/gohugoio/hugoTestModule2" } }, "dependencies": { "moo": "1.2.3", "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" }, "name": "mypack", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "version": "1.2.3" } ` }) // https://github.com/gohugoio/hugo/issues/7690 b.AssertFileContent("package.hugo.json", origPackageJSON) }) t.Run("Create package.json, no default, no package.json", func(t *testing.T) { b := newTestBuilder(t, "") b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "github.com/gohugoio/hugoTestModule2", "tailwindcss": "github.com/gohugoio/hugoTestModule2" } }, "dependencies": { "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" }, "name": "myhugosite", "version": "0.1.0" } ` }) }) } // TODO(bep) this fails when testmodBuilder is also building ... func TestHugoModulesMatrix(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } t.Parallel() if !htesting.IsCI() || hugo.GoMinorVersion() < 12 { // https://github.com/golang/go/issues/26794 // There were some concurrent issues with Go modules in < Go 12. t.Skip("skip this on local host and for Go <= 1.11 due to a bug in Go's stdlib") } if testing.Short() { t.Skip() } rnd := rand.New(rand.NewSource(time.Now().UnixNano())) gooss := []string{"linux", "darwin", "windows"} goos := gooss[rnd.Intn(len(gooss))] ignoreVendor := rnd.Intn(2) == 0 testmods := mods.CreateModules(goos).Collect() rnd.Shuffle(len(testmods), func(i, j int) { testmods[i], testmods[j] = testmods[j], testmods[i] }) for _, m := range testmods[:2] { c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-modules-test") c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workingDir) v.Set("publishDir", "public") configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q theme = %q ignoreVendorPaths = %q ` ignoreVendorPaths := "" if ignoreVendor { ignoreVendorPaths = "github.com/**" } config := fmt.Sprintf(configTemplate, workingDir, m.Path(), ignoreVendorPaths) b := newTestSitesBuilder(t) // Need to use OS fs for this. b.Fs = hugofs.NewDefaultOld(v) b.WithWorkingDir(workingDir).WithConfigFile("toml", config) b.WithContent("page.md", ` --- title: "Foo" --- `) b.WithTemplates("home.html", ` {{ $mod := .Site.Data.modinfo.module }} Mod Name: {{ $mod.name }} Mod Version: {{ $mod.version }} ---- {{ range $k, $v := .Site.Data.modinfo }} - {{ $k }}: {{ range $kk, $vv := $v }}{{ $kk }}: {{ $vv }}|{{ end -}} {{ end }} `) b.WithSourceFile("go.mod", ` module github.com/gohugoio/tests/testHugoModules `) b.Build(BuildCfg{}) // Verify that go.mod is autopopulated with all the modules in config.toml. b.AssertFileContent("go.mod", m.Path()) b.AssertFileContent("public/index.html", "Mod Name: "+m.Name(), "Mod Version: v1.4.0") b.AssertFileContent("public/index.html", createChildModMatchers(m, ignoreVendor, m.Vendor)...) } } func createChildModMatchers(m *mods.Md, ignoreVendor, vendored bool) []string { // Child dependencies are one behind. expectMinorVersion := 3 if !ignoreVendor && vendored { // Vendored modules are stuck at v1.1.0. expectMinorVersion = 1 } expectVersion := fmt.Sprintf("v1.%d.0", expectMinorVersion) var matchers []string for _, mm := range m.Children { matchers = append( matchers, fmt.Sprintf("%s: name: %s|version: %s", mm.Name(), mm.Name(), expectVersion)) matchers = append(matchers, createChildModMatchers(mm, ignoreVendor, vendored || mm.Vendor)...) } return matchers } func TestModulesWithContent(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" defaultContentLanguage = "en" [module] [[module.imports]] path="a" [[module.imports.mounts]] source="myacontent" target="content/blog" lang="en" [[module.imports]] path="b" [[module.imports.mounts]] source="mybcontent" target="content/blog" lang="nn" [[module.imports]] path="c" [[module.imports]] path="d" [languages] [languages.en] title = "Title in English" languageName = "English" weight = 1 [languages.nn] languageName = "Nynorsk" weight = 2 title = "Tittel på nynorsk" [languages.nb] languageName = "Bokmål" weight = 3 title = "Tittel på bokmål" [languages.fr] languageName = "French" weight = 4 title = "French Title" `) b.WithTemplatesAdded("index.html", ` {{ range .Site.RegularPages }} |{{ .Title }}|{{ .RelPermalink }}|{{ .Plain }} {{ end }} {{ $data := .Site.Data }} Data Common: {{ $data.common.value }} Data C: {{ $data.c.value }} Data D: {{ $data.d.value }} All Data: {{ $data }} i18n hello1: {{ i18n "hello1" . }} i18n theme: {{ i18n "theme" . }} i18n theme2: {{ i18n "theme2" . }} `) content := func(id string) string { return fmt.Sprintf(`--- title: Title %s --- Content %s `, id, id) } i18nContent := func(id, value string) string { return fmt.Sprintf(` [%s] other = %q `, id, value) } // Content files b.WithSourceFile("themes/a/myacontent/page.md", content("theme-a-en")) b.WithSourceFile("themes/b/mybcontent/page.md", content("theme-b-nn")) b.WithSourceFile("themes/c/content/blog/c.md", content("theme-c-nn")) // Data files b.WithSourceFile("data/common.toml", `value="Project"`) b.WithSourceFile("themes/c/data/common.toml", `value="Theme C"`) b.WithSourceFile("themes/c/data/c.toml", `value="Hugo Rocks!"`) b.WithSourceFile("themes/d/data/c.toml", `value="Hugo Rodcks!"`) b.WithSourceFile("themes/d/data/d.toml", `value="Hugo Rodks!"`) // i18n files b.WithSourceFile("i18n/en.toml", i18nContent("hello1", "Project")) b.WithSourceFile("themes/c/i18n/en.toml", ` [hello1] other="Theme C Hello" [theme] other="Theme C" `) b.WithSourceFile("themes/d/i18n/en.toml", i18nContent("theme", "Theme D")) b.WithSourceFile("themes/d/i18n/en.toml", i18nContent("theme2", "Theme2 D")) // Static files b.WithSourceFile("themes/c/static/hello.txt", `Hugo Rocks!"`) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "|Title theme-a-en|/blog/page/|Content theme-a-en") b.AssertFileContent("public/nn/index.html", "|Title theme-b-nn|/nn/blog/page/|Content theme-b-nn") // Data b.AssertFileContent("public/index.html", "Data Common: Project", "Data C: Hugo Rocks!", "Data D: Hugo Rodks!", ) // i18n b.AssertFileContent("public/index.html", "i18n hello1: Project", "i18n theme: Theme C", "i18n theme2: Theme2 D", ) } func TestModulesIgnoreConfig(t *testing.T) { b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="a" ignoreConfig=true `) b.WithSourceFile("themes/a/config.toml", ` [params] a = "Should Be Ignored!" `) b.WithTemplatesAdded("index.html", `Params: {{ .Site.Params }}`) b.Build(BuildCfg{}) b.AssertFileContentFn("public/index.html", func(s string) bool { return !strings.Contains(s, "Ignored") }) } func TestModulesDisabled(t *testing.T) { b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="a" [[module.imports]] path="b" disable=true `) b.WithSourceFile("themes/a/config.toml", ` [params] a = "A param" `) b.WithSourceFile("themes/b/config.toml", ` [params] b = "B param" `) b.WithTemplatesAdded("index.html", `Params: {{ .Site.Params }}`) b.Build(BuildCfg{}) b.AssertFileContentFn("public/index.html", func(s string) bool { return strings.Contains(s, "A param") && !strings.Contains(s, "B param") }) } func TestModulesIncompatible(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="ok" [[module.imports]] path="incompat1" [[module.imports]] path="incompat2" [[module.imports]] path="incompat3" `) b.WithSourceFile("themes/ok/data/ok.toml", `title = "OK"`) b.WithSourceFile("themes/incompat1/config.toml", ` [module] [module.hugoVersion] min = "0.33.2" max = "0.45.0" `) // Old setup. b.WithSourceFile("themes/incompat2/theme.toml", ` min_version = "5.0.0" `) // Issue 6162 b.WithSourceFile("themes/incompat3/theme.toml", ` min_version = 0.55.0 `) logger := loggers.NewDefault() b.WithLogger(logger) b.Build(BuildCfg{}) c := qt.New(t) c.Assert(logger.LoggCount(logg.LevelWarn), qt.Equals, 3) } func TestModulesSymlinks(t *testing.T) { skipSymlink(t) wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mod-sym") c.Assert(err, qt.IsNil) // We need to use the OS fs for this. cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) defer clean() const homeTemplate = ` Data: {{ .Site.Data }} ` createDirsAndFiles := func(baseDir string) { for _, dir := range files.ComponentFolders { realDir := filepath.Join(baseDir, dir, "real") c.Assert(os.MkdirAll(realDir, 0777), qt.IsNil) c.Assert(afero.WriteFile(fs.Source, filepath.Join(realDir, "data.toml"), []byte("[hello]\nother = \"hello\""), 0777), qt.IsNil) } c.Assert(afero.WriteFile(fs.Source, filepath.Join(baseDir, "layouts", "index.html"), []byte(homeTemplate), 0777), qt.IsNil) } // Create project dirs and files. createDirsAndFiles(workingDir) // Create one module inside the default themes folder. themeDir := filepath.Join(workingDir, "themes", "mymod") createDirsAndFiles(themeDir) createSymlinks := func(baseDir, id string) { for _, dir := range files.ComponentFolders { // Issue #9119: private use language tags cannot exceed 8 characters. if dir != "i18n" { c.Assert(os.Chdir(filepath.Join(baseDir, dir)), qt.IsNil) c.Assert(os.Symlink("real", fmt.Sprintf("realsym%s", id)), qt.IsNil) c.Assert(os.Chdir(filepath.Join(baseDir, dir, "real")), qt.IsNil) c.Assert(os.Symlink("data.toml", fmt.Sprintf(filepath.FromSlash("datasym%s.toml"), id)), qt.IsNil) } } } createSymlinks(workingDir, "project") createSymlinks(themeDir, "mod") config := ` baseURL = "https://example.com" theme="mymod" defaultContentLanguage="nn" defaultContentLanguageInSubDir=true [languages] [languages.nn] weight = 1 [languages.en] weight = 2 ` b := newTestSitesBuilder(t).WithNothingAdded().WithWorkingDir(workingDir) b.WithLogger(loggers.NewDefault()) b.Fs = fs b.WithConfigFile("toml", config) c.Assert(os.Chdir(workingDir), qt.IsNil) b.Build(BuildCfg{}) b.AssertFileContentFn(filepath.Join("public", "en", "index.html"), func(s string) bool { // Symbolic links only followed in project. There should be WARNING logs. return !strings.Contains(s, "symmod") && strings.Contains(s, "symproject") }) bfs := b.H.BaseFs for i, componentFs := range []afero.Fs{ bfs.Static[""].Fs, bfs.Archetypes.Fs, bfs.Content.Fs, bfs.Data.Fs, bfs.Assets.Fs, bfs.I18n.Fs, } { if i != 0 { continue } for j, id := range []string{"mod", "project"} { statCheck := func(fs afero.Fs, filename string, isDir bool) { shouldFail := j == 0 if !shouldFail && i == 0 { // Static dirs only supports symlinks for files shouldFail = isDir } _, err := fs.Stat(filepath.FromSlash(filename)) if err != nil { if i > 0 && strings.HasSuffix(filename, "toml") && strings.Contains(err.Error(), "files not supported") { // OK return } } if shouldFail { c.Assert(err, qt.Not(qt.IsNil)) c.Assert(err, qt.Equals, hugofs.ErrPermissionSymlink) } else { c.Assert(err, qt.IsNil) } } c.Logf("Checking %d:%d %q", i, j, id) statCheck(componentFs, fmt.Sprintf("realsym%s", id), true) statCheck(componentFs, fmt.Sprintf("real/datasym%s.toml", id), false) } } } func TestMountsProject(t *testing.T) { t.Parallel() config := ` baseURL="https://example.org" [module] [[module.mounts]] source="mycontent" target="content" ` b := newTestSitesBuilder(t). WithConfigFile("toml", config). WithSourceFile(filepath.Join("mycontent", "mypage.md"), ` --- title: "My Page" --- `) b.Build(BuildCfg{}) // helpers.PrintFs(b.H.Fs.Source, "public", os.Stdout) b.AssertFileContent("public/mypage/index.html", "Permalink: https://example.org/mypage/") } // https://github.com/gohugoio/hugo/issues/6684 func TestMountsContentFile(t *testing.T) { t.Parallel() c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-modules-content-file") c.Assert(err, qt.IsNil) defer clean() configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q [module] [[module.mounts]] source = "README.md" target = "content/_index.md" [[module.mounts]] source = "mycontent" target = "content/blog" ` tomlConfig := fmt.Sprintf(configTemplate, workingDir) b := newTestSitesBuilder(t).Running() cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig) b.WithTemplatesAdded("index.html", ` {{ .Title }} {{ .Content }} {{ $readme := .Site.GetPage "/README.md" }} {{ with $readme }}README: {{ .Title }}|Filename: {{ path.Join .File.Filename }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} {{ $mypage := .Site.GetPage "/blog/mypage.md" }} {{ with $mypage }}MYPAGE: {{ .Title }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} {{ $mybundle := .Site.GetPage "/blog/mybundle" }} {{ with $mybundle }}MYBUNDLE: {{ .Title }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} `, "_default/_markup/render-link.html", ` {{ $link := .Destination }} {{ $isRemote := strings.HasPrefix $link "http" }} {{- if not $isRemote -}} {{ $url := urls.Parse .Destination }} {{ $fragment := "" }} {{- with $url.Fragment }}{{ $fragment = printf "#%s" . }}{{ end -}} {{- with .Page.GetPage $url.Path }}{{ $link = printf "%s%s" .Permalink $fragment }}{{ end }}{{ end -}} <a href="{{ $link | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if $isRemote }} target="_blank"{{ end }}>{{ .Text | safeHTML }}</a> `) os.Mkdir(filepath.Join(workingDir, "mycontent"), 0777) os.Mkdir(filepath.Join(workingDir, "mycontent", "mybundle"), 0777) b.WithSourceFile("README.md", `--- title: "Readme Title" --- Readme Content. `, filepath.Join("mycontent", "mypage.md"), ` --- title: "My Page" --- * [Relative Link From Page](mybundle) * [Relative Link From Page, filename](mybundle/index.md) * [Link using original path](/mycontent/mybundle/index.md) `, filepath.Join("mycontent", "mybundle", "index.md"), ` --- title: "My Bundle" --- * [Dot Relative Link From Bundle](../mypage.md) * [Link using original path](/mycontent/mypage.md) * [Link to Home](/) * [Link to Home, README.md](/README.md) * [Link to Home, _index.md](/_index.md) `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` README: Readme Title /README.md|Path: _index.md|FilePath: README.md Readme Content. MYPAGE: My Page|Path: blog/mypage.md|FilePath: mycontent/mypage.md| MYBUNDLE: My Bundle|Path: blog/mybundle/index.md|FilePath: mycontent/mybundle/index.md| `) b.AssertFileContent("public/blog/mypage/index.html", ` <a href="https://example.com/blog/mybundle/">Relative Link From Page</a> <a href="https://example.com/blog/mybundle/">Relative Link From Page, filename</a> <a href="https://example.com/blog/mybundle/">Link using original path</a> `) b.AssertFileContent("public/blog/mybundle/index.html", ` <a href="https://example.com/blog/mypage/">Dot Relative Link From Bundle</a> <a href="https://example.com/blog/mypage/">Link using original path</a> <a href="https://example.com/">Link to Home</a> <a href="https://example.com/">Link to Home, README.md</a> <a href="https://example.com/">Link to Home, _index.md</a> `) b.EditFiles("README.md", `--- title: "Readme Edit" --- `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Readme Edit `) } func TestMountsPaths(t *testing.T) { c := qt.New(t) type test struct { b *sitesBuilder clean func() workingDir string } prepare := func(c *qt.C, mounts string) test { workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mounts-paths") c.Assert(err, qt.IsNil) configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q %s ` tomlConfig := fmt.Sprintf(configTemplate, workingDir, mounts) tomlConfig = strings.Replace(tomlConfig, "WORKING_DIR", workingDir, -1) b := newTestSitesBuilder(c).Running() cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) os.MkdirAll(filepath.Join(workingDir, "content", "blog"), 0777) b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig) return test{ b: b, clean: clean, workingDir: workingDir, } } c.Run("Default", func(c *qt.C) { mounts := `` test := prepare(c, mounts) b := test.b defer test.clean() b.WithContent("blog/p1.md", `--- title: P1 ---`) b.Build(BuildCfg{}) p := b.GetPage("blog/p1.md") f := p.File().FileInfo().Meta() b.Assert(filepath.ToSlash(f.Path), qt.Equals, "blog/p1.md") b.Assert(filepath.ToSlash(f.PathFile()), qt.Equals, "content/blog/p1.md") b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(test.workingDir, "layouts", "_default", "single.html")), qt.Equals, filepath.FromSlash("_default/single.html")) }) c.Run("Mounts", func(c *qt.C) { absDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mounts-paths-abs") c.Assert(err, qt.IsNil) defer clean() mounts := `[module] [[module.mounts]] source = "README.md" target = "content/_index.md" [[module.mounts]] source = "mycontent" target = "content/blog" [[module.mounts]] source = "subdir/mypartials" target = "layouts/partials" [[module.mounts]] source = %q target = "layouts/shortcodes" ` mounts = fmt.Sprintf(mounts, filepath.Join(absDir, "/abs/myshortcodes")) test := prepare(c, mounts) b := test.b defer test.clean() subContentDir := filepath.Join(test.workingDir, "mycontent", "sub") os.MkdirAll(subContentDir, 0777) myPartialsDir := filepath.Join(test.workingDir, "subdir", "mypartials") os.MkdirAll(myPartialsDir, 0777) absShortcodesDir := filepath.Join(absDir, "abs", "myshortcodes") os.MkdirAll(absShortcodesDir, 0777) b.WithSourceFile("README.md", "---\ntitle: Readme\n---") b.WithSourceFile("mycontent/sub/p1.md", "---\ntitle: P1\n---") b.WithSourceFile(filepath.Join(absShortcodesDir, "myshort.html"), "MYSHORT") b.WithSourceFile(filepath.Join(myPartialsDir, "mypartial.html"), "MYPARTIAL") b.Build(BuildCfg{}) p1_1 := b.GetPage("/blog/sub/p1.md") p1_2 := b.GetPage("/mycontent/sub/p1.md") b.Assert(p1_1, qt.Not(qt.IsNil)) b.Assert(p1_2, qt.Equals, p1_1) f := p1_1.File().FileInfo().Meta() b.Assert(filepath.ToSlash(f.Path), qt.Equals, "blog/sub/p1.md") b.Assert(filepath.ToSlash(f.PathFile()), qt.Equals, "mycontent/sub/p1.md") b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(myPartialsDir, "mypartial.html")), qt.Equals, filepath.FromSlash("partials/mypartial.html")) b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(absShortcodesDir, "myshort.html")), qt.Equals, filepath.FromSlash("shortcodes/myshort.html")) b.Assert(b.H.BaseFs.Content.Path(filepath.Join(subContentDir, "p1.md")), qt.Equals, filepath.FromSlash("blog/sub/p1.md")) b.Assert(b.H.BaseFs.Content.Path(filepath.Join(test.workingDir, "README.md")), qt.Equals, filepath.FromSlash("_index.md")) }) } // https://github.com/gohugoio/hugo/issues/6299 func TestSiteWithGoModButNoModules(t *testing.T) { t.Parallel() c := qt.New(t) // We need to use the OS fs for this. workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-no-mod") c.Assert(err, qt.IsNil) cfg := config.New() cfg.Set("workingDir", workDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) defer clean() b := newTestSitesBuilder(t) b.Fs = fs b.WithWorkingDir(workDir).WithViper(cfg) b.WithSourceFile("go.mod", "") b.Build(BuildCfg{}) } // https://github.com/gohugoio/hugo/issues/6622 func TestModuleAbsMount(t *testing.T) { t.Parallel() c := qt.New(t) // We need to use the OS fs for this. workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-project") c.Assert(err, qt.IsNil) absContentDir, clean2, err := htesting.CreateTempDir(hugofs.Os, "hugo-content") c.Assert(err, qt.IsNil) cfg := config.New() cfg.Set("workingDir", workDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) config := fmt.Sprintf(` workingDir=%q [module] [[module.mounts]] source = %q target = "content" `, workDir, absContentDir) defer clean1() defer clean2() b := newTestSitesBuilder(t) b.Fs = fs contentFilename := filepath.Join(absContentDir, "p1.md") afero.WriteFile(hugofs.Os, contentFilename, []byte(` --- title: Abs --- Content. `), 0777) b.WithWorkingDir(workDir).WithConfigFile("toml", config) b.WithContent("dummy.md", "") b.WithTemplatesAdded("index.html", ` {{ $p1 := site.GetPage "p1" }} P1: {{ $p1.Title }}|{{ $p1.RelPermalink }}|Filename: {{ $p1.File.Filename }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "P1: Abs|/p1/", "Filename: "+contentFilename) } // Issue 9426 func TestMountSameSource(t *testing.T) { config := `baseURL = 'https://example.org/' languageCode = 'en-us' title = 'Hugo GitHub Issue #9426' disableKinds = ['RSS','sitemap','taxonomy','term'] [[module.mounts]] source = "content" target = "content" [[module.mounts]] source = "extra-content" target = "content/resources-a" [[module.mounts]] source = "extra-content" target = "content/resources-b" ` b := newTestSitesBuilder(t).WithConfigFile("toml", config) b.WithContent("p1.md", "") b.WithSourceFile( "extra-content/_index.md", "", "extra-content/subdir/_index.md", "", "extra-content/subdir/about.md", "", ) b.Build(BuildCfg{}) b.AssertFileContent("public/resources-a/subdir/about/index.html", "Single") b.AssertFileContent("public/resources-b/subdir/about/index.html", "Single") }
// 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 hugolib import ( "fmt" "math/rand" "os" "path/filepath" "strings" "testing" "time" "github.com/bep/logg" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/modules/npm" "github.com/spf13/afero" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugofs" qt "github.com/frankban/quicktest" "github.com/gohugoio/testmodBuilder/mods" ) func TestHugoModulesVariants(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } tomlConfig := ` baseURL="https://example.org" workingDir = %q [module] [[module.imports]] path="github.com/gohugoio/hugoTestModule2" %s ` createConfig := func(workingDir, moduleOpts string) string { return fmt.Sprintf(tomlConfig, workingDir, moduleOpts) } newTestBuilder := func(t testing.TB, moduleOpts string) *sitesBuilder { b := newTestSitesBuilder(t) tempDir := t.TempDir() workingDir := filepath.Join(tempDir, "myhugosite") b.Assert(os.MkdirAll(workingDir, 0777), qt.IsNil) cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) b.WithWorkingDir(workingDir).WithConfigFile("toml", createConfig(workingDir, moduleOpts)) b.WithTemplates( "index.html", ` Param from module: {{ site.Params.Hugo }}| {{ $js := resources.Get "jslibs/alpinejs/alpine.js" }} JS imported in module: {{ with $js }}{{ .RelPermalink }}{{ end }}| `, "_default/single.html", `{{ .Content }}`) b.WithContent("p1.md", `--- title: "Page" --- [A link](https://bep.is) `) b.WithSourceFile("go.mod", ` module github.com/gohugoio/tests/testHugoModules `) b.WithSourceFile("go.sum", ` github.com/gohugoio/hugoTestModule2 v0.0.0-20200131160637-9657d7697877 h1:WLM2bQCKIWo04T6NsIWsX/Vtirhf0TnpY66xyqGlgVY= github.com/gohugoio/hugoTestModule2 v0.0.0-20200131160637-9657d7697877/go.mod h1:CBFZS3khIAXKxReMwq0le8sEl/D8hcXmixlOHVv+Gd0= `) return b } t.Run("Target in subfolder", func(t *testing.T) { b := newTestBuilder(t, "ignoreImports=true") b.Build(BuildCfg{}) b.AssertFileContent("public/p1/index.html", `<p>Page|https://bep.is|Title: |Text: A link|END</p>`) }) t.Run("Ignore config", func(t *testing.T) { b := newTestBuilder(t, "ignoreConfig=true") b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Param from module: | JS imported in module: | `) }) t.Run("Ignore imports", func(t *testing.T) { b := newTestBuilder(t, "ignoreImports=true") b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Param from module: Rocks| JS imported in module: | `) }) t.Run("Create package.json", func(t *testing.T) { b := newTestBuilder(t, "") b.WithSourceFile("package.json", `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "nonon": "error" } }`) b.WithSourceFile("package.hugo.json", `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "foo": "1.2.3" }, "devDependencies": { "postcss-cli": "7.8.0", "tailwindcss": "1.8.0" } }`) b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "foo": "project", "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "project", "tailwindcss": "project" } }, "dependencies": { "foo": "1.2.3", "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.8.0", "tailwindcss": "1.8.0" }, "name": "mypack", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "version": "1.2.3" } ` }) }) t.Run("Create package.json, no default", func(t *testing.T) { b := newTestBuilder(t, "") const origPackageJSON = `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "moo": "1.2.3" } }` b.WithSourceFile("package.json", origPackageJSON) b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "moo": "project", "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "github.com/gohugoio/hugoTestModule2", "tailwindcss": "github.com/gohugoio/hugoTestModule2" } }, "dependencies": { "moo": "1.2.3", "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" }, "name": "mypack", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "version": "1.2.3" } ` }) // https://github.com/gohugoio/hugo/issues/7690 b.AssertFileContent("package.hugo.json", origPackageJSON) }) t.Run("Create package.json, no default, no package.json", func(t *testing.T) { b := newTestBuilder(t, "") b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "github.com/gohugoio/hugoTestModule2", "tailwindcss": "github.com/gohugoio/hugoTestModule2" } }, "dependencies": { "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" }, "name": "myhugosite", "version": "0.1.0" } ` }) }) } // TODO(bep) this fails when testmodBuilder is also building ... func TestHugoModulesMatrix(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } t.Parallel() if !htesting.IsCI() || hugo.GoMinorVersion() < 12 { // https://github.com/golang/go/issues/26794 // There were some concurrent issues with Go modules in < Go 12. t.Skip("skip this on local host and for Go <= 1.11 due to a bug in Go's stdlib") } if testing.Short() { t.Skip() } rnd := rand.New(rand.NewSource(time.Now().UnixNano())) gooss := []string{"linux", "darwin", "windows"} goos := gooss[rnd.Intn(len(gooss))] ignoreVendor := rnd.Intn(2) == 0 testmods := mods.CreateModules(goos).Collect() rnd.Shuffle(len(testmods), func(i, j int) { testmods[i], testmods[j] = testmods[j], testmods[i] }) for _, m := range testmods[:2] { c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-modules-test") c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workingDir) v.Set("publishDir", "public") configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q theme = %q ignoreVendorPaths = %q ` ignoreVendorPaths := "" if ignoreVendor { ignoreVendorPaths = "github.com/**" } config := fmt.Sprintf(configTemplate, workingDir, m.Path(), ignoreVendorPaths) b := newTestSitesBuilder(t) // Need to use OS fs for this. b.Fs = hugofs.NewDefaultOld(v) b.WithWorkingDir(workingDir).WithConfigFile("toml", config) b.WithContent("page.md", ` --- title: "Foo" --- `) b.WithTemplates("home.html", ` {{ $mod := .Site.Data.modinfo.module }} Mod Name: {{ $mod.name }} Mod Version: {{ $mod.version }} ---- {{ range $k, $v := .Site.Data.modinfo }} - {{ $k }}: {{ range $kk, $vv := $v }}{{ $kk }}: {{ $vv }}|{{ end -}} {{ end }} `) b.WithSourceFile("go.mod", ` module github.com/gohugoio/tests/testHugoModules `) b.Build(BuildCfg{}) // Verify that go.mod is autopopulated with all the modules in config.toml. b.AssertFileContent("go.mod", m.Path()) b.AssertFileContent("public/index.html", "Mod Name: "+m.Name(), "Mod Version: v1.4.0") b.AssertFileContent("public/index.html", createChildModMatchers(m, ignoreVendor, m.Vendor)...) } } func createChildModMatchers(m *mods.Md, ignoreVendor, vendored bool) []string { // Child dependencies are one behind. expectMinorVersion := 3 if !ignoreVendor && vendored { // Vendored modules are stuck at v1.1.0. expectMinorVersion = 1 } expectVersion := fmt.Sprintf("v1.%d.0", expectMinorVersion) var matchers []string for _, mm := range m.Children { matchers = append( matchers, fmt.Sprintf("%s: name: %s|version: %s", mm.Name(), mm.Name(), expectVersion)) matchers = append(matchers, createChildModMatchers(mm, ignoreVendor, vendored || mm.Vendor)...) } return matchers } func TestModulesWithContent(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" defaultContentLanguage = "en" [module] [[module.imports]] path="a" [[module.imports.mounts]] source="myacontent" target="content/blog" lang="en" [[module.imports]] path="b" [[module.imports.mounts]] source="mybcontent" target="content/blog" lang="nn" [[module.imports]] path="c" [[module.imports]] path="d" [languages] [languages.en] title = "Title in English" languageName = "English" weight = 1 [languages.nn] languageName = "Nynorsk" weight = 2 title = "Tittel på nynorsk" [languages.nb] languageName = "Bokmål" weight = 3 title = "Tittel på bokmål" [languages.fr] languageName = "French" weight = 4 title = "French Title" `) b.WithTemplatesAdded("index.html", ` {{ range .Site.RegularPages }} |{{ .Title }}|{{ .RelPermalink }}|{{ .Plain }} {{ end }} {{ $data := .Site.Data }} Data Common: {{ $data.common.value }} Data C: {{ $data.c.value }} Data D: {{ $data.d.value }} All Data: {{ $data }} i18n hello1: {{ i18n "hello1" . }} i18n theme: {{ i18n "theme" . }} i18n theme2: {{ i18n "theme2" . }} `) content := func(id string) string { return fmt.Sprintf(`--- title: Title %s --- Content %s `, id, id) } i18nContent := func(id, value string) string { return fmt.Sprintf(` [%s] other = %q `, id, value) } // Content files b.WithSourceFile("themes/a/myacontent/page.md", content("theme-a-en")) b.WithSourceFile("themes/b/mybcontent/page.md", content("theme-b-nn")) b.WithSourceFile("themes/c/content/blog/c.md", content("theme-c-nn")) // Data files b.WithSourceFile("data/common.toml", `value="Project"`) b.WithSourceFile("themes/c/data/common.toml", `value="Theme C"`) b.WithSourceFile("themes/c/data/c.toml", `value="Hugo Rocks!"`) b.WithSourceFile("themes/d/data/c.toml", `value="Hugo Rodcks!"`) b.WithSourceFile("themes/d/data/d.toml", `value="Hugo Rodks!"`) // i18n files b.WithSourceFile("i18n/en.toml", i18nContent("hello1", "Project")) b.WithSourceFile("themes/c/i18n/en.toml", ` [hello1] other="Theme C Hello" [theme] other="Theme C" `) b.WithSourceFile("themes/d/i18n/en.toml", i18nContent("theme", "Theme D")) b.WithSourceFile("themes/d/i18n/en.toml", i18nContent("theme2", "Theme2 D")) // Static files b.WithSourceFile("themes/c/static/hello.txt", `Hugo Rocks!"`) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "|Title theme-a-en|/blog/page/|Content theme-a-en") b.AssertFileContent("public/nn/index.html", "|Title theme-b-nn|/nn/blog/page/|Content theme-b-nn") // Data b.AssertFileContent("public/index.html", "Data Common: Project", "Data C: Hugo Rocks!", "Data D: Hugo Rodks!", ) // i18n b.AssertFileContent("public/index.html", "i18n hello1: Project", "i18n theme: Theme C", "i18n theme2: Theme2 D", ) } func TestModulesIgnoreConfig(t *testing.T) { b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="a" ignoreConfig=true `) b.WithSourceFile("themes/a/config.toml", ` [params] a = "Should Be Ignored!" `) b.WithTemplatesAdded("index.html", `Params: {{ .Site.Params }}`) b.Build(BuildCfg{}) b.AssertFileContentFn("public/index.html", func(s string) bool { return !strings.Contains(s, "Ignored") }) } func TestModulesDisabled(t *testing.T) { b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="a" [[module.imports]] path="b" disable=true `) b.WithSourceFile("themes/a/config.toml", ` [params] a = "A param" `) b.WithSourceFile("themes/b/config.toml", ` [params] b = "B param" `) b.WithTemplatesAdded("index.html", `Params: {{ .Site.Params }}`) b.Build(BuildCfg{}) b.AssertFileContentFn("public/index.html", func(s string) bool { return strings.Contains(s, "A param") && !strings.Contains(s, "B param") }) } func TestModulesIncompatible(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="ok" [[module.imports]] path="incompat1" [[module.imports]] path="incompat2" [[module.imports]] path="incompat3" `) b.WithSourceFile("themes/ok/data/ok.toml", `title = "OK"`) b.WithSourceFile("themes/incompat1/config.toml", ` [module] [module.hugoVersion] min = "0.33.2" max = "0.45.0" `) // Old setup. b.WithSourceFile("themes/incompat2/theme.toml", ` min_version = "5.0.0" `) // Issue 6162 b.WithSourceFile("themes/incompat3/theme.toml", ` min_version = 0.55.0 `) logger := loggers.NewDefault() b.WithLogger(logger) b.Build(BuildCfg{}) c := qt.New(t) c.Assert(logger.LoggCount(logg.LevelWarn), qt.Equals, 3) } func TestModulesSymlinks(t *testing.T) { skipSymlink(t) wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mod-sym") c.Assert(err, qt.IsNil) // We need to use the OS fs for this. cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) defer clean() const homeTemplate = ` Data: {{ .Site.Data }} ` createDirsAndFiles := func(baseDir string) { for _, dir := range files.ComponentFolders { realDir := filepath.Join(baseDir, dir, "real") c.Assert(os.MkdirAll(realDir, 0777), qt.IsNil) c.Assert(afero.WriteFile(fs.Source, filepath.Join(realDir, "data.toml"), []byte("[hello]\nother = \"hello\""), 0777), qt.IsNil) } c.Assert(afero.WriteFile(fs.Source, filepath.Join(baseDir, "layouts", "index.html"), []byte(homeTemplate), 0777), qt.IsNil) } // Create project dirs and files. createDirsAndFiles(workingDir) // Create one module inside the default themes folder. themeDir := filepath.Join(workingDir, "themes", "mymod") createDirsAndFiles(themeDir) createSymlinks := func(baseDir, id string) { for _, dir := range files.ComponentFolders { // Issue #9119: private use language tags cannot exceed 8 characters. if dir != "i18n" { c.Assert(os.Chdir(filepath.Join(baseDir, dir)), qt.IsNil) c.Assert(os.Symlink("real", fmt.Sprintf("realsym%s", id)), qt.IsNil) c.Assert(os.Chdir(filepath.Join(baseDir, dir, "real")), qt.IsNil) c.Assert(os.Symlink("data.toml", fmt.Sprintf(filepath.FromSlash("datasym%s.toml"), id)), qt.IsNil) } } } createSymlinks(workingDir, "project") createSymlinks(themeDir, "mod") config := ` baseURL = "https://example.com" theme="mymod" defaultContentLanguage="nn" defaultContentLanguageInSubDir=true [languages] [languages.nn] weight = 1 [languages.en] weight = 2 ` b := newTestSitesBuilder(t).WithNothingAdded().WithWorkingDir(workingDir) b.WithLogger(loggers.NewDefault()) b.Fs = fs b.WithConfigFile("toml", config) c.Assert(os.Chdir(workingDir), qt.IsNil) b.Build(BuildCfg{}) b.AssertFileContentFn(filepath.Join("public", "en", "index.html"), func(s string) bool { // Symbolic links only followed in project. There should be WARNING logs. return !strings.Contains(s, "symmod") && strings.Contains(s, "symproject") }) bfs := b.H.BaseFs for i, componentFs := range []afero.Fs{ bfs.Static[""].Fs, bfs.Archetypes.Fs, bfs.Content.Fs, bfs.Data.Fs, bfs.Assets.Fs, bfs.I18n.Fs, } { if i != 0 { continue } for j, id := range []string{"mod", "project"} { statCheck := func(fs afero.Fs, filename string, isDir bool) { shouldFail := j == 0 if !shouldFail && i == 0 { // Static dirs only supports symlinks for files shouldFail = isDir } _, err := fs.Stat(filepath.FromSlash(filename)) if err != nil { if i > 0 && strings.HasSuffix(filename, "toml") && strings.Contains(err.Error(), "files not supported") { // OK return } } if shouldFail { c.Assert(err, qt.Not(qt.IsNil)) c.Assert(err, qt.Equals, hugofs.ErrPermissionSymlink) } else { c.Assert(err, qt.IsNil) } } c.Logf("Checking %d:%d %q", i, j, id) statCheck(componentFs, fmt.Sprintf("realsym%s", id), true) statCheck(componentFs, fmt.Sprintf("real/datasym%s.toml", id), false) } } } func TestMountsProject(t *testing.T) { t.Parallel() config := ` baseURL="https://example.org" [module] [[module.mounts]] source="mycontent" target="content" ` b := newTestSitesBuilder(t). WithConfigFile("toml", config). WithSourceFile(filepath.Join("mycontent", "mypage.md"), ` --- title: "My Page" --- `) b.Build(BuildCfg{}) // helpers.PrintFs(b.H.Fs.Source, "public", os.Stdout) b.AssertFileContent("public/mypage/index.html", "Permalink: https://example.org/mypage/") } // https://github.com/gohugoio/hugo/issues/6684 func TestMountsContentFile(t *testing.T) { t.Parallel() c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-modules-content-file") c.Assert(err, qt.IsNil) defer clean() configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q [module] [[module.mounts]] source = "README.md" target = "content/_index.md" [[module.mounts]] source = "mycontent" target = "content/blog" ` tomlConfig := fmt.Sprintf(configTemplate, workingDir) b := newTestSitesBuilder(t).Running() cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig) b.WithTemplatesAdded("index.html", ` {{ .Title }} {{ .Content }} {{ $readme := .Site.GetPage "/README.md" }} {{ with $readme }}README: {{ .Title }}|Filename: {{ path.Join .File.Filename }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} {{ $mypage := .Site.GetPage "/blog/mypage.md" }} {{ with $mypage }}MYPAGE: {{ .Title }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} {{ $mybundle := .Site.GetPage "/blog/mybundle" }} {{ with $mybundle }}MYBUNDLE: {{ .Title }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} `, "_default/_markup/render-link.html", ` {{ $link := .Destination }} {{ $isRemote := strings.HasPrefix $link "http" }} {{- if not $isRemote -}} {{ $url := urls.Parse .Destination }} {{ $fragment := "" }} {{- with $url.Fragment }}{{ $fragment = printf "#%s" . }}{{ end -}} {{- with .Page.GetPage $url.Path }}{{ $link = printf "%s%s" .Permalink $fragment }}{{ end }}{{ end -}} <a href="{{ $link | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if $isRemote }} target="_blank"{{ end }}>{{ .Text | safeHTML }}</a> `) os.Mkdir(filepath.Join(workingDir, "mycontent"), 0777) os.Mkdir(filepath.Join(workingDir, "mycontent", "mybundle"), 0777) b.WithSourceFile("README.md", `--- title: "Readme Title" --- Readme Content. `, filepath.Join("mycontent", "mypage.md"), ` --- title: "My Page" --- * [Relative Link From Page](mybundle) * [Relative Link From Page, filename](mybundle/index.md) * [Link using original path](/mycontent/mybundle/index.md) `, filepath.Join("mycontent", "mybundle", "index.md"), ` --- title: "My Bundle" --- * [Dot Relative Link From Bundle](../mypage.md) * [Link using original path](/mycontent/mypage.md) * [Link to Home](/) * [Link to Home, README.md](/README.md) * [Link to Home, _index.md](/_index.md) `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` README: Readme Title /README.md|Path: _index.md|FilePath: README.md Readme Content. MYPAGE: My Page|Path: blog/mypage.md|FilePath: mycontent/mypage.md| MYBUNDLE: My Bundle|Path: blog/mybundle/index.md|FilePath: mycontent/mybundle/index.md| `) b.AssertFileContent("public/blog/mypage/index.html", ` <a href="https://example.com/blog/mybundle/">Relative Link From Page</a> <a href="https://example.com/blog/mybundle/">Relative Link From Page, filename</a> <a href="https://example.com/blog/mybundle/">Link using original path</a> `) b.AssertFileContent("public/blog/mybundle/index.html", ` <a href="https://example.com/blog/mypage/">Dot Relative Link From Bundle</a> <a href="https://example.com/blog/mypage/">Link using original path</a> <a href="https://example.com/">Link to Home</a> <a href="https://example.com/">Link to Home, README.md</a> <a href="https://example.com/">Link to Home, _index.md</a> `) b.EditFiles("README.md", `--- title: "Readme Edit" --- `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Readme Edit `) } func TestMountsPaths(t *testing.T) { c := qt.New(t) type test struct { b *sitesBuilder clean func() workingDir string } prepare := func(c *qt.C, mounts string) test { workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mounts-paths") c.Assert(err, qt.IsNil) configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q %s ` tomlConfig := fmt.Sprintf(configTemplate, workingDir, mounts) tomlConfig = strings.Replace(tomlConfig, "WORKING_DIR", workingDir, -1) b := newTestSitesBuilder(c).Running() cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) os.MkdirAll(filepath.Join(workingDir, "content", "blog"), 0777) b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig) return test{ b: b, clean: clean, workingDir: workingDir, } } c.Run("Default", func(c *qt.C) { mounts := `` test := prepare(c, mounts) b := test.b defer test.clean() b.WithContent("blog/p1.md", `--- title: P1 ---`) b.Build(BuildCfg{}) p := b.GetPage("blog/p1.md") f := p.File().FileInfo().Meta() b.Assert(filepath.ToSlash(f.Path), qt.Equals, "blog/p1.md") b.Assert(filepath.ToSlash(f.PathFile()), qt.Equals, "content/blog/p1.md") b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(test.workingDir, "layouts", "_default", "single.html")), qt.Equals, filepath.FromSlash("_default/single.html")) }) c.Run("Mounts", func(c *qt.C) { absDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mounts-paths-abs") c.Assert(err, qt.IsNil) defer clean() mounts := `[module] [[module.mounts]] source = "README.md" target = "content/_index.md" [[module.mounts]] source = "mycontent" target = "content/blog" [[module.mounts]] source = "subdir/mypartials" target = "layouts/partials" [[module.mounts]] source = %q target = "layouts/shortcodes" ` mounts = fmt.Sprintf(mounts, filepath.Join(absDir, "/abs/myshortcodes")) test := prepare(c, mounts) b := test.b defer test.clean() subContentDir := filepath.Join(test.workingDir, "mycontent", "sub") os.MkdirAll(subContentDir, 0777) myPartialsDir := filepath.Join(test.workingDir, "subdir", "mypartials") os.MkdirAll(myPartialsDir, 0777) absShortcodesDir := filepath.Join(absDir, "abs", "myshortcodes") os.MkdirAll(absShortcodesDir, 0777) b.WithSourceFile("README.md", "---\ntitle: Readme\n---") b.WithSourceFile("mycontent/sub/p1.md", "---\ntitle: P1\n---") b.WithSourceFile(filepath.Join(absShortcodesDir, "myshort.html"), "MYSHORT") b.WithSourceFile(filepath.Join(myPartialsDir, "mypartial.html"), "MYPARTIAL") b.Build(BuildCfg{}) p1_1 := b.GetPage("/blog/sub/p1.md") p1_2 := b.GetPage("/mycontent/sub/p1.md") b.Assert(p1_1, qt.Not(qt.IsNil)) b.Assert(p1_2, qt.Equals, p1_1) f := p1_1.File().FileInfo().Meta() b.Assert(filepath.ToSlash(f.Path), qt.Equals, "blog/sub/p1.md") b.Assert(filepath.ToSlash(f.PathFile()), qt.Equals, "mycontent/sub/p1.md") b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(myPartialsDir, "mypartial.html")), qt.Equals, filepath.FromSlash("partials/mypartial.html")) b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(absShortcodesDir, "myshort.html")), qt.Equals, filepath.FromSlash("shortcodes/myshort.html")) b.Assert(b.H.BaseFs.Content.Path(filepath.Join(subContentDir, "p1.md")), qt.Equals, filepath.FromSlash("blog/sub/p1.md")) b.Assert(b.H.BaseFs.Content.Path(filepath.Join(test.workingDir, "README.md")), qt.Equals, filepath.FromSlash("_index.md")) }) } // https://github.com/gohugoio/hugo/issues/6299 func TestSiteWithGoModButNoModules(t *testing.T) { t.Parallel() c := qt.New(t) // We need to use the OS fs for this. workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-no-mod") c.Assert(err, qt.IsNil) cfg := config.New() cfg.Set("workingDir", workDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) defer clean() b := newTestSitesBuilder(t) b.Fs = fs b.WithWorkingDir(workDir).WithViper(cfg) b.WithSourceFile("go.mod", "") b.Build(BuildCfg{}) } // https://github.com/gohugoio/hugo/issues/6622 func TestModuleAbsMount(t *testing.T) { t.Parallel() c := qt.New(t) // We need to use the OS fs for this. workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-project") c.Assert(err, qt.IsNil) absContentDir, clean2, err := htesting.CreateTempDir(hugofs.Os, "hugo-content") c.Assert(err, qt.IsNil) cfg := config.New() cfg.Set("workingDir", workDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) config := fmt.Sprintf(` workingDir=%q [module] [[module.mounts]] source = %q target = "content" `, workDir, absContentDir) defer clean1() defer clean2() b := newTestSitesBuilder(t) b.Fs = fs contentFilename := filepath.Join(absContentDir, "p1.md") afero.WriteFile(hugofs.Os, contentFilename, []byte(` --- title: Abs --- Content. `), 0777) b.WithWorkingDir(workDir).WithConfigFile("toml", config) b.WithContent("dummy.md", "") b.WithTemplatesAdded("index.html", ` {{ $p1 := site.GetPage "p1" }} P1: {{ $p1.Title }}|{{ $p1.RelPermalink }}|Filename: {{ $p1.File.Filename }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "P1: Abs|/p1/", "Filename: "+contentFilename) } // Issue 9426 func TestMountSameSource(t *testing.T) { config := `baseURL = 'https://example.org/' languageCode = 'en-us' title = 'Hugo GitHub Issue #9426' disableKinds = ['RSS','sitemap','taxonomy','term'] [[module.mounts]] source = "content" target = "content" [[module.mounts]] source = "extra-content" target = "content/resources-a" [[module.mounts]] source = "extra-content" target = "content/resources-b" ` b := newTestSitesBuilder(t).WithConfigFile("toml", config) b.WithContent("p1.md", "") b.WithSourceFile( "extra-content/_index.md", "", "extra-content/subdir/_index.md", "", "extra-content/subdir/about.md", "", ) b.Build(BuildCfg{}) b.AssertFileContent("public/resources-a/subdir/about/index.html", "Single") b.AssertFileContent("public/resources-b/subdir/about/index.html", "Single") } func TestMountData(t *testing.T) { files := ` -- hugo.toml -- baseURL = 'https://example.org/' disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] [[module.mounts]] source = "data" target = "data" [[module.mounts]] source = "extra-data" target = "data/extra" -- extra-data/test.yaml -- message: Hugo Rocks -- layouts/index.html -- {{ site.Data.extra.test.message }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/index.html", "Hugo Rocks") }
dvdksn
79f15be5b0e47a788f62e50ba3e354c247a65f6b
286821e360e13b3a174854914c9cedd437bdd25e
OK, the bug fix itself looks good, but I would appreciate if you could rewrite the test to use `NewIntegrationTestBuilder()`. The assertion API is similar. I'm slowly rewriting existing tests to use that setup, so I would hate to merge new stuff with the old testSitesBuilder that I'm trying to get rid of ...
bep
27
gohugoio/hugo
11,220
fix: dotpath for Hugo modules mounted as data
Fixes #10681 Before this change, data files from Hugo modules were always mounted at the root of the `data` directory. The File and FileMetaInfo structs for modules are different from 'native' data directories. This changes how the keyParts for data files are generated so that data from modules or native directories are treated the same. > **Note** > > This might not be the best way of solving this issue. Perhaps it's preferred > to change how file metadata gets created, so that the properties for native > and module data directories are the same. I just couldn't figure out how to > do that. Signed-off-by: David Karlsson <[email protected]>
null
2023-07-07 15:39:22+00:00
2023-07-15 09:13:08+00:00
hugolib/hugo_modules_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 hugolib import ( "fmt" "math/rand" "os" "path/filepath" "strings" "testing" "time" "github.com/bep/logg" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/modules/npm" "github.com/spf13/afero" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugofs" qt "github.com/frankban/quicktest" "github.com/gohugoio/testmodBuilder/mods" ) func TestHugoModulesVariants(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } tomlConfig := ` baseURL="https://example.org" workingDir = %q [module] [[module.imports]] path="github.com/gohugoio/hugoTestModule2" %s ` createConfig := func(workingDir, moduleOpts string) string { return fmt.Sprintf(tomlConfig, workingDir, moduleOpts) } newTestBuilder := func(t testing.TB, moduleOpts string) *sitesBuilder { b := newTestSitesBuilder(t) tempDir := t.TempDir() workingDir := filepath.Join(tempDir, "myhugosite") b.Assert(os.MkdirAll(workingDir, 0777), qt.IsNil) cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) b.WithWorkingDir(workingDir).WithConfigFile("toml", createConfig(workingDir, moduleOpts)) b.WithTemplates( "index.html", ` Param from module: {{ site.Params.Hugo }}| {{ $js := resources.Get "jslibs/alpinejs/alpine.js" }} JS imported in module: {{ with $js }}{{ .RelPermalink }}{{ end }}| `, "_default/single.html", `{{ .Content }}`) b.WithContent("p1.md", `--- title: "Page" --- [A link](https://bep.is) `) b.WithSourceFile("go.mod", ` module github.com/gohugoio/tests/testHugoModules `) b.WithSourceFile("go.sum", ` github.com/gohugoio/hugoTestModule2 v0.0.0-20200131160637-9657d7697877 h1:WLM2bQCKIWo04T6NsIWsX/Vtirhf0TnpY66xyqGlgVY= github.com/gohugoio/hugoTestModule2 v0.0.0-20200131160637-9657d7697877/go.mod h1:CBFZS3khIAXKxReMwq0le8sEl/D8hcXmixlOHVv+Gd0= `) return b } t.Run("Target in subfolder", func(t *testing.T) { b := newTestBuilder(t, "ignoreImports=true") b.Build(BuildCfg{}) b.AssertFileContent("public/p1/index.html", `<p>Page|https://bep.is|Title: |Text: A link|END</p>`) }) t.Run("Ignore config", func(t *testing.T) { b := newTestBuilder(t, "ignoreConfig=true") b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Param from module: | JS imported in module: | `) }) t.Run("Ignore imports", func(t *testing.T) { b := newTestBuilder(t, "ignoreImports=true") b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Param from module: Rocks| JS imported in module: | `) }) t.Run("Create package.json", func(t *testing.T) { b := newTestBuilder(t, "") b.WithSourceFile("package.json", `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "nonon": "error" } }`) b.WithSourceFile("package.hugo.json", `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "foo": "1.2.3" }, "devDependencies": { "postcss-cli": "7.8.0", "tailwindcss": "1.8.0" } }`) b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "foo": "project", "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "project", "tailwindcss": "project" } }, "dependencies": { "foo": "1.2.3", "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.8.0", "tailwindcss": "1.8.0" }, "name": "mypack", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "version": "1.2.3" } ` }) }) t.Run("Create package.json, no default", func(t *testing.T) { b := newTestBuilder(t, "") const origPackageJSON = `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "moo": "1.2.3" } }` b.WithSourceFile("package.json", origPackageJSON) b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "moo": "project", "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "github.com/gohugoio/hugoTestModule2", "tailwindcss": "github.com/gohugoio/hugoTestModule2" } }, "dependencies": { "moo": "1.2.3", "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" }, "name": "mypack", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "version": "1.2.3" } ` }) // https://github.com/gohugoio/hugo/issues/7690 b.AssertFileContent("package.hugo.json", origPackageJSON) }) t.Run("Create package.json, no default, no package.json", func(t *testing.T) { b := newTestBuilder(t, "") b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "github.com/gohugoio/hugoTestModule2", "tailwindcss": "github.com/gohugoio/hugoTestModule2" } }, "dependencies": { "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" }, "name": "myhugosite", "version": "0.1.0" } ` }) }) } // TODO(bep) this fails when testmodBuilder is also building ... func TestHugoModulesMatrix(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } t.Parallel() if !htesting.IsCI() || hugo.GoMinorVersion() < 12 { // https://github.com/golang/go/issues/26794 // There were some concurrent issues with Go modules in < Go 12. t.Skip("skip this on local host and for Go <= 1.11 due to a bug in Go's stdlib") } if testing.Short() { t.Skip() } rnd := rand.New(rand.NewSource(time.Now().UnixNano())) gooss := []string{"linux", "darwin", "windows"} goos := gooss[rnd.Intn(len(gooss))] ignoreVendor := rnd.Intn(2) == 0 testmods := mods.CreateModules(goos).Collect() rnd.Shuffle(len(testmods), func(i, j int) { testmods[i], testmods[j] = testmods[j], testmods[i] }) for _, m := range testmods[:2] { c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-modules-test") c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workingDir) v.Set("publishDir", "public") configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q theme = %q ignoreVendorPaths = %q ` ignoreVendorPaths := "" if ignoreVendor { ignoreVendorPaths = "github.com/**" } config := fmt.Sprintf(configTemplate, workingDir, m.Path(), ignoreVendorPaths) b := newTestSitesBuilder(t) // Need to use OS fs for this. b.Fs = hugofs.NewDefaultOld(v) b.WithWorkingDir(workingDir).WithConfigFile("toml", config) b.WithContent("page.md", ` --- title: "Foo" --- `) b.WithTemplates("home.html", ` {{ $mod := .Site.Data.modinfo.module }} Mod Name: {{ $mod.name }} Mod Version: {{ $mod.version }} ---- {{ range $k, $v := .Site.Data.modinfo }} - {{ $k }}: {{ range $kk, $vv := $v }}{{ $kk }}: {{ $vv }}|{{ end -}} {{ end }} `) b.WithSourceFile("go.mod", ` module github.com/gohugoio/tests/testHugoModules `) b.Build(BuildCfg{}) // Verify that go.mod is autopopulated with all the modules in config.toml. b.AssertFileContent("go.mod", m.Path()) b.AssertFileContent("public/index.html", "Mod Name: "+m.Name(), "Mod Version: v1.4.0") b.AssertFileContent("public/index.html", createChildModMatchers(m, ignoreVendor, m.Vendor)...) } } func createChildModMatchers(m *mods.Md, ignoreVendor, vendored bool) []string { // Child dependencies are one behind. expectMinorVersion := 3 if !ignoreVendor && vendored { // Vendored modules are stuck at v1.1.0. expectMinorVersion = 1 } expectVersion := fmt.Sprintf("v1.%d.0", expectMinorVersion) var matchers []string for _, mm := range m.Children { matchers = append( matchers, fmt.Sprintf("%s: name: %s|version: %s", mm.Name(), mm.Name(), expectVersion)) matchers = append(matchers, createChildModMatchers(mm, ignoreVendor, vendored || mm.Vendor)...) } return matchers } func TestModulesWithContent(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" defaultContentLanguage = "en" [module] [[module.imports]] path="a" [[module.imports.mounts]] source="myacontent" target="content/blog" lang="en" [[module.imports]] path="b" [[module.imports.mounts]] source="mybcontent" target="content/blog" lang="nn" [[module.imports]] path="c" [[module.imports]] path="d" [languages] [languages.en] title = "Title in English" languageName = "English" weight = 1 [languages.nn] languageName = "Nynorsk" weight = 2 title = "Tittel på nynorsk" [languages.nb] languageName = "Bokmål" weight = 3 title = "Tittel på bokmål" [languages.fr] languageName = "French" weight = 4 title = "French Title" `) b.WithTemplatesAdded("index.html", ` {{ range .Site.RegularPages }} |{{ .Title }}|{{ .RelPermalink }}|{{ .Plain }} {{ end }} {{ $data := .Site.Data }} Data Common: {{ $data.common.value }} Data C: {{ $data.c.value }} Data D: {{ $data.d.value }} All Data: {{ $data }} i18n hello1: {{ i18n "hello1" . }} i18n theme: {{ i18n "theme" . }} i18n theme2: {{ i18n "theme2" . }} `) content := func(id string) string { return fmt.Sprintf(`--- title: Title %s --- Content %s `, id, id) } i18nContent := func(id, value string) string { return fmt.Sprintf(` [%s] other = %q `, id, value) } // Content files b.WithSourceFile("themes/a/myacontent/page.md", content("theme-a-en")) b.WithSourceFile("themes/b/mybcontent/page.md", content("theme-b-nn")) b.WithSourceFile("themes/c/content/blog/c.md", content("theme-c-nn")) // Data files b.WithSourceFile("data/common.toml", `value="Project"`) b.WithSourceFile("themes/c/data/common.toml", `value="Theme C"`) b.WithSourceFile("themes/c/data/c.toml", `value="Hugo Rocks!"`) b.WithSourceFile("themes/d/data/c.toml", `value="Hugo Rodcks!"`) b.WithSourceFile("themes/d/data/d.toml", `value="Hugo Rodks!"`) // i18n files b.WithSourceFile("i18n/en.toml", i18nContent("hello1", "Project")) b.WithSourceFile("themes/c/i18n/en.toml", ` [hello1] other="Theme C Hello" [theme] other="Theme C" `) b.WithSourceFile("themes/d/i18n/en.toml", i18nContent("theme", "Theme D")) b.WithSourceFile("themes/d/i18n/en.toml", i18nContent("theme2", "Theme2 D")) // Static files b.WithSourceFile("themes/c/static/hello.txt", `Hugo Rocks!"`) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "|Title theme-a-en|/blog/page/|Content theme-a-en") b.AssertFileContent("public/nn/index.html", "|Title theme-b-nn|/nn/blog/page/|Content theme-b-nn") // Data b.AssertFileContent("public/index.html", "Data Common: Project", "Data C: Hugo Rocks!", "Data D: Hugo Rodks!", ) // i18n b.AssertFileContent("public/index.html", "i18n hello1: Project", "i18n theme: Theme C", "i18n theme2: Theme2 D", ) } func TestModulesIgnoreConfig(t *testing.T) { b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="a" ignoreConfig=true `) b.WithSourceFile("themes/a/config.toml", ` [params] a = "Should Be Ignored!" `) b.WithTemplatesAdded("index.html", `Params: {{ .Site.Params }}`) b.Build(BuildCfg{}) b.AssertFileContentFn("public/index.html", func(s string) bool { return !strings.Contains(s, "Ignored") }) } func TestModulesDisabled(t *testing.T) { b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="a" [[module.imports]] path="b" disable=true `) b.WithSourceFile("themes/a/config.toml", ` [params] a = "A param" `) b.WithSourceFile("themes/b/config.toml", ` [params] b = "B param" `) b.WithTemplatesAdded("index.html", `Params: {{ .Site.Params }}`) b.Build(BuildCfg{}) b.AssertFileContentFn("public/index.html", func(s string) bool { return strings.Contains(s, "A param") && !strings.Contains(s, "B param") }) } func TestModulesIncompatible(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="ok" [[module.imports]] path="incompat1" [[module.imports]] path="incompat2" [[module.imports]] path="incompat3" `) b.WithSourceFile("themes/ok/data/ok.toml", `title = "OK"`) b.WithSourceFile("themes/incompat1/config.toml", ` [module] [module.hugoVersion] min = "0.33.2" max = "0.45.0" `) // Old setup. b.WithSourceFile("themes/incompat2/theme.toml", ` min_version = "5.0.0" `) // Issue 6162 b.WithSourceFile("themes/incompat3/theme.toml", ` min_version = 0.55.0 `) logger := loggers.NewDefault() b.WithLogger(logger) b.Build(BuildCfg{}) c := qt.New(t) c.Assert(logger.LoggCount(logg.LevelWarn), qt.Equals, 3) } func TestModulesSymlinks(t *testing.T) { skipSymlink(t) wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mod-sym") c.Assert(err, qt.IsNil) // We need to use the OS fs for this. cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) defer clean() const homeTemplate = ` Data: {{ .Site.Data }} ` createDirsAndFiles := func(baseDir string) { for _, dir := range files.ComponentFolders { realDir := filepath.Join(baseDir, dir, "real") c.Assert(os.MkdirAll(realDir, 0777), qt.IsNil) c.Assert(afero.WriteFile(fs.Source, filepath.Join(realDir, "data.toml"), []byte("[hello]\nother = \"hello\""), 0777), qt.IsNil) } c.Assert(afero.WriteFile(fs.Source, filepath.Join(baseDir, "layouts", "index.html"), []byte(homeTemplate), 0777), qt.IsNil) } // Create project dirs and files. createDirsAndFiles(workingDir) // Create one module inside the default themes folder. themeDir := filepath.Join(workingDir, "themes", "mymod") createDirsAndFiles(themeDir) createSymlinks := func(baseDir, id string) { for _, dir := range files.ComponentFolders { // Issue #9119: private use language tags cannot exceed 8 characters. if dir != "i18n" { c.Assert(os.Chdir(filepath.Join(baseDir, dir)), qt.IsNil) c.Assert(os.Symlink("real", fmt.Sprintf("realsym%s", id)), qt.IsNil) c.Assert(os.Chdir(filepath.Join(baseDir, dir, "real")), qt.IsNil) c.Assert(os.Symlink("data.toml", fmt.Sprintf(filepath.FromSlash("datasym%s.toml"), id)), qt.IsNil) } } } createSymlinks(workingDir, "project") createSymlinks(themeDir, "mod") config := ` baseURL = "https://example.com" theme="mymod" defaultContentLanguage="nn" defaultContentLanguageInSubDir=true [languages] [languages.nn] weight = 1 [languages.en] weight = 2 ` b := newTestSitesBuilder(t).WithNothingAdded().WithWorkingDir(workingDir) b.WithLogger(loggers.NewDefault()) b.Fs = fs b.WithConfigFile("toml", config) c.Assert(os.Chdir(workingDir), qt.IsNil) b.Build(BuildCfg{}) b.AssertFileContentFn(filepath.Join("public", "en", "index.html"), func(s string) bool { // Symbolic links only followed in project. There should be WARNING logs. return !strings.Contains(s, "symmod") && strings.Contains(s, "symproject") }) bfs := b.H.BaseFs for i, componentFs := range []afero.Fs{ bfs.Static[""].Fs, bfs.Archetypes.Fs, bfs.Content.Fs, bfs.Data.Fs, bfs.Assets.Fs, bfs.I18n.Fs, } { if i != 0 { continue } for j, id := range []string{"mod", "project"} { statCheck := func(fs afero.Fs, filename string, isDir bool) { shouldFail := j == 0 if !shouldFail && i == 0 { // Static dirs only supports symlinks for files shouldFail = isDir } _, err := fs.Stat(filepath.FromSlash(filename)) if err != nil { if i > 0 && strings.HasSuffix(filename, "toml") && strings.Contains(err.Error(), "files not supported") { // OK return } } if shouldFail { c.Assert(err, qt.Not(qt.IsNil)) c.Assert(err, qt.Equals, hugofs.ErrPermissionSymlink) } else { c.Assert(err, qt.IsNil) } } c.Logf("Checking %d:%d %q", i, j, id) statCheck(componentFs, fmt.Sprintf("realsym%s", id), true) statCheck(componentFs, fmt.Sprintf("real/datasym%s.toml", id), false) } } } func TestMountsProject(t *testing.T) { t.Parallel() config := ` baseURL="https://example.org" [module] [[module.mounts]] source="mycontent" target="content" ` b := newTestSitesBuilder(t). WithConfigFile("toml", config). WithSourceFile(filepath.Join("mycontent", "mypage.md"), ` --- title: "My Page" --- `) b.Build(BuildCfg{}) // helpers.PrintFs(b.H.Fs.Source, "public", os.Stdout) b.AssertFileContent("public/mypage/index.html", "Permalink: https://example.org/mypage/") } // https://github.com/gohugoio/hugo/issues/6684 func TestMountsContentFile(t *testing.T) { t.Parallel() c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-modules-content-file") c.Assert(err, qt.IsNil) defer clean() configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q [module] [[module.mounts]] source = "README.md" target = "content/_index.md" [[module.mounts]] source = "mycontent" target = "content/blog" ` tomlConfig := fmt.Sprintf(configTemplate, workingDir) b := newTestSitesBuilder(t).Running() cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig) b.WithTemplatesAdded("index.html", ` {{ .Title }} {{ .Content }} {{ $readme := .Site.GetPage "/README.md" }} {{ with $readme }}README: {{ .Title }}|Filename: {{ path.Join .File.Filename }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} {{ $mypage := .Site.GetPage "/blog/mypage.md" }} {{ with $mypage }}MYPAGE: {{ .Title }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} {{ $mybundle := .Site.GetPage "/blog/mybundle" }} {{ with $mybundle }}MYBUNDLE: {{ .Title }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} `, "_default/_markup/render-link.html", ` {{ $link := .Destination }} {{ $isRemote := strings.HasPrefix $link "http" }} {{- if not $isRemote -}} {{ $url := urls.Parse .Destination }} {{ $fragment := "" }} {{- with $url.Fragment }}{{ $fragment = printf "#%s" . }}{{ end -}} {{- with .Page.GetPage $url.Path }}{{ $link = printf "%s%s" .Permalink $fragment }}{{ end }}{{ end -}} <a href="{{ $link | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if $isRemote }} target="_blank"{{ end }}>{{ .Text | safeHTML }}</a> `) os.Mkdir(filepath.Join(workingDir, "mycontent"), 0777) os.Mkdir(filepath.Join(workingDir, "mycontent", "mybundle"), 0777) b.WithSourceFile("README.md", `--- title: "Readme Title" --- Readme Content. `, filepath.Join("mycontent", "mypage.md"), ` --- title: "My Page" --- * [Relative Link From Page](mybundle) * [Relative Link From Page, filename](mybundle/index.md) * [Link using original path](/mycontent/mybundle/index.md) `, filepath.Join("mycontent", "mybundle", "index.md"), ` --- title: "My Bundle" --- * [Dot Relative Link From Bundle](../mypage.md) * [Link using original path](/mycontent/mypage.md) * [Link to Home](/) * [Link to Home, README.md](/README.md) * [Link to Home, _index.md](/_index.md) `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` README: Readme Title /README.md|Path: _index.md|FilePath: README.md Readme Content. MYPAGE: My Page|Path: blog/mypage.md|FilePath: mycontent/mypage.md| MYBUNDLE: My Bundle|Path: blog/mybundle/index.md|FilePath: mycontent/mybundle/index.md| `) b.AssertFileContent("public/blog/mypage/index.html", ` <a href="https://example.com/blog/mybundle/">Relative Link From Page</a> <a href="https://example.com/blog/mybundle/">Relative Link From Page, filename</a> <a href="https://example.com/blog/mybundle/">Link using original path</a> `) b.AssertFileContent("public/blog/mybundle/index.html", ` <a href="https://example.com/blog/mypage/">Dot Relative Link From Bundle</a> <a href="https://example.com/blog/mypage/">Link using original path</a> <a href="https://example.com/">Link to Home</a> <a href="https://example.com/">Link to Home, README.md</a> <a href="https://example.com/">Link to Home, _index.md</a> `) b.EditFiles("README.md", `--- title: "Readme Edit" --- `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Readme Edit `) } func TestMountsPaths(t *testing.T) { c := qt.New(t) type test struct { b *sitesBuilder clean func() workingDir string } prepare := func(c *qt.C, mounts string) test { workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mounts-paths") c.Assert(err, qt.IsNil) configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q %s ` tomlConfig := fmt.Sprintf(configTemplate, workingDir, mounts) tomlConfig = strings.Replace(tomlConfig, "WORKING_DIR", workingDir, -1) b := newTestSitesBuilder(c).Running() cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) os.MkdirAll(filepath.Join(workingDir, "content", "blog"), 0777) b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig) return test{ b: b, clean: clean, workingDir: workingDir, } } c.Run("Default", func(c *qt.C) { mounts := `` test := prepare(c, mounts) b := test.b defer test.clean() b.WithContent("blog/p1.md", `--- title: P1 ---`) b.Build(BuildCfg{}) p := b.GetPage("blog/p1.md") f := p.File().FileInfo().Meta() b.Assert(filepath.ToSlash(f.Path), qt.Equals, "blog/p1.md") b.Assert(filepath.ToSlash(f.PathFile()), qt.Equals, "content/blog/p1.md") b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(test.workingDir, "layouts", "_default", "single.html")), qt.Equals, filepath.FromSlash("_default/single.html")) }) c.Run("Mounts", func(c *qt.C) { absDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mounts-paths-abs") c.Assert(err, qt.IsNil) defer clean() mounts := `[module] [[module.mounts]] source = "README.md" target = "content/_index.md" [[module.mounts]] source = "mycontent" target = "content/blog" [[module.mounts]] source = "subdir/mypartials" target = "layouts/partials" [[module.mounts]] source = %q target = "layouts/shortcodes" ` mounts = fmt.Sprintf(mounts, filepath.Join(absDir, "/abs/myshortcodes")) test := prepare(c, mounts) b := test.b defer test.clean() subContentDir := filepath.Join(test.workingDir, "mycontent", "sub") os.MkdirAll(subContentDir, 0777) myPartialsDir := filepath.Join(test.workingDir, "subdir", "mypartials") os.MkdirAll(myPartialsDir, 0777) absShortcodesDir := filepath.Join(absDir, "abs", "myshortcodes") os.MkdirAll(absShortcodesDir, 0777) b.WithSourceFile("README.md", "---\ntitle: Readme\n---") b.WithSourceFile("mycontent/sub/p1.md", "---\ntitle: P1\n---") b.WithSourceFile(filepath.Join(absShortcodesDir, "myshort.html"), "MYSHORT") b.WithSourceFile(filepath.Join(myPartialsDir, "mypartial.html"), "MYPARTIAL") b.Build(BuildCfg{}) p1_1 := b.GetPage("/blog/sub/p1.md") p1_2 := b.GetPage("/mycontent/sub/p1.md") b.Assert(p1_1, qt.Not(qt.IsNil)) b.Assert(p1_2, qt.Equals, p1_1) f := p1_1.File().FileInfo().Meta() b.Assert(filepath.ToSlash(f.Path), qt.Equals, "blog/sub/p1.md") b.Assert(filepath.ToSlash(f.PathFile()), qt.Equals, "mycontent/sub/p1.md") b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(myPartialsDir, "mypartial.html")), qt.Equals, filepath.FromSlash("partials/mypartial.html")) b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(absShortcodesDir, "myshort.html")), qt.Equals, filepath.FromSlash("shortcodes/myshort.html")) b.Assert(b.H.BaseFs.Content.Path(filepath.Join(subContentDir, "p1.md")), qt.Equals, filepath.FromSlash("blog/sub/p1.md")) b.Assert(b.H.BaseFs.Content.Path(filepath.Join(test.workingDir, "README.md")), qt.Equals, filepath.FromSlash("_index.md")) }) } // https://github.com/gohugoio/hugo/issues/6299 func TestSiteWithGoModButNoModules(t *testing.T) { t.Parallel() c := qt.New(t) // We need to use the OS fs for this. workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-no-mod") c.Assert(err, qt.IsNil) cfg := config.New() cfg.Set("workingDir", workDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) defer clean() b := newTestSitesBuilder(t) b.Fs = fs b.WithWorkingDir(workDir).WithViper(cfg) b.WithSourceFile("go.mod", "") b.Build(BuildCfg{}) } // https://github.com/gohugoio/hugo/issues/6622 func TestModuleAbsMount(t *testing.T) { t.Parallel() c := qt.New(t) // We need to use the OS fs for this. workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-project") c.Assert(err, qt.IsNil) absContentDir, clean2, err := htesting.CreateTempDir(hugofs.Os, "hugo-content") c.Assert(err, qt.IsNil) cfg := config.New() cfg.Set("workingDir", workDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) config := fmt.Sprintf(` workingDir=%q [module] [[module.mounts]] source = %q target = "content" `, workDir, absContentDir) defer clean1() defer clean2() b := newTestSitesBuilder(t) b.Fs = fs contentFilename := filepath.Join(absContentDir, "p1.md") afero.WriteFile(hugofs.Os, contentFilename, []byte(` --- title: Abs --- Content. `), 0777) b.WithWorkingDir(workDir).WithConfigFile("toml", config) b.WithContent("dummy.md", "") b.WithTemplatesAdded("index.html", ` {{ $p1 := site.GetPage "p1" }} P1: {{ $p1.Title }}|{{ $p1.RelPermalink }}|Filename: {{ $p1.File.Filename }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "P1: Abs|/p1/", "Filename: "+contentFilename) } // Issue 9426 func TestMountSameSource(t *testing.T) { config := `baseURL = 'https://example.org/' languageCode = 'en-us' title = 'Hugo GitHub Issue #9426' disableKinds = ['RSS','sitemap','taxonomy','term'] [[module.mounts]] source = "content" target = "content" [[module.mounts]] source = "extra-content" target = "content/resources-a" [[module.mounts]] source = "extra-content" target = "content/resources-b" ` b := newTestSitesBuilder(t).WithConfigFile("toml", config) b.WithContent("p1.md", "") b.WithSourceFile( "extra-content/_index.md", "", "extra-content/subdir/_index.md", "", "extra-content/subdir/about.md", "", ) b.Build(BuildCfg{}) b.AssertFileContent("public/resources-a/subdir/about/index.html", "Single") b.AssertFileContent("public/resources-b/subdir/about/index.html", "Single") }
// 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 hugolib import ( "fmt" "math/rand" "os" "path/filepath" "strings" "testing" "time" "github.com/bep/logg" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/modules/npm" "github.com/spf13/afero" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/hugofs" qt "github.com/frankban/quicktest" "github.com/gohugoio/testmodBuilder/mods" ) func TestHugoModulesVariants(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } tomlConfig := ` baseURL="https://example.org" workingDir = %q [module] [[module.imports]] path="github.com/gohugoio/hugoTestModule2" %s ` createConfig := func(workingDir, moduleOpts string) string { return fmt.Sprintf(tomlConfig, workingDir, moduleOpts) } newTestBuilder := func(t testing.TB, moduleOpts string) *sitesBuilder { b := newTestSitesBuilder(t) tempDir := t.TempDir() workingDir := filepath.Join(tempDir, "myhugosite") b.Assert(os.MkdirAll(workingDir, 0777), qt.IsNil) cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) b.WithWorkingDir(workingDir).WithConfigFile("toml", createConfig(workingDir, moduleOpts)) b.WithTemplates( "index.html", ` Param from module: {{ site.Params.Hugo }}| {{ $js := resources.Get "jslibs/alpinejs/alpine.js" }} JS imported in module: {{ with $js }}{{ .RelPermalink }}{{ end }}| `, "_default/single.html", `{{ .Content }}`) b.WithContent("p1.md", `--- title: "Page" --- [A link](https://bep.is) `) b.WithSourceFile("go.mod", ` module github.com/gohugoio/tests/testHugoModules `) b.WithSourceFile("go.sum", ` github.com/gohugoio/hugoTestModule2 v0.0.0-20200131160637-9657d7697877 h1:WLM2bQCKIWo04T6NsIWsX/Vtirhf0TnpY66xyqGlgVY= github.com/gohugoio/hugoTestModule2 v0.0.0-20200131160637-9657d7697877/go.mod h1:CBFZS3khIAXKxReMwq0le8sEl/D8hcXmixlOHVv+Gd0= `) return b } t.Run("Target in subfolder", func(t *testing.T) { b := newTestBuilder(t, "ignoreImports=true") b.Build(BuildCfg{}) b.AssertFileContent("public/p1/index.html", `<p>Page|https://bep.is|Title: |Text: A link|END</p>`) }) t.Run("Ignore config", func(t *testing.T) { b := newTestBuilder(t, "ignoreConfig=true") b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Param from module: | JS imported in module: | `) }) t.Run("Ignore imports", func(t *testing.T) { b := newTestBuilder(t, "ignoreImports=true") b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Param from module: Rocks| JS imported in module: | `) }) t.Run("Create package.json", func(t *testing.T) { b := newTestBuilder(t, "") b.WithSourceFile("package.json", `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "nonon": "error" } }`) b.WithSourceFile("package.hugo.json", `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "foo": "1.2.3" }, "devDependencies": { "postcss-cli": "7.8.0", "tailwindcss": "1.8.0" } }`) b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "foo": "project", "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "project", "tailwindcss": "project" } }, "dependencies": { "foo": "1.2.3", "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.8.0", "tailwindcss": "1.8.0" }, "name": "mypack", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "version": "1.2.3" } ` }) }) t.Run("Create package.json, no default", func(t *testing.T) { b := newTestBuilder(t, "") const origPackageJSON = `{ "name": "mypack", "version": "1.2.3", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "dependencies": { "moo": "1.2.3" } }` b.WithSourceFile("package.json", origPackageJSON) b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "moo": "project", "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "github.com/gohugoio/hugoTestModule2", "tailwindcss": "github.com/gohugoio/hugoTestModule2" } }, "dependencies": { "moo": "1.2.3", "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" }, "name": "mypack", "scripts": { "client": "wait-on http://localhost:1313 && open http://localhost:1313", "start": "run-p client server", "test": "echo 'hoge' > hoge" }, "version": "1.2.3" } ` }) // https://github.com/gohugoio/hugo/issues/7690 b.AssertFileContent("package.hugo.json", origPackageJSON) }) t.Run("Create package.json, no default, no package.json", func(t *testing.T) { b := newTestBuilder(t, "") b.Build(BuildCfg{}) b.Assert(npm.Pack(b.H.BaseFs.SourceFs, b.H.BaseFs.Assets.Dirs), qt.IsNil) b.AssertFileContentFn("package.json", func(s string) bool { return s == `{ "comments": { "dependencies": { "react-dom": "github.com/gohugoio/hugoTestModule2" }, "devDependencies": { "@babel/cli": "github.com/gohugoio/hugoTestModule2", "@babel/core": "github.com/gohugoio/hugoTestModule2", "@babel/preset-env": "github.com/gohugoio/hugoTestModule2", "postcss-cli": "github.com/gohugoio/hugoTestModule2", "tailwindcss": "github.com/gohugoio/hugoTestModule2" } }, "dependencies": { "react-dom": "^16.13.1" }, "devDependencies": { "@babel/cli": "7.8.4", "@babel/core": "7.9.0", "@babel/preset-env": "7.9.5", "postcss-cli": "7.1.0", "tailwindcss": "1.2.0" }, "name": "myhugosite", "version": "0.1.0" } ` }) }) } // TODO(bep) this fails when testmodBuilder is also building ... func TestHugoModulesMatrix(t *testing.T) { if !htesting.IsCI() { t.Skip("skip (relative) long running modules test when running locally") } t.Parallel() if !htesting.IsCI() || hugo.GoMinorVersion() < 12 { // https://github.com/golang/go/issues/26794 // There were some concurrent issues with Go modules in < Go 12. t.Skip("skip this on local host and for Go <= 1.11 due to a bug in Go's stdlib") } if testing.Short() { t.Skip() } rnd := rand.New(rand.NewSource(time.Now().UnixNano())) gooss := []string{"linux", "darwin", "windows"} goos := gooss[rnd.Intn(len(gooss))] ignoreVendor := rnd.Intn(2) == 0 testmods := mods.CreateModules(goos).Collect() rnd.Shuffle(len(testmods), func(i, j int) { testmods[i], testmods[j] = testmods[j], testmods[i] }) for _, m := range testmods[:2] { c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-modules-test") c.Assert(err, qt.IsNil) defer clean() v := config.New() v.Set("workingDir", workingDir) v.Set("publishDir", "public") configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q theme = %q ignoreVendorPaths = %q ` ignoreVendorPaths := "" if ignoreVendor { ignoreVendorPaths = "github.com/**" } config := fmt.Sprintf(configTemplate, workingDir, m.Path(), ignoreVendorPaths) b := newTestSitesBuilder(t) // Need to use OS fs for this. b.Fs = hugofs.NewDefaultOld(v) b.WithWorkingDir(workingDir).WithConfigFile("toml", config) b.WithContent("page.md", ` --- title: "Foo" --- `) b.WithTemplates("home.html", ` {{ $mod := .Site.Data.modinfo.module }} Mod Name: {{ $mod.name }} Mod Version: {{ $mod.version }} ---- {{ range $k, $v := .Site.Data.modinfo }} - {{ $k }}: {{ range $kk, $vv := $v }}{{ $kk }}: {{ $vv }}|{{ end -}} {{ end }} `) b.WithSourceFile("go.mod", ` module github.com/gohugoio/tests/testHugoModules `) b.Build(BuildCfg{}) // Verify that go.mod is autopopulated with all the modules in config.toml. b.AssertFileContent("go.mod", m.Path()) b.AssertFileContent("public/index.html", "Mod Name: "+m.Name(), "Mod Version: v1.4.0") b.AssertFileContent("public/index.html", createChildModMatchers(m, ignoreVendor, m.Vendor)...) } } func createChildModMatchers(m *mods.Md, ignoreVendor, vendored bool) []string { // Child dependencies are one behind. expectMinorVersion := 3 if !ignoreVendor && vendored { // Vendored modules are stuck at v1.1.0. expectMinorVersion = 1 } expectVersion := fmt.Sprintf("v1.%d.0", expectMinorVersion) var matchers []string for _, mm := range m.Children { matchers = append( matchers, fmt.Sprintf("%s: name: %s|version: %s", mm.Name(), mm.Name(), expectVersion)) matchers = append(matchers, createChildModMatchers(mm, ignoreVendor, vendored || mm.Vendor)...) } return matchers } func TestModulesWithContent(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" defaultContentLanguage = "en" [module] [[module.imports]] path="a" [[module.imports.mounts]] source="myacontent" target="content/blog" lang="en" [[module.imports]] path="b" [[module.imports.mounts]] source="mybcontent" target="content/blog" lang="nn" [[module.imports]] path="c" [[module.imports]] path="d" [languages] [languages.en] title = "Title in English" languageName = "English" weight = 1 [languages.nn] languageName = "Nynorsk" weight = 2 title = "Tittel på nynorsk" [languages.nb] languageName = "Bokmål" weight = 3 title = "Tittel på bokmål" [languages.fr] languageName = "French" weight = 4 title = "French Title" `) b.WithTemplatesAdded("index.html", ` {{ range .Site.RegularPages }} |{{ .Title }}|{{ .RelPermalink }}|{{ .Plain }} {{ end }} {{ $data := .Site.Data }} Data Common: {{ $data.common.value }} Data C: {{ $data.c.value }} Data D: {{ $data.d.value }} All Data: {{ $data }} i18n hello1: {{ i18n "hello1" . }} i18n theme: {{ i18n "theme" . }} i18n theme2: {{ i18n "theme2" . }} `) content := func(id string) string { return fmt.Sprintf(`--- title: Title %s --- Content %s `, id, id) } i18nContent := func(id, value string) string { return fmt.Sprintf(` [%s] other = %q `, id, value) } // Content files b.WithSourceFile("themes/a/myacontent/page.md", content("theme-a-en")) b.WithSourceFile("themes/b/mybcontent/page.md", content("theme-b-nn")) b.WithSourceFile("themes/c/content/blog/c.md", content("theme-c-nn")) // Data files b.WithSourceFile("data/common.toml", `value="Project"`) b.WithSourceFile("themes/c/data/common.toml", `value="Theme C"`) b.WithSourceFile("themes/c/data/c.toml", `value="Hugo Rocks!"`) b.WithSourceFile("themes/d/data/c.toml", `value="Hugo Rodcks!"`) b.WithSourceFile("themes/d/data/d.toml", `value="Hugo Rodks!"`) // i18n files b.WithSourceFile("i18n/en.toml", i18nContent("hello1", "Project")) b.WithSourceFile("themes/c/i18n/en.toml", ` [hello1] other="Theme C Hello" [theme] other="Theme C" `) b.WithSourceFile("themes/d/i18n/en.toml", i18nContent("theme", "Theme D")) b.WithSourceFile("themes/d/i18n/en.toml", i18nContent("theme2", "Theme2 D")) // Static files b.WithSourceFile("themes/c/static/hello.txt", `Hugo Rocks!"`) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "|Title theme-a-en|/blog/page/|Content theme-a-en") b.AssertFileContent("public/nn/index.html", "|Title theme-b-nn|/nn/blog/page/|Content theme-b-nn") // Data b.AssertFileContent("public/index.html", "Data Common: Project", "Data C: Hugo Rocks!", "Data D: Hugo Rodks!", ) // i18n b.AssertFileContent("public/index.html", "i18n hello1: Project", "i18n theme: Theme C", "i18n theme2: Theme2 D", ) } func TestModulesIgnoreConfig(t *testing.T) { b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="a" ignoreConfig=true `) b.WithSourceFile("themes/a/config.toml", ` [params] a = "Should Be Ignored!" `) b.WithTemplatesAdded("index.html", `Params: {{ .Site.Params }}`) b.Build(BuildCfg{}) b.AssertFileContentFn("public/index.html", func(s string) bool { return !strings.Contains(s, "Ignored") }) } func TestModulesDisabled(t *testing.T) { b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="a" [[module.imports]] path="b" disable=true `) b.WithSourceFile("themes/a/config.toml", ` [params] a = "A param" `) b.WithSourceFile("themes/b/config.toml", ` [params] b = "B param" `) b.WithTemplatesAdded("index.html", `Params: {{ .Site.Params }}`) b.Build(BuildCfg{}) b.AssertFileContentFn("public/index.html", func(s string) bool { return strings.Contains(s, "A param") && !strings.Contains(s, "B param") }) } func TestModulesIncompatible(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).WithWorkingDir("/site").WithConfigFile("toml", ` baseURL="https://example.org" workingDir="/site" [module] [[module.imports]] path="ok" [[module.imports]] path="incompat1" [[module.imports]] path="incompat2" [[module.imports]] path="incompat3" `) b.WithSourceFile("themes/ok/data/ok.toml", `title = "OK"`) b.WithSourceFile("themes/incompat1/config.toml", ` [module] [module.hugoVersion] min = "0.33.2" max = "0.45.0" `) // Old setup. b.WithSourceFile("themes/incompat2/theme.toml", ` min_version = "5.0.0" `) // Issue 6162 b.WithSourceFile("themes/incompat3/theme.toml", ` min_version = 0.55.0 `) logger := loggers.NewDefault() b.WithLogger(logger) b.Build(BuildCfg{}) c := qt.New(t) c.Assert(logger.LoggCount(logg.LevelWarn), qt.Equals, 3) } func TestModulesSymlinks(t *testing.T) { skipSymlink(t) wd, _ := os.Getwd() defer func() { os.Chdir(wd) }() c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mod-sym") c.Assert(err, qt.IsNil) // We need to use the OS fs for this. cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) defer clean() const homeTemplate = ` Data: {{ .Site.Data }} ` createDirsAndFiles := func(baseDir string) { for _, dir := range files.ComponentFolders { realDir := filepath.Join(baseDir, dir, "real") c.Assert(os.MkdirAll(realDir, 0777), qt.IsNil) c.Assert(afero.WriteFile(fs.Source, filepath.Join(realDir, "data.toml"), []byte("[hello]\nother = \"hello\""), 0777), qt.IsNil) } c.Assert(afero.WriteFile(fs.Source, filepath.Join(baseDir, "layouts", "index.html"), []byte(homeTemplate), 0777), qt.IsNil) } // Create project dirs and files. createDirsAndFiles(workingDir) // Create one module inside the default themes folder. themeDir := filepath.Join(workingDir, "themes", "mymod") createDirsAndFiles(themeDir) createSymlinks := func(baseDir, id string) { for _, dir := range files.ComponentFolders { // Issue #9119: private use language tags cannot exceed 8 characters. if dir != "i18n" { c.Assert(os.Chdir(filepath.Join(baseDir, dir)), qt.IsNil) c.Assert(os.Symlink("real", fmt.Sprintf("realsym%s", id)), qt.IsNil) c.Assert(os.Chdir(filepath.Join(baseDir, dir, "real")), qt.IsNil) c.Assert(os.Symlink("data.toml", fmt.Sprintf(filepath.FromSlash("datasym%s.toml"), id)), qt.IsNil) } } } createSymlinks(workingDir, "project") createSymlinks(themeDir, "mod") config := ` baseURL = "https://example.com" theme="mymod" defaultContentLanguage="nn" defaultContentLanguageInSubDir=true [languages] [languages.nn] weight = 1 [languages.en] weight = 2 ` b := newTestSitesBuilder(t).WithNothingAdded().WithWorkingDir(workingDir) b.WithLogger(loggers.NewDefault()) b.Fs = fs b.WithConfigFile("toml", config) c.Assert(os.Chdir(workingDir), qt.IsNil) b.Build(BuildCfg{}) b.AssertFileContentFn(filepath.Join("public", "en", "index.html"), func(s string) bool { // Symbolic links only followed in project. There should be WARNING logs. return !strings.Contains(s, "symmod") && strings.Contains(s, "symproject") }) bfs := b.H.BaseFs for i, componentFs := range []afero.Fs{ bfs.Static[""].Fs, bfs.Archetypes.Fs, bfs.Content.Fs, bfs.Data.Fs, bfs.Assets.Fs, bfs.I18n.Fs, } { if i != 0 { continue } for j, id := range []string{"mod", "project"} { statCheck := func(fs afero.Fs, filename string, isDir bool) { shouldFail := j == 0 if !shouldFail && i == 0 { // Static dirs only supports symlinks for files shouldFail = isDir } _, err := fs.Stat(filepath.FromSlash(filename)) if err != nil { if i > 0 && strings.HasSuffix(filename, "toml") && strings.Contains(err.Error(), "files not supported") { // OK return } } if shouldFail { c.Assert(err, qt.Not(qt.IsNil)) c.Assert(err, qt.Equals, hugofs.ErrPermissionSymlink) } else { c.Assert(err, qt.IsNil) } } c.Logf("Checking %d:%d %q", i, j, id) statCheck(componentFs, fmt.Sprintf("realsym%s", id), true) statCheck(componentFs, fmt.Sprintf("real/datasym%s.toml", id), false) } } } func TestMountsProject(t *testing.T) { t.Parallel() config := ` baseURL="https://example.org" [module] [[module.mounts]] source="mycontent" target="content" ` b := newTestSitesBuilder(t). WithConfigFile("toml", config). WithSourceFile(filepath.Join("mycontent", "mypage.md"), ` --- title: "My Page" --- `) b.Build(BuildCfg{}) // helpers.PrintFs(b.H.Fs.Source, "public", os.Stdout) b.AssertFileContent("public/mypage/index.html", "Permalink: https://example.org/mypage/") } // https://github.com/gohugoio/hugo/issues/6684 func TestMountsContentFile(t *testing.T) { t.Parallel() c := qt.New(t) workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-modules-content-file") c.Assert(err, qt.IsNil) defer clean() configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q [module] [[module.mounts]] source = "README.md" target = "content/_index.md" [[module.mounts]] source = "mycontent" target = "content/blog" ` tomlConfig := fmt.Sprintf(configTemplate, workingDir) b := newTestSitesBuilder(t).Running() cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig) b.WithTemplatesAdded("index.html", ` {{ .Title }} {{ .Content }} {{ $readme := .Site.GetPage "/README.md" }} {{ with $readme }}README: {{ .Title }}|Filename: {{ path.Join .File.Filename }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} {{ $mypage := .Site.GetPage "/blog/mypage.md" }} {{ with $mypage }}MYPAGE: {{ .Title }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} {{ $mybundle := .Site.GetPage "/blog/mybundle" }} {{ with $mybundle }}MYBUNDLE: {{ .Title }}|Path: {{ path.Join .File.Path }}|FilePath: {{ path.Join .File.FileInfo.Meta.PathFile }}|{{ end }} `, "_default/_markup/render-link.html", ` {{ $link := .Destination }} {{ $isRemote := strings.HasPrefix $link "http" }} {{- if not $isRemote -}} {{ $url := urls.Parse .Destination }} {{ $fragment := "" }} {{- with $url.Fragment }}{{ $fragment = printf "#%s" . }}{{ end -}} {{- with .Page.GetPage $url.Path }}{{ $link = printf "%s%s" .Permalink $fragment }}{{ end }}{{ end -}} <a href="{{ $link | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if $isRemote }} target="_blank"{{ end }}>{{ .Text | safeHTML }}</a> `) os.Mkdir(filepath.Join(workingDir, "mycontent"), 0777) os.Mkdir(filepath.Join(workingDir, "mycontent", "mybundle"), 0777) b.WithSourceFile("README.md", `--- title: "Readme Title" --- Readme Content. `, filepath.Join("mycontent", "mypage.md"), ` --- title: "My Page" --- * [Relative Link From Page](mybundle) * [Relative Link From Page, filename](mybundle/index.md) * [Link using original path](/mycontent/mybundle/index.md) `, filepath.Join("mycontent", "mybundle", "index.md"), ` --- title: "My Bundle" --- * [Dot Relative Link From Bundle](../mypage.md) * [Link using original path](/mycontent/mypage.md) * [Link to Home](/) * [Link to Home, README.md](/README.md) * [Link to Home, _index.md](/_index.md) `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` README: Readme Title /README.md|Path: _index.md|FilePath: README.md Readme Content. MYPAGE: My Page|Path: blog/mypage.md|FilePath: mycontent/mypage.md| MYBUNDLE: My Bundle|Path: blog/mybundle/index.md|FilePath: mycontent/mybundle/index.md| `) b.AssertFileContent("public/blog/mypage/index.html", ` <a href="https://example.com/blog/mybundle/">Relative Link From Page</a> <a href="https://example.com/blog/mybundle/">Relative Link From Page, filename</a> <a href="https://example.com/blog/mybundle/">Link using original path</a> `) b.AssertFileContent("public/blog/mybundle/index.html", ` <a href="https://example.com/blog/mypage/">Dot Relative Link From Bundle</a> <a href="https://example.com/blog/mypage/">Link using original path</a> <a href="https://example.com/">Link to Home</a> <a href="https://example.com/">Link to Home, README.md</a> <a href="https://example.com/">Link to Home, _index.md</a> `) b.EditFiles("README.md", `--- title: "Readme Edit" --- `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", ` Readme Edit `) } func TestMountsPaths(t *testing.T) { c := qt.New(t) type test struct { b *sitesBuilder clean func() workingDir string } prepare := func(c *qt.C, mounts string) test { workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mounts-paths") c.Assert(err, qt.IsNil) configTemplate := ` baseURL = "https://example.com" title = "My Modular Site" workingDir = %q %s ` tomlConfig := fmt.Sprintf(configTemplate, workingDir, mounts) tomlConfig = strings.Replace(tomlConfig, "WORKING_DIR", workingDir, -1) b := newTestSitesBuilder(c).Running() cfg := config.New() cfg.Set("workingDir", workingDir) cfg.Set("publishDir", "public") b.Fs = hugofs.NewDefaultOld(cfg) os.MkdirAll(filepath.Join(workingDir, "content", "blog"), 0777) b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig) return test{ b: b, clean: clean, workingDir: workingDir, } } c.Run("Default", func(c *qt.C) { mounts := `` test := prepare(c, mounts) b := test.b defer test.clean() b.WithContent("blog/p1.md", `--- title: P1 ---`) b.Build(BuildCfg{}) p := b.GetPage("blog/p1.md") f := p.File().FileInfo().Meta() b.Assert(filepath.ToSlash(f.Path), qt.Equals, "blog/p1.md") b.Assert(filepath.ToSlash(f.PathFile()), qt.Equals, "content/blog/p1.md") b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(test.workingDir, "layouts", "_default", "single.html")), qt.Equals, filepath.FromSlash("_default/single.html")) }) c.Run("Mounts", func(c *qt.C) { absDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mounts-paths-abs") c.Assert(err, qt.IsNil) defer clean() mounts := `[module] [[module.mounts]] source = "README.md" target = "content/_index.md" [[module.mounts]] source = "mycontent" target = "content/blog" [[module.mounts]] source = "subdir/mypartials" target = "layouts/partials" [[module.mounts]] source = %q target = "layouts/shortcodes" ` mounts = fmt.Sprintf(mounts, filepath.Join(absDir, "/abs/myshortcodes")) test := prepare(c, mounts) b := test.b defer test.clean() subContentDir := filepath.Join(test.workingDir, "mycontent", "sub") os.MkdirAll(subContentDir, 0777) myPartialsDir := filepath.Join(test.workingDir, "subdir", "mypartials") os.MkdirAll(myPartialsDir, 0777) absShortcodesDir := filepath.Join(absDir, "abs", "myshortcodes") os.MkdirAll(absShortcodesDir, 0777) b.WithSourceFile("README.md", "---\ntitle: Readme\n---") b.WithSourceFile("mycontent/sub/p1.md", "---\ntitle: P1\n---") b.WithSourceFile(filepath.Join(absShortcodesDir, "myshort.html"), "MYSHORT") b.WithSourceFile(filepath.Join(myPartialsDir, "mypartial.html"), "MYPARTIAL") b.Build(BuildCfg{}) p1_1 := b.GetPage("/blog/sub/p1.md") p1_2 := b.GetPage("/mycontent/sub/p1.md") b.Assert(p1_1, qt.Not(qt.IsNil)) b.Assert(p1_2, qt.Equals, p1_1) f := p1_1.File().FileInfo().Meta() b.Assert(filepath.ToSlash(f.Path), qt.Equals, "blog/sub/p1.md") b.Assert(filepath.ToSlash(f.PathFile()), qt.Equals, "mycontent/sub/p1.md") b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(myPartialsDir, "mypartial.html")), qt.Equals, filepath.FromSlash("partials/mypartial.html")) b.Assert(b.H.BaseFs.Layouts.Path(filepath.Join(absShortcodesDir, "myshort.html")), qt.Equals, filepath.FromSlash("shortcodes/myshort.html")) b.Assert(b.H.BaseFs.Content.Path(filepath.Join(subContentDir, "p1.md")), qt.Equals, filepath.FromSlash("blog/sub/p1.md")) b.Assert(b.H.BaseFs.Content.Path(filepath.Join(test.workingDir, "README.md")), qt.Equals, filepath.FromSlash("_index.md")) }) } // https://github.com/gohugoio/hugo/issues/6299 func TestSiteWithGoModButNoModules(t *testing.T) { t.Parallel() c := qt.New(t) // We need to use the OS fs for this. workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-no-mod") c.Assert(err, qt.IsNil) cfg := config.New() cfg.Set("workingDir", workDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) defer clean() b := newTestSitesBuilder(t) b.Fs = fs b.WithWorkingDir(workDir).WithViper(cfg) b.WithSourceFile("go.mod", "") b.Build(BuildCfg{}) } // https://github.com/gohugoio/hugo/issues/6622 func TestModuleAbsMount(t *testing.T) { t.Parallel() c := qt.New(t) // We need to use the OS fs for this. workDir, clean1, err := htesting.CreateTempDir(hugofs.Os, "hugo-project") c.Assert(err, qt.IsNil) absContentDir, clean2, err := htesting.CreateTempDir(hugofs.Os, "hugo-content") c.Assert(err, qt.IsNil) cfg := config.New() cfg.Set("workingDir", workDir) cfg.Set("publishDir", "public") fs := hugofs.NewFromOld(hugofs.Os, cfg) config := fmt.Sprintf(` workingDir=%q [module] [[module.mounts]] source = %q target = "content" `, workDir, absContentDir) defer clean1() defer clean2() b := newTestSitesBuilder(t) b.Fs = fs contentFilename := filepath.Join(absContentDir, "p1.md") afero.WriteFile(hugofs.Os, contentFilename, []byte(` --- title: Abs --- Content. `), 0777) b.WithWorkingDir(workDir).WithConfigFile("toml", config) b.WithContent("dummy.md", "") b.WithTemplatesAdded("index.html", ` {{ $p1 := site.GetPage "p1" }} P1: {{ $p1.Title }}|{{ $p1.RelPermalink }}|Filename: {{ $p1.File.Filename }} `) b.Build(BuildCfg{}) b.AssertFileContent("public/index.html", "P1: Abs|/p1/", "Filename: "+contentFilename) } // Issue 9426 func TestMountSameSource(t *testing.T) { config := `baseURL = 'https://example.org/' languageCode = 'en-us' title = 'Hugo GitHub Issue #9426' disableKinds = ['RSS','sitemap','taxonomy','term'] [[module.mounts]] source = "content" target = "content" [[module.mounts]] source = "extra-content" target = "content/resources-a" [[module.mounts]] source = "extra-content" target = "content/resources-b" ` b := newTestSitesBuilder(t).WithConfigFile("toml", config) b.WithContent("p1.md", "") b.WithSourceFile( "extra-content/_index.md", "", "extra-content/subdir/_index.md", "", "extra-content/subdir/about.md", "", ) b.Build(BuildCfg{}) b.AssertFileContent("public/resources-a/subdir/about/index.html", "Single") b.AssertFileContent("public/resources-b/subdir/about/index.html", "Single") } func TestMountData(t *testing.T) { files := ` -- hugo.toml -- baseURL = 'https://example.org/' disableKinds = ["taxonomy", "term", "RSS", "sitemap", "robotsTXT", "page", "section"] [[module.mounts]] source = "data" target = "data" [[module.mounts]] source = "extra-data" target = "data/extra" -- extra-data/test.yaml -- message: Hugo Rocks -- layouts/index.html -- {{ site.Data.extra.test.message }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/index.html", "Hugo Rocks") }
dvdksn
79f15be5b0e47a788f62e50ba3e354c247a65f6b
286821e360e13b3a174854914c9cedd437bdd25e
OK; done
dvdksn
28
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
@jmooring the only functional change in this PR is the above. My take is that if people use `:title` in their permalinks config for sections, they mean it. I guess skipping this for branch pages was motivated by not repeating the section name, but then it's not possible to use the front matter title in the URLs and it feels a little bit too magic. A permalink config for sections that would make sense is `:sections[:last]/:title`. Agree?
bep
29
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
there is a typo in `configuration` ```suggestion return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) ```
alexandear
30
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
```suggestion // To successfully be backward compatible, "default" patterns need to be set for both page and term ```
alexandear
31
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
Testing with hugo v0.115.0-DEV-e1992b66... Given this content structure: ```text content/ ├── books/ │   └── fiction/ │   ├── 2023/ │   │   ├── book-1.md │   │   └── _index.md │   └── _index.md └── _index.md ``` And to produce this: ``` public/ ├── libros/ │   ├── fiction/ │   │   ├── 2023/ │   │   │   ├── book-1/ │   │   │   │   └── index.html │   │   │   └── index.html │   │   └── index.html │   └── index.html └── index.html ``` I can do this (it works): ``` [permalinks.page] books = '/libros/:sections[1:]/:title' [permalinks.section] books = '/libros/:sections[1:]' ``` If I understand your previous comment, I should also be able to do this: ``` [[permalinks.page] books = '/libros/:sections[1:]/:title' [permalinks.section] books = '/libros/:sections[1:last]/:title' ``` But it panics with `panic: runtime error: slice bounds out of range [1:0]`. I am using `:last` incorrectly in this case?
jmooring
32
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
>But it panics with panic: runtime error: slice bounds out of range [1:0]. I am using :last incorrectly in this case? The above looks like an (odd) bug. There should be no "slice bounds out of range" with these constructs, but I have obviously a hole in my test coverage. I will fix that.
bep
33
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
@jmooring I have pushed a commit that fixes your example.
bep
34
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
hugo v0.115.0-DEV-e1992b6 still panics with `panic: runtime error: slice bounds out of range [1:0]`. Same config... ```text [permalinks.page] books = '/libros/:sections[1:]/:title' [permalinks.section] books = '/libros/:sections[1:last]/:title' ```
jmooring
35
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
Hmm...
bep
36
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
OK; I see that my "git push" had failed (I probably had a amend locally); I just force pushed it now. Sorry for the noise.
bep
37
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
Testing with hugo v0.115.0-DEV-5c0216ed No panic, but it is creating an index page that I don't expect. config ```toml [permalinks.page] books = '/libros/:sections[1:]/:title' # Works as expected # [permalinks.section] # books = '/libros/:sections[1:]' # Does not work as I expect [permalinks.section] books = '/libros/:sections[1:last]/:title' ``` published ```text public/ ├── libros/ │ ├── books/ <-- this section should not exist │ │ └── index.html │ └── fiction/ │ ├── 2023/ │ │ ├── book-1/ │ │ │ └── index.html │ │ └── index.html │ └── index.html └── index.html ``` Test site if you need it: ```text git clone --single-branch -b hugo-github-issue-11185 https://github.com/jmooring/hugo-testing hugo-github-issue-11185 cd hugo-github-issue-11185 rm -rf public/ && hugo && tree public ```
jmooring
38
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
>books/ <-- this section should not exist Well, it is how you have configured your permalinks :-) But I see your point, I will think about it. But if you had said: ``` [permalinks.section] books = '/libros/:sections[1:]' ``` You would get closer. It's the `:title` that creates your "unwanted section". But I need to think about this a little ...
bep
39
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
@jmooring I have thought a little, and I haven't found a simpler solution than expanding the syntax a little: ``` [permalinks.section] books = '/libros/:sections[1:last]/:slug|:sections[last]' ``` This would make both of these the same: ``` [permalinks.section] books = '/:slugorfilename' ``` ``` [permalinks.section] books = '/:slug|:filename' ``` ??
bep
40
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
I think I would prefer to document what currently works: ``` [permalinks.page] books = '/libros/:sections[1:]/:title' [permalinks.section] books = '/libros/:sections[1:]' ``` The OR pipe is interesting, but I can see it being misused, generating "why doesn't this work" questions.
jmooring
41
gohugoio/hugo
11,185
Misc permalinks adjustments
Fixes #9448 Fixes #11184 See #8523
null
2023-06-28 14:09:47+00:00
2023-06-29 08:14:20+00:00
resources/page/permalinks.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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { if p.File().TranslationBaseName() == "_index" { return "", nil } return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := p.File().TranslationBaseName() if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n > len(ss) { return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } v := s[toN(s)] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } return s[toN1(s):toN2(s)] } }
// 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 page import ( "fmt" "os" "path" "path/filepath" "regexp" "strconv" "strings" "time" "errors" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" ) // PermalinkExpander holds permalin mappings per section. type PermalinkExpander struct { // knownPermalinkAttributes maps :tags in a permalink specification to a // function which, given a page and the tag, returns the resulting string // to be used to replace that tag. knownPermalinkAttributes map[string]pageToPermaAttribute expanders map[string]map[string]func(Page) (string, error) urlize func(uri string) string } // Time for checking date formats. Every field is different than the // Go reference time for date formatting. This ensures that formatting this date // with a Go time format always has a different output than the format itself. var referenceTime = time.Date(2019, time.November, 9, 23, 1, 42, 1, time.UTC) // Return the callback for the given permalink attribute and a boolean indicating if the attribute is valid or not. func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { if callback, ok := p.knownPermalinkAttributes[attr]; ok { return callback, true } if strings.HasPrefix(attr, "sections[") { fn := p.toSliceFunc(strings.TrimPrefix(attr, "sections")) return func(p Page, s string) (string, error) { return path.Join(fn(p.CurrentSection().SectionsEntries())...), nil }, true } // Make sure this comes after all the other checks. if referenceTime.Format(attr) != attr { return p.pageToPermalinkDate, true } return nil, false } // NewPermalinkExpander creates a new PermalinkExpander configured by the given // urlize func. func NewPermalinkExpander(urlize func(uri string) string, patterns map[string]map[string]string) (PermalinkExpander, error) { p := PermalinkExpander{urlize: urlize} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": p.pageToPermalinkDate, "month": p.pageToPermalinkDate, "monthname": p.pageToPermalinkDate, "day": p.pageToPermalinkDate, "weekday": p.pageToPermalinkDate, "weekdayname": p.pageToPermalinkDate, "yearday": p.pageToPermalinkDate, "section": p.pageToPermalinkSection, "sections": p.pageToPermalinkSections, "title": p.pageToPermalinkTitle, "slug": p.pageToPermalinkSlugElseTitle, "slugorfilename": p.pageToPermalinkSlugElseFilename, "filename": p.pageToPermalinkFilename, } p.expanders = make(map[string]map[string]func(Page) (string, error)) for kind, patterns := range patterns { e, err := p.parse(patterns) if err != nil { return p, err } p.expanders[kind] = e } return p, nil } // Expand expands the path in p according to the rules defined for the given key. // If no rules are found for the given key, an empty string is returned. func (l PermalinkExpander) Expand(key string, p Page) (string, error) { expanders, found := l.expanders[p.Kind()] if !found { return "", nil } expand, found := expanders[key] if !found { return "", nil } return expand(p) } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. const sectionCutSet = " /" + string(os.PathSeparator) for k, pattern := range patterns { k = strings.Trim(k, sectionCutSet) if !l.validate(pattern) { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkIllFormed} } pattern := pattern matches := attributeRegexp.FindAllStringSubmatch(pattern, -1) callbacks := make([]pageToPermaAttribute, len(matches)) replacements := make([]string, len(matches)) for i, m := range matches { replacement := m[0] attr := replacement[1:] replacements[i] = replacement callback, ok := l.callback(attr) if !ok { return nil, &permalinkExpandError{pattern: pattern, err: errPermalinkAttributeUnknown} } callbacks[i] = callback } expanders[k] = func(p Page) (string, error) { if matches == nil { return pattern, nil } newField := pattern for i, replacement := range replacements { attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } newField = strings.Replace(newField, replacement, newAttr, 1) } return newField, nil } } return expanders, nil } // pageToPermaAttribute is the type of a function which, given a page and a tag // can return a string to go in that position in the page (or an error) type pageToPermaAttribute func(Page, string) (string, error) var attributeRegexp = regexp.MustCompile(`:\w+(\[.+?\])?`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { if len(pp) == 0 { return false } fragments := strings.Split(pp[1:], "/") bail := false for i := range fragments { if bail { return false } if len(fragments[i]) == 0 { bail = true continue } matches := attributeRegexp.FindAllStringSubmatch(fragments[i], -1) if matches == nil { continue } for _, match := range matches { k := match[0][1:] if _, ok := l.callback(k); !ok { return false } } } return true } type permalinkExpandError struct { pattern string err error } func (pee *permalinkExpandError) Error() string { return fmt.Sprintf("error expanding %q: %s", pee.pattern, pee.err) } var ( errPermalinkIllFormed = errors.New("permalink ill-formed") errPermalinkAttributeUnknown = errors.New("permalink attribute not recognised") ) func (l PermalinkExpander) pageToPermalinkDate(p Page, dateField string) (string, error) { // a Page contains a Node which provides a field Date, time.Time switch dateField { case "year": return strconv.Itoa(p.Date().Year()), nil case "month": return fmt.Sprintf("%02d", int(p.Date().Month())), nil case "monthname": return p.Date().Month().String(), nil case "day": return fmt.Sprintf("%02d", p.Date().Day()), nil case "weekday": return strconv.Itoa(int(p.Date().Weekday())), nil case "weekdayname": return p.Date().Weekday().String(), nil case "yearday": return strconv.Itoa(p.Date().YearDay()), nil } return p.Date().Format(dateField), nil } // pageToPermalinkTitle returns the URL-safe form of the title func (l PermalinkExpander) pageToPermalinkTitle(p Page, _ string) (string, error) { return l.urlize(p.Title()), nil } // pageToPermalinkFilename returns the URL-safe form of the filename func (l PermalinkExpander) pageToPermalinkFilename(p Page, _ string) (string, error) { name := l.translationBaseName(p) if name == "index" { // Page bundles; the directory name will hopefully have a better name. dir := strings.TrimSuffix(p.File().Dir(), helpers.FilePathSeparator) _, name = filepath.Split(dir) } else if name == "_index" { return "", nil } return l.urlize(name), nil } // if the page has a slug, return the slug, else return the title func (l PermalinkExpander) pageToPermalinkSlugElseTitle(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkTitle(p, a) } // if the page has a slug, return the slug, else return the filename func (l PermalinkExpander) pageToPermalinkSlugElseFilename(p Page, a string) (string, error) { if p.Slug() != "" { return l.urlize(p.Slug()), nil } return l.pageToPermalinkFilename(p, a) } func (l PermalinkExpander) pageToPermalinkSection(p Page, _ string) (string, error) { return p.Section(), nil } func (l PermalinkExpander) pageToPermalinkSections(p Page, _ string) (string, error) { return p.CurrentSection().SectionsPath(), nil } func (l PermalinkExpander) translationBaseName(p Page) string { if p.File().IsZero() { return "" } return p.File().TranslationBaseName() } var ( nilSliceFunc = func(s []string) []string { return nil } allSliceFunc = func(s []string) []string { return s } ) // toSliceFunc returns a slice func that slices s according to the cut spec. // The cut spec must be on form [low:high] (one or both can be omitted), // also allowing single slice indices (e.g. [2]) and the special [last] keyword // giving the last element of the slice. // The returned function will be lenient and not panic in out of bounds situation. // // The current use case for this is to use parts of the sections path in permalinks. func (l PermalinkExpander) toSliceFunc(cut string) func(s []string) []string { cut = strings.ToLower(strings.TrimSpace(cut)) if cut == "" { return allSliceFunc } if len(cut) < 3 || (cut[0] != '[' || cut[len(cut)-1] != ']') { return nilSliceFunc } toNFunc := func(s string, low bool) func(ss []string) int { if s == "" { if low { return func(ss []string) int { return 0 } } else { return func(ss []string) int { return len(ss) } } } if s == "last" { return func(ss []string) int { return len(ss) - 1 } } n, _ := strconv.Atoi(s) if n < 0 { n = 0 } return func(ss []string) int { // Prevent out of bound situations. It would not make // much sense to panic here. if n >= len(ss) { if low { return -1 } return len(ss) } return n } } opsStr := cut[1 : len(cut)-1] opts := strings.Split(opsStr, ":") if !strings.Contains(opsStr, ":") { toN := toNFunc(opts[0], true) return func(s []string) []string { if len(s) == 0 { return nil } n := toN(s) if n < 0 { return []string{} } v := s[n] if v == "" { return nil } return []string{v} } } toN1, toN2 := toNFunc(opts[0], true), toNFunc(opts[1], false) return func(s []string) []string { if len(s) == 0 { return nil } n1, n2 := toN1(s), toN2(s) if n1 < 0 || n2 < 0 { return []string{} } return s[n1:n2] } } var permalinksKindsSuppurt = []string{KindPage, KindSection, KindTaxonomy, KindTerm} // DecodePermalinksConfig decodes the permalinks configuration in the given map func DecodePermalinksConfig(m map[string]any) (map[string]map[string]string, error) { permalinksConfig := make(map[string]map[string]string) permalinksConfig[KindPage] = make(map[string]string) permalinksConfig[KindSection] = make(map[string]string) permalinksConfig[KindTaxonomy] = make(map[string]string) permalinksConfig[KindTerm] = make(map[string]string) config := maps.CleanConfigStringMap(m) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term permalinksConfig[KindPage][k] = v permalinksConfig[KindTerm][k] = v case maps.Params: // [permalinks.key] // xyz = ??? if helpers.InStringArray(permalinksKindsSuppurt, k) { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: permalinksConfig[k][k2] = v2 default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return nil, fmt.Errorf("permalinks configuration not supported for kind %q, supported kinds are %v", k, permalinksKindsSuppurt) } default: return nil, fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return permalinksConfig, nil }
bep
80ecb958951783eb03e23a81800102d0e33db6e1
7917961d59b0dc216e49f59dc0255f9b46534115
Yea, lets hold off on that idea until later.
bep
42
gohugoio/hugo
11,178
commands: Fix panic when running hugo new theme without theme name
This PR closes #11162.
null
2023-06-27 14:37:30+00:00
2023-06-28 14:20:54+00:00
commands/new.go
// Copyright 2023 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 commands import ( "bytes" "context" "errors" "fmt" "path/filepath" "strings" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/afero" "github.com/spf13/cobra" ) func newNewCommand() *newCommand { var ( force bool contentType string format string ) var c *newCommand c = &newCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "content", use: "content [path]", short: "Create new content for your site", long: `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return errors.New("path needs to be provided") } h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } return create.NewContent(h, contentType, args[0], force) }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().StringVarP(&contentType, "kind", "k", "", "content type to create") cmd.Flags().String("editor", "", "edit new content with this editor, if provided") cmd.Flags().BoolVarP(&force, "force", "f", false, "overwrite file if it already exists") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") applyLocalFlagsBuildConfig(cmd, r) }, }, &simpleCommand{ name: "site", use: "site [path]", short: "Create a new site (skeleton)", long: `Create a new site in the provided directory. The new site will have the correct structure, but no content or theme yet. Use ` + "`hugo new [contentPath]`" + ` to create new content.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return errors.New("path needs to be provided") } createpath, err := filepath.Abs(filepath.Clean(args[0])) if err != nil { return err } cfg := config.New() cfg.Set("workingDir", createpath) cfg.Set("publishDir", "public") conf, err := r.ConfigFromProvider(r.configVersionID.Load(), flagsToCfg(cd, cfg)) if err != nil { return err } sourceFs := conf.fs.Source archeTypePath := filepath.Join(createpath, "archetypes") dirs := []string{ archeTypePath, filepath.Join(createpath, "assets"), filepath.Join(createpath, "content"), filepath.Join(createpath, "data"), filepath.Join(createpath, "layouts"), filepath.Join(createpath, "static"), filepath.Join(createpath, "themes"), } if exists, _ := helpers.Exists(createpath, sourceFs); exists { if isDir, _ := helpers.IsDir(createpath, sourceFs); !isDir { return errors.New(createpath + " already exists but not a directory") } isEmpty, _ := helpers.IsEmpty(createpath, sourceFs) switch { case !isEmpty && !force: return errors.New(createpath + " already exists and is not empty. See --force.") case !isEmpty && force: all := append(dirs, filepath.Join(createpath, "hugo."+format)) for _, path := range all { if exists, _ := helpers.Exists(path, sourceFs); exists { return errors.New(path + " already exists") } } } } for _, dir := range dirs { if err := sourceFs.MkdirAll(dir, 0777); err != nil { return fmt.Errorf("failed to create dir: %w", err) } } c.newSiteCreateConfig(sourceFs, createpath, format) // Create a default archetype file. helpers.SafeWriteToDisk(filepath.Join(archeTypePath, "default.md"), strings.NewReader(create.DefaultArchetypeTemplateTemplate), sourceFs) r.Printf("Congratulations! Your new Hugo site is created in %s.\n\n", createpath) r.Println(c.newSiteNextStepsText()) return nil }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVarP(&force, "force", "f", false, "init inside non-empty directory") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") }, }, &simpleCommand{ name: "theme", use: "theme [name]", short: "Create a new theme (skeleton)", long: `Create a new theme (skeleton) called [name] in ./themes. New theme is a skeleton. Please add content to the touched files. Add your name to the copyright line in the license and adjust the theme.toml file according to your needs.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } ps := h.PathSpec sourceFs := ps.Fs.Source themesDir := h.Configs.LoadingInfo.BaseConfig.ThemesDir createpath := ps.AbsPathify(filepath.Join(themesDir, args[0])) r.Println("Creating theme at", createpath) if x, _ := helpers.Exists(createpath, sourceFs); x { return errors.New(createpath + " already exists") } for _, filename := range []string{ "index.html", "404.html", "_default/list.html", "_default/single.html", "partials/head.html", "partials/header.html", "partials/footer.html", } { touchFile(sourceFs, filepath.Join(createpath, "layouts", filename)) } baseofDefault := []byte(`<!DOCTYPE html> <html> {{- partial "head.html" . -}} <body> {{- partial "header.html" . -}} <div id="content"> {{- block "main" . }}{{- end }} </div> {{- partial "footer.html" . -}} </body> </html> `) err = helpers.WriteToDisk(filepath.Join(createpath, "layouts", "_default", "baseof.html"), bytes.NewReader(baseofDefault), sourceFs) if err != nil { return err } mkdir(createpath, "archetypes") archDefault := []byte("+++\n+++\n") err = helpers.WriteToDisk(filepath.Join(createpath, "archetypes", "default.md"), bytes.NewReader(archDefault), sourceFs) if err != nil { return err } mkdir(createpath, "static", "js") mkdir(createpath, "static", "css") by := []byte(`The MIT License (MIT) Copyright (c) ` + htime.Now().Format("2006") + ` YOUR_NAME_HERE 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. `) err = helpers.WriteToDisk(filepath.Join(createpath, "LICENSE"), bytes.NewReader(by), sourceFs) if err != nil { return err } c.createThemeMD(ps.Fs.Source, createpath) return nil }, }, }, } return c } type newCommand struct { rootCmd *rootCommand commands []simplecobra.Commander } func (c *newCommand) Commands() []simplecobra.Commander { return c.commands } func (c *newCommand) Name() string { return "new" } func (c *newCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *newCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Create new content for your site" cmd.Long = `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.` cmd.RunE = nil return nil } func (c *newCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.rootCmd = cd.Root.Command.(*rootCommand) return nil } func (c *newCommand) newSiteCreateConfig(fs afero.Fs, inpath string, kind string) (err error) { in := map[string]string{ "baseURL": "http://example.org/", "title": "My New Hugo Site", "languageCode": "en-us", } var buf bytes.Buffer err = parser.InterfaceToConfig(in, metadecoders.FormatFromString(kind), &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+kind), &buf, fs) } func (c *newCommand) newSiteNextStepsText() string { var nextStepsText bytes.Buffer nextStepsText.WriteString(`Just a few more steps and you're ready to go: 1. Download a theme into the same-named folder. Choose a theme from https://themes.gohugo.io/ or create your own with the "hugo new theme <THEMENAME>" command. 2. Perhaps you want to add some content. You can add single files with "hugo new `) nextStepsText.WriteString(filepath.Join("<SECTIONNAME>", "<FILENAME>.<FORMAT>")) nextStepsText.WriteString(`". 3. Start the built-in live server via "hugo server". Visit https://gohugo.io/ for quickstart guide and full documentation.`) return nextStepsText.String() } func (c *newCommand) createThemeMD(fs afero.Fs, inpath string) (err error) { by := []byte(`# theme.toml template for a Hugo theme # See https://github.com/gohugoio/hugoThemes#themetoml for an example name = "` + strings.Title(helpers.MakeTitle(filepath.Base(inpath))) + `" license = "MIT" licenselink = "https://github.com/yourname/yourtheme/blob/master/LICENSE" description = "" homepage = "http://example.com/" tags = [] features = [] min_version = "0.114.0" [author] name = "" homepage = "" # If porting an existing theme [original] name = "" homepage = "" repo = "" `) err = helpers.WriteToDisk(filepath.Join(inpath, "theme.toml"), bytes.NewReader(by), fs) if err != nil { return } err = helpers.WriteToDisk(filepath.Join(inpath, "hugo.toml"), strings.NewReader("# Theme config.\n"), fs) if err != nil { return } return nil }
// Copyright 2023 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 commands import ( "bytes" "context" "errors" "fmt" "path/filepath" "strings" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/afero" "github.com/spf13/cobra" ) func newNewCommand() *newCommand { var ( force bool contentType string format string ) var c *newCommand c = &newCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "content", use: "content [path]", short: "Create new content for your site", long: `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return newUserError("path needs to be provided") } h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } return create.NewContent(h, contentType, args[0], force) }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().StringVarP(&contentType, "kind", "k", "", "content type to create") cmd.Flags().String("editor", "", "edit new content with this editor, if provided") cmd.Flags().BoolVarP(&force, "force", "f", false, "overwrite file if it already exists") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") applyLocalFlagsBuildConfig(cmd, r) }, }, &simpleCommand{ name: "site", use: "site [path]", short: "Create a new site (skeleton)", long: `Create a new site in the provided directory. The new site will have the correct structure, but no content or theme yet. Use ` + "`hugo new [contentPath]`" + ` to create new content.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return newUserError("path needs to be provided") } createpath, err := filepath.Abs(filepath.Clean(args[0])) if err != nil { return err } cfg := config.New() cfg.Set("workingDir", createpath) cfg.Set("publishDir", "public") conf, err := r.ConfigFromProvider(r.configVersionID.Load(), flagsToCfg(cd, cfg)) if err != nil { return err } sourceFs := conf.fs.Source archeTypePath := filepath.Join(createpath, "archetypes") dirs := []string{ archeTypePath, filepath.Join(createpath, "assets"), filepath.Join(createpath, "content"), filepath.Join(createpath, "data"), filepath.Join(createpath, "layouts"), filepath.Join(createpath, "static"), filepath.Join(createpath, "themes"), } if exists, _ := helpers.Exists(createpath, sourceFs); exists { if isDir, _ := helpers.IsDir(createpath, sourceFs); !isDir { return errors.New(createpath + " already exists but not a directory") } isEmpty, _ := helpers.IsEmpty(createpath, sourceFs) switch { case !isEmpty && !force: return errors.New(createpath + " already exists and is not empty. See --force.") case !isEmpty && force: all := append(dirs, filepath.Join(createpath, "hugo."+format)) for _, path := range all { if exists, _ := helpers.Exists(path, sourceFs); exists { return errors.New(path + " already exists") } } } } for _, dir := range dirs { if err := sourceFs.MkdirAll(dir, 0777); err != nil { return fmt.Errorf("failed to create dir: %w", err) } } c.newSiteCreateConfig(sourceFs, createpath, format) // Create a default archetype file. helpers.SafeWriteToDisk(filepath.Join(archeTypePath, "default.md"), strings.NewReader(create.DefaultArchetypeTemplateTemplate), sourceFs) r.Printf("Congratulations! Your new Hugo site is created in %s.\n\n", createpath) r.Println(c.newSiteNextStepsText()) return nil }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVarP(&force, "force", "f", false, "init inside non-empty directory") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") }, }, &simpleCommand{ name: "theme", use: "theme [name]", short: "Create a new theme (skeleton)", long: `Create a new theme (skeleton) called [name] in ./themes. New theme is a skeleton. Please add content to the touched files. Add your name to the copyright line in the license and adjust the theme.toml file according to your needs.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return newUserError("theme name needs to be provided") } h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } ps := h.PathSpec sourceFs := ps.Fs.Source themesDir := h.Configs.LoadingInfo.BaseConfig.ThemesDir createpath := ps.AbsPathify(filepath.Join(themesDir, args[0])) r.Println("Creating theme at", createpath) if x, _ := helpers.Exists(createpath, sourceFs); x { return errors.New(createpath + " already exists") } for _, filename := range []string{ "index.html", "404.html", "_default/list.html", "_default/single.html", "partials/head.html", "partials/header.html", "partials/footer.html", } { touchFile(sourceFs, filepath.Join(createpath, "layouts", filename)) } baseofDefault := []byte(`<!DOCTYPE html> <html> {{- partial "head.html" . -}} <body> {{- partial "header.html" . -}} <div id="content"> {{- block "main" . }}{{- end }} </div> {{- partial "footer.html" . -}} </body> </html> `) err = helpers.WriteToDisk(filepath.Join(createpath, "layouts", "_default", "baseof.html"), bytes.NewReader(baseofDefault), sourceFs) if err != nil { return err } mkdir(createpath, "archetypes") archDefault := []byte("+++\n+++\n") err = helpers.WriteToDisk(filepath.Join(createpath, "archetypes", "default.md"), bytes.NewReader(archDefault), sourceFs) if err != nil { return err } mkdir(createpath, "static", "js") mkdir(createpath, "static", "css") by := []byte(`The MIT License (MIT) Copyright (c) ` + htime.Now().Format("2006") + ` YOUR_NAME_HERE 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. `) err = helpers.WriteToDisk(filepath.Join(createpath, "LICENSE"), bytes.NewReader(by), sourceFs) if err != nil { return err } c.createThemeMD(ps.Fs.Source, createpath) return nil }, }, }, } return c } type newCommand struct { rootCmd *rootCommand commands []simplecobra.Commander } func (c *newCommand) Commands() []simplecobra.Commander { return c.commands } func (c *newCommand) Name() string { return "new" } func (c *newCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *newCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Create new content for your site" cmd.Long = `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.` cmd.RunE = nil return nil } func (c *newCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.rootCmd = cd.Root.Command.(*rootCommand) return nil } func (c *newCommand) newSiteCreateConfig(fs afero.Fs, inpath string, kind string) (err error) { in := map[string]string{ "baseURL": "http://example.org/", "title": "My New Hugo Site", "languageCode": "en-us", } var buf bytes.Buffer err = parser.InterfaceToConfig(in, metadecoders.FormatFromString(kind), &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+kind), &buf, fs) } func (c *newCommand) newSiteNextStepsText() string { var nextStepsText bytes.Buffer nextStepsText.WriteString(`Just a few more steps and you're ready to go: 1. Download a theme into the same-named folder. Choose a theme from https://themes.gohugo.io/ or create your own with the "hugo new theme <THEMENAME>" command. 2. Perhaps you want to add some content. You can add single files with "hugo new `) nextStepsText.WriteString(filepath.Join("<SECTIONNAME>", "<FILENAME>.<FORMAT>")) nextStepsText.WriteString(`". 3. Start the built-in live server via "hugo server". Visit https://gohugo.io/ for quickstart guide and full documentation.`) return nextStepsText.String() } func (c *newCommand) createThemeMD(fs afero.Fs, inpath string) (err error) { by := []byte(`# theme.toml template for a Hugo theme # See https://github.com/gohugoio/hugoThemes#themetoml for an example name = "` + strings.Title(helpers.MakeTitle(filepath.Base(inpath))) + `" license = "MIT" licenselink = "https://github.com/yourname/yourtheme/blob/master/LICENSE" description = "" homepage = "http://example.com/" tags = [] features = [] min_version = "0.114.0" [author] name = "" homepage = "" # If porting an existing theme [original] name = "" homepage = "" repo = "" `) err = helpers.WriteToDisk(filepath.Join(inpath, "theme.toml"), bytes.NewReader(by), fs) if err != nil { return } err = helpers.WriteToDisk(filepath.Join(inpath, "hugo.toml"), strings.NewReader("# Theme config.\n"), fs) if err != nil { return } return nil }
deining
12646750aa186cf3bf50266f8eddf9cfebc3c9c9
635cc346cef6c6c7ada4dd1010a631613568d51d
There's some logic above to distinguish between "command errors" (which we show the help output + an error message) and "runtime errors". I think the above is in the first category, so if you could replace the above with ```go return newUserError("theme name needs to be provided") ```
bep
43
gohugoio/hugo
11,178
commands: Fix panic when running hugo new theme without theme name
This PR closes #11162.
null
2023-06-27 14:37:30+00:00
2023-06-28 14:20:54+00:00
commands/new.go
// Copyright 2023 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 commands import ( "bytes" "context" "errors" "fmt" "path/filepath" "strings" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/afero" "github.com/spf13/cobra" ) func newNewCommand() *newCommand { var ( force bool contentType string format string ) var c *newCommand c = &newCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "content", use: "content [path]", short: "Create new content for your site", long: `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return errors.New("path needs to be provided") } h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } return create.NewContent(h, contentType, args[0], force) }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().StringVarP(&contentType, "kind", "k", "", "content type to create") cmd.Flags().String("editor", "", "edit new content with this editor, if provided") cmd.Flags().BoolVarP(&force, "force", "f", false, "overwrite file if it already exists") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") applyLocalFlagsBuildConfig(cmd, r) }, }, &simpleCommand{ name: "site", use: "site [path]", short: "Create a new site (skeleton)", long: `Create a new site in the provided directory. The new site will have the correct structure, but no content or theme yet. Use ` + "`hugo new [contentPath]`" + ` to create new content.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return errors.New("path needs to be provided") } createpath, err := filepath.Abs(filepath.Clean(args[0])) if err != nil { return err } cfg := config.New() cfg.Set("workingDir", createpath) cfg.Set("publishDir", "public") conf, err := r.ConfigFromProvider(r.configVersionID.Load(), flagsToCfg(cd, cfg)) if err != nil { return err } sourceFs := conf.fs.Source archeTypePath := filepath.Join(createpath, "archetypes") dirs := []string{ archeTypePath, filepath.Join(createpath, "assets"), filepath.Join(createpath, "content"), filepath.Join(createpath, "data"), filepath.Join(createpath, "layouts"), filepath.Join(createpath, "static"), filepath.Join(createpath, "themes"), } if exists, _ := helpers.Exists(createpath, sourceFs); exists { if isDir, _ := helpers.IsDir(createpath, sourceFs); !isDir { return errors.New(createpath + " already exists but not a directory") } isEmpty, _ := helpers.IsEmpty(createpath, sourceFs) switch { case !isEmpty && !force: return errors.New(createpath + " already exists and is not empty. See --force.") case !isEmpty && force: all := append(dirs, filepath.Join(createpath, "hugo."+format)) for _, path := range all { if exists, _ := helpers.Exists(path, sourceFs); exists { return errors.New(path + " already exists") } } } } for _, dir := range dirs { if err := sourceFs.MkdirAll(dir, 0777); err != nil { return fmt.Errorf("failed to create dir: %w", err) } } c.newSiteCreateConfig(sourceFs, createpath, format) // Create a default archetype file. helpers.SafeWriteToDisk(filepath.Join(archeTypePath, "default.md"), strings.NewReader(create.DefaultArchetypeTemplateTemplate), sourceFs) r.Printf("Congratulations! Your new Hugo site is created in %s.\n\n", createpath) r.Println(c.newSiteNextStepsText()) return nil }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVarP(&force, "force", "f", false, "init inside non-empty directory") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") }, }, &simpleCommand{ name: "theme", use: "theme [name]", short: "Create a new theme (skeleton)", long: `Create a new theme (skeleton) called [name] in ./themes. New theme is a skeleton. Please add content to the touched files. Add your name to the copyright line in the license and adjust the theme.toml file according to your needs.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } ps := h.PathSpec sourceFs := ps.Fs.Source themesDir := h.Configs.LoadingInfo.BaseConfig.ThemesDir createpath := ps.AbsPathify(filepath.Join(themesDir, args[0])) r.Println("Creating theme at", createpath) if x, _ := helpers.Exists(createpath, sourceFs); x { return errors.New(createpath + " already exists") } for _, filename := range []string{ "index.html", "404.html", "_default/list.html", "_default/single.html", "partials/head.html", "partials/header.html", "partials/footer.html", } { touchFile(sourceFs, filepath.Join(createpath, "layouts", filename)) } baseofDefault := []byte(`<!DOCTYPE html> <html> {{- partial "head.html" . -}} <body> {{- partial "header.html" . -}} <div id="content"> {{- block "main" . }}{{- end }} </div> {{- partial "footer.html" . -}} </body> </html> `) err = helpers.WriteToDisk(filepath.Join(createpath, "layouts", "_default", "baseof.html"), bytes.NewReader(baseofDefault), sourceFs) if err != nil { return err } mkdir(createpath, "archetypes") archDefault := []byte("+++\n+++\n") err = helpers.WriteToDisk(filepath.Join(createpath, "archetypes", "default.md"), bytes.NewReader(archDefault), sourceFs) if err != nil { return err } mkdir(createpath, "static", "js") mkdir(createpath, "static", "css") by := []byte(`The MIT License (MIT) Copyright (c) ` + htime.Now().Format("2006") + ` YOUR_NAME_HERE 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. `) err = helpers.WriteToDisk(filepath.Join(createpath, "LICENSE"), bytes.NewReader(by), sourceFs) if err != nil { return err } c.createThemeMD(ps.Fs.Source, createpath) return nil }, }, }, } return c } type newCommand struct { rootCmd *rootCommand commands []simplecobra.Commander } func (c *newCommand) Commands() []simplecobra.Commander { return c.commands } func (c *newCommand) Name() string { return "new" } func (c *newCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *newCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Create new content for your site" cmd.Long = `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.` cmd.RunE = nil return nil } func (c *newCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.rootCmd = cd.Root.Command.(*rootCommand) return nil } func (c *newCommand) newSiteCreateConfig(fs afero.Fs, inpath string, kind string) (err error) { in := map[string]string{ "baseURL": "http://example.org/", "title": "My New Hugo Site", "languageCode": "en-us", } var buf bytes.Buffer err = parser.InterfaceToConfig(in, metadecoders.FormatFromString(kind), &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+kind), &buf, fs) } func (c *newCommand) newSiteNextStepsText() string { var nextStepsText bytes.Buffer nextStepsText.WriteString(`Just a few more steps and you're ready to go: 1. Download a theme into the same-named folder. Choose a theme from https://themes.gohugo.io/ or create your own with the "hugo new theme <THEMENAME>" command. 2. Perhaps you want to add some content. You can add single files with "hugo new `) nextStepsText.WriteString(filepath.Join("<SECTIONNAME>", "<FILENAME>.<FORMAT>")) nextStepsText.WriteString(`". 3. Start the built-in live server via "hugo server". Visit https://gohugo.io/ for quickstart guide and full documentation.`) return nextStepsText.String() } func (c *newCommand) createThemeMD(fs afero.Fs, inpath string) (err error) { by := []byte(`# theme.toml template for a Hugo theme # See https://github.com/gohugoio/hugoThemes#themetoml for an example name = "` + strings.Title(helpers.MakeTitle(filepath.Base(inpath))) + `" license = "MIT" licenselink = "https://github.com/yourname/yourtheme/blob/master/LICENSE" description = "" homepage = "http://example.com/" tags = [] features = [] min_version = "0.114.0" [author] name = "" homepage = "" # If porting an existing theme [original] name = "" homepage = "" repo = "" `) err = helpers.WriteToDisk(filepath.Join(inpath, "theme.toml"), bytes.NewReader(by), fs) if err != nil { return } err = helpers.WriteToDisk(filepath.Join(inpath, "hugo.toml"), strings.NewReader("# Theme config.\n"), fs) if err != nil { return } return nil }
// Copyright 2023 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 commands import ( "bytes" "context" "errors" "fmt" "path/filepath" "strings" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/afero" "github.com/spf13/cobra" ) func newNewCommand() *newCommand { var ( force bool contentType string format string ) var c *newCommand c = &newCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "content", use: "content [path]", short: "Create new content for your site", long: `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return newUserError("path needs to be provided") } h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } return create.NewContent(h, contentType, args[0], force) }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().StringVarP(&contentType, "kind", "k", "", "content type to create") cmd.Flags().String("editor", "", "edit new content with this editor, if provided") cmd.Flags().BoolVarP(&force, "force", "f", false, "overwrite file if it already exists") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") applyLocalFlagsBuildConfig(cmd, r) }, }, &simpleCommand{ name: "site", use: "site [path]", short: "Create a new site (skeleton)", long: `Create a new site in the provided directory. The new site will have the correct structure, but no content or theme yet. Use ` + "`hugo new [contentPath]`" + ` to create new content.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return newUserError("path needs to be provided") } createpath, err := filepath.Abs(filepath.Clean(args[0])) if err != nil { return err } cfg := config.New() cfg.Set("workingDir", createpath) cfg.Set("publishDir", "public") conf, err := r.ConfigFromProvider(r.configVersionID.Load(), flagsToCfg(cd, cfg)) if err != nil { return err } sourceFs := conf.fs.Source archeTypePath := filepath.Join(createpath, "archetypes") dirs := []string{ archeTypePath, filepath.Join(createpath, "assets"), filepath.Join(createpath, "content"), filepath.Join(createpath, "data"), filepath.Join(createpath, "layouts"), filepath.Join(createpath, "static"), filepath.Join(createpath, "themes"), } if exists, _ := helpers.Exists(createpath, sourceFs); exists { if isDir, _ := helpers.IsDir(createpath, sourceFs); !isDir { return errors.New(createpath + " already exists but not a directory") } isEmpty, _ := helpers.IsEmpty(createpath, sourceFs) switch { case !isEmpty && !force: return errors.New(createpath + " already exists and is not empty. See --force.") case !isEmpty && force: all := append(dirs, filepath.Join(createpath, "hugo."+format)) for _, path := range all { if exists, _ := helpers.Exists(path, sourceFs); exists { return errors.New(path + " already exists") } } } } for _, dir := range dirs { if err := sourceFs.MkdirAll(dir, 0777); err != nil { return fmt.Errorf("failed to create dir: %w", err) } } c.newSiteCreateConfig(sourceFs, createpath, format) // Create a default archetype file. helpers.SafeWriteToDisk(filepath.Join(archeTypePath, "default.md"), strings.NewReader(create.DefaultArchetypeTemplateTemplate), sourceFs) r.Printf("Congratulations! Your new Hugo site is created in %s.\n\n", createpath) r.Println(c.newSiteNextStepsText()) return nil }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVarP(&force, "force", "f", false, "init inside non-empty directory") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") }, }, &simpleCommand{ name: "theme", use: "theme [name]", short: "Create a new theme (skeleton)", long: `Create a new theme (skeleton) called [name] in ./themes. New theme is a skeleton. Please add content to the touched files. Add your name to the copyright line in the license and adjust the theme.toml file according to your needs.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return newUserError("theme name needs to be provided") } h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } ps := h.PathSpec sourceFs := ps.Fs.Source themesDir := h.Configs.LoadingInfo.BaseConfig.ThemesDir createpath := ps.AbsPathify(filepath.Join(themesDir, args[0])) r.Println("Creating theme at", createpath) if x, _ := helpers.Exists(createpath, sourceFs); x { return errors.New(createpath + " already exists") } for _, filename := range []string{ "index.html", "404.html", "_default/list.html", "_default/single.html", "partials/head.html", "partials/header.html", "partials/footer.html", } { touchFile(sourceFs, filepath.Join(createpath, "layouts", filename)) } baseofDefault := []byte(`<!DOCTYPE html> <html> {{- partial "head.html" . -}} <body> {{- partial "header.html" . -}} <div id="content"> {{- block "main" . }}{{- end }} </div> {{- partial "footer.html" . -}} </body> </html> `) err = helpers.WriteToDisk(filepath.Join(createpath, "layouts", "_default", "baseof.html"), bytes.NewReader(baseofDefault), sourceFs) if err != nil { return err } mkdir(createpath, "archetypes") archDefault := []byte("+++\n+++\n") err = helpers.WriteToDisk(filepath.Join(createpath, "archetypes", "default.md"), bytes.NewReader(archDefault), sourceFs) if err != nil { return err } mkdir(createpath, "static", "js") mkdir(createpath, "static", "css") by := []byte(`The MIT License (MIT) Copyright (c) ` + htime.Now().Format("2006") + ` YOUR_NAME_HERE 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. `) err = helpers.WriteToDisk(filepath.Join(createpath, "LICENSE"), bytes.NewReader(by), sourceFs) if err != nil { return err } c.createThemeMD(ps.Fs.Source, createpath) return nil }, }, }, } return c } type newCommand struct { rootCmd *rootCommand commands []simplecobra.Commander } func (c *newCommand) Commands() []simplecobra.Commander { return c.commands } func (c *newCommand) Name() string { return "new" } func (c *newCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *newCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Create new content for your site" cmd.Long = `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.` cmd.RunE = nil return nil } func (c *newCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.rootCmd = cd.Root.Command.(*rootCommand) return nil } func (c *newCommand) newSiteCreateConfig(fs afero.Fs, inpath string, kind string) (err error) { in := map[string]string{ "baseURL": "http://example.org/", "title": "My New Hugo Site", "languageCode": "en-us", } var buf bytes.Buffer err = parser.InterfaceToConfig(in, metadecoders.FormatFromString(kind), &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+kind), &buf, fs) } func (c *newCommand) newSiteNextStepsText() string { var nextStepsText bytes.Buffer nextStepsText.WriteString(`Just a few more steps and you're ready to go: 1. Download a theme into the same-named folder. Choose a theme from https://themes.gohugo.io/ or create your own with the "hugo new theme <THEMENAME>" command. 2. Perhaps you want to add some content. You can add single files with "hugo new `) nextStepsText.WriteString(filepath.Join("<SECTIONNAME>", "<FILENAME>.<FORMAT>")) nextStepsText.WriteString(`". 3. Start the built-in live server via "hugo server". Visit https://gohugo.io/ for quickstart guide and full documentation.`) return nextStepsText.String() } func (c *newCommand) createThemeMD(fs afero.Fs, inpath string) (err error) { by := []byte(`# theme.toml template for a Hugo theme # See https://github.com/gohugoio/hugoThemes#themetoml for an example name = "` + strings.Title(helpers.MakeTitle(filepath.Base(inpath))) + `" license = "MIT" licenselink = "https://github.com/yourname/yourtheme/blob/master/LICENSE" description = "" homepage = "http://example.com/" tags = [] features = [] min_version = "0.114.0" [author] name = "" homepage = "" # If porting an existing theme [original] name = "" homepage = "" repo = "" `) err = helpers.WriteToDisk(filepath.Join(inpath, "theme.toml"), bytes.NewReader(by), fs) if err != nil { return } err = helpers.WriteToDisk(filepath.Join(inpath, "hugo.toml"), strings.NewReader("# Theme config.\n"), fs) if err != nil { return } return nil }
deining
12646750aa186cf3bf50266f8eddf9cfebc3c9c9
635cc346cef6c6c7ada4dd1010a631613568d51d
Also, it would be good if you could adjust the commit message to be in line with the contribution guidelines.
bep
44
gohugoio/hugo
11,178
commands: Fix panic when running hugo new theme without theme name
This PR closes #11162.
null
2023-06-27 14:37:30+00:00
2023-06-28 14:20:54+00:00
commands/new.go
// Copyright 2023 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 commands import ( "bytes" "context" "errors" "fmt" "path/filepath" "strings" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/afero" "github.com/spf13/cobra" ) func newNewCommand() *newCommand { var ( force bool contentType string format string ) var c *newCommand c = &newCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "content", use: "content [path]", short: "Create new content for your site", long: `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return errors.New("path needs to be provided") } h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } return create.NewContent(h, contentType, args[0], force) }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().StringVarP(&contentType, "kind", "k", "", "content type to create") cmd.Flags().String("editor", "", "edit new content with this editor, if provided") cmd.Flags().BoolVarP(&force, "force", "f", false, "overwrite file if it already exists") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") applyLocalFlagsBuildConfig(cmd, r) }, }, &simpleCommand{ name: "site", use: "site [path]", short: "Create a new site (skeleton)", long: `Create a new site in the provided directory. The new site will have the correct structure, but no content or theme yet. Use ` + "`hugo new [contentPath]`" + ` to create new content.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return errors.New("path needs to be provided") } createpath, err := filepath.Abs(filepath.Clean(args[0])) if err != nil { return err } cfg := config.New() cfg.Set("workingDir", createpath) cfg.Set("publishDir", "public") conf, err := r.ConfigFromProvider(r.configVersionID.Load(), flagsToCfg(cd, cfg)) if err != nil { return err } sourceFs := conf.fs.Source archeTypePath := filepath.Join(createpath, "archetypes") dirs := []string{ archeTypePath, filepath.Join(createpath, "assets"), filepath.Join(createpath, "content"), filepath.Join(createpath, "data"), filepath.Join(createpath, "layouts"), filepath.Join(createpath, "static"), filepath.Join(createpath, "themes"), } if exists, _ := helpers.Exists(createpath, sourceFs); exists { if isDir, _ := helpers.IsDir(createpath, sourceFs); !isDir { return errors.New(createpath + " already exists but not a directory") } isEmpty, _ := helpers.IsEmpty(createpath, sourceFs) switch { case !isEmpty && !force: return errors.New(createpath + " already exists and is not empty. See --force.") case !isEmpty && force: all := append(dirs, filepath.Join(createpath, "hugo."+format)) for _, path := range all { if exists, _ := helpers.Exists(path, sourceFs); exists { return errors.New(path + " already exists") } } } } for _, dir := range dirs { if err := sourceFs.MkdirAll(dir, 0777); err != nil { return fmt.Errorf("failed to create dir: %w", err) } } c.newSiteCreateConfig(sourceFs, createpath, format) // Create a default archetype file. helpers.SafeWriteToDisk(filepath.Join(archeTypePath, "default.md"), strings.NewReader(create.DefaultArchetypeTemplateTemplate), sourceFs) r.Printf("Congratulations! Your new Hugo site is created in %s.\n\n", createpath) r.Println(c.newSiteNextStepsText()) return nil }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVarP(&force, "force", "f", false, "init inside non-empty directory") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") }, }, &simpleCommand{ name: "theme", use: "theme [name]", short: "Create a new theme (skeleton)", long: `Create a new theme (skeleton) called [name] in ./themes. New theme is a skeleton. Please add content to the touched files. Add your name to the copyright line in the license and adjust the theme.toml file according to your needs.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } ps := h.PathSpec sourceFs := ps.Fs.Source themesDir := h.Configs.LoadingInfo.BaseConfig.ThemesDir createpath := ps.AbsPathify(filepath.Join(themesDir, args[0])) r.Println("Creating theme at", createpath) if x, _ := helpers.Exists(createpath, sourceFs); x { return errors.New(createpath + " already exists") } for _, filename := range []string{ "index.html", "404.html", "_default/list.html", "_default/single.html", "partials/head.html", "partials/header.html", "partials/footer.html", } { touchFile(sourceFs, filepath.Join(createpath, "layouts", filename)) } baseofDefault := []byte(`<!DOCTYPE html> <html> {{- partial "head.html" . -}} <body> {{- partial "header.html" . -}} <div id="content"> {{- block "main" . }}{{- end }} </div> {{- partial "footer.html" . -}} </body> </html> `) err = helpers.WriteToDisk(filepath.Join(createpath, "layouts", "_default", "baseof.html"), bytes.NewReader(baseofDefault), sourceFs) if err != nil { return err } mkdir(createpath, "archetypes") archDefault := []byte("+++\n+++\n") err = helpers.WriteToDisk(filepath.Join(createpath, "archetypes", "default.md"), bytes.NewReader(archDefault), sourceFs) if err != nil { return err } mkdir(createpath, "static", "js") mkdir(createpath, "static", "css") by := []byte(`The MIT License (MIT) Copyright (c) ` + htime.Now().Format("2006") + ` YOUR_NAME_HERE 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. `) err = helpers.WriteToDisk(filepath.Join(createpath, "LICENSE"), bytes.NewReader(by), sourceFs) if err != nil { return err } c.createThemeMD(ps.Fs.Source, createpath) return nil }, }, }, } return c } type newCommand struct { rootCmd *rootCommand commands []simplecobra.Commander } func (c *newCommand) Commands() []simplecobra.Commander { return c.commands } func (c *newCommand) Name() string { return "new" } func (c *newCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *newCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Create new content for your site" cmd.Long = `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.` cmd.RunE = nil return nil } func (c *newCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.rootCmd = cd.Root.Command.(*rootCommand) return nil } func (c *newCommand) newSiteCreateConfig(fs afero.Fs, inpath string, kind string) (err error) { in := map[string]string{ "baseURL": "http://example.org/", "title": "My New Hugo Site", "languageCode": "en-us", } var buf bytes.Buffer err = parser.InterfaceToConfig(in, metadecoders.FormatFromString(kind), &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+kind), &buf, fs) } func (c *newCommand) newSiteNextStepsText() string { var nextStepsText bytes.Buffer nextStepsText.WriteString(`Just a few more steps and you're ready to go: 1. Download a theme into the same-named folder. Choose a theme from https://themes.gohugo.io/ or create your own with the "hugo new theme <THEMENAME>" command. 2. Perhaps you want to add some content. You can add single files with "hugo new `) nextStepsText.WriteString(filepath.Join("<SECTIONNAME>", "<FILENAME>.<FORMAT>")) nextStepsText.WriteString(`". 3. Start the built-in live server via "hugo server". Visit https://gohugo.io/ for quickstart guide and full documentation.`) return nextStepsText.String() } func (c *newCommand) createThemeMD(fs afero.Fs, inpath string) (err error) { by := []byte(`# theme.toml template for a Hugo theme # See https://github.com/gohugoio/hugoThemes#themetoml for an example name = "` + strings.Title(helpers.MakeTitle(filepath.Base(inpath))) + `" license = "MIT" licenselink = "https://github.com/yourname/yourtheme/blob/master/LICENSE" description = "" homepage = "http://example.com/" tags = [] features = [] min_version = "0.114.0" [author] name = "" homepage = "" # If porting an existing theme [original] name = "" homepage = "" repo = "" `) err = helpers.WriteToDisk(filepath.Join(inpath, "theme.toml"), bytes.NewReader(by), fs) if err != nil { return } err = helpers.WriteToDisk(filepath.Join(inpath, "hugo.toml"), strings.NewReader("# Theme config.\n"), fs) if err != nil { return } return nil }
// Copyright 2023 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 commands import ( "bytes" "context" "errors" "fmt" "path/filepath" "strings" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/spf13/afero" "github.com/spf13/cobra" ) func newNewCommand() *newCommand { var ( force bool contentType string format string ) var c *newCommand c = &newCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "content", use: "content [path]", short: "Create new content for your site", long: `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return newUserError("path needs to be provided") } h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } return create.NewContent(h, contentType, args[0], force) }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().StringVarP(&contentType, "kind", "k", "", "content type to create") cmd.Flags().String("editor", "", "edit new content with this editor, if provided") cmd.Flags().BoolVarP(&force, "force", "f", false, "overwrite file if it already exists") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") applyLocalFlagsBuildConfig(cmd, r) }, }, &simpleCommand{ name: "site", use: "site [path]", short: "Create a new site (skeleton)", long: `Create a new site in the provided directory. The new site will have the correct structure, but no content or theme yet. Use ` + "`hugo new [contentPath]`" + ` to create new content.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return newUserError("path needs to be provided") } createpath, err := filepath.Abs(filepath.Clean(args[0])) if err != nil { return err } cfg := config.New() cfg.Set("workingDir", createpath) cfg.Set("publishDir", "public") conf, err := r.ConfigFromProvider(r.configVersionID.Load(), flagsToCfg(cd, cfg)) if err != nil { return err } sourceFs := conf.fs.Source archeTypePath := filepath.Join(createpath, "archetypes") dirs := []string{ archeTypePath, filepath.Join(createpath, "assets"), filepath.Join(createpath, "content"), filepath.Join(createpath, "data"), filepath.Join(createpath, "layouts"), filepath.Join(createpath, "static"), filepath.Join(createpath, "themes"), } if exists, _ := helpers.Exists(createpath, sourceFs); exists { if isDir, _ := helpers.IsDir(createpath, sourceFs); !isDir { return errors.New(createpath + " already exists but not a directory") } isEmpty, _ := helpers.IsEmpty(createpath, sourceFs) switch { case !isEmpty && !force: return errors.New(createpath + " already exists and is not empty. See --force.") case !isEmpty && force: all := append(dirs, filepath.Join(createpath, "hugo."+format)) for _, path := range all { if exists, _ := helpers.Exists(path, sourceFs); exists { return errors.New(path + " already exists") } } } } for _, dir := range dirs { if err := sourceFs.MkdirAll(dir, 0777); err != nil { return fmt.Errorf("failed to create dir: %w", err) } } c.newSiteCreateConfig(sourceFs, createpath, format) // Create a default archetype file. helpers.SafeWriteToDisk(filepath.Join(archeTypePath, "default.md"), strings.NewReader(create.DefaultArchetypeTemplateTemplate), sourceFs) r.Printf("Congratulations! Your new Hugo site is created in %s.\n\n", createpath) r.Println(c.newSiteNextStepsText()) return nil }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVarP(&force, "force", "f", false, "init inside non-empty directory") cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)") }, }, &simpleCommand{ name: "theme", use: "theme [name]", short: "Create a new theme (skeleton)", long: `Create a new theme (skeleton) called [name] in ./themes. New theme is a skeleton. Please add content to the touched files. Add your name to the copyright line in the license and adjust the theme.toml file according to your needs.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 1 { return newUserError("theme name needs to be provided") } h, err := r.Hugo(flagsToCfg(cd, nil)) if err != nil { return err } ps := h.PathSpec sourceFs := ps.Fs.Source themesDir := h.Configs.LoadingInfo.BaseConfig.ThemesDir createpath := ps.AbsPathify(filepath.Join(themesDir, args[0])) r.Println("Creating theme at", createpath) if x, _ := helpers.Exists(createpath, sourceFs); x { return errors.New(createpath + " already exists") } for _, filename := range []string{ "index.html", "404.html", "_default/list.html", "_default/single.html", "partials/head.html", "partials/header.html", "partials/footer.html", } { touchFile(sourceFs, filepath.Join(createpath, "layouts", filename)) } baseofDefault := []byte(`<!DOCTYPE html> <html> {{- partial "head.html" . -}} <body> {{- partial "header.html" . -}} <div id="content"> {{- block "main" . }}{{- end }} </div> {{- partial "footer.html" . -}} </body> </html> `) err = helpers.WriteToDisk(filepath.Join(createpath, "layouts", "_default", "baseof.html"), bytes.NewReader(baseofDefault), sourceFs) if err != nil { return err } mkdir(createpath, "archetypes") archDefault := []byte("+++\n+++\n") err = helpers.WriteToDisk(filepath.Join(createpath, "archetypes", "default.md"), bytes.NewReader(archDefault), sourceFs) if err != nil { return err } mkdir(createpath, "static", "js") mkdir(createpath, "static", "css") by := []byte(`The MIT License (MIT) Copyright (c) ` + htime.Now().Format("2006") + ` YOUR_NAME_HERE 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. `) err = helpers.WriteToDisk(filepath.Join(createpath, "LICENSE"), bytes.NewReader(by), sourceFs) if err != nil { return err } c.createThemeMD(ps.Fs.Source, createpath) return nil }, }, }, } return c } type newCommand struct { rootCmd *rootCommand commands []simplecobra.Commander } func (c *newCommand) Commands() []simplecobra.Commander { return c.commands } func (c *newCommand) Name() string { return "new" } func (c *newCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *newCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Create new content for your site" cmd.Long = `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.` cmd.RunE = nil return nil } func (c *newCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.rootCmd = cd.Root.Command.(*rootCommand) return nil } func (c *newCommand) newSiteCreateConfig(fs afero.Fs, inpath string, kind string) (err error) { in := map[string]string{ "baseURL": "http://example.org/", "title": "My New Hugo Site", "languageCode": "en-us", } var buf bytes.Buffer err = parser.InterfaceToConfig(in, metadecoders.FormatFromString(kind), &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+kind), &buf, fs) } func (c *newCommand) newSiteNextStepsText() string { var nextStepsText bytes.Buffer nextStepsText.WriteString(`Just a few more steps and you're ready to go: 1. Download a theme into the same-named folder. Choose a theme from https://themes.gohugo.io/ or create your own with the "hugo new theme <THEMENAME>" command. 2. Perhaps you want to add some content. You can add single files with "hugo new `) nextStepsText.WriteString(filepath.Join("<SECTIONNAME>", "<FILENAME>.<FORMAT>")) nextStepsText.WriteString(`". 3. Start the built-in live server via "hugo server". Visit https://gohugo.io/ for quickstart guide and full documentation.`) return nextStepsText.String() } func (c *newCommand) createThemeMD(fs afero.Fs, inpath string) (err error) { by := []byte(`# theme.toml template for a Hugo theme # See https://github.com/gohugoio/hugoThemes#themetoml for an example name = "` + strings.Title(helpers.MakeTitle(filepath.Base(inpath))) + `" license = "MIT" licenselink = "https://github.com/yourname/yourtheme/blob/master/LICENSE" description = "" homepage = "http://example.com/" tags = [] features = [] min_version = "0.114.0" [author] name = "" homepage = "" # If porting an existing theme [original] name = "" homepage = "" repo = "" `) err = helpers.WriteToDisk(filepath.Join(inpath, "theme.toml"), bytes.NewReader(by), fs) if err != nil { return } err = helpers.WriteToDisk(filepath.Join(inpath, "hugo.toml"), strings.NewReader("# Theme config.\n"), fs) if err != nil { return } return nil }
deining
12646750aa186cf3bf50266f8eddf9cfebc3c9c9
635cc346cef6c6c7ada4dd1010a631613568d51d
> There's some logic above to distinguish between "command errors" (which we show the help output + an error message) and "runtime errors". > > I think the above is in the first category, so if you could replace the above with > > ```go > return newUserError("theme name needs to be provided") > ``` Changed as requested. For the sake to consistency, I changed this at two other locations, too.
deining
45
gohugoio/hugo
11,170
Print help message when command is triggered with no flags
This PR aims to fix [this](https://github.com/gohugoio/hugo/issues/11165) issue. Starting from release [v0.112.0](https://github.com/gohugoio/hugo/releases/tag/v0.112.0) and via this [commit](https://github.com/gohugoio/hugo/commit/241b21b0fd34d91fccb2ce69874110dceae6f926), `import`, `new`, `convert`, `list` and `gen` commands produce no output when triggered with no flags. This PR reverts to the old behaviour by printing the help message by default.
null
2023-06-26 18:28:49+00:00
2023-06-28 12:58:36+00:00
commands/convert.go
// Copyright 2023 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 commands import ( "bytes" "context" "fmt" "path/filepath" "strings" "time" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources/page" "github.com/spf13/cobra" ) func newConvertCommand() *convertCommand { var c *convertCommand c = &convertCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "toJSON", short: "Convert front matter to JSON", long: `toJSON converts all front matter in the content directory to use JSON for the front matter.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { return c.convertContents(metadecoders.JSON) }, withc: func(cmd *cobra.Command, r *rootCommand) { }, }, &simpleCommand{ name: "toTOML", short: "Convert front matter to TOML", long: `toTOML converts all front matter in the content directory to use TOML for the front matter.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { return c.convertContents(metadecoders.TOML) }, withc: func(cmd *cobra.Command, r *rootCommand) { }, }, &simpleCommand{ name: "toYAML", short: "Convert front matter to YAML", long: `toYAML converts all front matter in the content directory to use YAML for the front matter.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { return c.convertContents(metadecoders.YAML) }, withc: func(cmd *cobra.Command, r *rootCommand) { }, }, }, } return c } type convertCommand struct { // Flags. outputDir string unsafe bool // Deps. r *rootCommand h *hugolib.HugoSites // Commands. commands []simplecobra.Commander } func (c *convertCommand) Commands() []simplecobra.Commander { return c.commands } func (c *convertCommand) Name() string { return "convert" } func (c *convertCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *convertCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Convert your content to different formats" cmd.Long = `Convert your content (e.g. front matter) to different formats. See convert's subcommands toJSON, toTOML and toYAML for more information.` cmd.PersistentFlags().StringVarP(&c.outputDir, "output", "o", "", "filesystem path to write files to") cmd.PersistentFlags().BoolVar(&c.unsafe, "unsafe", false, "enable less safe operations, please backup first") return nil } func (c *convertCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.r = cd.Root.Command.(*rootCommand) cfg := config.New() cfg.Set("buildDrafts", true) h, err := c.r.Hugo(flagsToCfg(cd, cfg)) if err != nil { return err } c.h = h return nil } func (c *convertCommand) convertAndSavePage(p page.Page, site *hugolib.Site, targetFormat metadecoders.Format) error { // The resources are not in .Site.AllPages. for _, r := range p.Resources().ByType("page") { if err := c.convertAndSavePage(r.(page.Page), site, targetFormat); err != nil { return err } } if p.File().IsZero() { // No content file. return nil } errMsg := fmt.Errorf("error processing file %q", p.File().Path()) site.Log.Infoln("attempting to convert", p.File().Filename()) f := p.File() file, err := f.FileInfo().Meta().Open() if err != nil { site.Log.Errorln(errMsg) file.Close() return nil } pf, err := pageparser.ParseFrontMatterAndContent(file) if err != nil { site.Log.Errorln(errMsg) file.Close() return err } file.Close() // better handling of dates in formats that don't have support for them if pf.FrontMatterFormat == metadecoders.JSON || pf.FrontMatterFormat == metadecoders.YAML || pf.FrontMatterFormat == metadecoders.TOML { for k, v := range pf.FrontMatter { switch vv := v.(type) { case time.Time: pf.FrontMatter[k] = vv.Format(time.RFC3339) } } } var newContent bytes.Buffer err = parser.InterfaceToFrontMatter(pf.FrontMatter, targetFormat, &newContent) if err != nil { site.Log.Errorln(errMsg) return err } newContent.Write(pf.Content) newFilename := p.File().Filename() if c.outputDir != "" { contentDir := strings.TrimSuffix(newFilename, p.File().Path()) contentDir = filepath.Base(contentDir) newFilename = filepath.Join(c.outputDir, contentDir, p.File().Path()) } fs := hugofs.Os if err := helpers.WriteToDisk(newFilename, &newContent, fs); err != nil { return fmt.Errorf("failed to save file %q:: %w", newFilename, err) } return nil } func (c *convertCommand) convertContents(format metadecoders.Format) error { if c.outputDir == "" && !c.unsafe { return newUserError("Unsafe operation not allowed, use --unsafe or set a different output path") } if err := c.h.Build(hugolib.BuildCfg{SkipRender: true}); err != nil { return err } site := c.h.Sites[0] var pagesBackedByFile page.Pages for _, p := range site.AllPages() { if p.File().IsZero() { continue } pagesBackedByFile = append(pagesBackedByFile, p) } site.Log.Println("processing", len(pagesBackedByFile), "content files") for _, p := range site.AllPages() { if err := c.convertAndSavePage(p, site, format); err != nil { return err } } return nil }
// Copyright 2023 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 commands import ( "bytes" "context" "fmt" "path/filepath" "strings" "time" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources/page" "github.com/spf13/cobra" ) func newConvertCommand() *convertCommand { var c *convertCommand c = &convertCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "toJSON", short: "Convert front matter to JSON", long: `toJSON converts all front matter in the content directory to use JSON for the front matter.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { return c.convertContents(metadecoders.JSON) }, withc: func(cmd *cobra.Command, r *rootCommand) { }, }, &simpleCommand{ name: "toTOML", short: "Convert front matter to TOML", long: `toTOML converts all front matter in the content directory to use TOML for the front matter.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { return c.convertContents(metadecoders.TOML) }, withc: func(cmd *cobra.Command, r *rootCommand) { }, }, &simpleCommand{ name: "toYAML", short: "Convert front matter to YAML", long: `toYAML converts all front matter in the content directory to use YAML for the front matter.`, run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { return c.convertContents(metadecoders.YAML) }, withc: func(cmd *cobra.Command, r *rootCommand) { }, }, }, } return c } type convertCommand struct { // Flags. outputDir string unsafe bool // Deps. r *rootCommand h *hugolib.HugoSites // Commands. commands []simplecobra.Commander } func (c *convertCommand) Commands() []simplecobra.Commander { return c.commands } func (c *convertCommand) Name() string { return "convert" } func (c *convertCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *convertCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Convert your content to different formats" cmd.Long = `Convert your content (e.g. front matter) to different formats. See convert's subcommands toJSON, toTOML and toYAML for more information.` cmd.PersistentFlags().StringVarP(&c.outputDir, "output", "o", "", "filesystem path to write files to") cmd.PersistentFlags().BoolVar(&c.unsafe, "unsafe", false, "enable less safe operations, please backup first") cmd.RunE = nil return nil } func (c *convertCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.r = cd.Root.Command.(*rootCommand) cfg := config.New() cfg.Set("buildDrafts", true) h, err := c.r.Hugo(flagsToCfg(cd, cfg)) if err != nil { return err } c.h = h return nil } func (c *convertCommand) convertAndSavePage(p page.Page, site *hugolib.Site, targetFormat metadecoders.Format) error { // The resources are not in .Site.AllPages. for _, r := range p.Resources().ByType("page") { if err := c.convertAndSavePage(r.(page.Page), site, targetFormat); err != nil { return err } } if p.File().IsZero() { // No content file. return nil } errMsg := fmt.Errorf("error processing file %q", p.File().Path()) site.Log.Infoln("attempting to convert", p.File().Filename()) f := p.File() file, err := f.FileInfo().Meta().Open() if err != nil { site.Log.Errorln(errMsg) file.Close() return nil } pf, err := pageparser.ParseFrontMatterAndContent(file) if err != nil { site.Log.Errorln(errMsg) file.Close() return err } file.Close() // better handling of dates in formats that don't have support for them if pf.FrontMatterFormat == metadecoders.JSON || pf.FrontMatterFormat == metadecoders.YAML || pf.FrontMatterFormat == metadecoders.TOML { for k, v := range pf.FrontMatter { switch vv := v.(type) { case time.Time: pf.FrontMatter[k] = vv.Format(time.RFC3339) } } } var newContent bytes.Buffer err = parser.InterfaceToFrontMatter(pf.FrontMatter, targetFormat, &newContent) if err != nil { site.Log.Errorln(errMsg) return err } newContent.Write(pf.Content) newFilename := p.File().Filename() if c.outputDir != "" { contentDir := strings.TrimSuffix(newFilename, p.File().Path()) contentDir = filepath.Base(contentDir) newFilename = filepath.Join(c.outputDir, contentDir, p.File().Path()) } fs := hugofs.Os if err := helpers.WriteToDisk(newFilename, &newContent, fs); err != nil { return fmt.Errorf("failed to save file %q:: %w", newFilename, err) } return nil } func (c *convertCommand) convertContents(format metadecoders.Format) error { if c.outputDir == "" && !c.unsafe { return newUserError("Unsafe operation not allowed, use --unsafe or set a different output path") } if err := c.h.Build(hugolib.BuildCfg{SkipRender: true}); err != nil { return err } site := c.h.Sites[0] var pagesBackedByFile page.Pages for _, p := range site.AllPages() { if p.File().IsZero() { continue } pagesBackedByFile = append(pagesBackedByFile, p) } site.Log.Println("processing", len(pagesBackedByFile), "content files") for _, p := range site.AllPages() { if err := c.convertAndSavePage(p, site, format); err != nil { return err } } return nil }
roshanavand
79639c981cf69193fb21d97773d928c089714750
12646750aa186cf3bf50266f8eddf9cfebc3c9c9
Can you explain the code above? I don't see the relevance to the issue title ...
bep
46
gohugoio/hugo
11,143
commands: Update Jekyll post-import output
Update CLI output after a successful Jekyll import to suggest a maintained theme and include clearer steps to running a server locally. Fixes #10715. I followed the suggestion made by @jmooring to clarify the next steps.
null
2023-06-21 14:10:54+00:00
2023-06-21 18:38:55+00:00
commands/import.go
// Copyright 2023 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 commands import ( "bytes" "context" "errors" "fmt" "io" "log" "os" "path/filepath" "regexp" "strconv" "strings" "time" "unicode" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/spf13/afero" "github.com/spf13/cobra" ) func newImportCommand() *importCommand { var c *importCommand c = &importCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "jekyll", short: "hugo import from Jekyll", long: `hugo import from Jekyll. Import from Jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.", run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 2 { return newUserError(`import from jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.") } return c.importFromJekyll(args) }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVar(&c.force, "force", false, "allow import into non-empty target directory") }, }, }, } return c } type importCommand struct { r *rootCommand force bool commands []simplecobra.Commander } func (c *importCommand) Commands() []simplecobra.Commander { return c.commands } func (c *importCommand) Name() string { return "import" } func (c *importCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *importCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Import your site from others." cmd.Long = `Import your site from other web site generators like Jekyll. Import requires a subcommand, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`." return nil } func (c *importCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.r = cd.Root.Command.(*rootCommand) return nil } func (i *importCommand) createConfigFromJekyll(fs afero.Fs, inpath string, kind metadecoders.Format, jekyllConfig map[string]any) (err error) { title := "My New Hugo Site" baseURL := "http://example.org/" for key, value := range jekyllConfig { lowerKey := strings.ToLower(key) switch lowerKey { case "title": if str, ok := value.(string); ok { title = str } case "url": if str, ok := value.(string); ok { baseURL = str } } } in := map[string]any{ "baseURL": baseURL, "title": title, "languageCode": "en-us", "disablePathToLower": true, } var buf bytes.Buffer err = parser.InterfaceToConfig(in, kind, &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+string(kind)), &buf, fs) } func (c *importCommand) getJekyllDirInfo(fs afero.Fs, jekyllRoot string) (map[string]bool, bool) { postDirs := make(map[string]bool) hasAnyPost := false if entries, err := os.ReadDir(jekyllRoot); err == nil { for _, entry := range entries { if entry.IsDir() { subDir := filepath.Join(jekyllRoot, entry.Name()) if isPostDir, hasAnyPostInDir := c.retrieveJekyllPostDir(fs, subDir); isPostDir { postDirs[entry.Name()] = hasAnyPostInDir if hasAnyPostInDir { hasAnyPost = true } } } } } return postDirs, hasAnyPost } func (c *importCommand) createSiteFromJekyll(jekyllRoot, targetDir string, jekyllPostDirs map[string]bool) error { fs := &afero.OsFs{} if exists, _ := helpers.Exists(targetDir, fs); exists { if isDir, _ := helpers.IsDir(targetDir, fs); !isDir { return errors.New("target path \"" + targetDir + "\" exists but is not a directory") } isEmpty, _ := helpers.IsEmpty(targetDir, fs) if !isEmpty && !c.force { return errors.New("target path \"" + targetDir + "\" exists and is not empty") } } jekyllConfig := c.loadJekyllConfig(fs, jekyllRoot) mkdir(targetDir, "layouts") mkdir(targetDir, "content") mkdir(targetDir, "archetypes") mkdir(targetDir, "static") mkdir(targetDir, "data") mkdir(targetDir, "themes") c.createConfigFromJekyll(fs, targetDir, "yaml", jekyllConfig) c.copyJekyllFilesAndFolders(jekyllRoot, filepath.Join(targetDir, "static"), jekyllPostDirs) return nil } func (c *importCommand) convertJekyllContent(m any, content string) (string, error) { metadata, _ := maps.ToStringMapE(m) lines := strings.Split(content, "\n") var resultLines []string for _, line := range lines { resultLines = append(resultLines, strings.Trim(line, "\r\n")) } content = strings.Join(resultLines, "\n") excerptSep := "<!--more-->" if value, ok := metadata["excerpt_separator"]; ok { if str, strOk := value.(string); strOk { content = strings.Replace(content, strings.TrimSpace(str), excerptSep, -1) } } replaceList := []struct { re *regexp.Regexp replace string }{ {regexp.MustCompile("(?i)<!-- more -->"), "<!--more-->"}, {regexp.MustCompile(`\{%\s*raw\s*%\}\s*(.*?)\s*\{%\s*endraw\s*%\}`), "$1"}, {regexp.MustCompile(`{%\s*endhighlight\s*%}`), "{{< / highlight >}}"}, } for _, replace := range replaceList { content = replace.re.ReplaceAllString(content, replace.replace) } replaceListFunc := []struct { re *regexp.Regexp replace func(string) string }{ // Octopress image tag: http://octopress.org/docs/plugins/image-tag/ {regexp.MustCompile(`{%\s+img\s*(.*?)\s*%}`), c.replaceImageTag}, {regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`), c.replaceHighlightTag}, } for _, replace := range replaceListFunc { content = replace.re.ReplaceAllStringFunc(content, replace.replace) } var buf bytes.Buffer if len(metadata) != 0 { err := parser.InterfaceToFrontMatter(m, metadecoders.YAML, &buf) if err != nil { return "", err } } buf.WriteString(content) return buf.String(), nil } func (c *importCommand) convertJekyllMetaData(m any, postName string, postDate time.Time, draft bool) (any, error) { metadata, err := maps.ToStringMapE(m) if err != nil { return nil, err } if draft { metadata["draft"] = true } for key, value := range metadata { lowerKey := strings.ToLower(key) switch lowerKey { case "layout": delete(metadata, key) case "permalink": if str, ok := value.(string); ok { metadata["url"] = str } delete(metadata, key) case "category": if str, ok := value.(string); ok { metadata["categories"] = []string{str} } delete(metadata, key) case "excerpt_separator": if key != lowerKey { delete(metadata, key) metadata[lowerKey] = value } case "date": if str, ok := value.(string); ok { re := regexp.MustCompile(`(\d+):(\d+):(\d+)`) r := re.FindAllStringSubmatch(str, -1) if len(r) > 0 { hour, _ := strconv.Atoi(r[0][1]) minute, _ := strconv.Atoi(r[0][2]) second, _ := strconv.Atoi(r[0][3]) postDate = time.Date(postDate.Year(), postDate.Month(), postDate.Day(), hour, minute, second, 0, time.UTC) } } delete(metadata, key) } } metadata["date"] = postDate.Format(time.RFC3339) return metadata, nil } func (c *importCommand) convertJekyllPost(path, relPath, targetDir string, draft bool) error { log.Println("Converting", path) filename := filepath.Base(path) postDate, postName, err := c.parseJekyllFilename(filename) if err != nil { c.r.Printf("Failed to parse filename '%s': %s. Skipping.", filename, err) return nil } log.Println(filename, postDate, postName) targetFile := filepath.Join(targetDir, relPath) targetParentDir := filepath.Dir(targetFile) os.MkdirAll(targetParentDir, 0777) contentBytes, err := os.ReadFile(path) if err != nil { c.r.logger.Errorln("Read file error:", path) return err } pf, err := pageparser.ParseFrontMatterAndContent(bytes.NewReader(contentBytes)) if err != nil { return fmt.Errorf("failed to parse file %q: %s", filename, err) } newmetadata, err := c.convertJekyllMetaData(pf.FrontMatter, postName, postDate, draft) if err != nil { return fmt.Errorf("failed to convert metadata for file %q: %s", filename, err) } content, err := c.convertJekyllContent(newmetadata, string(pf.Content)) if err != nil { return fmt.Errorf("failed to convert content for file %q: %s", filename, err) } fs := hugofs.Os if err := helpers.WriteToDisk(targetFile, strings.NewReader(content), fs); err != nil { return fmt.Errorf("failed to save file %q: %s", filename, err) } return nil } func (c *importCommand) copyJekyllFilesAndFolders(jekyllRoot, dest string, jekyllPostDirs map[string]bool) (err error) { fs := hugofs.Os fi, err := fs.Stat(jekyllRoot) if err != nil { return err } if !fi.IsDir() { return errors.New(jekyllRoot + " is not a directory") } err = os.MkdirAll(dest, fi.Mode()) if err != nil { return err } entries, err := os.ReadDir(jekyllRoot) if err != nil { return err } for _, entry := range entries { sfp := filepath.Join(jekyllRoot, entry.Name()) dfp := filepath.Join(dest, entry.Name()) if entry.IsDir() { if entry.Name()[0] != '_' && entry.Name()[0] != '.' { if _, ok := jekyllPostDirs[entry.Name()]; !ok { err = hugio.CopyDir(fs, sfp, dfp, nil) if err != nil { c.r.logger.Errorln(err) } } } } else { lowerEntryName := strings.ToLower(entry.Name()) exceptSuffix := []string{ ".md", ".markdown", ".html", ".htm", ".xml", ".textile", "rakefile", "gemfile", ".lock", } isExcept := false for _, suffix := range exceptSuffix { if strings.HasSuffix(lowerEntryName, suffix) { isExcept = true break } } if !isExcept && entry.Name()[0] != '.' && entry.Name()[0] != '_' { err = hugio.CopyFile(fs, sfp, dfp) if err != nil { c.r.logger.Errorln(err) } } } } return nil } func (c *importCommand) importFromJekyll(args []string) error { jekyllRoot, err := filepath.Abs(filepath.Clean(args[0])) if err != nil { return newUserError("path error:", args[0]) } targetDir, err := filepath.Abs(filepath.Clean(args[1])) if err != nil { return newUserError("path error:", args[1]) } c.r.Println("Import Jekyll from:", jekyllRoot, "to:", targetDir) if strings.HasPrefix(filepath.Dir(targetDir), jekyllRoot) { return newUserError("abort: target path should not be inside the Jekyll root") } fs := afero.NewOsFs() jekyllPostDirs, hasAnyPost := c.getJekyllDirInfo(fs, jekyllRoot) if !hasAnyPost { return errors.New("abort: jekyll root contains neither posts nor drafts") } err = c.createSiteFromJekyll(jekyllRoot, targetDir, jekyllPostDirs) if err != nil { return newUserError(err) } c.r.Println("Importing...") fileCount := 0 callback := func(path string, fi hugofs.FileMetaInfo, err error) error { if err != nil { return err } if fi.IsDir() { return nil } relPath, err := filepath.Rel(jekyllRoot, path) if err != nil { return newUserError("get rel path error:", path) } relPath = filepath.ToSlash(relPath) draft := false switch { case strings.Contains(relPath, "_posts/"): relPath = filepath.Join("content/post", strings.Replace(relPath, "_posts/", "", -1)) case strings.Contains(relPath, "_drafts/"): relPath = filepath.Join("content/draft", strings.Replace(relPath, "_drafts/", "", -1)) draft = true default: return nil } fileCount++ return c.convertJekyllPost(path, relPath, targetDir, draft) } for jekyllPostDir, hasAnyPostInDir := range jekyllPostDirs { if hasAnyPostInDir { if err = helpers.SymbolicWalk(hugofs.Os, filepath.Join(jekyllRoot, jekyllPostDir), callback); err != nil { return err } } } c.r.Println("Congratulations!", fileCount, "post(s) imported!") c.r.Println("Now, start Hugo by yourself:\n" + "$ git clone https://github.com/spf13/herring-cove.git " + args[1] + "/themes/herring-cove") c.r.Println("$ cd " + args[1] + "\n$ hugo server --theme=herring-cove") return nil } func (c *importCommand) loadJekyllConfig(fs afero.Fs, jekyllRoot string) map[string]any { path := filepath.Join(jekyllRoot, "_config.yml") exists, err := helpers.Exists(path, fs) if err != nil || !exists { c.r.Println("_config.yaml not found: Is the specified Jekyll root correct?") return nil } f, err := fs.Open(path) if err != nil { return nil } defer f.Close() b, err := io.ReadAll(f) if err != nil { return nil } m, err := metadecoders.Default.UnmarshalToMap(b, metadecoders.YAML) if err != nil { return nil } return m } func (c *importCommand) parseJekyllFilename(filename string) (time.Time, string, error) { re := regexp.MustCompile(`(\d+-\d+-\d+)-(.+)\..*`) r := re.FindAllStringSubmatch(filename, -1) if len(r) == 0 { return htime.Now(), "", errors.New("filename not match") } postDate, err := time.Parse("2006-1-2", r[0][1]) if err != nil { return htime.Now(), "", err } postName := r[0][2] return postDate, postName, nil } func (c *importCommand) replaceHighlightTag(match string) string { r := regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`) parts := r.FindStringSubmatch(match) lastQuote := rune(0) f := func(c rune) bool { switch { case c == lastQuote: lastQuote = rune(0) return false case lastQuote != rune(0): return false case unicode.In(c, unicode.Quotation_Mark): lastQuote = c return false default: return unicode.IsSpace(c) } } // splitting string by space but considering quoted section items := strings.FieldsFunc(parts[1], f) result := bytes.NewBufferString("{{< highlight ") result.WriteString(items[0]) // language options := items[1:] for i, opt := range options { opt = strings.Replace(opt, "\"", "", -1) if opt == "linenos" { opt = "linenos=table" } if i == 0 { opt = " \"" + opt } if i < len(options)-1 { opt += "," } else if i == len(options)-1 { opt += "\"" } result.WriteString(opt) } result.WriteString(" >}}") return result.String() } func (c *importCommand) replaceImageTag(match string) string { r := regexp.MustCompile(`{%\s+img\s*(\p{L}*)\s+([\S]*/[\S]+)\s+(\d*)\s*(\d*)\s*(.*?)\s*%}`) result := bytes.NewBufferString("{{< figure ") parts := r.FindStringSubmatch(match) // Index 0 is the entire string, ignore c.replaceOptionalPart(result, "class", parts[1]) c.replaceOptionalPart(result, "src", parts[2]) c.replaceOptionalPart(result, "width", parts[3]) c.replaceOptionalPart(result, "height", parts[4]) // title + alt part := parts[5] if len(part) > 0 { splits := strings.Split(part, "'") lenSplits := len(splits) if lenSplits == 1 { c.replaceOptionalPart(result, "title", splits[0]) } else if lenSplits == 3 { c.replaceOptionalPart(result, "title", splits[1]) } else if lenSplits == 5 { c.replaceOptionalPart(result, "title", splits[1]) c.replaceOptionalPart(result, "alt", splits[3]) } } result.WriteString(">}}") return result.String() } func (c *importCommand) replaceOptionalPart(buffer *bytes.Buffer, partName string, part string) { if len(part) > 0 { buffer.WriteString(partName + "=\"" + part + "\" ") } } func (c *importCommand) retrieveJekyllPostDir(fs afero.Fs, dir string) (bool, bool) { if strings.HasSuffix(dir, "_posts") || strings.HasSuffix(dir, "_drafts") { isEmpty, _ := helpers.IsEmpty(dir, fs) return true, !isEmpty } if entries, err := os.ReadDir(dir); err == nil { for _, entry := range entries { if entry.IsDir() { subDir := filepath.Join(dir, entry.Name()) if isPostDir, hasAnyPost := c.retrieveJekyllPostDir(fs, subDir); isPostDir { return isPostDir, hasAnyPost } } } } return false, true }
// Copyright 2023 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 commands import ( "bytes" "context" "errors" "fmt" "io" "log" "os" "path/filepath" "regexp" "strconv" "strings" "time" "unicode" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/spf13/afero" "github.com/spf13/cobra" ) func newImportCommand() *importCommand { var c *importCommand c = &importCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "jekyll", short: "hugo import from Jekyll", long: `hugo import from Jekyll. Import from Jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.", run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 2 { return newUserError(`import from jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.") } return c.importFromJekyll(args) }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVar(&c.force, "force", false, "allow import into non-empty target directory") }, }, }, } return c } type importCommand struct { r *rootCommand force bool commands []simplecobra.Commander } func (c *importCommand) Commands() []simplecobra.Commander { return c.commands } func (c *importCommand) Name() string { return "import" } func (c *importCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *importCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Import your site from others." cmd.Long = `Import your site from other web site generators like Jekyll. Import requires a subcommand, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`." return nil } func (c *importCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.r = cd.Root.Command.(*rootCommand) return nil } func (i *importCommand) createConfigFromJekyll(fs afero.Fs, inpath string, kind metadecoders.Format, jekyllConfig map[string]any) (err error) { title := "My New Hugo Site" baseURL := "http://example.org/" for key, value := range jekyllConfig { lowerKey := strings.ToLower(key) switch lowerKey { case "title": if str, ok := value.(string); ok { title = str } case "url": if str, ok := value.(string); ok { baseURL = str } } } in := map[string]any{ "baseURL": baseURL, "title": title, "languageCode": "en-us", "disablePathToLower": true, } var buf bytes.Buffer err = parser.InterfaceToConfig(in, kind, &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+string(kind)), &buf, fs) } func (c *importCommand) getJekyllDirInfo(fs afero.Fs, jekyllRoot string) (map[string]bool, bool) { postDirs := make(map[string]bool) hasAnyPost := false if entries, err := os.ReadDir(jekyllRoot); err == nil { for _, entry := range entries { if entry.IsDir() { subDir := filepath.Join(jekyllRoot, entry.Name()) if isPostDir, hasAnyPostInDir := c.retrieveJekyllPostDir(fs, subDir); isPostDir { postDirs[entry.Name()] = hasAnyPostInDir if hasAnyPostInDir { hasAnyPost = true } } } } } return postDirs, hasAnyPost } func (c *importCommand) createSiteFromJekyll(jekyllRoot, targetDir string, jekyllPostDirs map[string]bool) error { fs := &afero.OsFs{} if exists, _ := helpers.Exists(targetDir, fs); exists { if isDir, _ := helpers.IsDir(targetDir, fs); !isDir { return errors.New("target path \"" + targetDir + "\" exists but is not a directory") } isEmpty, _ := helpers.IsEmpty(targetDir, fs) if !isEmpty && !c.force { return errors.New("target path \"" + targetDir + "\" exists and is not empty") } } jekyllConfig := c.loadJekyllConfig(fs, jekyllRoot) mkdir(targetDir, "layouts") mkdir(targetDir, "content") mkdir(targetDir, "archetypes") mkdir(targetDir, "static") mkdir(targetDir, "data") mkdir(targetDir, "themes") c.createConfigFromJekyll(fs, targetDir, "yaml", jekyllConfig) c.copyJekyllFilesAndFolders(jekyllRoot, filepath.Join(targetDir, "static"), jekyllPostDirs) return nil } func (c *importCommand) convertJekyllContent(m any, content string) (string, error) { metadata, _ := maps.ToStringMapE(m) lines := strings.Split(content, "\n") var resultLines []string for _, line := range lines { resultLines = append(resultLines, strings.Trim(line, "\r\n")) } content = strings.Join(resultLines, "\n") excerptSep := "<!--more-->" if value, ok := metadata["excerpt_separator"]; ok { if str, strOk := value.(string); strOk { content = strings.Replace(content, strings.TrimSpace(str), excerptSep, -1) } } replaceList := []struct { re *regexp.Regexp replace string }{ {regexp.MustCompile("(?i)<!-- more -->"), "<!--more-->"}, {regexp.MustCompile(`\{%\s*raw\s*%\}\s*(.*?)\s*\{%\s*endraw\s*%\}`), "$1"}, {regexp.MustCompile(`{%\s*endhighlight\s*%}`), "{{< / highlight >}}"}, } for _, replace := range replaceList { content = replace.re.ReplaceAllString(content, replace.replace) } replaceListFunc := []struct { re *regexp.Regexp replace func(string) string }{ // Octopress image tag: http://octopress.org/docs/plugins/image-tag/ {regexp.MustCompile(`{%\s+img\s*(.*?)\s*%}`), c.replaceImageTag}, {regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`), c.replaceHighlightTag}, } for _, replace := range replaceListFunc { content = replace.re.ReplaceAllStringFunc(content, replace.replace) } var buf bytes.Buffer if len(metadata) != 0 { err := parser.InterfaceToFrontMatter(m, metadecoders.YAML, &buf) if err != nil { return "", err } } buf.WriteString(content) return buf.String(), nil } func (c *importCommand) convertJekyllMetaData(m any, postName string, postDate time.Time, draft bool) (any, error) { metadata, err := maps.ToStringMapE(m) if err != nil { return nil, err } if draft { metadata["draft"] = true } for key, value := range metadata { lowerKey := strings.ToLower(key) switch lowerKey { case "layout": delete(metadata, key) case "permalink": if str, ok := value.(string); ok { metadata["url"] = str } delete(metadata, key) case "category": if str, ok := value.(string); ok { metadata["categories"] = []string{str} } delete(metadata, key) case "excerpt_separator": if key != lowerKey { delete(metadata, key) metadata[lowerKey] = value } case "date": if str, ok := value.(string); ok { re := regexp.MustCompile(`(\d+):(\d+):(\d+)`) r := re.FindAllStringSubmatch(str, -1) if len(r) > 0 { hour, _ := strconv.Atoi(r[0][1]) minute, _ := strconv.Atoi(r[0][2]) second, _ := strconv.Atoi(r[0][3]) postDate = time.Date(postDate.Year(), postDate.Month(), postDate.Day(), hour, minute, second, 0, time.UTC) } } delete(metadata, key) } } metadata["date"] = postDate.Format(time.RFC3339) return metadata, nil } func (c *importCommand) convertJekyllPost(path, relPath, targetDir string, draft bool) error { log.Println("Converting", path) filename := filepath.Base(path) postDate, postName, err := c.parseJekyllFilename(filename) if err != nil { c.r.Printf("Failed to parse filename '%s': %s. Skipping.", filename, err) return nil } log.Println(filename, postDate, postName) targetFile := filepath.Join(targetDir, relPath) targetParentDir := filepath.Dir(targetFile) os.MkdirAll(targetParentDir, 0777) contentBytes, err := os.ReadFile(path) if err != nil { c.r.logger.Errorln("Read file error:", path) return err } pf, err := pageparser.ParseFrontMatterAndContent(bytes.NewReader(contentBytes)) if err != nil { return fmt.Errorf("failed to parse file %q: %s", filename, err) } newmetadata, err := c.convertJekyllMetaData(pf.FrontMatter, postName, postDate, draft) if err != nil { return fmt.Errorf("failed to convert metadata for file %q: %s", filename, err) } content, err := c.convertJekyllContent(newmetadata, string(pf.Content)) if err != nil { return fmt.Errorf("failed to convert content for file %q: %s", filename, err) } fs := hugofs.Os if err := helpers.WriteToDisk(targetFile, strings.NewReader(content), fs); err != nil { return fmt.Errorf("failed to save file %q: %s", filename, err) } return nil } func (c *importCommand) copyJekyllFilesAndFolders(jekyllRoot, dest string, jekyllPostDirs map[string]bool) (err error) { fs := hugofs.Os fi, err := fs.Stat(jekyllRoot) if err != nil { return err } if !fi.IsDir() { return errors.New(jekyllRoot + " is not a directory") } err = os.MkdirAll(dest, fi.Mode()) if err != nil { return err } entries, err := os.ReadDir(jekyllRoot) if err != nil { return err } for _, entry := range entries { sfp := filepath.Join(jekyllRoot, entry.Name()) dfp := filepath.Join(dest, entry.Name()) if entry.IsDir() { if entry.Name()[0] != '_' && entry.Name()[0] != '.' { if _, ok := jekyllPostDirs[entry.Name()]; !ok { err = hugio.CopyDir(fs, sfp, dfp, nil) if err != nil { c.r.logger.Errorln(err) } } } } else { lowerEntryName := strings.ToLower(entry.Name()) exceptSuffix := []string{ ".md", ".markdown", ".html", ".htm", ".xml", ".textile", "rakefile", "gemfile", ".lock", } isExcept := false for _, suffix := range exceptSuffix { if strings.HasSuffix(lowerEntryName, suffix) { isExcept = true break } } if !isExcept && entry.Name()[0] != '.' && entry.Name()[0] != '_' { err = hugio.CopyFile(fs, sfp, dfp) if err != nil { c.r.logger.Errorln(err) } } } } return nil } func (c *importCommand) importFromJekyll(args []string) error { jekyllRoot, err := filepath.Abs(filepath.Clean(args[0])) if err != nil { return newUserError("path error:", args[0]) } targetDir, err := filepath.Abs(filepath.Clean(args[1])) if err != nil { return newUserError("path error:", args[1]) } c.r.Println("Import Jekyll from:", jekyllRoot, "to:", targetDir) if strings.HasPrefix(filepath.Dir(targetDir), jekyllRoot) { return newUserError("abort: target path should not be inside the Jekyll root") } fs := afero.NewOsFs() jekyllPostDirs, hasAnyPost := c.getJekyllDirInfo(fs, jekyllRoot) if !hasAnyPost { return errors.New("abort: jekyll root contains neither posts nor drafts") } err = c.createSiteFromJekyll(jekyllRoot, targetDir, jekyllPostDirs) if err != nil { return newUserError(err) } c.r.Println("Importing...") fileCount := 0 callback := func(path string, fi hugofs.FileMetaInfo, err error) error { if err != nil { return err } if fi.IsDir() { return nil } relPath, err := filepath.Rel(jekyllRoot, path) if err != nil { return newUserError("get rel path error:", path) } relPath = filepath.ToSlash(relPath) draft := false switch { case strings.Contains(relPath, "_posts/"): relPath = filepath.Join("content/post", strings.Replace(relPath, "_posts/", "", -1)) case strings.Contains(relPath, "_drafts/"): relPath = filepath.Join("content/draft", strings.Replace(relPath, "_drafts/", "", -1)) draft = true default: return nil } fileCount++ return c.convertJekyllPost(path, relPath, targetDir, draft) } for jekyllPostDir, hasAnyPostInDir := range jekyllPostDirs { if hasAnyPostInDir { if err = helpers.SymbolicWalk(hugofs.Os, filepath.Join(jekyllRoot, jekyllPostDir), callback); err != nil { return err } } } c.r.Println("Congratulations!", fileCount, "post(s) imported!") c.r.Println("Now, start Hugo by yourself:\n") c.r.Println("cd " + args[1]) c.r.Println("git init") c.r.Println("git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke themes/ananke") c.r.Println("echo \"theme = 'ananke'\" > hugo.toml") c.r.Println("hugo server") return nil } func (c *importCommand) loadJekyllConfig(fs afero.Fs, jekyllRoot string) map[string]any { path := filepath.Join(jekyllRoot, "_config.yml") exists, err := helpers.Exists(path, fs) if err != nil || !exists { c.r.Println("_config.yaml not found: Is the specified Jekyll root correct?") return nil } f, err := fs.Open(path) if err != nil { return nil } defer f.Close() b, err := io.ReadAll(f) if err != nil { return nil } m, err := metadecoders.Default.UnmarshalToMap(b, metadecoders.YAML) if err != nil { return nil } return m } func (c *importCommand) parseJekyllFilename(filename string) (time.Time, string, error) { re := regexp.MustCompile(`(\d+-\d+-\d+)-(.+)\..*`) r := re.FindAllStringSubmatch(filename, -1) if len(r) == 0 { return htime.Now(), "", errors.New("filename not match") } postDate, err := time.Parse("2006-1-2", r[0][1]) if err != nil { return htime.Now(), "", err } postName := r[0][2] return postDate, postName, nil } func (c *importCommand) replaceHighlightTag(match string) string { r := regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`) parts := r.FindStringSubmatch(match) lastQuote := rune(0) f := func(c rune) bool { switch { case c == lastQuote: lastQuote = rune(0) return false case lastQuote != rune(0): return false case unicode.In(c, unicode.Quotation_Mark): lastQuote = c return false default: return unicode.IsSpace(c) } } // splitting string by space but considering quoted section items := strings.FieldsFunc(parts[1], f) result := bytes.NewBufferString("{{< highlight ") result.WriteString(items[0]) // language options := items[1:] for i, opt := range options { opt = strings.Replace(opt, "\"", "", -1) if opt == "linenos" { opt = "linenos=table" } if i == 0 { opt = " \"" + opt } if i < len(options)-1 { opt += "," } else if i == len(options)-1 { opt += "\"" } result.WriteString(opt) } result.WriteString(" >}}") return result.String() } func (c *importCommand) replaceImageTag(match string) string { r := regexp.MustCompile(`{%\s+img\s*(\p{L}*)\s+([\S]*/[\S]+)\s+(\d*)\s*(\d*)\s*(.*?)\s*%}`) result := bytes.NewBufferString("{{< figure ") parts := r.FindStringSubmatch(match) // Index 0 is the entire string, ignore c.replaceOptionalPart(result, "class", parts[1]) c.replaceOptionalPart(result, "src", parts[2]) c.replaceOptionalPart(result, "width", parts[3]) c.replaceOptionalPart(result, "height", parts[4]) // title + alt part := parts[5] if len(part) > 0 { splits := strings.Split(part, "'") lenSplits := len(splits) if lenSplits == 1 { c.replaceOptionalPart(result, "title", splits[0]) } else if lenSplits == 3 { c.replaceOptionalPart(result, "title", splits[1]) } else if lenSplits == 5 { c.replaceOptionalPart(result, "title", splits[1]) c.replaceOptionalPart(result, "alt", splits[3]) } } result.WriteString(">}}") return result.String() } func (c *importCommand) replaceOptionalPart(buffer *bytes.Buffer, partName string, part string) { if len(part) > 0 { buffer.WriteString(partName + "=\"" + part + "\" ") } } func (c *importCommand) retrieveJekyllPostDir(fs afero.Fs, dir string) (bool, bool) { if strings.HasSuffix(dir, "_posts") || strings.HasSuffix(dir, "_drafts") { isEmpty, _ := helpers.IsEmpty(dir, fs) return true, !isEmpty } if entries, err := os.ReadDir(dir); err == nil { for _, entry := range entries { if entry.IsDir() { subDir := filepath.Join(dir, entry.Name()) if isPostDir, hasAnyPost := c.retrieveJekyllPostDir(fs, subDir); isPostDir { return isPostDir, hasAnyPost } } } } return false, true }
brianknight10
941818295d10a00ef557bce30ee9df86affc9f0f
49336bfc58f088ced757696f63c4abf0e105ab9d
```suggestion c.r.Println("echo \"theme = 'ananke'\" > hugo.toml") ```
jmooring
47
gohugoio/hugo
11,143
commands: Update Jekyll post-import output
Update CLI output after a successful Jekyll import to suggest a maintained theme and include clearer steps to running a server locally. Fixes #10715. I followed the suggestion made by @jmooring to clarify the next steps.
null
2023-06-21 14:10:54+00:00
2023-06-21 18:38:55+00:00
commands/import.go
// Copyright 2023 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 commands import ( "bytes" "context" "errors" "fmt" "io" "log" "os" "path/filepath" "regexp" "strconv" "strings" "time" "unicode" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/spf13/afero" "github.com/spf13/cobra" ) func newImportCommand() *importCommand { var c *importCommand c = &importCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "jekyll", short: "hugo import from Jekyll", long: `hugo import from Jekyll. Import from Jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.", run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 2 { return newUserError(`import from jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.") } return c.importFromJekyll(args) }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVar(&c.force, "force", false, "allow import into non-empty target directory") }, }, }, } return c } type importCommand struct { r *rootCommand force bool commands []simplecobra.Commander } func (c *importCommand) Commands() []simplecobra.Commander { return c.commands } func (c *importCommand) Name() string { return "import" } func (c *importCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *importCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Import your site from others." cmd.Long = `Import your site from other web site generators like Jekyll. Import requires a subcommand, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`." return nil } func (c *importCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.r = cd.Root.Command.(*rootCommand) return nil } func (i *importCommand) createConfigFromJekyll(fs afero.Fs, inpath string, kind metadecoders.Format, jekyllConfig map[string]any) (err error) { title := "My New Hugo Site" baseURL := "http://example.org/" for key, value := range jekyllConfig { lowerKey := strings.ToLower(key) switch lowerKey { case "title": if str, ok := value.(string); ok { title = str } case "url": if str, ok := value.(string); ok { baseURL = str } } } in := map[string]any{ "baseURL": baseURL, "title": title, "languageCode": "en-us", "disablePathToLower": true, } var buf bytes.Buffer err = parser.InterfaceToConfig(in, kind, &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+string(kind)), &buf, fs) } func (c *importCommand) getJekyllDirInfo(fs afero.Fs, jekyllRoot string) (map[string]bool, bool) { postDirs := make(map[string]bool) hasAnyPost := false if entries, err := os.ReadDir(jekyllRoot); err == nil { for _, entry := range entries { if entry.IsDir() { subDir := filepath.Join(jekyllRoot, entry.Name()) if isPostDir, hasAnyPostInDir := c.retrieveJekyllPostDir(fs, subDir); isPostDir { postDirs[entry.Name()] = hasAnyPostInDir if hasAnyPostInDir { hasAnyPost = true } } } } } return postDirs, hasAnyPost } func (c *importCommand) createSiteFromJekyll(jekyllRoot, targetDir string, jekyllPostDirs map[string]bool) error { fs := &afero.OsFs{} if exists, _ := helpers.Exists(targetDir, fs); exists { if isDir, _ := helpers.IsDir(targetDir, fs); !isDir { return errors.New("target path \"" + targetDir + "\" exists but is not a directory") } isEmpty, _ := helpers.IsEmpty(targetDir, fs) if !isEmpty && !c.force { return errors.New("target path \"" + targetDir + "\" exists and is not empty") } } jekyllConfig := c.loadJekyllConfig(fs, jekyllRoot) mkdir(targetDir, "layouts") mkdir(targetDir, "content") mkdir(targetDir, "archetypes") mkdir(targetDir, "static") mkdir(targetDir, "data") mkdir(targetDir, "themes") c.createConfigFromJekyll(fs, targetDir, "yaml", jekyllConfig) c.copyJekyllFilesAndFolders(jekyllRoot, filepath.Join(targetDir, "static"), jekyllPostDirs) return nil } func (c *importCommand) convertJekyllContent(m any, content string) (string, error) { metadata, _ := maps.ToStringMapE(m) lines := strings.Split(content, "\n") var resultLines []string for _, line := range lines { resultLines = append(resultLines, strings.Trim(line, "\r\n")) } content = strings.Join(resultLines, "\n") excerptSep := "<!--more-->" if value, ok := metadata["excerpt_separator"]; ok { if str, strOk := value.(string); strOk { content = strings.Replace(content, strings.TrimSpace(str), excerptSep, -1) } } replaceList := []struct { re *regexp.Regexp replace string }{ {regexp.MustCompile("(?i)<!-- more -->"), "<!--more-->"}, {regexp.MustCompile(`\{%\s*raw\s*%\}\s*(.*?)\s*\{%\s*endraw\s*%\}`), "$1"}, {regexp.MustCompile(`{%\s*endhighlight\s*%}`), "{{< / highlight >}}"}, } for _, replace := range replaceList { content = replace.re.ReplaceAllString(content, replace.replace) } replaceListFunc := []struct { re *regexp.Regexp replace func(string) string }{ // Octopress image tag: http://octopress.org/docs/plugins/image-tag/ {regexp.MustCompile(`{%\s+img\s*(.*?)\s*%}`), c.replaceImageTag}, {regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`), c.replaceHighlightTag}, } for _, replace := range replaceListFunc { content = replace.re.ReplaceAllStringFunc(content, replace.replace) } var buf bytes.Buffer if len(metadata) != 0 { err := parser.InterfaceToFrontMatter(m, metadecoders.YAML, &buf) if err != nil { return "", err } } buf.WriteString(content) return buf.String(), nil } func (c *importCommand) convertJekyllMetaData(m any, postName string, postDate time.Time, draft bool) (any, error) { metadata, err := maps.ToStringMapE(m) if err != nil { return nil, err } if draft { metadata["draft"] = true } for key, value := range metadata { lowerKey := strings.ToLower(key) switch lowerKey { case "layout": delete(metadata, key) case "permalink": if str, ok := value.(string); ok { metadata["url"] = str } delete(metadata, key) case "category": if str, ok := value.(string); ok { metadata["categories"] = []string{str} } delete(metadata, key) case "excerpt_separator": if key != lowerKey { delete(metadata, key) metadata[lowerKey] = value } case "date": if str, ok := value.(string); ok { re := regexp.MustCompile(`(\d+):(\d+):(\d+)`) r := re.FindAllStringSubmatch(str, -1) if len(r) > 0 { hour, _ := strconv.Atoi(r[0][1]) minute, _ := strconv.Atoi(r[0][2]) second, _ := strconv.Atoi(r[0][3]) postDate = time.Date(postDate.Year(), postDate.Month(), postDate.Day(), hour, minute, second, 0, time.UTC) } } delete(metadata, key) } } metadata["date"] = postDate.Format(time.RFC3339) return metadata, nil } func (c *importCommand) convertJekyllPost(path, relPath, targetDir string, draft bool) error { log.Println("Converting", path) filename := filepath.Base(path) postDate, postName, err := c.parseJekyllFilename(filename) if err != nil { c.r.Printf("Failed to parse filename '%s': %s. Skipping.", filename, err) return nil } log.Println(filename, postDate, postName) targetFile := filepath.Join(targetDir, relPath) targetParentDir := filepath.Dir(targetFile) os.MkdirAll(targetParentDir, 0777) contentBytes, err := os.ReadFile(path) if err != nil { c.r.logger.Errorln("Read file error:", path) return err } pf, err := pageparser.ParseFrontMatterAndContent(bytes.NewReader(contentBytes)) if err != nil { return fmt.Errorf("failed to parse file %q: %s", filename, err) } newmetadata, err := c.convertJekyllMetaData(pf.FrontMatter, postName, postDate, draft) if err != nil { return fmt.Errorf("failed to convert metadata for file %q: %s", filename, err) } content, err := c.convertJekyllContent(newmetadata, string(pf.Content)) if err != nil { return fmt.Errorf("failed to convert content for file %q: %s", filename, err) } fs := hugofs.Os if err := helpers.WriteToDisk(targetFile, strings.NewReader(content), fs); err != nil { return fmt.Errorf("failed to save file %q: %s", filename, err) } return nil } func (c *importCommand) copyJekyllFilesAndFolders(jekyllRoot, dest string, jekyllPostDirs map[string]bool) (err error) { fs := hugofs.Os fi, err := fs.Stat(jekyllRoot) if err != nil { return err } if !fi.IsDir() { return errors.New(jekyllRoot + " is not a directory") } err = os.MkdirAll(dest, fi.Mode()) if err != nil { return err } entries, err := os.ReadDir(jekyllRoot) if err != nil { return err } for _, entry := range entries { sfp := filepath.Join(jekyllRoot, entry.Name()) dfp := filepath.Join(dest, entry.Name()) if entry.IsDir() { if entry.Name()[0] != '_' && entry.Name()[0] != '.' { if _, ok := jekyllPostDirs[entry.Name()]; !ok { err = hugio.CopyDir(fs, sfp, dfp, nil) if err != nil { c.r.logger.Errorln(err) } } } } else { lowerEntryName := strings.ToLower(entry.Name()) exceptSuffix := []string{ ".md", ".markdown", ".html", ".htm", ".xml", ".textile", "rakefile", "gemfile", ".lock", } isExcept := false for _, suffix := range exceptSuffix { if strings.HasSuffix(lowerEntryName, suffix) { isExcept = true break } } if !isExcept && entry.Name()[0] != '.' && entry.Name()[0] != '_' { err = hugio.CopyFile(fs, sfp, dfp) if err != nil { c.r.logger.Errorln(err) } } } } return nil } func (c *importCommand) importFromJekyll(args []string) error { jekyllRoot, err := filepath.Abs(filepath.Clean(args[0])) if err != nil { return newUserError("path error:", args[0]) } targetDir, err := filepath.Abs(filepath.Clean(args[1])) if err != nil { return newUserError("path error:", args[1]) } c.r.Println("Import Jekyll from:", jekyllRoot, "to:", targetDir) if strings.HasPrefix(filepath.Dir(targetDir), jekyllRoot) { return newUserError("abort: target path should not be inside the Jekyll root") } fs := afero.NewOsFs() jekyllPostDirs, hasAnyPost := c.getJekyllDirInfo(fs, jekyllRoot) if !hasAnyPost { return errors.New("abort: jekyll root contains neither posts nor drafts") } err = c.createSiteFromJekyll(jekyllRoot, targetDir, jekyllPostDirs) if err != nil { return newUserError(err) } c.r.Println("Importing...") fileCount := 0 callback := func(path string, fi hugofs.FileMetaInfo, err error) error { if err != nil { return err } if fi.IsDir() { return nil } relPath, err := filepath.Rel(jekyllRoot, path) if err != nil { return newUserError("get rel path error:", path) } relPath = filepath.ToSlash(relPath) draft := false switch { case strings.Contains(relPath, "_posts/"): relPath = filepath.Join("content/post", strings.Replace(relPath, "_posts/", "", -1)) case strings.Contains(relPath, "_drafts/"): relPath = filepath.Join("content/draft", strings.Replace(relPath, "_drafts/", "", -1)) draft = true default: return nil } fileCount++ return c.convertJekyllPost(path, relPath, targetDir, draft) } for jekyllPostDir, hasAnyPostInDir := range jekyllPostDirs { if hasAnyPostInDir { if err = helpers.SymbolicWalk(hugofs.Os, filepath.Join(jekyllRoot, jekyllPostDir), callback); err != nil { return err } } } c.r.Println("Congratulations!", fileCount, "post(s) imported!") c.r.Println("Now, start Hugo by yourself:\n" + "$ git clone https://github.com/spf13/herring-cove.git " + args[1] + "/themes/herring-cove") c.r.Println("$ cd " + args[1] + "\n$ hugo server --theme=herring-cove") return nil } func (c *importCommand) loadJekyllConfig(fs afero.Fs, jekyllRoot string) map[string]any { path := filepath.Join(jekyllRoot, "_config.yml") exists, err := helpers.Exists(path, fs) if err != nil || !exists { c.r.Println("_config.yaml not found: Is the specified Jekyll root correct?") return nil } f, err := fs.Open(path) if err != nil { return nil } defer f.Close() b, err := io.ReadAll(f) if err != nil { return nil } m, err := metadecoders.Default.UnmarshalToMap(b, metadecoders.YAML) if err != nil { return nil } return m } func (c *importCommand) parseJekyllFilename(filename string) (time.Time, string, error) { re := regexp.MustCompile(`(\d+-\d+-\d+)-(.+)\..*`) r := re.FindAllStringSubmatch(filename, -1) if len(r) == 0 { return htime.Now(), "", errors.New("filename not match") } postDate, err := time.Parse("2006-1-2", r[0][1]) if err != nil { return htime.Now(), "", err } postName := r[0][2] return postDate, postName, nil } func (c *importCommand) replaceHighlightTag(match string) string { r := regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`) parts := r.FindStringSubmatch(match) lastQuote := rune(0) f := func(c rune) bool { switch { case c == lastQuote: lastQuote = rune(0) return false case lastQuote != rune(0): return false case unicode.In(c, unicode.Quotation_Mark): lastQuote = c return false default: return unicode.IsSpace(c) } } // splitting string by space but considering quoted section items := strings.FieldsFunc(parts[1], f) result := bytes.NewBufferString("{{< highlight ") result.WriteString(items[0]) // language options := items[1:] for i, opt := range options { opt = strings.Replace(opt, "\"", "", -1) if opt == "linenos" { opt = "linenos=table" } if i == 0 { opt = " \"" + opt } if i < len(options)-1 { opt += "," } else if i == len(options)-1 { opt += "\"" } result.WriteString(opt) } result.WriteString(" >}}") return result.String() } func (c *importCommand) replaceImageTag(match string) string { r := regexp.MustCompile(`{%\s+img\s*(\p{L}*)\s+([\S]*/[\S]+)\s+(\d*)\s*(\d*)\s*(.*?)\s*%}`) result := bytes.NewBufferString("{{< figure ") parts := r.FindStringSubmatch(match) // Index 0 is the entire string, ignore c.replaceOptionalPart(result, "class", parts[1]) c.replaceOptionalPart(result, "src", parts[2]) c.replaceOptionalPart(result, "width", parts[3]) c.replaceOptionalPart(result, "height", parts[4]) // title + alt part := parts[5] if len(part) > 0 { splits := strings.Split(part, "'") lenSplits := len(splits) if lenSplits == 1 { c.replaceOptionalPart(result, "title", splits[0]) } else if lenSplits == 3 { c.replaceOptionalPart(result, "title", splits[1]) } else if lenSplits == 5 { c.replaceOptionalPart(result, "title", splits[1]) c.replaceOptionalPart(result, "alt", splits[3]) } } result.WriteString(">}}") return result.String() } func (c *importCommand) replaceOptionalPart(buffer *bytes.Buffer, partName string, part string) { if len(part) > 0 { buffer.WriteString(partName + "=\"" + part + "\" ") } } func (c *importCommand) retrieveJekyllPostDir(fs afero.Fs, dir string) (bool, bool) { if strings.HasSuffix(dir, "_posts") || strings.HasSuffix(dir, "_drafts") { isEmpty, _ := helpers.IsEmpty(dir, fs) return true, !isEmpty } if entries, err := os.ReadDir(dir); err == nil { for _, entry := range entries { if entry.IsDir() { subDir := filepath.Join(dir, entry.Name()) if isPostDir, hasAnyPost := c.retrieveJekyllPostDir(fs, subDir); isPostDir { return isPostDir, hasAnyPost } } } } return false, true }
// Copyright 2023 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 commands import ( "bytes" "context" "errors" "fmt" "io" "log" "os" "path/filepath" "regexp" "strconv" "strings" "time" "unicode" "github.com/bep/simplecobra" "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/pageparser" "github.com/spf13/afero" "github.com/spf13/cobra" ) func newImportCommand() *importCommand { var c *importCommand c = &importCommand{ commands: []simplecobra.Commander{ &simpleCommand{ name: "jekyll", short: "hugo import from Jekyll", long: `hugo import from Jekyll. Import from Jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.", run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { if len(args) < 2 { return newUserError(`import from jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.") } return c.importFromJekyll(args) }, withc: func(cmd *cobra.Command, r *rootCommand) { cmd.Flags().BoolVar(&c.force, "force", false, "allow import into non-empty target directory") }, }, }, } return c } type importCommand struct { r *rootCommand force bool commands []simplecobra.Commander } func (c *importCommand) Commands() []simplecobra.Commander { return c.commands } func (c *importCommand) Name() string { return "import" } func (c *importCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { return nil } func (c *importCommand) Init(cd *simplecobra.Commandeer) error { cmd := cd.CobraCommand cmd.Short = "Import your site from others." cmd.Long = `Import your site from other web site generators like Jekyll. Import requires a subcommand, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`." return nil } func (c *importCommand) PreRun(cd, runner *simplecobra.Commandeer) error { c.r = cd.Root.Command.(*rootCommand) return nil } func (i *importCommand) createConfigFromJekyll(fs afero.Fs, inpath string, kind metadecoders.Format, jekyllConfig map[string]any) (err error) { title := "My New Hugo Site" baseURL := "http://example.org/" for key, value := range jekyllConfig { lowerKey := strings.ToLower(key) switch lowerKey { case "title": if str, ok := value.(string); ok { title = str } case "url": if str, ok := value.(string); ok { baseURL = str } } } in := map[string]any{ "baseURL": baseURL, "title": title, "languageCode": "en-us", "disablePathToLower": true, } var buf bytes.Buffer err = parser.InterfaceToConfig(in, kind, &buf) if err != nil { return err } return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+string(kind)), &buf, fs) } func (c *importCommand) getJekyllDirInfo(fs afero.Fs, jekyllRoot string) (map[string]bool, bool) { postDirs := make(map[string]bool) hasAnyPost := false if entries, err := os.ReadDir(jekyllRoot); err == nil { for _, entry := range entries { if entry.IsDir() { subDir := filepath.Join(jekyllRoot, entry.Name()) if isPostDir, hasAnyPostInDir := c.retrieveJekyllPostDir(fs, subDir); isPostDir { postDirs[entry.Name()] = hasAnyPostInDir if hasAnyPostInDir { hasAnyPost = true } } } } } return postDirs, hasAnyPost } func (c *importCommand) createSiteFromJekyll(jekyllRoot, targetDir string, jekyllPostDirs map[string]bool) error { fs := &afero.OsFs{} if exists, _ := helpers.Exists(targetDir, fs); exists { if isDir, _ := helpers.IsDir(targetDir, fs); !isDir { return errors.New("target path \"" + targetDir + "\" exists but is not a directory") } isEmpty, _ := helpers.IsEmpty(targetDir, fs) if !isEmpty && !c.force { return errors.New("target path \"" + targetDir + "\" exists and is not empty") } } jekyllConfig := c.loadJekyllConfig(fs, jekyllRoot) mkdir(targetDir, "layouts") mkdir(targetDir, "content") mkdir(targetDir, "archetypes") mkdir(targetDir, "static") mkdir(targetDir, "data") mkdir(targetDir, "themes") c.createConfigFromJekyll(fs, targetDir, "yaml", jekyllConfig) c.copyJekyllFilesAndFolders(jekyllRoot, filepath.Join(targetDir, "static"), jekyllPostDirs) return nil } func (c *importCommand) convertJekyllContent(m any, content string) (string, error) { metadata, _ := maps.ToStringMapE(m) lines := strings.Split(content, "\n") var resultLines []string for _, line := range lines { resultLines = append(resultLines, strings.Trim(line, "\r\n")) } content = strings.Join(resultLines, "\n") excerptSep := "<!--more-->" if value, ok := metadata["excerpt_separator"]; ok { if str, strOk := value.(string); strOk { content = strings.Replace(content, strings.TrimSpace(str), excerptSep, -1) } } replaceList := []struct { re *regexp.Regexp replace string }{ {regexp.MustCompile("(?i)<!-- more -->"), "<!--more-->"}, {regexp.MustCompile(`\{%\s*raw\s*%\}\s*(.*?)\s*\{%\s*endraw\s*%\}`), "$1"}, {regexp.MustCompile(`{%\s*endhighlight\s*%}`), "{{< / highlight >}}"}, } for _, replace := range replaceList { content = replace.re.ReplaceAllString(content, replace.replace) } replaceListFunc := []struct { re *regexp.Regexp replace func(string) string }{ // Octopress image tag: http://octopress.org/docs/plugins/image-tag/ {regexp.MustCompile(`{%\s+img\s*(.*?)\s*%}`), c.replaceImageTag}, {regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`), c.replaceHighlightTag}, } for _, replace := range replaceListFunc { content = replace.re.ReplaceAllStringFunc(content, replace.replace) } var buf bytes.Buffer if len(metadata) != 0 { err := parser.InterfaceToFrontMatter(m, metadecoders.YAML, &buf) if err != nil { return "", err } } buf.WriteString(content) return buf.String(), nil } func (c *importCommand) convertJekyllMetaData(m any, postName string, postDate time.Time, draft bool) (any, error) { metadata, err := maps.ToStringMapE(m) if err != nil { return nil, err } if draft { metadata["draft"] = true } for key, value := range metadata { lowerKey := strings.ToLower(key) switch lowerKey { case "layout": delete(metadata, key) case "permalink": if str, ok := value.(string); ok { metadata["url"] = str } delete(metadata, key) case "category": if str, ok := value.(string); ok { metadata["categories"] = []string{str} } delete(metadata, key) case "excerpt_separator": if key != lowerKey { delete(metadata, key) metadata[lowerKey] = value } case "date": if str, ok := value.(string); ok { re := regexp.MustCompile(`(\d+):(\d+):(\d+)`) r := re.FindAllStringSubmatch(str, -1) if len(r) > 0 { hour, _ := strconv.Atoi(r[0][1]) minute, _ := strconv.Atoi(r[0][2]) second, _ := strconv.Atoi(r[0][3]) postDate = time.Date(postDate.Year(), postDate.Month(), postDate.Day(), hour, minute, second, 0, time.UTC) } } delete(metadata, key) } } metadata["date"] = postDate.Format(time.RFC3339) return metadata, nil } func (c *importCommand) convertJekyllPost(path, relPath, targetDir string, draft bool) error { log.Println("Converting", path) filename := filepath.Base(path) postDate, postName, err := c.parseJekyllFilename(filename) if err != nil { c.r.Printf("Failed to parse filename '%s': %s. Skipping.", filename, err) return nil } log.Println(filename, postDate, postName) targetFile := filepath.Join(targetDir, relPath) targetParentDir := filepath.Dir(targetFile) os.MkdirAll(targetParentDir, 0777) contentBytes, err := os.ReadFile(path) if err != nil { c.r.logger.Errorln("Read file error:", path) return err } pf, err := pageparser.ParseFrontMatterAndContent(bytes.NewReader(contentBytes)) if err != nil { return fmt.Errorf("failed to parse file %q: %s", filename, err) } newmetadata, err := c.convertJekyllMetaData(pf.FrontMatter, postName, postDate, draft) if err != nil { return fmt.Errorf("failed to convert metadata for file %q: %s", filename, err) } content, err := c.convertJekyllContent(newmetadata, string(pf.Content)) if err != nil { return fmt.Errorf("failed to convert content for file %q: %s", filename, err) } fs := hugofs.Os if err := helpers.WriteToDisk(targetFile, strings.NewReader(content), fs); err != nil { return fmt.Errorf("failed to save file %q: %s", filename, err) } return nil } func (c *importCommand) copyJekyllFilesAndFolders(jekyllRoot, dest string, jekyllPostDirs map[string]bool) (err error) { fs := hugofs.Os fi, err := fs.Stat(jekyllRoot) if err != nil { return err } if !fi.IsDir() { return errors.New(jekyllRoot + " is not a directory") } err = os.MkdirAll(dest, fi.Mode()) if err != nil { return err } entries, err := os.ReadDir(jekyllRoot) if err != nil { return err } for _, entry := range entries { sfp := filepath.Join(jekyllRoot, entry.Name()) dfp := filepath.Join(dest, entry.Name()) if entry.IsDir() { if entry.Name()[0] != '_' && entry.Name()[0] != '.' { if _, ok := jekyllPostDirs[entry.Name()]; !ok { err = hugio.CopyDir(fs, sfp, dfp, nil) if err != nil { c.r.logger.Errorln(err) } } } } else { lowerEntryName := strings.ToLower(entry.Name()) exceptSuffix := []string{ ".md", ".markdown", ".html", ".htm", ".xml", ".textile", "rakefile", "gemfile", ".lock", } isExcept := false for _, suffix := range exceptSuffix { if strings.HasSuffix(lowerEntryName, suffix) { isExcept = true break } } if !isExcept && entry.Name()[0] != '.' && entry.Name()[0] != '_' { err = hugio.CopyFile(fs, sfp, dfp) if err != nil { c.r.logger.Errorln(err) } } } } return nil } func (c *importCommand) importFromJekyll(args []string) error { jekyllRoot, err := filepath.Abs(filepath.Clean(args[0])) if err != nil { return newUserError("path error:", args[0]) } targetDir, err := filepath.Abs(filepath.Clean(args[1])) if err != nil { return newUserError("path error:", args[1]) } c.r.Println("Import Jekyll from:", jekyllRoot, "to:", targetDir) if strings.HasPrefix(filepath.Dir(targetDir), jekyllRoot) { return newUserError("abort: target path should not be inside the Jekyll root") } fs := afero.NewOsFs() jekyllPostDirs, hasAnyPost := c.getJekyllDirInfo(fs, jekyllRoot) if !hasAnyPost { return errors.New("abort: jekyll root contains neither posts nor drafts") } err = c.createSiteFromJekyll(jekyllRoot, targetDir, jekyllPostDirs) if err != nil { return newUserError(err) } c.r.Println("Importing...") fileCount := 0 callback := func(path string, fi hugofs.FileMetaInfo, err error) error { if err != nil { return err } if fi.IsDir() { return nil } relPath, err := filepath.Rel(jekyllRoot, path) if err != nil { return newUserError("get rel path error:", path) } relPath = filepath.ToSlash(relPath) draft := false switch { case strings.Contains(relPath, "_posts/"): relPath = filepath.Join("content/post", strings.Replace(relPath, "_posts/", "", -1)) case strings.Contains(relPath, "_drafts/"): relPath = filepath.Join("content/draft", strings.Replace(relPath, "_drafts/", "", -1)) draft = true default: return nil } fileCount++ return c.convertJekyllPost(path, relPath, targetDir, draft) } for jekyllPostDir, hasAnyPostInDir := range jekyllPostDirs { if hasAnyPostInDir { if err = helpers.SymbolicWalk(hugofs.Os, filepath.Join(jekyllRoot, jekyllPostDir), callback); err != nil { return err } } } c.r.Println("Congratulations!", fileCount, "post(s) imported!") c.r.Println("Now, start Hugo by yourself:\n") c.r.Println("cd " + args[1]) c.r.Println("git init") c.r.Println("git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke themes/ananke") c.r.Println("echo \"theme = 'ananke'\" > hugo.toml") c.r.Println("hugo server") return nil } func (c *importCommand) loadJekyllConfig(fs afero.Fs, jekyllRoot string) map[string]any { path := filepath.Join(jekyllRoot, "_config.yml") exists, err := helpers.Exists(path, fs) if err != nil || !exists { c.r.Println("_config.yaml not found: Is the specified Jekyll root correct?") return nil } f, err := fs.Open(path) if err != nil { return nil } defer f.Close() b, err := io.ReadAll(f) if err != nil { return nil } m, err := metadecoders.Default.UnmarshalToMap(b, metadecoders.YAML) if err != nil { return nil } return m } func (c *importCommand) parseJekyllFilename(filename string) (time.Time, string, error) { re := regexp.MustCompile(`(\d+-\d+-\d+)-(.+)\..*`) r := re.FindAllStringSubmatch(filename, -1) if len(r) == 0 { return htime.Now(), "", errors.New("filename not match") } postDate, err := time.Parse("2006-1-2", r[0][1]) if err != nil { return htime.Now(), "", err } postName := r[0][2] return postDate, postName, nil } func (c *importCommand) replaceHighlightTag(match string) string { r := regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`) parts := r.FindStringSubmatch(match) lastQuote := rune(0) f := func(c rune) bool { switch { case c == lastQuote: lastQuote = rune(0) return false case lastQuote != rune(0): return false case unicode.In(c, unicode.Quotation_Mark): lastQuote = c return false default: return unicode.IsSpace(c) } } // splitting string by space but considering quoted section items := strings.FieldsFunc(parts[1], f) result := bytes.NewBufferString("{{< highlight ") result.WriteString(items[0]) // language options := items[1:] for i, opt := range options { opt = strings.Replace(opt, "\"", "", -1) if opt == "linenos" { opt = "linenos=table" } if i == 0 { opt = " \"" + opt } if i < len(options)-1 { opt += "," } else if i == len(options)-1 { opt += "\"" } result.WriteString(opt) } result.WriteString(" >}}") return result.String() } func (c *importCommand) replaceImageTag(match string) string { r := regexp.MustCompile(`{%\s+img\s*(\p{L}*)\s+([\S]*/[\S]+)\s+(\d*)\s*(\d*)\s*(.*?)\s*%}`) result := bytes.NewBufferString("{{< figure ") parts := r.FindStringSubmatch(match) // Index 0 is the entire string, ignore c.replaceOptionalPart(result, "class", parts[1]) c.replaceOptionalPart(result, "src", parts[2]) c.replaceOptionalPart(result, "width", parts[3]) c.replaceOptionalPart(result, "height", parts[4]) // title + alt part := parts[5] if len(part) > 0 { splits := strings.Split(part, "'") lenSplits := len(splits) if lenSplits == 1 { c.replaceOptionalPart(result, "title", splits[0]) } else if lenSplits == 3 { c.replaceOptionalPart(result, "title", splits[1]) } else if lenSplits == 5 { c.replaceOptionalPart(result, "title", splits[1]) c.replaceOptionalPart(result, "alt", splits[3]) } } result.WriteString(">}}") return result.String() } func (c *importCommand) replaceOptionalPart(buffer *bytes.Buffer, partName string, part string) { if len(part) > 0 { buffer.WriteString(partName + "=\"" + part + "\" ") } } func (c *importCommand) retrieveJekyllPostDir(fs afero.Fs, dir string) (bool, bool) { if strings.HasSuffix(dir, "_posts") || strings.HasSuffix(dir, "_drafts") { isEmpty, _ := helpers.IsEmpty(dir, fs) return true, !isEmpty } if entries, err := os.ReadDir(dir); err == nil { for _, entry := range entries { if entry.IsDir() { subDir := filepath.Join(dir, entry.Name()) if isPostDir, hasAnyPost := c.retrieveJekyllPostDir(fs, subDir); isPostDir { return isPostDir, hasAnyPost } } } } return false, true }
brianknight10
941818295d10a00ef557bce30ee9df86affc9f0f
49336bfc58f088ced757696f63c4abf0e105ab9d
Thanks - old habits die hard :)
brianknight10
48
gohugoio/hugo
11,114
Fix upstream Go templates bug with reversed key/value assignment
Fix upstream Go templates bug with reversed key/value assignment The template packages are based on go1.20.5 with the patch in befec5ddbbfbd81ec84e74e15a38044d67f8785b added. This also includes a security fix that now disallows Go template actions in JS literals (inside backticks). This will throw an error saying "... appears in a JS template literal". If you're really sure this isn't a security risk in your case, you can revert to the old behaviour: ```toml [security] [security.gotemplates] allowActionJSTmpl = true ``` See https://github.com/golang/go/issues/59234 Fixes #11112
null
2023-06-15 14:41:33+00:00
2023-06-15 21:04:34+00:00
tpl/internal/go_templates/htmltemplate/hugo_template.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 template import ( template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
// 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 template import ( "sync/atomic" template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) // See https://github.com/golang/go/issues/59234 // Moved here to avoid dependency on Go's internal/debug package. var SecurityAllowActionJSTmpl atomic.Bool /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
bep
0f989d5e21b200d848b45a4e305958636fd00779
ee359df172ece11989e9b1bf35c2d376f2608ac6
@jmooring this has been in Go since 1.20.3, but will be introduced in Hugo with this PR. I fear it will ... break stuff. What do you think?
bep
49
gohugoio/hugo
11,114
Fix upstream Go templates bug with reversed key/value assignment
Fix upstream Go templates bug with reversed key/value assignment The template packages are based on go1.20.5 with the patch in befec5ddbbfbd81ec84e74e15a38044d67f8785b added. This also includes a security fix that now disallows Go template actions in JS literals (inside backticks). This will throw an error saying "... appears in a JS template literal". If you're really sure this isn't a security risk in your case, you can revert to the old behaviour: ```toml [security] [security.gotemplates] allowActionJSTmpl = true ``` See https://github.com/golang/go/issues/59234 Fixes #11112
null
2023-06-15 14:41:33+00:00
2023-06-15 21:04:34+00:00
tpl/internal/go_templates/htmltemplate/hugo_template.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 template import ( template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
// 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 template import ( "sync/atomic" template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) // See https://github.com/golang/go/issues/59234 // Moved here to avoid dependency on Go's internal/debug package. var SecurityAllowActionJSTmpl atomic.Bool /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
bep
0f989d5e21b200d848b45a4e305958636fd00779
ee359df172ece11989e9b1bf35c2d376f2608ac6
Ideal: If the choice is between backwards compatibility and security, then security wins. Practical: It depends on how many sites will break, and to some extent, which sites. I will need to work with this PR to understand the effects before I can provide meaningful feedback and examples.
jmooring
50
gohugoio/hugo
11,114
Fix upstream Go templates bug with reversed key/value assignment
Fix upstream Go templates bug with reversed key/value assignment The template packages are based on go1.20.5 with the patch in befec5ddbbfbd81ec84e74e15a38044d67f8785b added. This also includes a security fix that now disallows Go template actions in JS literals (inside backticks). This will throw an error saying "... appears in a JS template literal". If you're really sure this isn't a security risk in your case, you can revert to the old behaviour: ```toml [security] [security.gotemplates] allowActionJSTmpl = true ``` See https://github.com/golang/go/issues/59234 Fixes #11112
null
2023-06-15 14:41:33+00:00
2023-06-15 21:04:34+00:00
tpl/internal/go_templates/htmltemplate/hugo_template.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 template import ( template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
// 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 template import ( "sync/atomic" template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) // See https://github.com/golang/go/issues/59234 // Moved here to avoid dependency on Go's internal/debug package. var SecurityAllowActionJSTmpl atomic.Bool /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
bep
0f989d5e21b200d848b45a4e305958636fd00779
ee359df172ece11989e9b1bf35c2d376f2608ac6
I think it's worth it to have this default secure, but add an option for it in Hugo's security config. I don't think either of us can know how much this will break until it ... breaks.
bep
51
gohugoio/hugo
11,114
Fix upstream Go templates bug with reversed key/value assignment
Fix upstream Go templates bug with reversed key/value assignment The template packages are based on go1.20.5 with the patch in befec5ddbbfbd81ec84e74e15a38044d67f8785b added. This also includes a security fix that now disallows Go template actions in JS literals (inside backticks). This will throw an error saying "... appears in a JS template literal". If you're really sure this isn't a security risk in your case, you can revert to the old behaviour: ```toml [security] [security.gotemplates] allowActionJSTmpl = true ``` See https://github.com/golang/go/issues/59234 Fixes #11112
null
2023-06-15 14:41:33+00:00
2023-06-15 21:04:34+00:00
tpl/internal/go_templates/htmltemplate/hugo_template.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 template import ( template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
// 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 template import ( "sync/atomic" template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) // See https://github.com/golang/go/issues/59234 // Moved here to avoid dependency on Go's internal/debug package. var SecurityAllowActionJSTmpl atomic.Bool /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
bep
0f989d5e21b200d848b45a4e305958636fd00779
ee359df172ece11989e9b1bf35c2d376f2608ac6
I'm fine with that approach.
jmooring
52
gohugoio/hugo
11,114
Fix upstream Go templates bug with reversed key/value assignment
Fix upstream Go templates bug with reversed key/value assignment The template packages are based on go1.20.5 with the patch in befec5ddbbfbd81ec84e74e15a38044d67f8785b added. This also includes a security fix that now disallows Go template actions in JS literals (inside backticks). This will throw an error saying "... appears in a JS template literal". If you're really sure this isn't a security risk in your case, you can revert to the old behaviour: ```toml [security] [security.gotemplates] allowActionJSTmpl = true ``` See https://github.com/golang/go/issues/59234 Fixes #11112
null
2023-06-15 14:41:33+00:00
2023-06-15 21:04:34+00:00
tpl/internal/go_templates/htmltemplate/hugo_template.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 template import ( template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
// 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 template import ( "sync/atomic" template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) // See https://github.com/golang/go/issues/59234 // Moved here to avoid dependency on Go's internal/debug package. var SecurityAllowActionJSTmpl atomic.Bool /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
bep
0f989d5e21b200d848b45a4e305958636fd00779
ee359df172ece11989e9b1bf35c2d376f2608ac6
OK, the above seem to be restricted to just script inside back ticks, which should be pretty rare: ```js var a = `{{.Title }}`; ```
bep
53
gohugoio/hugo
11,114
Fix upstream Go templates bug with reversed key/value assignment
Fix upstream Go templates bug with reversed key/value assignment The template packages are based on go1.20.5 with the patch in befec5ddbbfbd81ec84e74e15a38044d67f8785b added. This also includes a security fix that now disallows Go template actions in JS literals (inside backticks). This will throw an error saying "... appears in a JS template literal". If you're really sure this isn't a security risk in your case, you can revert to the old behaviour: ```toml [security] [security.gotemplates] allowActionJSTmpl = true ``` See https://github.com/golang/go/issues/59234 Fixes #11112
null
2023-06-15 14:41:33+00:00
2023-06-15 21:04:34+00:00
tpl/internal/go_templates/htmltemplate/hugo_template.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 template import ( template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
// 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 template import ( "sync/atomic" template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate" ) // See https://github.com/golang/go/issues/59234 // Moved here to avoid dependency on Go's internal/debug package. var SecurityAllowActionJSTmpl atomic.Bool /* This files contains the Hugo related addons. All the other files in this package is auto generated. */ // Export it so we can populate Hugo's func map with it, which makes it faster. var GoFuncs = funcMap // Prepare returns a template ready for execution. func (t *Template) Prepare() (*template.Template, error) { if err := t.escape(); err != nil { return nil, err } return t.text, nil } // See https://github.com/golang/go/issues/5884 func StripTags(html string) string { return stripTags(html) }
bep
0f989d5e21b200d848b45a4e305958636fd00779
ee359df172ece11989e9b1bf35c2d376f2608ac6
The only example usage of JS template literals that I can remember seeing is <https://github.com/gohugoio/hugo/issues/10707>.
jmooring
54
gohugoio/hugo
11,104
Misc Append fixes
- tpl/collections: Fix append when appending a slice to a slice of slices - common/collections: Always make a copy of the input slice in Append
null
2023-06-14 07:52:07+00:00
2023-06-14 18:18:54+00:00
common/collections/append.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 collections import ( "fmt" "reflect" ) // Append appends from to a slice to and returns the resulting slice. // If length of from is one and the only element is a slice of same type as to, // it will be appended. func Append(to any, from ...any) (any, error) { if len(from) == 0 { return to, nil } tov, toIsNil := indirect(reflect.ValueOf(to)) toIsNil = toIsNil || to == nil var tot reflect.Type if !toIsNil { if tov.Kind() != reflect.Slice { return nil, fmt.Errorf("expected a slice, got %T", to) } tot = tov.Type().Elem() if tot.Kind() == reflect.Slice { totvt := tot.Elem() fromvs := make([]reflect.Value, len(from)) for i, f := range from { fromv := reflect.ValueOf(f) fromt := fromv.Type() if fromt.Kind() == reflect.Slice { fromt = fromt.Elem() } if totvt != fromt { return nil, fmt.Errorf("cannot append slice of %s to slice of %s", fromt, totvt) } else { fromvs[i] = fromv } } return reflect.Append(tov, fromvs...).Interface(), nil } toIsNil = tov.Len() == 0 if len(from) == 1 { fromv := reflect.ValueOf(from[0]) fromt := fromv.Type() if fromt.Kind() == reflect.Slice { fromt = fromt.Elem() } if fromv.Kind() == reflect.Slice { if toIsNil { // If we get nil []string, we just return the []string return from[0], nil } // If we get []string []string, we append the from slice to to if tot == fromt { return reflect.AppendSlice(tov, fromv).Interface(), nil } else if !fromt.AssignableTo(tot) { // Fall back to a []interface{} slice. return appendToInterfaceSliceFromValues(tov, fromv) } } } } if toIsNil { return Slice(from...), nil } for _, f := range from { fv := reflect.ValueOf(f) if !fv.Type().AssignableTo(tot) { // Fall back to a []interface{} slice. tov, _ := indirect(reflect.ValueOf(to)) return appendToInterfaceSlice(tov, from...) } tov = reflect.Append(tov, fv) } return tov.Interface(), nil } func appendToInterfaceSliceFromValues(slice1, slice2 reflect.Value) ([]any, error) { var tos []any for _, slice := range []reflect.Value{slice1, slice2} { for i := 0; i < slice.Len(); i++ { tos = append(tos, slice.Index(i).Interface()) } } return tos, nil } func appendToInterfaceSlice(tov reflect.Value, from ...any) ([]any, error) { var tos []any for i := 0; i < tov.Len(); i++ { tos = append(tos, tov.Index(i).Interface()) } tos = append(tos, from...) return tos, nil } // indirect is borrowed from the Go stdlib: 'text/template/exec.go' // TODO(bep) consolidate func indirect(v reflect.Value) (rv reflect.Value, isNil bool) { for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() { if v.IsNil() { return v, true } if v.Kind() == reflect.Interface && v.NumMethod() > 0 { break } } return v, false }
// 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 collections import ( "fmt" "reflect" ) // Append appends from to a slice to and returns the resulting slice. // If length of from is one and the only element is a slice of same type as to, // it will be appended. func Append(to any, from ...any) (any, error) { if len(from) == 0 { return to, nil } tov, toIsNil := indirect(reflect.ValueOf(to)) toIsNil = toIsNil || to == nil var tot reflect.Type if !toIsNil { if tov.Kind() == reflect.Slice { // Create a copy of tov, so we don't modify the original. c := reflect.MakeSlice(tov.Type(), tov.Len(), tov.Len()+len(from)) reflect.Copy(c, tov) tov = c } if tov.Kind() != reflect.Slice { return nil, fmt.Errorf("expected a slice, got %T", to) } tot = tov.Type().Elem() if tot.Kind() == reflect.Slice { totvt := tot.Elem() fromvs := make([]reflect.Value, len(from)) for i, f := range from { fromv := reflect.ValueOf(f) fromt := fromv.Type() if fromt.Kind() == reflect.Slice { fromt = fromt.Elem() } if totvt != fromt { return nil, fmt.Errorf("cannot append slice of %s to slice of %s", fromt, totvt) } else { fromvs[i] = fromv } } return reflect.Append(tov, fromvs...).Interface(), nil } toIsNil = tov.Len() == 0 if len(from) == 1 { fromv := reflect.ValueOf(from[0]) fromt := fromv.Type() if fromt.Kind() == reflect.Slice { fromt = fromt.Elem() } if fromv.Kind() == reflect.Slice { if toIsNil { // If we get nil []string, we just return the []string return from[0], nil } // If we get []string []string, we append the from slice to to if tot == fromt { return reflect.AppendSlice(tov, fromv).Interface(), nil } else if !fromt.AssignableTo(tot) { // Fall back to a []interface{} slice. return appendToInterfaceSliceFromValues(tov, fromv) } } } } if toIsNil { return Slice(from...), nil } for _, f := range from { fv := reflect.ValueOf(f) if !fv.Type().AssignableTo(tot) { // Fall back to a []interface{} slice. tov, _ := indirect(reflect.ValueOf(to)) return appendToInterfaceSlice(tov, from...) } tov = reflect.Append(tov, fv) } return tov.Interface(), nil } func appendToInterfaceSliceFromValues(slice1, slice2 reflect.Value) ([]any, error) { var tos []any for _, slice := range []reflect.Value{slice1, slice2} { for i := 0; i < slice.Len(); i++ { tos = append(tos, slice.Index(i).Interface()) } } return tos, nil } func appendToInterfaceSlice(tov reflect.Value, from ...any) ([]any, error) { var tos []any for i := 0; i < tov.Len(); i++ { tos = append(tos, tov.Index(i).Interface()) } tos = append(tos, from...) return tos, nil } // indirect is borrowed from the Go stdlib: 'text/template/exec.go' // TODO(bep) consolidate func indirect(v reflect.Value) (rv reflect.Value, isNil bool) { for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() { if v.IsNil() { return v, true } if v.Kind() == reflect.Interface && v.NumMethod() > 0 { break } } return v, false }
bep
d178fe94fe26ce2cf8096f330f3d160af3ec818d
f73c5675341d41cb41b886b089544701022b5c12
we can omit `else` here: ```suggestion } fromvs[i] = fromv ```
alexandear
55
gohugoio/hugo
11,104
Misc Append fixes
- tpl/collections: Fix append when appending a slice to a slice of slices - common/collections: Always make a copy of the input slice in Append
null
2023-06-14 07:52:07+00:00
2023-06-14 18:18:54+00:00
common/collections/append.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 collections import ( "fmt" "reflect" ) // Append appends from to a slice to and returns the resulting slice. // If length of from is one and the only element is a slice of same type as to, // it will be appended. func Append(to any, from ...any) (any, error) { if len(from) == 0 { return to, nil } tov, toIsNil := indirect(reflect.ValueOf(to)) toIsNil = toIsNil || to == nil var tot reflect.Type if !toIsNil { if tov.Kind() != reflect.Slice { return nil, fmt.Errorf("expected a slice, got %T", to) } tot = tov.Type().Elem() if tot.Kind() == reflect.Slice { totvt := tot.Elem() fromvs := make([]reflect.Value, len(from)) for i, f := range from { fromv := reflect.ValueOf(f) fromt := fromv.Type() if fromt.Kind() == reflect.Slice { fromt = fromt.Elem() } if totvt != fromt { return nil, fmt.Errorf("cannot append slice of %s to slice of %s", fromt, totvt) } else { fromvs[i] = fromv } } return reflect.Append(tov, fromvs...).Interface(), nil } toIsNil = tov.Len() == 0 if len(from) == 1 { fromv := reflect.ValueOf(from[0]) fromt := fromv.Type() if fromt.Kind() == reflect.Slice { fromt = fromt.Elem() } if fromv.Kind() == reflect.Slice { if toIsNil { // If we get nil []string, we just return the []string return from[0], nil } // If we get []string []string, we append the from slice to to if tot == fromt { return reflect.AppendSlice(tov, fromv).Interface(), nil } else if !fromt.AssignableTo(tot) { // Fall back to a []interface{} slice. return appendToInterfaceSliceFromValues(tov, fromv) } } } } if toIsNil { return Slice(from...), nil } for _, f := range from { fv := reflect.ValueOf(f) if !fv.Type().AssignableTo(tot) { // Fall back to a []interface{} slice. tov, _ := indirect(reflect.ValueOf(to)) return appendToInterfaceSlice(tov, from...) } tov = reflect.Append(tov, fv) } return tov.Interface(), nil } func appendToInterfaceSliceFromValues(slice1, slice2 reflect.Value) ([]any, error) { var tos []any for _, slice := range []reflect.Value{slice1, slice2} { for i := 0; i < slice.Len(); i++ { tos = append(tos, slice.Index(i).Interface()) } } return tos, nil } func appendToInterfaceSlice(tov reflect.Value, from ...any) ([]any, error) { var tos []any for i := 0; i < tov.Len(); i++ { tos = append(tos, tov.Index(i).Interface()) } tos = append(tos, from...) return tos, nil } // indirect is borrowed from the Go stdlib: 'text/template/exec.go' // TODO(bep) consolidate func indirect(v reflect.Value) (rv reflect.Value, isNil bool) { for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() { if v.IsNil() { return v, true } if v.Kind() == reflect.Interface && v.NumMethod() > 0 { break } } return v, false }
// 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 collections import ( "fmt" "reflect" ) // Append appends from to a slice to and returns the resulting slice. // If length of from is one and the only element is a slice of same type as to, // it will be appended. func Append(to any, from ...any) (any, error) { if len(from) == 0 { return to, nil } tov, toIsNil := indirect(reflect.ValueOf(to)) toIsNil = toIsNil || to == nil var tot reflect.Type if !toIsNil { if tov.Kind() == reflect.Slice { // Create a copy of tov, so we don't modify the original. c := reflect.MakeSlice(tov.Type(), tov.Len(), tov.Len()+len(from)) reflect.Copy(c, tov) tov = c } if tov.Kind() != reflect.Slice { return nil, fmt.Errorf("expected a slice, got %T", to) } tot = tov.Type().Elem() if tot.Kind() == reflect.Slice { totvt := tot.Elem() fromvs := make([]reflect.Value, len(from)) for i, f := range from { fromv := reflect.ValueOf(f) fromt := fromv.Type() if fromt.Kind() == reflect.Slice { fromt = fromt.Elem() } if totvt != fromt { return nil, fmt.Errorf("cannot append slice of %s to slice of %s", fromt, totvt) } else { fromvs[i] = fromv } } return reflect.Append(tov, fromvs...).Interface(), nil } toIsNil = tov.Len() == 0 if len(from) == 1 { fromv := reflect.ValueOf(from[0]) fromt := fromv.Type() if fromt.Kind() == reflect.Slice { fromt = fromt.Elem() } if fromv.Kind() == reflect.Slice { if toIsNil { // If we get nil []string, we just return the []string return from[0], nil } // If we get []string []string, we append the from slice to to if tot == fromt { return reflect.AppendSlice(tov, fromv).Interface(), nil } else if !fromt.AssignableTo(tot) { // Fall back to a []interface{} slice. return appendToInterfaceSliceFromValues(tov, fromv) } } } } if toIsNil { return Slice(from...), nil } for _, f := range from { fv := reflect.ValueOf(f) if !fv.Type().AssignableTo(tot) { // Fall back to a []interface{} slice. tov, _ := indirect(reflect.ValueOf(to)) return appendToInterfaceSlice(tov, from...) } tov = reflect.Append(tov, fv) } return tov.Interface(), nil } func appendToInterfaceSliceFromValues(slice1, slice2 reflect.Value) ([]any, error) { var tos []any for _, slice := range []reflect.Value{slice1, slice2} { for i := 0; i < slice.Len(); i++ { tos = append(tos, slice.Index(i).Interface()) } } return tos, nil } func appendToInterfaceSlice(tov reflect.Value, from ...any) ([]any, error) { var tos []any for i := 0; i < tov.Len(); i++ { tos = append(tos, tov.Index(i).Interface()) } tos = append(tos, from...) return tos, nil } // indirect is borrowed from the Go stdlib: 'text/template/exec.go' // TODO(bep) consolidate func indirect(v reflect.Value) (rv reflect.Value, isNil bool) { for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() { if v.IsNil() { return v, true } if v.Kind() == reflect.Interface && v.NumMethod() > 0 { break } } return v, false }
bep
d178fe94fe26ce2cf8096f330f3d160af3ec818d
f73c5675341d41cb41b886b089544701022b5c12
@alexandear If you see something obviously buggy in my PRs, please shout, but I'm not a fan of nit picking/cosmetic suggestions from the side line. I do agree with you in this particular case, but it's not important enough.
bep
56
gohugoio/hugo
11,032
tpl/tplimpl: Use .Language.LanguageCode in built-in templates
If this is merged, I will update the documentation in the docs repo after release.
null
2023-05-27 22:24:37+00:00
2023-05-30 18:10:17+00:00
tpl/tplimpl/embedded/templates/_default/rss.xml
{{- $pctx := . -}} {{- if .IsHome -}}{{ $pctx = .Site }}{{- end -}} {{- $pages := slice -}} {{- if or $.IsHome $.IsSection -}} {{- $pages = $pctx.RegularPages -}} {{- else -}} {{- $pages = $pctx.Pages -}} {{- end -}} {{- $limit := .Site.Config.Services.RSS.Limit -}} {{- if ge $limit 1 -}} {{- $pages = $pages | first $limit -}} {{- end -}} {{- printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }} <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>{{ if eq .Title .Site.Title }}{{ .Site.Title }}{{ else }}{{ with .Title }}{{.}} on {{ end }}{{ .Site.Title }}{{ end }}</title> <link>{{ .Permalink }}</link> <description>Recent content {{ if ne .Title .Site.Title }}{{ with .Title }}in {{.}} {{ end }}{{ end }}on {{ .Site.Title }}</description> <generator>Hugo -- gohugo.io</generator>{{ with .Site.LanguageCode }} <language>{{.}}</language>{{end}}{{ with .Site.Author.email }} <managingEditor>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</managingEditor>{{end}}{{ with .Site.Author.email }} <webMaster>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</webMaster>{{end}}{{ with .Site.Copyright }} <copyright>{{.}}</copyright>{{end}}{{ if not .Date.IsZero }} <lastBuildDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</lastBuildDate>{{ end }} {{- with .OutputFormats.Get "RSS" -}} {{ printf "<atom:link href=%q rel=\"self\" type=%q />" .Permalink .MediaType | safeHTML }} {{- end -}} {{ range $pages }} <item> <title>{{ .Title }}</title> <link>{{ .Permalink }}</link> <pubDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</pubDate> {{ with .Site.Author.email }}<author>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</author>{{end}} <guid>{{ .Permalink }}</guid> <description>{{ .Summary | html }}</description> </item> {{ end }} </channel> </rss>
{{- $pctx := . -}} {{- if .IsHome -}}{{ $pctx = .Site }}{{- end -}} {{- $pages := slice -}} {{- if or $.IsHome $.IsSection -}} {{- $pages = $pctx.RegularPages -}} {{- else -}} {{- $pages = $pctx.Pages -}} {{- end -}} {{- $limit := .Site.Config.Services.RSS.Limit -}} {{- if ge $limit 1 -}} {{- $pages = $pages | first $limit -}} {{- end -}} {{- printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }} <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>{{ if eq .Title .Site.Title }}{{ .Site.Title }}{{ else }}{{ with .Title }}{{.}} on {{ end }}{{ .Site.Title }}{{ end }}</title> <link>{{ .Permalink }}</link> <description>Recent content {{ if ne .Title .Site.Title }}{{ with .Title }}in {{.}} {{ end }}{{ end }}on {{ .Site.Title }}</description> <generator>Hugo -- gohugo.io</generator> <language>{{ site.Language.LanguageCode }}</language>{{ with .Site.Author.email }} <managingEditor>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</managingEditor>{{end}}{{ with .Site.Author.email }} <webMaster>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</webMaster>{{end}}{{ with .Site.Copyright }} <copyright>{{.}}</copyright>{{end}}{{ if not .Date.IsZero }} <lastBuildDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</lastBuildDate>{{ end }} {{- with .OutputFormats.Get "RSS" -}} {{ printf "<atom:link href=%q rel=\"self\" type=%q />" .Permalink .MediaType | safeHTML }} {{- end -}} {{ range $pages }} <item> <title>{{ .Title }}</title> <link>{{ .Permalink }}</link> <pubDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</pubDate> {{ with .Site.Author.email }}<author>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</author>{{end}} <guid>{{ .Permalink }}</guid> <description>{{ .Summary | html }}</description> </item> {{ end }} </channel> </rss>
jmooring
9cdca1f9582597c3998e44cd16509ead362a90df
ff77a927f9c032f5a65eff2daf1f7f8c04103711
`site.Language.LanguageCode` will fall back to `Lang` if `LanguageCode` is not set. See https://github.com/gohugoio/hugo/blob/ffdbce5787a45e8537b7a77515ca06e4deee2504/langs/language.go#L111
bep
57
gohugoio/hugo
11,032
tpl/tplimpl: Use .Language.LanguageCode in built-in templates
If this is merged, I will update the documentation in the docs repo after release.
null
2023-05-27 22:24:37+00:00
2023-05-30 18:10:17+00:00
tpl/tplimpl/embedded/templates/_default/rss.xml
{{- $pctx := . -}} {{- if .IsHome -}}{{ $pctx = .Site }}{{- end -}} {{- $pages := slice -}} {{- if or $.IsHome $.IsSection -}} {{- $pages = $pctx.RegularPages -}} {{- else -}} {{- $pages = $pctx.Pages -}} {{- end -}} {{- $limit := .Site.Config.Services.RSS.Limit -}} {{- if ge $limit 1 -}} {{- $pages = $pages | first $limit -}} {{- end -}} {{- printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }} <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>{{ if eq .Title .Site.Title }}{{ .Site.Title }}{{ else }}{{ with .Title }}{{.}} on {{ end }}{{ .Site.Title }}{{ end }}</title> <link>{{ .Permalink }}</link> <description>Recent content {{ if ne .Title .Site.Title }}{{ with .Title }}in {{.}} {{ end }}{{ end }}on {{ .Site.Title }}</description> <generator>Hugo -- gohugo.io</generator>{{ with .Site.LanguageCode }} <language>{{.}}</language>{{end}}{{ with .Site.Author.email }} <managingEditor>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</managingEditor>{{end}}{{ with .Site.Author.email }} <webMaster>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</webMaster>{{end}}{{ with .Site.Copyright }} <copyright>{{.}}</copyright>{{end}}{{ if not .Date.IsZero }} <lastBuildDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</lastBuildDate>{{ end }} {{- with .OutputFormats.Get "RSS" -}} {{ printf "<atom:link href=%q rel=\"self\" type=%q />" .Permalink .MediaType | safeHTML }} {{- end -}} {{ range $pages }} <item> <title>{{ .Title }}</title> <link>{{ .Permalink }}</link> <pubDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</pubDate> {{ with .Site.Author.email }}<author>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</author>{{end}} <guid>{{ .Permalink }}</guid> <description>{{ .Summary | html }}</description> </item> {{ end }} </channel> </rss>
{{- $pctx := . -}} {{- if .IsHome -}}{{ $pctx = .Site }}{{- end -}} {{- $pages := slice -}} {{- if or $.IsHome $.IsSection -}} {{- $pages = $pctx.RegularPages -}} {{- else -}} {{- $pages = $pctx.Pages -}} {{- end -}} {{- $limit := .Site.Config.Services.RSS.Limit -}} {{- if ge $limit 1 -}} {{- $pages = $pages | first $limit -}} {{- end -}} {{- printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }} <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>{{ if eq .Title .Site.Title }}{{ .Site.Title }}{{ else }}{{ with .Title }}{{.}} on {{ end }}{{ .Site.Title }}{{ end }}</title> <link>{{ .Permalink }}</link> <description>Recent content {{ if ne .Title .Site.Title }}{{ with .Title }}in {{.}} {{ end }}{{ end }}on {{ .Site.Title }}</description> <generator>Hugo -- gohugo.io</generator> <language>{{ site.Language.LanguageCode }}</language>{{ with .Site.Author.email }} <managingEditor>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</managingEditor>{{end}}{{ with .Site.Author.email }} <webMaster>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</webMaster>{{end}}{{ with .Site.Copyright }} <copyright>{{.}}</copyright>{{end}}{{ if not .Date.IsZero }} <lastBuildDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</lastBuildDate>{{ end }} {{- with .OutputFormats.Get "RSS" -}} {{ printf "<atom:link href=%q rel=\"self\" type=%q />" .Permalink .MediaType | safeHTML }} {{- end -}} {{ range $pages }} <item> <title>{{ .Title }}</title> <link>{{ .Permalink }}</link> <pubDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</pubDate> {{ with .Site.Author.email }}<author>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</author>{{end}} <guid>{{ .Permalink }}</guid> <description>{{ .Summary | html }}</description> </item> {{ end }} </channel> </rss>
jmooring
9cdca1f9582597c3998e44cd16509ead362a90df
ff77a927f9c032f5a65eff2daf1f7f8c04103711
Note that the above was also how `site.LanguageCode` behaved before.
bep
58
gohugoio/hugo
11,032
tpl/tplimpl: Use .Language.LanguageCode in built-in templates
If this is merged, I will update the documentation in the docs repo after release.
null
2023-05-27 22:24:37+00:00
2023-05-30 18:10:17+00:00
tpl/tplimpl/embedded/templates/_default/rss.xml
{{- $pctx := . -}} {{- if .IsHome -}}{{ $pctx = .Site }}{{- end -}} {{- $pages := slice -}} {{- if or $.IsHome $.IsSection -}} {{- $pages = $pctx.RegularPages -}} {{- else -}} {{- $pages = $pctx.Pages -}} {{- end -}} {{- $limit := .Site.Config.Services.RSS.Limit -}} {{- if ge $limit 1 -}} {{- $pages = $pages | first $limit -}} {{- end -}} {{- printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }} <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>{{ if eq .Title .Site.Title }}{{ .Site.Title }}{{ else }}{{ with .Title }}{{.}} on {{ end }}{{ .Site.Title }}{{ end }}</title> <link>{{ .Permalink }}</link> <description>Recent content {{ if ne .Title .Site.Title }}{{ with .Title }}in {{.}} {{ end }}{{ end }}on {{ .Site.Title }}</description> <generator>Hugo -- gohugo.io</generator>{{ with .Site.LanguageCode }} <language>{{.}}</language>{{end}}{{ with .Site.Author.email }} <managingEditor>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</managingEditor>{{end}}{{ with .Site.Author.email }} <webMaster>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</webMaster>{{end}}{{ with .Site.Copyright }} <copyright>{{.}}</copyright>{{end}}{{ if not .Date.IsZero }} <lastBuildDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</lastBuildDate>{{ end }} {{- with .OutputFormats.Get "RSS" -}} {{ printf "<atom:link href=%q rel=\"self\" type=%q />" .Permalink .MediaType | safeHTML }} {{- end -}} {{ range $pages }} <item> <title>{{ .Title }}</title> <link>{{ .Permalink }}</link> <pubDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</pubDate> {{ with .Site.Author.email }}<author>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</author>{{end}} <guid>{{ .Permalink }}</guid> <description>{{ .Summary | html }}</description> </item> {{ end }} </channel> </rss>
{{- $pctx := . -}} {{- if .IsHome -}}{{ $pctx = .Site }}{{- end -}} {{- $pages := slice -}} {{- if or $.IsHome $.IsSection -}} {{- $pages = $pctx.RegularPages -}} {{- else -}} {{- $pages = $pctx.Pages -}} {{- end -}} {{- $limit := .Site.Config.Services.RSS.Limit -}} {{- if ge $limit 1 -}} {{- $pages = $pages | first $limit -}} {{- end -}} {{- printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }} <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> <title>{{ if eq .Title .Site.Title }}{{ .Site.Title }}{{ else }}{{ with .Title }}{{.}} on {{ end }}{{ .Site.Title }}{{ end }}</title> <link>{{ .Permalink }}</link> <description>Recent content {{ if ne .Title .Site.Title }}{{ with .Title }}in {{.}} {{ end }}{{ end }}on {{ .Site.Title }}</description> <generator>Hugo -- gohugo.io</generator> <language>{{ site.Language.LanguageCode }}</language>{{ with .Site.Author.email }} <managingEditor>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</managingEditor>{{end}}{{ with .Site.Author.email }} <webMaster>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</webMaster>{{end}}{{ with .Site.Copyright }} <copyright>{{.}}</copyright>{{end}}{{ if not .Date.IsZero }} <lastBuildDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</lastBuildDate>{{ end }} {{- with .OutputFormats.Get "RSS" -}} {{ printf "<atom:link href=%q rel=\"self\" type=%q />" .Permalink .MediaType | safeHTML }} {{- end -}} {{ range $pages }} <item> <title>{{ .Title }}</title> <link>{{ .Permalink }}</link> <pubDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</pubDate> {{ with .Site.Author.email }}<author>{{.}}{{ with $.Site.Author.name }} ({{.}}){{end}}</author>{{end}} <guid>{{ .Permalink }}</guid> <description>{{ .Summary | html }}</description> </item> {{ end }} </channel> </rss>
jmooring
9cdca1f9582597c3998e44cd16509ead362a90df
ff77a927f9c032f5a65eff2daf1f7f8c04103711
Changes made as requested. I like that `site.Language.LanguageCode` falls back to `site.Language.Lang`. Note: I verified that is new behavior. In v0.111.3, site.LanguageCode returned an empty string if languageCode was not set in site configuration. Thanks for the change.
jmooring
59
gohugoio/hugo
10,967
tpl/urls: Return empty string when JoinPath has zero args
null
null
2023-05-19 15:30:57+00:00
2023-05-20 09:14:18+00:00
tpl/urls/urls.go
// Copyright 2017 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 urls provides template functions to deal with URLs. package urls import ( "errors" "fmt" "html/template" "net/url" "github.com/gohugoio/hugo/common/urls" "github.com/gohugoio/hugo/deps" "github.com/spf13/cast" ) // New returns a new instance of the urls-namespaced template functions. func New(deps *deps.Deps) *Namespace { return &Namespace{ deps: deps, multihost: deps.Conf.IsMultihost(), } } // Namespace provides template functions for the "urls" namespace. type Namespace struct { deps *deps.Deps multihost bool } // AbsURL takes the string s and converts it to an absolute URL. func (ns *Namespace) AbsURL(s any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", nil } return template.HTML(ns.deps.PathSpec.AbsURL(ss, false)), nil } // Parse parses rawurl into a URL structure. The rawurl may be relative or // absolute. func (ns *Namespace) Parse(rawurl any) (*url.URL, error) { s, err := cast.ToStringE(rawurl) if err != nil { return nil, fmt.Errorf("Error in Parse: %w", err) } return url.Parse(s) } // RelURL takes the string s and prepends the relative path according to a // page's position in the project directory structure. func (ns *Namespace) RelURL(s any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", nil } return template.HTML(ns.deps.PathSpec.RelURL(ss, false)), nil } // URLize returns the the strings s formatted as an URL. func (ns *Namespace) URLize(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", nil } return ns.deps.PathSpec.URLize(ss), nil } // Anchorize creates sanitized anchor name version of the string s that is compatible // with how your configured markdown renderer does it. func (ns *Namespace) Anchorize(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", nil } return ns.deps.ContentSpec.SanitizeAnchorName(ss), nil } // Ref returns the absolute URL path to a given content item from Page p. func (ns *Namespace) Ref(p any, args any) (template.HTML, error) { pp, ok := p.(urls.RefLinker) if !ok { return "", errors.New("invalid Page received in Ref") } argsm, err := ns.refArgsToMap(args) if err != nil { return "", err } s, err := pp.Ref(argsm) return template.HTML(s), err } // RelRef returns the relative URL path to a given content item from Page p. func (ns *Namespace) RelRef(p any, args any) (template.HTML, error) { pp, ok := p.(urls.RefLinker) if !ok { return "", errors.New("invalid Page received in RelRef") } argsm, err := ns.refArgsToMap(args) if err != nil { return "", err } s, err := pp.RelRef(argsm) return template.HTML(s), err } func (ns *Namespace) refArgsToMap(args any) (map[string]any, error) { var ( s string of string ) v := args if _, ok := v.([]any); ok { v = cast.ToStringSlice(v) } switch v := v.(type) { case map[string]any: return v, nil case map[string]string: m := make(map[string]any) for k, v := range v { m[k] = v } return m, nil case []string: if len(v) == 0 || len(v) > 2 { return nil, fmt.Errorf("invalid number of arguments to ref") } // These where the options before we introduced the map type: s = v[0] if len(v) == 2 { of = v[1] } default: var err error s, err = cast.ToStringE(args) if err != nil { return nil, err } } return map[string]any{ "path": s, "outputFormat": of, }, nil } // RelLangURL takes the string s and prepends the relative path according to a // page's position in the project directory structure and the current language. func (ns *Namespace) RelLangURL(s any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return template.HTML(ns.deps.PathSpec.RelURL(ss, !ns.multihost)), nil } // AbsLangURL the string s and converts it to an absolute URL according // to a page's position in the project directory structure and the current // language. func (ns *Namespace) AbsLangURL(s any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return template.HTML(ns.deps.PathSpec.AbsURL(ss, !ns.multihost)), nil } // JoinPath joins the provided elements into a URL string and cleans the result // of any ./ or ../ elements. func (ns *Namespace) JoinPath(elements ...any) (string, error) { var selements []string for _, e := range elements { switch v := e.(type) { case []string: for _, e := range v { selements = append(selements, e) } case []any: for _, e := range v { se, err := cast.ToStringE(e) if err != nil { return "", err } selements = append(selements, se) } default: se, err := cast.ToStringE(e) if err != nil { return "", err } selements = append(selements, se) } } result, err := url.JoinPath(selements[0], selements[1:]...) if err != nil { return "", err } return result, nil }
// Copyright 2017 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 urls provides template functions to deal with URLs. package urls import ( "errors" "fmt" "html/template" "net/url" "github.com/gohugoio/hugo/common/urls" "github.com/gohugoio/hugo/deps" "github.com/spf13/cast" ) // New returns a new instance of the urls-namespaced template functions. func New(deps *deps.Deps) *Namespace { return &Namespace{ deps: deps, multihost: deps.Conf.IsMultihost(), } } // Namespace provides template functions for the "urls" namespace. type Namespace struct { deps *deps.Deps multihost bool } // AbsURL takes the string s and converts it to an absolute URL. func (ns *Namespace) AbsURL(s any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", nil } return template.HTML(ns.deps.PathSpec.AbsURL(ss, false)), nil } // Parse parses rawurl into a URL structure. The rawurl may be relative or // absolute. func (ns *Namespace) Parse(rawurl any) (*url.URL, error) { s, err := cast.ToStringE(rawurl) if err != nil { return nil, fmt.Errorf("Error in Parse: %w", err) } return url.Parse(s) } // RelURL takes the string s and prepends the relative path according to a // page's position in the project directory structure. func (ns *Namespace) RelURL(s any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", nil } return template.HTML(ns.deps.PathSpec.RelURL(ss, false)), nil } // URLize returns the the strings s formatted as an URL. func (ns *Namespace) URLize(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", nil } return ns.deps.PathSpec.URLize(ss), nil } // Anchorize creates sanitized anchor name version of the string s that is compatible // with how your configured markdown renderer does it. func (ns *Namespace) Anchorize(s any) (string, error) { ss, err := cast.ToStringE(s) if err != nil { return "", nil } return ns.deps.ContentSpec.SanitizeAnchorName(ss), nil } // Ref returns the absolute URL path to a given content item from Page p. func (ns *Namespace) Ref(p any, args any) (template.HTML, error) { pp, ok := p.(urls.RefLinker) if !ok { return "", errors.New("invalid Page received in Ref") } argsm, err := ns.refArgsToMap(args) if err != nil { return "", err } s, err := pp.Ref(argsm) return template.HTML(s), err } // RelRef returns the relative URL path to a given content item from Page p. func (ns *Namespace) RelRef(p any, args any) (template.HTML, error) { pp, ok := p.(urls.RefLinker) if !ok { return "", errors.New("invalid Page received in RelRef") } argsm, err := ns.refArgsToMap(args) if err != nil { return "", err } s, err := pp.RelRef(argsm) return template.HTML(s), err } func (ns *Namespace) refArgsToMap(args any) (map[string]any, error) { var ( s string of string ) v := args if _, ok := v.([]any); ok { v = cast.ToStringSlice(v) } switch v := v.(type) { case map[string]any: return v, nil case map[string]string: m := make(map[string]any) for k, v := range v { m[k] = v } return m, nil case []string: if len(v) == 0 || len(v) > 2 { return nil, fmt.Errorf("invalid number of arguments to ref") } // These where the options before we introduced the map type: s = v[0] if len(v) == 2 { of = v[1] } default: var err error s, err = cast.ToStringE(args) if err != nil { return nil, err } } return map[string]any{ "path": s, "outputFormat": of, }, nil } // RelLangURL takes the string s and prepends the relative path according to a // page's position in the project directory structure and the current language. func (ns *Namespace) RelLangURL(s any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return template.HTML(ns.deps.PathSpec.RelURL(ss, !ns.multihost)), nil } // AbsLangURL the string s and converts it to an absolute URL according // to a page's position in the project directory structure and the current // language. func (ns *Namespace) AbsLangURL(s any) (template.HTML, error) { ss, err := cast.ToStringE(s) if err != nil { return "", err } return template.HTML(ns.deps.PathSpec.AbsURL(ss, !ns.multihost)), nil } // JoinPath joins the provided elements into a URL string and cleans the result // of any ./ or ../ elements. If the argument list is empty, JoinPath returns // an empty string. func (ns *Namespace) JoinPath(elements ...any) (string, error) { if len(elements) == 0 { return "", nil } var selements []string for _, e := range elements { switch v := e.(type) { case []string: selements = append(selements, v...) case []any: for _, e := range v { se, err := cast.ToStringE(e) if err != nil { return "", err } selements = append(selements, se) } default: se, err := cast.ToStringE(e) if err != nil { return "", err } selements = append(selements, se) } } result, err := url.JoinPath(selements[0], selements[1:]...) if err != nil { return "", err } return result, nil }
jmooring
065ae003a5dc9173a1200fa1ab2d8927b002b1ab
150d190ff041f7da905afea7f3b9ca6bd4a31a48
I think we should get this behaviour in line with `path.Join` -- just checked, and it returned an empty string in this case.
bep
60
gohugoio/hugo
10,945
tpl: Add math.Abs
Fixes #10941.
null
2023-05-15 09:30:15+00:00
2023-05-16 16:32:07+00:00
tpl/math/math.go
// Copyright 2017 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 math provides template functions for mathematical operations. package math import ( "errors" "math" "sync/atomic" _math "github.com/gohugoio/hugo/common/math" "github.com/spf13/cast" ) var ( errMustTwoNumbersError = errors.New("must provide at least two numbers") ) // New returns a new instance of the math-namespaced template functions. func New() *Namespace { return &Namespace{} } // Namespace provides template functions for the "math" namespace. type Namespace struct{} // Add adds the multivalued addends n1 and n2 or more values. func (ns *Namespace) Add(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '+') } // Ceil returns the least integer value greater than or equal to n. func (ns *Namespace) Ceil(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Ceil operator can't be used with non-float value") } return math.Ceil(xf), nil } // Div divides n1 by n2. func (ns *Namespace) Div(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '/') } // Floor returns the greatest integer value less than or equal to n. func (ns *Namespace) Floor(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Floor operator can't be used with non-float value") } return math.Floor(xf), nil } // Log returns the natural logarithm of the number n. func (ns *Namespace) Log(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Log operator can't be used with non integer or float value") } return math.Log(af), nil } // Max returns the greater of the multivalued numbers n1 and n2 or more values. func (ns *Namespace) Max(inputs ...any) (maximum float64, err error) { if len(inputs) < 2 { err = errMustTwoNumbersError return } var value float64 for index, input := range inputs { value, err = cast.ToFloat64E(input) if err != nil { err = errors.New("Max operator can't be used with non-float value") return } if index == 0 { maximum = value continue } maximum = math.Max(value, maximum) } return } // Min returns the smaller of multivalued numbers n1 and n2 or more values. func (ns *Namespace) Min(inputs ...any) (minimum float64, err error) { if len(inputs) < 2 { err = errMustTwoNumbersError return } var value float64 for index, input := range inputs { value, err = cast.ToFloat64E(input) if err != nil { err = errors.New("Max operator can't be used with non-float value") return } if index == 0 { minimum = value continue } minimum = math.Min(value, minimum) } return } // Mod returns n1 % n2. func (ns *Namespace) Mod(n1, n2 any) (int64, error) { ai, erra := cast.ToInt64E(n1) bi, errb := cast.ToInt64E(n2) if erra != nil || errb != nil { return 0, errors.New("modulo operator can't be used with non integer value") } if bi == 0 { return 0, errors.New("the number can't be divided by zero at modulo operation") } return ai % bi, nil } // ModBool returns the boolean of n1 % n2. If n1 % n2 == 0, return true. func (ns *Namespace) ModBool(n1, n2 any) (bool, error) { res, err := ns.Mod(n1, n2) if err != nil { return false, err } return res == int64(0), nil } // Mul multiplies the multivalued numbers n1 and n2 or more values. func (ns *Namespace) Mul(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '*') } // Pow returns n1 raised to the power of n2. func (ns *Namespace) Pow(n1, n2 any) (float64, error) { af, erra := cast.ToFloat64E(n1) bf, errb := cast.ToFloat64E(n2) if erra != nil || errb != nil { return 0, errors.New("Pow operator can't be used with non-float value") } return math.Pow(af, bf), nil } // Round returns the integer nearest to n, rounding half away from zero. func (ns *Namespace) Round(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Round operator can't be used with non-float value") } return _round(xf), nil } // Sqrt returns the square root of the number n. func (ns *Namespace) Sqrt(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Sqrt operator can't be used with non integer or float value") } return math.Sqrt(af), nil } // Sub subtracts multivalued. func (ns *Namespace) Sub(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '-') } func (ns *Namespace) doArithmetic(inputs []any, operation rune) (value any, err error) { if len(inputs) < 2 { return nil, errMustTwoNumbersError } value = inputs[0] for i := 1; i < len(inputs); i++ { value, err = _math.DoArithmetic(value, inputs[i], operation) if err != nil { return } } return } var counter uint64 // Counter increments and returns a global counter. // This was originally added to be used in tests where now.UnixNano did not // have the needed precision (especially on Windows). // Note that given the parallel nature of Hugo, you cannot use this to get sequences of numbers, // and the counter will reset on new builds. // <docsmeta>{"identifiers": ["now.UnixNano"] }</docsmeta> func (ns *Namespace) Counter() uint64 { return atomic.AddUint64(&counter, uint64(1)) }
// Copyright 2017 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 math provides template functions for mathematical operations. package math import ( "errors" "math" "sync/atomic" _math "github.com/gohugoio/hugo/common/math" "github.com/spf13/cast" ) var ( errMustTwoNumbersError = errors.New("must provide at least two numbers") ) // New returns a new instance of the math-namespaced template functions. func New() *Namespace { return &Namespace{} } // Namespace provides template functions for the "math" namespace. type Namespace struct{} // Abs returns the absolute value of n. func (ns *Namespace) Abs(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("the math.Abs function requires a numeric argument") } return math.Abs(af), nil } // Add adds the multivalued addends n1 and n2 or more values. func (ns *Namespace) Add(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '+') } // Ceil returns the least integer value greater than or equal to n. func (ns *Namespace) Ceil(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Ceil operator can't be used with non-float value") } return math.Ceil(xf), nil } // Div divides n1 by n2. func (ns *Namespace) Div(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '/') } // Floor returns the greatest integer value less than or equal to n. func (ns *Namespace) Floor(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Floor operator can't be used with non-float value") } return math.Floor(xf), nil } // Log returns the natural logarithm of the number n. func (ns *Namespace) Log(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Log operator can't be used with non integer or float value") } return math.Log(af), nil } // Max returns the greater of the multivalued numbers n1 and n2 or more values. func (ns *Namespace) Max(inputs ...any) (maximum float64, err error) { if len(inputs) < 2 { err = errMustTwoNumbersError return } var value float64 for index, input := range inputs { value, err = cast.ToFloat64E(input) if err != nil { err = errors.New("Max operator can't be used with non-float value") return } if index == 0 { maximum = value continue } maximum = math.Max(value, maximum) } return } // Min returns the smaller of multivalued numbers n1 and n2 or more values. func (ns *Namespace) Min(inputs ...any) (minimum float64, err error) { if len(inputs) < 2 { err = errMustTwoNumbersError return } var value float64 for index, input := range inputs { value, err = cast.ToFloat64E(input) if err != nil { err = errors.New("Max operator can't be used with non-float value") return } if index == 0 { minimum = value continue } minimum = math.Min(value, minimum) } return } // Mod returns n1 % n2. func (ns *Namespace) Mod(n1, n2 any) (int64, error) { ai, erra := cast.ToInt64E(n1) bi, errb := cast.ToInt64E(n2) if erra != nil || errb != nil { return 0, errors.New("modulo operator can't be used with non integer value") } if bi == 0 { return 0, errors.New("the number can't be divided by zero at modulo operation") } return ai % bi, nil } // ModBool returns the boolean of n1 % n2. If n1 % n2 == 0, return true. func (ns *Namespace) ModBool(n1, n2 any) (bool, error) { res, err := ns.Mod(n1, n2) if err != nil { return false, err } return res == int64(0), nil } // Mul multiplies the multivalued numbers n1 and n2 or more values. func (ns *Namespace) Mul(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '*') } // Pow returns n1 raised to the power of n2. func (ns *Namespace) Pow(n1, n2 any) (float64, error) { af, erra := cast.ToFloat64E(n1) bf, errb := cast.ToFloat64E(n2) if erra != nil || errb != nil { return 0, errors.New("Pow operator can't be used with non-float value") } return math.Pow(af, bf), nil } // Round returns the integer nearest to n, rounding half away from zero. func (ns *Namespace) Round(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Round operator can't be used with non-float value") } return _round(xf), nil } // Sqrt returns the square root of the number n. func (ns *Namespace) Sqrt(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Sqrt operator can't be used with non integer or float value") } return math.Sqrt(af), nil } // Sub subtracts multivalued. func (ns *Namespace) Sub(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '-') } func (ns *Namespace) doArithmetic(inputs []any, operation rune) (value any, err error) { if len(inputs) < 2 { return nil, errMustTwoNumbersError } value = inputs[0] for i := 1; i < len(inputs); i++ { value, err = _math.DoArithmetic(value, inputs[i], operation) if err != nil { return } } return } var counter uint64 // Counter increments and returns a global counter. // This was originally added to be used in tests where now.UnixNano did not // have the needed precision (especially on Windows). // Note that given the parallel nature of Hugo, you cannot use this to get sequences of numbers, // and the counter will reset on new builds. // <docsmeta>{"identifiers": ["now.UnixNano"] }</docsmeta> func (ns *Namespace) Counter() uint64 { return atomic.AddUint64(&counter, uint64(1)) }
alexandear
241b21b0fd34d91fccb2ce69874110dceae6f926
bda082c98c7a0abdb019f12bb21cbaa7b0e8f60e
```suggestion return 0, errors.New("the math.Abs function requires a numeric argument") ```
jmooring
61
gohugoio/hugo
10,865
postCSS: improve validation of option 'config'
This PR follows up on #10846. It adds validation for the `config` option: if the value given for 'config` is not a directory, a warning is emitted. **With this patch applied:** ``` git clone --single-branch -b hugo-github-issue-10846 https://github.com/jmooring/hugo-testing hugo-github-issue-10846 cd hugo-github-issue-10846 npm ci hugo_0.112.dev Start building sites … hugo v0.112.0-DEV-720f41aab4fa9185957be65c5c7a92261715e297+extended linux/amd64 BuildDate=2023-03-25T20:05:11Z WARN 2023/03/25 21:35:33 found no layout file for "HTML" for kind "home": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2023/03/25 21:35:33 found no layout file for "HTML" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2023/03/25 21:35:33 found no layout file for "HTML" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2023/03/25 21:35:33 postcss config "mydir/postcss.config.js" must be a directory ``` Note the last line with the warning. **Without this patch:** No warning is emitted / no error is thrown.
null
2023-03-25 20:38:34+00:00
2023-05-22 16:14:10+00:00
resources/resource_transformers/postcss/postcss.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 postcss import ( "bytes" "crypto/sha256" "encoding/hex" "fmt" "io" "path" "path/filepath" "regexp" "strconv" "strings" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/internal" "github.com/spf13/afero" "github.com/spf13/cast" "errors" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) const importIdentifier = "@import" var ( cssSyntaxErrorRe = regexp.MustCompile(`> (\d+) \|`) shouldImportRe = regexp.MustCompile(`^@import ["'].*["'];?\s*(/\*.*\*/)?$`) ) // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } func decodeOptions(m map[string]any) (opts Options, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) if !opts.NoMap { // There was for a long time a discrepancy between documentation and // implementation for the noMap property, so we need to support both // camel and snake case. opts.NoMap = cast.ToBool(m["no-map"]) } return } // Client is the client used to do PostCSS transformations. type Client struct { rs *resources.Spec } // Process transforms the given Resource with the PostCSS processor. func (c *Client) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) { return res.Transform(&postcssTransformation{rs: c.rs, optionsm: options}) } // Some of the options from https://github.com/postcss/postcss-cli type Options struct { // Set a custom path to look for a config file. Config string NoMap bool // Disable the default inline sourcemaps // Enable inlining of @import statements. // Does so recursively, but currently once only per file; // that is, it's not possible to import the same file in // different scopes (root, media query...) // Note that this import routine does not care about the CSS spec, // so you can have @import anywhere in the file. InlineImports bool // When InlineImports is enabled, we fail the build if an import cannot be resolved. // You can enable this to allow the build to continue and leave the import statement in place. // Note that the inline importer does not process url location or imports with media queries, // so those will be left as-is even without enabling this option. SkipInlineImportsNotFound bool // Options for when not using a config file Use string // List of postcss plugins to use Parser string // Custom postcss parser Stringifier string // Custom postcss stringifier Syntax string // Custom postcss syntax } func (opts Options) toArgs() []string { var args []string if opts.NoMap { args = append(args, "--no-map") } if opts.Use != "" { args = append(args, "--use") args = append(args, strings.Fields(opts.Use)...) } if opts.Parser != "" { args = append(args, "--parser", opts.Parser) } if opts.Stringifier != "" { args = append(args, "--stringifier", opts.Stringifier) } if opts.Syntax != "" { args = append(args, "--syntax", opts.Syntax) } return args } type postcssTransformation struct { optionsm map[string]any rs *resources.Spec } func (t *postcssTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("postcss", t.optionsm) } // Transform shells out to postcss-cli to do the heavy lifting. // For this to work, you need some additional tools. To install them globally: // npm install -g postcss-cli // npm install -g autoprefixer func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { const binaryName = "postcss" ex := t.rs.ExecHelper var configFile string logger := t.rs.Logger var options Options if t.optionsm != nil { var err error options, err = decodeOptions(t.optionsm) if err != nil { return err } } if options.Config != "" { configFile = options.Config } else { configFile = "postcss.config.js" } configFile = filepath.Clean(configFile) // We need an absolute filename to the config file. if !filepath.IsAbs(configFile) { configFile = t.rs.BaseFs.ResolveJSConfigFile(configFile) if configFile == "" && options.Config != "" { // Only fail if the user specified config file is not found. return fmt.Errorf("postcss config %q not found:", options.Config) } } var cmdArgs []any if configFile != "" { logger.Infoln("postcss: use config file", configFile) cmdArgs = []any{"--config", configFile} } if optArgs := options.toArgs(); len(optArgs) > 0 { cmdArgs = append(cmdArgs, collections.StringSliceToInterfaceSlice(optArgs)...) } var errBuf bytes.Buffer infoW := loggers.LoggerToWriterWithPrefix(logger.Info(), "postcss") stderr := io.MultiWriter(infoW, &errBuf) cmdArgs = append(cmdArgs, hexec.WithStderr(stderr)) cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To)) cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs))) cmd, err := ex.Npx(binaryName, cmdArgs...) if err != nil { if hexec.IsNotFound(err) { // This may be on a CI server etc. Will fall back to pre-built assets. return herrors.ErrFeatureNotAvailable } return err } stdin, err := cmd.StdinPipe() if err != nil { return err } src := ctx.From imp := newImportResolver( ctx.From, ctx.InPath, options, t.rs.Assets.Fs, t.rs.Logger, ) if options.InlineImports { var err error src, err = imp.resolve() if err != nil { return err } } go func() { defer stdin.Close() io.Copy(stdin, src) }() err = cmd.Run() if err != nil { if hexec.IsNotFound(err) { return herrors.ErrFeatureNotAvailable } return imp.toFileError(errBuf.String()) } return nil } type fileOffset struct { Filename string Offset int } type importResolver struct { r io.Reader inPath string opts Options contentSeen map[string]bool linemap map[int]fileOffset fs afero.Fs logger loggers.Logger } func newImportResolver(r io.Reader, inPath string, opts Options, fs afero.Fs, logger loggers.Logger) *importResolver { return &importResolver{ r: r, inPath: inPath, fs: fs, logger: logger, linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool), opts: opts, } } func (imp *importResolver) contentHash(filename string) ([]byte, string) { b, err := afero.ReadFile(imp.fs, filename) if err != nil { return nil, "" } h := sha256.New() h.Write(b) return b, hex.EncodeToString(h.Sum(nil)) } func (imp *importResolver) importRecursive( lineNum int, content string, inPath string) (int, string, error) { basePath := path.Dir(inPath) var replacements []string lines := strings.Split(content, "\n") trackLine := func(i, offset int, line string) { // TODO(bep) this is not very efficient. imp.linemap[i+lineNum] = fileOffset{Filename: inPath, Offset: offset} } i := 0 for offset, line := range lines { i++ lineTrimmed := strings.TrimSpace(line) column := strings.Index(line, lineTrimmed) line = lineTrimmed if !imp.shouldImport(line) { trackLine(i, offset, line) } else { path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';") filename := filepath.Join(basePath, path) importContent, hash := imp.contentHash(filename) if importContent == nil { if imp.opts.SkipInlineImportsNotFound { trackLine(i, offset, line) continue } pos := text.Position{ Filename: inPath, LineNumber: offset + 1, ColumnNumber: column + 1, } return 0, "", herrors.NewFileErrorFromFileInPos(fmt.Errorf("failed to resolve CSS @import \"%s\"", filename), pos, imp.fs, nil) } i-- if imp.contentSeen[hash] { i++ // Just replace the line with an empty string. replacements = append(replacements, []string{line, ""}...) trackLine(i, offset, "IMPORT") continue } imp.contentSeen[hash] = true // Handle recursive imports. l, nested, err := imp.importRecursive(i+lineNum, string(importContent), filepath.ToSlash(filename)) if err != nil { return 0, "", err } trackLine(i, offset, line) i += l importContent = []byte(nested) replacements = append(replacements, []string{line, string(importContent)}...) } } if len(replacements) > 0 { repl := strings.NewReplacer(replacements...) content = repl.Replace(content) } return i, content, nil } func (imp *importResolver) resolve() (io.Reader, error) { const importIdentifier = "@import" content, err := io.ReadAll(imp.r) if err != nil { return nil, err } contents := string(content) _, newContent, err := imp.importRecursive(0, contents, imp.inPath) if err != nil { return nil, err } return strings.NewReader(newContent), nil } // See https://www.w3schools.com/cssref/pr_import_rule.asp // We currently only support simple file imports, no urls, no media queries. // So this is OK: // // @import "navigation.css"; // // This is not: // // @import url("navigation.css"); // @import "mobstyle.css" screen and (max-width: 768px); func (imp *importResolver) shouldImport(s string) bool { if !strings.HasPrefix(s, importIdentifier) { return false } if strings.Contains(s, "url(") { return false } return shouldImportRe.MatchString(s) } func (imp *importResolver) toFileError(output string) error { output = strings.TrimSpace(loggers.RemoveANSIColours(output)) inErr := errors.New(output) match := cssSyntaxErrorRe.FindStringSubmatch(output) if match == nil { return inErr } lineNum, err := strconv.Atoi(match[1]) if err != nil { return inErr } file, ok := imp.linemap[lineNum] if !ok { return inErr } fi, err := imp.fs.Stat(file.Filename) if err != nil { return inErr } meta := fi.(hugofs.FileMetaInfo).Meta() realFilename := meta.Filename f, err := meta.Open() if err != nil { return inErr } defer f.Close() ferr := herrors.NewFileErrorFromName(inErr, realFilename) pos := ferr.Position() pos.LineNumber = file.Offset + 1 return ferr.UpdatePosition(pos).UpdateContent(f, nil) //return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher) }
// 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 postcss import ( "bytes" "crypto/sha256" "encoding/hex" "fmt" "io" "path" "path/filepath" "regexp" "strconv" "strings" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/internal" "github.com/spf13/afero" "github.com/spf13/cast" "errors" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) const importIdentifier = "@import" var ( cssSyntaxErrorRe = regexp.MustCompile(`> (\d+) \|`) shouldImportRe = regexp.MustCompile(`^@import ["'].*["'];?\s*(/\*.*\*/)?$`) ) // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } func decodeOptions(m map[string]any) (opts Options, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) if !opts.NoMap { // There was for a long time a discrepancy between documentation and // implementation for the noMap property, so we need to support both // camel and snake case. opts.NoMap = cast.ToBool(m["no-map"]) } return } // Client is the client used to do PostCSS transformations. type Client struct { rs *resources.Spec } // Process transforms the given Resource with the PostCSS processor. func (c *Client) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) { return res.Transform(&postcssTransformation{rs: c.rs, optionsm: options}) } // Some of the options from https://github.com/postcss/postcss-cli type Options struct { // Set a custom path to look for a config file. Config string NoMap bool // Disable the default inline sourcemaps // Enable inlining of @import statements. // Does so recursively, but currently once only per file; // that is, it's not possible to import the same file in // different scopes (root, media query...) // Note that this import routine does not care about the CSS spec, // so you can have @import anywhere in the file. InlineImports bool // When InlineImports is enabled, we fail the build if an import cannot be resolved. // You can enable this to allow the build to continue and leave the import statement in place. // Note that the inline importer does not process url location or imports with media queries, // so those will be left as-is even without enabling this option. SkipInlineImportsNotFound bool // Options for when not using a config file Use string // List of postcss plugins to use Parser string // Custom postcss parser Stringifier string // Custom postcss stringifier Syntax string // Custom postcss syntax } func (opts Options) toArgs() []string { var args []string if opts.NoMap { args = append(args, "--no-map") } if opts.Use != "" { args = append(args, "--use") args = append(args, strings.Fields(opts.Use)...) } if opts.Parser != "" { args = append(args, "--parser", opts.Parser) } if opts.Stringifier != "" { args = append(args, "--stringifier", opts.Stringifier) } if opts.Syntax != "" { args = append(args, "--syntax", opts.Syntax) } return args } type postcssTransformation struct { optionsm map[string]any rs *resources.Spec } func (t *postcssTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("postcss", t.optionsm) } // Transform shells out to postcss-cli to do the heavy lifting. // For this to work, you need some additional tools. To install them globally: // npm install -g postcss-cli // npm install -g autoprefixer func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { const binaryName = "postcss" ex := t.rs.ExecHelper var configFile string logger := t.rs.Logger var options Options if t.optionsm != nil { var err error options, err = decodeOptions(t.optionsm) if err != nil { return err } } if options.Config != "" { configFile = options.Config } else { configFile = "postcss.config.js" } configFile = filepath.Clean(configFile) isConfigFileDir := false // We need an absolute filename to the config file. if !filepath.IsAbs(configFile) { configFile, isConfigFileDir = t.rs.BaseFs.ResolveJSConfigFile(configFile) if configFile == "" && options.Config != "" { // Only fail if the user specified config file is not found. return fmt.Errorf("postcss config directory %q not found", options.Config) } if !isConfigFileDir { logger.Warnf("postcss config %q must be a directory", options.Config) } } var cmdArgs []any if configFile != "" { logger.Infoln("postcss: use config file", configFile) cmdArgs = []any{"--config", configFile} } if optArgs := options.toArgs(); len(optArgs) > 0 { cmdArgs = append(cmdArgs, collections.StringSliceToInterfaceSlice(optArgs)...) } var errBuf bytes.Buffer infoW := loggers.LoggerToWriterWithPrefix(logger.Info(), "postcss") stderr := io.MultiWriter(infoW, &errBuf) cmdArgs = append(cmdArgs, hexec.WithStderr(stderr)) cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To)) cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs))) cmd, err := ex.Npx(binaryName, cmdArgs...) if err != nil { if hexec.IsNotFound(err) { // This may be on a CI server etc. Will fall back to pre-built assets. return herrors.ErrFeatureNotAvailable } return err } stdin, err := cmd.StdinPipe() if err != nil { return err } src := ctx.From imp := newImportResolver( ctx.From, ctx.InPath, options, t.rs.Assets.Fs, t.rs.Logger, ) if options.InlineImports { var err error src, err = imp.resolve() if err != nil { return err } } go func() { defer stdin.Close() io.Copy(stdin, src) }() err = cmd.Run() if err != nil { if hexec.IsNotFound(err) { return herrors.ErrFeatureNotAvailable } return imp.toFileError(errBuf.String()) } return nil } type fileOffset struct { Filename string Offset int } type importResolver struct { r io.Reader inPath string opts Options contentSeen map[string]bool linemap map[int]fileOffset fs afero.Fs logger loggers.Logger } func newImportResolver(r io.Reader, inPath string, opts Options, fs afero.Fs, logger loggers.Logger) *importResolver { return &importResolver{ r: r, inPath: inPath, fs: fs, logger: logger, linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool), opts: opts, } } func (imp *importResolver) contentHash(filename string) ([]byte, string) { b, err := afero.ReadFile(imp.fs, filename) if err != nil { return nil, "" } h := sha256.New() h.Write(b) return b, hex.EncodeToString(h.Sum(nil)) } func (imp *importResolver) importRecursive( lineNum int, content string, inPath string) (int, string, error) { basePath := path.Dir(inPath) var replacements []string lines := strings.Split(content, "\n") trackLine := func(i, offset int, line string) { // TODO(bep) this is not very efficient. imp.linemap[i+lineNum] = fileOffset{Filename: inPath, Offset: offset} } i := 0 for offset, line := range lines { i++ lineTrimmed := strings.TrimSpace(line) column := strings.Index(line, lineTrimmed) line = lineTrimmed if !imp.shouldImport(line) { trackLine(i, offset, line) } else { path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';") filename := filepath.Join(basePath, path) importContent, hash := imp.contentHash(filename) if importContent == nil { if imp.opts.SkipInlineImportsNotFound { trackLine(i, offset, line) continue } pos := text.Position{ Filename: inPath, LineNumber: offset + 1, ColumnNumber: column + 1, } return 0, "", herrors.NewFileErrorFromFileInPos(fmt.Errorf("failed to resolve CSS @import \"%s\"", filename), pos, imp.fs, nil) } i-- if imp.contentSeen[hash] { i++ // Just replace the line with an empty string. replacements = append(replacements, []string{line, ""}...) trackLine(i, offset, "IMPORT") continue } imp.contentSeen[hash] = true // Handle recursive imports. l, nested, err := imp.importRecursive(i+lineNum, string(importContent), filepath.ToSlash(filename)) if err != nil { return 0, "", err } trackLine(i, offset, line) i += l importContent = []byte(nested) replacements = append(replacements, []string{line, string(importContent)}...) } } if len(replacements) > 0 { repl := strings.NewReplacer(replacements...) content = repl.Replace(content) } return i, content, nil } func (imp *importResolver) resolve() (io.Reader, error) { const importIdentifier = "@import" content, err := io.ReadAll(imp.r) if err != nil { return nil, err } contents := string(content) _, newContent, err := imp.importRecursive(0, contents, imp.inPath) if err != nil { return nil, err } return strings.NewReader(newContent), nil } // See https://www.w3schools.com/cssref/pr_import_rule.asp // We currently only support simple file imports, no urls, no media queries. // So this is OK: // // @import "navigation.css"; // // This is not: // // @import url("navigation.css"); // @import "mobstyle.css" screen and (max-width: 768px); func (imp *importResolver) shouldImport(s string) bool { if !strings.HasPrefix(s, importIdentifier) { return false } if strings.Contains(s, "url(") { return false } return shouldImportRe.MatchString(s) } func (imp *importResolver) toFileError(output string) error { output = strings.TrimSpace(loggers.RemoveANSIColours(output)) inErr := errors.New(output) match := cssSyntaxErrorRe.FindStringSubmatch(output) if match == nil { return inErr } lineNum, err := strconv.Atoi(match[1]) if err != nil { return inErr } file, ok := imp.linemap[lineNum] if !ok { return inErr } fi, err := imp.fs.Stat(file.Filename) if err != nil { return inErr } meta := fi.(hugofs.FileMetaInfo).Meta() realFilename := meta.Filename f, err := meta.Open() if err != nil { return inErr } defer f.Close() ferr := herrors.NewFileErrorFromName(inErr, realFilename) pos := ferr.Position() pos.LineNumber = file.Offset + 1 return ferr.UpdatePosition(pos).UpdateContent(f, nil) //return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher) }
deining
10d0fcc01f77b1edad16fbdd415825731f7419fb
9a0370e8eb71fed3ac04984020b6aa95c43f22ab
I guess these lines shouldn't be changed
alexandear
62
gohugoio/hugo
10,865
postCSS: improve validation of option 'config'
This PR follows up on #10846. It adds validation for the `config` option: if the value given for 'config` is not a directory, a warning is emitted. **With this patch applied:** ``` git clone --single-branch -b hugo-github-issue-10846 https://github.com/jmooring/hugo-testing hugo-github-issue-10846 cd hugo-github-issue-10846 npm ci hugo_0.112.dev Start building sites … hugo v0.112.0-DEV-720f41aab4fa9185957be65c5c7a92261715e297+extended linux/amd64 BuildDate=2023-03-25T20:05:11Z WARN 2023/03/25 21:35:33 found no layout file for "HTML" for kind "home": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2023/03/25 21:35:33 found no layout file for "HTML" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2023/03/25 21:35:33 found no layout file for "HTML" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2023/03/25 21:35:33 postcss config "mydir/postcss.config.js" must be a directory ``` Note the last line with the warning. **Without this patch:** No warning is emitted / no error is thrown.
null
2023-03-25 20:38:34+00:00
2023-05-22 16:14:10+00:00
resources/resource_transformers/postcss/postcss.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 postcss import ( "bytes" "crypto/sha256" "encoding/hex" "fmt" "io" "path" "path/filepath" "regexp" "strconv" "strings" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/internal" "github.com/spf13/afero" "github.com/spf13/cast" "errors" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) const importIdentifier = "@import" var ( cssSyntaxErrorRe = regexp.MustCompile(`> (\d+) \|`) shouldImportRe = regexp.MustCompile(`^@import ["'].*["'];?\s*(/\*.*\*/)?$`) ) // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } func decodeOptions(m map[string]any) (opts Options, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) if !opts.NoMap { // There was for a long time a discrepancy between documentation and // implementation for the noMap property, so we need to support both // camel and snake case. opts.NoMap = cast.ToBool(m["no-map"]) } return } // Client is the client used to do PostCSS transformations. type Client struct { rs *resources.Spec } // Process transforms the given Resource with the PostCSS processor. func (c *Client) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) { return res.Transform(&postcssTransformation{rs: c.rs, optionsm: options}) } // Some of the options from https://github.com/postcss/postcss-cli type Options struct { // Set a custom path to look for a config file. Config string NoMap bool // Disable the default inline sourcemaps // Enable inlining of @import statements. // Does so recursively, but currently once only per file; // that is, it's not possible to import the same file in // different scopes (root, media query...) // Note that this import routine does not care about the CSS spec, // so you can have @import anywhere in the file. InlineImports bool // When InlineImports is enabled, we fail the build if an import cannot be resolved. // You can enable this to allow the build to continue and leave the import statement in place. // Note that the inline importer does not process url location or imports with media queries, // so those will be left as-is even without enabling this option. SkipInlineImportsNotFound bool // Options for when not using a config file Use string // List of postcss plugins to use Parser string // Custom postcss parser Stringifier string // Custom postcss stringifier Syntax string // Custom postcss syntax } func (opts Options) toArgs() []string { var args []string if opts.NoMap { args = append(args, "--no-map") } if opts.Use != "" { args = append(args, "--use") args = append(args, strings.Fields(opts.Use)...) } if opts.Parser != "" { args = append(args, "--parser", opts.Parser) } if opts.Stringifier != "" { args = append(args, "--stringifier", opts.Stringifier) } if opts.Syntax != "" { args = append(args, "--syntax", opts.Syntax) } return args } type postcssTransformation struct { optionsm map[string]any rs *resources.Spec } func (t *postcssTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("postcss", t.optionsm) } // Transform shells out to postcss-cli to do the heavy lifting. // For this to work, you need some additional tools. To install them globally: // npm install -g postcss-cli // npm install -g autoprefixer func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { const binaryName = "postcss" ex := t.rs.ExecHelper var configFile string logger := t.rs.Logger var options Options if t.optionsm != nil { var err error options, err = decodeOptions(t.optionsm) if err != nil { return err } } if options.Config != "" { configFile = options.Config } else { configFile = "postcss.config.js" } configFile = filepath.Clean(configFile) // We need an absolute filename to the config file. if !filepath.IsAbs(configFile) { configFile = t.rs.BaseFs.ResolveJSConfigFile(configFile) if configFile == "" && options.Config != "" { // Only fail if the user specified config file is not found. return fmt.Errorf("postcss config %q not found:", options.Config) } } var cmdArgs []any if configFile != "" { logger.Infoln("postcss: use config file", configFile) cmdArgs = []any{"--config", configFile} } if optArgs := options.toArgs(); len(optArgs) > 0 { cmdArgs = append(cmdArgs, collections.StringSliceToInterfaceSlice(optArgs)...) } var errBuf bytes.Buffer infoW := loggers.LoggerToWriterWithPrefix(logger.Info(), "postcss") stderr := io.MultiWriter(infoW, &errBuf) cmdArgs = append(cmdArgs, hexec.WithStderr(stderr)) cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To)) cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs))) cmd, err := ex.Npx(binaryName, cmdArgs...) if err != nil { if hexec.IsNotFound(err) { // This may be on a CI server etc. Will fall back to pre-built assets. return herrors.ErrFeatureNotAvailable } return err } stdin, err := cmd.StdinPipe() if err != nil { return err } src := ctx.From imp := newImportResolver( ctx.From, ctx.InPath, options, t.rs.Assets.Fs, t.rs.Logger, ) if options.InlineImports { var err error src, err = imp.resolve() if err != nil { return err } } go func() { defer stdin.Close() io.Copy(stdin, src) }() err = cmd.Run() if err != nil { if hexec.IsNotFound(err) { return herrors.ErrFeatureNotAvailable } return imp.toFileError(errBuf.String()) } return nil } type fileOffset struct { Filename string Offset int } type importResolver struct { r io.Reader inPath string opts Options contentSeen map[string]bool linemap map[int]fileOffset fs afero.Fs logger loggers.Logger } func newImportResolver(r io.Reader, inPath string, opts Options, fs afero.Fs, logger loggers.Logger) *importResolver { return &importResolver{ r: r, inPath: inPath, fs: fs, logger: logger, linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool), opts: opts, } } func (imp *importResolver) contentHash(filename string) ([]byte, string) { b, err := afero.ReadFile(imp.fs, filename) if err != nil { return nil, "" } h := sha256.New() h.Write(b) return b, hex.EncodeToString(h.Sum(nil)) } func (imp *importResolver) importRecursive( lineNum int, content string, inPath string) (int, string, error) { basePath := path.Dir(inPath) var replacements []string lines := strings.Split(content, "\n") trackLine := func(i, offset int, line string) { // TODO(bep) this is not very efficient. imp.linemap[i+lineNum] = fileOffset{Filename: inPath, Offset: offset} } i := 0 for offset, line := range lines { i++ lineTrimmed := strings.TrimSpace(line) column := strings.Index(line, lineTrimmed) line = lineTrimmed if !imp.shouldImport(line) { trackLine(i, offset, line) } else { path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';") filename := filepath.Join(basePath, path) importContent, hash := imp.contentHash(filename) if importContent == nil { if imp.opts.SkipInlineImportsNotFound { trackLine(i, offset, line) continue } pos := text.Position{ Filename: inPath, LineNumber: offset + 1, ColumnNumber: column + 1, } return 0, "", herrors.NewFileErrorFromFileInPos(fmt.Errorf("failed to resolve CSS @import \"%s\"", filename), pos, imp.fs, nil) } i-- if imp.contentSeen[hash] { i++ // Just replace the line with an empty string. replacements = append(replacements, []string{line, ""}...) trackLine(i, offset, "IMPORT") continue } imp.contentSeen[hash] = true // Handle recursive imports. l, nested, err := imp.importRecursive(i+lineNum, string(importContent), filepath.ToSlash(filename)) if err != nil { return 0, "", err } trackLine(i, offset, line) i += l importContent = []byte(nested) replacements = append(replacements, []string{line, string(importContent)}...) } } if len(replacements) > 0 { repl := strings.NewReplacer(replacements...) content = repl.Replace(content) } return i, content, nil } func (imp *importResolver) resolve() (io.Reader, error) { const importIdentifier = "@import" content, err := io.ReadAll(imp.r) if err != nil { return nil, err } contents := string(content) _, newContent, err := imp.importRecursive(0, contents, imp.inPath) if err != nil { return nil, err } return strings.NewReader(newContent), nil } // See https://www.w3schools.com/cssref/pr_import_rule.asp // We currently only support simple file imports, no urls, no media queries. // So this is OK: // // @import "navigation.css"; // // This is not: // // @import url("navigation.css"); // @import "mobstyle.css" screen and (max-width: 768px); func (imp *importResolver) shouldImport(s string) bool { if !strings.HasPrefix(s, importIdentifier) { return false } if strings.Contains(s, "url(") { return false } return shouldImportRe.MatchString(s) } func (imp *importResolver) toFileError(output string) error { output = strings.TrimSpace(loggers.RemoveANSIColours(output)) inErr := errors.New(output) match := cssSyntaxErrorRe.FindStringSubmatch(output) if match == nil { return inErr } lineNum, err := strconv.Atoi(match[1]) if err != nil { return inErr } file, ok := imp.linemap[lineNum] if !ok { return inErr } fi, err := imp.fs.Stat(file.Filename) if err != nil { return inErr } meta := fi.(hugofs.FileMetaInfo).Meta() realFilename := meta.Filename f, err := meta.Open() if err != nil { return inErr } defer f.Close() ferr := herrors.NewFileErrorFromName(inErr, realFilename) pos := ferr.Position() pos.LineNumber = file.Offset + 1 return ferr.UpdatePosition(pos).UpdateContent(f, nil) //return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher) }
// 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 postcss import ( "bytes" "crypto/sha256" "encoding/hex" "fmt" "io" "path" "path/filepath" "regexp" "strconv" "strings" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/internal" "github.com/spf13/afero" "github.com/spf13/cast" "errors" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) const importIdentifier = "@import" var ( cssSyntaxErrorRe = regexp.MustCompile(`> (\d+) \|`) shouldImportRe = regexp.MustCompile(`^@import ["'].*["'];?\s*(/\*.*\*/)?$`) ) // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } func decodeOptions(m map[string]any) (opts Options, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) if !opts.NoMap { // There was for a long time a discrepancy between documentation and // implementation for the noMap property, so we need to support both // camel and snake case. opts.NoMap = cast.ToBool(m["no-map"]) } return } // Client is the client used to do PostCSS transformations. type Client struct { rs *resources.Spec } // Process transforms the given Resource with the PostCSS processor. func (c *Client) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) { return res.Transform(&postcssTransformation{rs: c.rs, optionsm: options}) } // Some of the options from https://github.com/postcss/postcss-cli type Options struct { // Set a custom path to look for a config file. Config string NoMap bool // Disable the default inline sourcemaps // Enable inlining of @import statements. // Does so recursively, but currently once only per file; // that is, it's not possible to import the same file in // different scopes (root, media query...) // Note that this import routine does not care about the CSS spec, // so you can have @import anywhere in the file. InlineImports bool // When InlineImports is enabled, we fail the build if an import cannot be resolved. // You can enable this to allow the build to continue and leave the import statement in place. // Note that the inline importer does not process url location or imports with media queries, // so those will be left as-is even without enabling this option. SkipInlineImportsNotFound bool // Options for when not using a config file Use string // List of postcss plugins to use Parser string // Custom postcss parser Stringifier string // Custom postcss stringifier Syntax string // Custom postcss syntax } func (opts Options) toArgs() []string { var args []string if opts.NoMap { args = append(args, "--no-map") } if opts.Use != "" { args = append(args, "--use") args = append(args, strings.Fields(opts.Use)...) } if opts.Parser != "" { args = append(args, "--parser", opts.Parser) } if opts.Stringifier != "" { args = append(args, "--stringifier", opts.Stringifier) } if opts.Syntax != "" { args = append(args, "--syntax", opts.Syntax) } return args } type postcssTransformation struct { optionsm map[string]any rs *resources.Spec } func (t *postcssTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("postcss", t.optionsm) } // Transform shells out to postcss-cli to do the heavy lifting. // For this to work, you need some additional tools. To install them globally: // npm install -g postcss-cli // npm install -g autoprefixer func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { const binaryName = "postcss" ex := t.rs.ExecHelper var configFile string logger := t.rs.Logger var options Options if t.optionsm != nil { var err error options, err = decodeOptions(t.optionsm) if err != nil { return err } } if options.Config != "" { configFile = options.Config } else { configFile = "postcss.config.js" } configFile = filepath.Clean(configFile) isConfigFileDir := false // We need an absolute filename to the config file. if !filepath.IsAbs(configFile) { configFile, isConfigFileDir = t.rs.BaseFs.ResolveJSConfigFile(configFile) if configFile == "" && options.Config != "" { // Only fail if the user specified config file is not found. return fmt.Errorf("postcss config directory %q not found", options.Config) } if !isConfigFileDir { logger.Warnf("postcss config %q must be a directory", options.Config) } } var cmdArgs []any if configFile != "" { logger.Infoln("postcss: use config file", configFile) cmdArgs = []any{"--config", configFile} } if optArgs := options.toArgs(); len(optArgs) > 0 { cmdArgs = append(cmdArgs, collections.StringSliceToInterfaceSlice(optArgs)...) } var errBuf bytes.Buffer infoW := loggers.LoggerToWriterWithPrefix(logger.Info(), "postcss") stderr := io.MultiWriter(infoW, &errBuf) cmdArgs = append(cmdArgs, hexec.WithStderr(stderr)) cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To)) cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs))) cmd, err := ex.Npx(binaryName, cmdArgs...) if err != nil { if hexec.IsNotFound(err) { // This may be on a CI server etc. Will fall back to pre-built assets. return herrors.ErrFeatureNotAvailable } return err } stdin, err := cmd.StdinPipe() if err != nil { return err } src := ctx.From imp := newImportResolver( ctx.From, ctx.InPath, options, t.rs.Assets.Fs, t.rs.Logger, ) if options.InlineImports { var err error src, err = imp.resolve() if err != nil { return err } } go func() { defer stdin.Close() io.Copy(stdin, src) }() err = cmd.Run() if err != nil { if hexec.IsNotFound(err) { return herrors.ErrFeatureNotAvailable } return imp.toFileError(errBuf.String()) } return nil } type fileOffset struct { Filename string Offset int } type importResolver struct { r io.Reader inPath string opts Options contentSeen map[string]bool linemap map[int]fileOffset fs afero.Fs logger loggers.Logger } func newImportResolver(r io.Reader, inPath string, opts Options, fs afero.Fs, logger loggers.Logger) *importResolver { return &importResolver{ r: r, inPath: inPath, fs: fs, logger: logger, linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool), opts: opts, } } func (imp *importResolver) contentHash(filename string) ([]byte, string) { b, err := afero.ReadFile(imp.fs, filename) if err != nil { return nil, "" } h := sha256.New() h.Write(b) return b, hex.EncodeToString(h.Sum(nil)) } func (imp *importResolver) importRecursive( lineNum int, content string, inPath string) (int, string, error) { basePath := path.Dir(inPath) var replacements []string lines := strings.Split(content, "\n") trackLine := func(i, offset int, line string) { // TODO(bep) this is not very efficient. imp.linemap[i+lineNum] = fileOffset{Filename: inPath, Offset: offset} } i := 0 for offset, line := range lines { i++ lineTrimmed := strings.TrimSpace(line) column := strings.Index(line, lineTrimmed) line = lineTrimmed if !imp.shouldImport(line) { trackLine(i, offset, line) } else { path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';") filename := filepath.Join(basePath, path) importContent, hash := imp.contentHash(filename) if importContent == nil { if imp.opts.SkipInlineImportsNotFound { trackLine(i, offset, line) continue } pos := text.Position{ Filename: inPath, LineNumber: offset + 1, ColumnNumber: column + 1, } return 0, "", herrors.NewFileErrorFromFileInPos(fmt.Errorf("failed to resolve CSS @import \"%s\"", filename), pos, imp.fs, nil) } i-- if imp.contentSeen[hash] { i++ // Just replace the line with an empty string. replacements = append(replacements, []string{line, ""}...) trackLine(i, offset, "IMPORT") continue } imp.contentSeen[hash] = true // Handle recursive imports. l, nested, err := imp.importRecursive(i+lineNum, string(importContent), filepath.ToSlash(filename)) if err != nil { return 0, "", err } trackLine(i, offset, line) i += l importContent = []byte(nested) replacements = append(replacements, []string{line, string(importContent)}...) } } if len(replacements) > 0 { repl := strings.NewReplacer(replacements...) content = repl.Replace(content) } return i, content, nil } func (imp *importResolver) resolve() (io.Reader, error) { const importIdentifier = "@import" content, err := io.ReadAll(imp.r) if err != nil { return nil, err } contents := string(content) _, newContent, err := imp.importRecursive(0, contents, imp.inPath) if err != nil { return nil, err } return strings.NewReader(newContent), nil } // See https://www.w3schools.com/cssref/pr_import_rule.asp // We currently only support simple file imports, no urls, no media queries. // So this is OK: // // @import "navigation.css"; // // This is not: // // @import url("navigation.css"); // @import "mobstyle.css" screen and (max-width: 768px); func (imp *importResolver) shouldImport(s string) bool { if !strings.HasPrefix(s, importIdentifier) { return false } if strings.Contains(s, "url(") { return false } return shouldImportRe.MatchString(s) } func (imp *importResolver) toFileError(output string) error { output = strings.TrimSpace(loggers.RemoveANSIColours(output)) inErr := errors.New(output) match := cssSyntaxErrorRe.FindStringSubmatch(output) if match == nil { return inErr } lineNum, err := strconv.Atoi(match[1]) if err != nil { return inErr } file, ok := imp.linemap[lineNum] if !ok { return inErr } fi, err := imp.fs.Stat(file.Filename) if err != nil { return inErr } meta := fi.(hugofs.FileMetaInfo).Meta() realFilename := meta.Filename f, err := meta.Open() if err != nil { return inErr } defer f.Close() ferr := herrors.NewFileErrorFromName(inErr, realFilename) pos := ferr.Position() pos.LineNumber = file.Offset + 1 return ferr.UpdatePosition(pos).UpdateContent(f, nil) //return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher) }
deining
10d0fcc01f77b1edad16fbdd415825731f7419fb
9a0370e8eb71fed3ac04984020b6aa95c43f22ab
I guess, but it's not the end of the world. I assume this comes from a `go fmt` -- which is odd.
bep
63
gohugoio/hugo
10,865
postCSS: improve validation of option 'config'
This PR follows up on #10846. It adds validation for the `config` option: if the value given for 'config` is not a directory, a warning is emitted. **With this patch applied:** ``` git clone --single-branch -b hugo-github-issue-10846 https://github.com/jmooring/hugo-testing hugo-github-issue-10846 cd hugo-github-issue-10846 npm ci hugo_0.112.dev Start building sites … hugo v0.112.0-DEV-720f41aab4fa9185957be65c5c7a92261715e297+extended linux/amd64 BuildDate=2023-03-25T20:05:11Z WARN 2023/03/25 21:35:33 found no layout file for "HTML" for kind "home": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2023/03/25 21:35:33 found no layout file for "HTML" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2023/03/25 21:35:33 found no layout file for "HTML" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2023/03/25 21:35:33 postcss config "mydir/postcss.config.js" must be a directory ``` Note the last line with the warning. **Without this patch:** No warning is emitted / no error is thrown.
null
2023-03-25 20:38:34+00:00
2023-05-22 16:14:10+00:00
resources/resource_transformers/postcss/postcss.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 postcss import ( "bytes" "crypto/sha256" "encoding/hex" "fmt" "io" "path" "path/filepath" "regexp" "strconv" "strings" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/internal" "github.com/spf13/afero" "github.com/spf13/cast" "errors" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) const importIdentifier = "@import" var ( cssSyntaxErrorRe = regexp.MustCompile(`> (\d+) \|`) shouldImportRe = regexp.MustCompile(`^@import ["'].*["'];?\s*(/\*.*\*/)?$`) ) // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } func decodeOptions(m map[string]any) (opts Options, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) if !opts.NoMap { // There was for a long time a discrepancy between documentation and // implementation for the noMap property, so we need to support both // camel and snake case. opts.NoMap = cast.ToBool(m["no-map"]) } return } // Client is the client used to do PostCSS transformations. type Client struct { rs *resources.Spec } // Process transforms the given Resource with the PostCSS processor. func (c *Client) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) { return res.Transform(&postcssTransformation{rs: c.rs, optionsm: options}) } // Some of the options from https://github.com/postcss/postcss-cli type Options struct { // Set a custom path to look for a config file. Config string NoMap bool // Disable the default inline sourcemaps // Enable inlining of @import statements. // Does so recursively, but currently once only per file; // that is, it's not possible to import the same file in // different scopes (root, media query...) // Note that this import routine does not care about the CSS spec, // so you can have @import anywhere in the file. InlineImports bool // When InlineImports is enabled, we fail the build if an import cannot be resolved. // You can enable this to allow the build to continue and leave the import statement in place. // Note that the inline importer does not process url location or imports with media queries, // so those will be left as-is even without enabling this option. SkipInlineImportsNotFound bool // Options for when not using a config file Use string // List of postcss plugins to use Parser string // Custom postcss parser Stringifier string // Custom postcss stringifier Syntax string // Custom postcss syntax } func (opts Options) toArgs() []string { var args []string if opts.NoMap { args = append(args, "--no-map") } if opts.Use != "" { args = append(args, "--use") args = append(args, strings.Fields(opts.Use)...) } if opts.Parser != "" { args = append(args, "--parser", opts.Parser) } if opts.Stringifier != "" { args = append(args, "--stringifier", opts.Stringifier) } if opts.Syntax != "" { args = append(args, "--syntax", opts.Syntax) } return args } type postcssTransformation struct { optionsm map[string]any rs *resources.Spec } func (t *postcssTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("postcss", t.optionsm) } // Transform shells out to postcss-cli to do the heavy lifting. // For this to work, you need some additional tools. To install them globally: // npm install -g postcss-cli // npm install -g autoprefixer func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { const binaryName = "postcss" ex := t.rs.ExecHelper var configFile string logger := t.rs.Logger var options Options if t.optionsm != nil { var err error options, err = decodeOptions(t.optionsm) if err != nil { return err } } if options.Config != "" { configFile = options.Config } else { configFile = "postcss.config.js" } configFile = filepath.Clean(configFile) // We need an absolute filename to the config file. if !filepath.IsAbs(configFile) { configFile = t.rs.BaseFs.ResolveJSConfigFile(configFile) if configFile == "" && options.Config != "" { // Only fail if the user specified config file is not found. return fmt.Errorf("postcss config %q not found:", options.Config) } } var cmdArgs []any if configFile != "" { logger.Infoln("postcss: use config file", configFile) cmdArgs = []any{"--config", configFile} } if optArgs := options.toArgs(); len(optArgs) > 0 { cmdArgs = append(cmdArgs, collections.StringSliceToInterfaceSlice(optArgs)...) } var errBuf bytes.Buffer infoW := loggers.LoggerToWriterWithPrefix(logger.Info(), "postcss") stderr := io.MultiWriter(infoW, &errBuf) cmdArgs = append(cmdArgs, hexec.WithStderr(stderr)) cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To)) cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs))) cmd, err := ex.Npx(binaryName, cmdArgs...) if err != nil { if hexec.IsNotFound(err) { // This may be on a CI server etc. Will fall back to pre-built assets. return herrors.ErrFeatureNotAvailable } return err } stdin, err := cmd.StdinPipe() if err != nil { return err } src := ctx.From imp := newImportResolver( ctx.From, ctx.InPath, options, t.rs.Assets.Fs, t.rs.Logger, ) if options.InlineImports { var err error src, err = imp.resolve() if err != nil { return err } } go func() { defer stdin.Close() io.Copy(stdin, src) }() err = cmd.Run() if err != nil { if hexec.IsNotFound(err) { return herrors.ErrFeatureNotAvailable } return imp.toFileError(errBuf.String()) } return nil } type fileOffset struct { Filename string Offset int } type importResolver struct { r io.Reader inPath string opts Options contentSeen map[string]bool linemap map[int]fileOffset fs afero.Fs logger loggers.Logger } func newImportResolver(r io.Reader, inPath string, opts Options, fs afero.Fs, logger loggers.Logger) *importResolver { return &importResolver{ r: r, inPath: inPath, fs: fs, logger: logger, linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool), opts: opts, } } func (imp *importResolver) contentHash(filename string) ([]byte, string) { b, err := afero.ReadFile(imp.fs, filename) if err != nil { return nil, "" } h := sha256.New() h.Write(b) return b, hex.EncodeToString(h.Sum(nil)) } func (imp *importResolver) importRecursive( lineNum int, content string, inPath string) (int, string, error) { basePath := path.Dir(inPath) var replacements []string lines := strings.Split(content, "\n") trackLine := func(i, offset int, line string) { // TODO(bep) this is not very efficient. imp.linemap[i+lineNum] = fileOffset{Filename: inPath, Offset: offset} } i := 0 for offset, line := range lines { i++ lineTrimmed := strings.TrimSpace(line) column := strings.Index(line, lineTrimmed) line = lineTrimmed if !imp.shouldImport(line) { trackLine(i, offset, line) } else { path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';") filename := filepath.Join(basePath, path) importContent, hash := imp.contentHash(filename) if importContent == nil { if imp.opts.SkipInlineImportsNotFound { trackLine(i, offset, line) continue } pos := text.Position{ Filename: inPath, LineNumber: offset + 1, ColumnNumber: column + 1, } return 0, "", herrors.NewFileErrorFromFileInPos(fmt.Errorf("failed to resolve CSS @import \"%s\"", filename), pos, imp.fs, nil) } i-- if imp.contentSeen[hash] { i++ // Just replace the line with an empty string. replacements = append(replacements, []string{line, ""}...) trackLine(i, offset, "IMPORT") continue } imp.contentSeen[hash] = true // Handle recursive imports. l, nested, err := imp.importRecursive(i+lineNum, string(importContent), filepath.ToSlash(filename)) if err != nil { return 0, "", err } trackLine(i, offset, line) i += l importContent = []byte(nested) replacements = append(replacements, []string{line, string(importContent)}...) } } if len(replacements) > 0 { repl := strings.NewReplacer(replacements...) content = repl.Replace(content) } return i, content, nil } func (imp *importResolver) resolve() (io.Reader, error) { const importIdentifier = "@import" content, err := io.ReadAll(imp.r) if err != nil { return nil, err } contents := string(content) _, newContent, err := imp.importRecursive(0, contents, imp.inPath) if err != nil { return nil, err } return strings.NewReader(newContent), nil } // See https://www.w3schools.com/cssref/pr_import_rule.asp // We currently only support simple file imports, no urls, no media queries. // So this is OK: // // @import "navigation.css"; // // This is not: // // @import url("navigation.css"); // @import "mobstyle.css" screen and (max-width: 768px); func (imp *importResolver) shouldImport(s string) bool { if !strings.HasPrefix(s, importIdentifier) { return false } if strings.Contains(s, "url(") { return false } return shouldImportRe.MatchString(s) } func (imp *importResolver) toFileError(output string) error { output = strings.TrimSpace(loggers.RemoveANSIColours(output)) inErr := errors.New(output) match := cssSyntaxErrorRe.FindStringSubmatch(output) if match == nil { return inErr } lineNum, err := strconv.Atoi(match[1]) if err != nil { return inErr } file, ok := imp.linemap[lineNum] if !ok { return inErr } fi, err := imp.fs.Stat(file.Filename) if err != nil { return inErr } meta := fi.(hugofs.FileMetaInfo).Meta() realFilename := meta.Filename f, err := meta.Open() if err != nil { return inErr } defer f.Close() ferr := herrors.NewFileErrorFromName(inErr, realFilename) pos := ferr.Position() pos.LineNumber = file.Offset + 1 return ferr.UpdatePosition(pos).UpdateContent(f, nil) //return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher) }
// 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 postcss import ( "bytes" "crypto/sha256" "encoding/hex" "fmt" "io" "path" "path/filepath" "regexp" "strconv" "strings" "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/resources/internal" "github.com/spf13/afero" "github.com/spf13/cast" "errors" "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) const importIdentifier = "@import" var ( cssSyntaxErrorRe = regexp.MustCompile(`> (\d+) \|`) shouldImportRe = regexp.MustCompile(`^@import ["'].*["'];?\s*(/\*.*\*/)?$`) ) // New creates a new Client with the given specification. func New(rs *resources.Spec) *Client { return &Client{rs: rs} } func decodeOptions(m map[string]any) (opts Options, err error) { if m == nil { return } err = mapstructure.WeakDecode(m, &opts) if !opts.NoMap { // There was for a long time a discrepancy between documentation and // implementation for the noMap property, so we need to support both // camel and snake case. opts.NoMap = cast.ToBool(m["no-map"]) } return } // Client is the client used to do PostCSS transformations. type Client struct { rs *resources.Spec } // Process transforms the given Resource with the PostCSS processor. func (c *Client) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) { return res.Transform(&postcssTransformation{rs: c.rs, optionsm: options}) } // Some of the options from https://github.com/postcss/postcss-cli type Options struct { // Set a custom path to look for a config file. Config string NoMap bool // Disable the default inline sourcemaps // Enable inlining of @import statements. // Does so recursively, but currently once only per file; // that is, it's not possible to import the same file in // different scopes (root, media query...) // Note that this import routine does not care about the CSS spec, // so you can have @import anywhere in the file. InlineImports bool // When InlineImports is enabled, we fail the build if an import cannot be resolved. // You can enable this to allow the build to continue and leave the import statement in place. // Note that the inline importer does not process url location or imports with media queries, // so those will be left as-is even without enabling this option. SkipInlineImportsNotFound bool // Options for when not using a config file Use string // List of postcss plugins to use Parser string // Custom postcss parser Stringifier string // Custom postcss stringifier Syntax string // Custom postcss syntax } func (opts Options) toArgs() []string { var args []string if opts.NoMap { args = append(args, "--no-map") } if opts.Use != "" { args = append(args, "--use") args = append(args, strings.Fields(opts.Use)...) } if opts.Parser != "" { args = append(args, "--parser", opts.Parser) } if opts.Stringifier != "" { args = append(args, "--stringifier", opts.Stringifier) } if opts.Syntax != "" { args = append(args, "--syntax", opts.Syntax) } return args } type postcssTransformation struct { optionsm map[string]any rs *resources.Spec } func (t *postcssTransformation) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey("postcss", t.optionsm) } // Transform shells out to postcss-cli to do the heavy lifting. // For this to work, you need some additional tools. To install them globally: // npm install -g postcss-cli // npm install -g autoprefixer func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { const binaryName = "postcss" ex := t.rs.ExecHelper var configFile string logger := t.rs.Logger var options Options if t.optionsm != nil { var err error options, err = decodeOptions(t.optionsm) if err != nil { return err } } if options.Config != "" { configFile = options.Config } else { configFile = "postcss.config.js" } configFile = filepath.Clean(configFile) isConfigFileDir := false // We need an absolute filename to the config file. if !filepath.IsAbs(configFile) { configFile, isConfigFileDir = t.rs.BaseFs.ResolveJSConfigFile(configFile) if configFile == "" && options.Config != "" { // Only fail if the user specified config file is not found. return fmt.Errorf("postcss config directory %q not found", options.Config) } if !isConfigFileDir { logger.Warnf("postcss config %q must be a directory", options.Config) } } var cmdArgs []any if configFile != "" { logger.Infoln("postcss: use config file", configFile) cmdArgs = []any{"--config", configFile} } if optArgs := options.toArgs(); len(optArgs) > 0 { cmdArgs = append(cmdArgs, collections.StringSliceToInterfaceSlice(optArgs)...) } var errBuf bytes.Buffer infoW := loggers.LoggerToWriterWithPrefix(logger.Info(), "postcss") stderr := io.MultiWriter(infoW, &errBuf) cmdArgs = append(cmdArgs, hexec.WithStderr(stderr)) cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To)) cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs))) cmd, err := ex.Npx(binaryName, cmdArgs...) if err != nil { if hexec.IsNotFound(err) { // This may be on a CI server etc. Will fall back to pre-built assets. return herrors.ErrFeatureNotAvailable } return err } stdin, err := cmd.StdinPipe() if err != nil { return err } src := ctx.From imp := newImportResolver( ctx.From, ctx.InPath, options, t.rs.Assets.Fs, t.rs.Logger, ) if options.InlineImports { var err error src, err = imp.resolve() if err != nil { return err } } go func() { defer stdin.Close() io.Copy(stdin, src) }() err = cmd.Run() if err != nil { if hexec.IsNotFound(err) { return herrors.ErrFeatureNotAvailable } return imp.toFileError(errBuf.String()) } return nil } type fileOffset struct { Filename string Offset int } type importResolver struct { r io.Reader inPath string opts Options contentSeen map[string]bool linemap map[int]fileOffset fs afero.Fs logger loggers.Logger } func newImportResolver(r io.Reader, inPath string, opts Options, fs afero.Fs, logger loggers.Logger) *importResolver { return &importResolver{ r: r, inPath: inPath, fs: fs, logger: logger, linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool), opts: opts, } } func (imp *importResolver) contentHash(filename string) ([]byte, string) { b, err := afero.ReadFile(imp.fs, filename) if err != nil { return nil, "" } h := sha256.New() h.Write(b) return b, hex.EncodeToString(h.Sum(nil)) } func (imp *importResolver) importRecursive( lineNum int, content string, inPath string) (int, string, error) { basePath := path.Dir(inPath) var replacements []string lines := strings.Split(content, "\n") trackLine := func(i, offset int, line string) { // TODO(bep) this is not very efficient. imp.linemap[i+lineNum] = fileOffset{Filename: inPath, Offset: offset} } i := 0 for offset, line := range lines { i++ lineTrimmed := strings.TrimSpace(line) column := strings.Index(line, lineTrimmed) line = lineTrimmed if !imp.shouldImport(line) { trackLine(i, offset, line) } else { path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';") filename := filepath.Join(basePath, path) importContent, hash := imp.contentHash(filename) if importContent == nil { if imp.opts.SkipInlineImportsNotFound { trackLine(i, offset, line) continue } pos := text.Position{ Filename: inPath, LineNumber: offset + 1, ColumnNumber: column + 1, } return 0, "", herrors.NewFileErrorFromFileInPos(fmt.Errorf("failed to resolve CSS @import \"%s\"", filename), pos, imp.fs, nil) } i-- if imp.contentSeen[hash] { i++ // Just replace the line with an empty string. replacements = append(replacements, []string{line, ""}...) trackLine(i, offset, "IMPORT") continue } imp.contentSeen[hash] = true // Handle recursive imports. l, nested, err := imp.importRecursive(i+lineNum, string(importContent), filepath.ToSlash(filename)) if err != nil { return 0, "", err } trackLine(i, offset, line) i += l importContent = []byte(nested) replacements = append(replacements, []string{line, string(importContent)}...) } } if len(replacements) > 0 { repl := strings.NewReplacer(replacements...) content = repl.Replace(content) } return i, content, nil } func (imp *importResolver) resolve() (io.Reader, error) { const importIdentifier = "@import" content, err := io.ReadAll(imp.r) if err != nil { return nil, err } contents := string(content) _, newContent, err := imp.importRecursive(0, contents, imp.inPath) if err != nil { return nil, err } return strings.NewReader(newContent), nil } // See https://www.w3schools.com/cssref/pr_import_rule.asp // We currently only support simple file imports, no urls, no media queries. // So this is OK: // // @import "navigation.css"; // // This is not: // // @import url("navigation.css"); // @import "mobstyle.css" screen and (max-width: 768px); func (imp *importResolver) shouldImport(s string) bool { if !strings.HasPrefix(s, importIdentifier) { return false } if strings.Contains(s, "url(") { return false } return shouldImportRe.MatchString(s) } func (imp *importResolver) toFileError(output string) error { output = strings.TrimSpace(loggers.RemoveANSIColours(output)) inErr := errors.New(output) match := cssSyntaxErrorRe.FindStringSubmatch(output) if match == nil { return inErr } lineNum, err := strconv.Atoi(match[1]) if err != nil { return inErr } file, ok := imp.linemap[lineNum] if !ok { return inErr } fi, err := imp.fs.Stat(file.Filename) if err != nil { return inErr } meta := fi.(hugofs.FileMetaInfo).Meta() realFilename := meta.Filename f, err := meta.Open() if err != nil { return inErr } defer f.Close() ferr := herrors.NewFileErrorFromName(inErr, realFilename) pos := ferr.Position() pos.LineNumber = file.Offset + 1 return ferr.UpdatePosition(pos).UpdateContent(f, nil) //return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher) }
deining
10d0fcc01f77b1edad16fbdd415825731f7419fb
9a0370e8eb71fed3ac04984020b6aa95c43f22ab
> I assume this comes from a `go fmt` Correct. > -- which is odd. Yes, kind of.
deining
64
gohugoio/hugo
10,847
resources/page: Allow section&taxonomy pages to have a permalink configuration
Allows using permalink configuration for sections (branch bundles) and also for taxonomy pages. Extends the current permalink configuration to be able to specified per page kind while also staying backward compatible: all permalink patterns not dedicated to a certain kind, get automatically added for both normal pages and term pages. Fixes #8523 Example config: ```toml [permalinks] docs = "/docs/1.0/:sections[1:]/:filename" # Will get added to both page & term permalinks [permalinks.section] docs = "/docs/1.0/:sections[1:]" [permalinks.page] [permalinks.term] [permalinks.taxonomy] ```
null
2023-03-17 23:56:51+00:00
2023-06-26 13:31:01+00:00
config/allconfig/alldecoders.go
// Copyright 2023 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 allconfig import ( "fmt" "strings" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/privacy" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/config/services" "github.com/gohugoio/hugo/deploy" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/minifiers" "github.com/gohugoio/hugo/modules" "github.com/gohugoio/hugo/navigation" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/related" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/mitchellh/mapstructure" "github.com/spf13/afero" "github.com/spf13/cast" ) type decodeConfig struct { p config.Provider c *Config fs afero.Fs bcfg config.BaseConfig } type decodeWeight struct { key string decode func(decodeWeight, decodeConfig) error getCompiler func(c *Config) configCompiler weight int } var allDecoderSetups = map[string]decodeWeight{ "": { key: "", weight: -100, // Always first. decode: func(d decodeWeight, p decodeConfig) error { if err := mapstructure.WeakDecode(p.p.Get(""), &p.c.RootConfig); err != nil { return err } // This need to match with Lang which is always lower case. p.c.RootConfig.DefaultContentLanguage = strings.ToLower(p.c.RootConfig.DefaultContentLanguage) return nil }, }, "imaging": { key: "imaging", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Imaging, err = images.DecodeConfig(p.p.GetStringMap(d.key)) return err }, }, "caches": { key: "caches", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Caches, err = filecache.DecodeConfig(p.fs, p.bcfg, p.p.GetStringMap(d.key)) if p.c.IgnoreCache { // Set MaxAge in all caches to 0. for k, cache := range p.c.Caches { cache.MaxAge = 0 p.c.Caches[k] = cache } } return err }, }, "build": { key: "build", decode: func(d decodeWeight, p decodeConfig) error { p.c.Build = config.DecodeBuildConfig(p.p) return nil }, getCompiler: func(c *Config) configCompiler { return &c.Build }, }, "frontmatter": { key: "frontmatter", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Frontmatter, err = pagemeta.DecodeFrontMatterConfig(p.p) return err }, }, "markup": { key: "markup", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Markup, err = markup_config.Decode(p.p) return err }, }, "server": { key: "server", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Server, err = config.DecodeServer(p.p) return err }, getCompiler: func(c *Config) configCompiler { return &c.Server }, }, "minify": { key: "minify", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Minify, err = minifiers.DecodeConfig(p.p.Get(d.key)) return err }, }, "mediaTypes": { key: "mediaTypes", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.MediaTypes, err = media.DecodeTypes(p.p.GetStringMap(d.key)) return err }, }, "outputs": { key: "outputs", decode: func(d decodeWeight, p decodeConfig) error { defaults := createDefaultOutputFormats(p.c.OutputFormats.Config) m := p.p.GetStringMap("outputs") p.c.Outputs = make(map[string][]string) for k, v := range m { s := types.ToStringSlicePreserveString(v) for i, v := range s { s[i] = strings.ToLower(v) } p.c.Outputs[k] = s } // Apply defaults. for k, v := range defaults { if _, found := p.c.Outputs[k]; !found { p.c.Outputs[k] = v } } return nil }, }, "outputFormats": { key: "outputFormats", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.OutputFormats, err = output.DecodeConfig(p.c.MediaTypes.Config, p.p.Get(d.key)) return err }, }, "params": { key: "params", decode: func(d decodeWeight, p decodeConfig) error { p.c.Params = maps.CleanConfigStringMap(p.p.GetStringMap("params")) if p.c.Params == nil { p.c.Params = make(map[string]any) } // Before Hugo 0.112.0 this was configured via site Params. if mainSections, found := p.c.Params["mainsections"]; found { p.c.MainSections = types.ToStringSlicePreserveString(mainSections) if p.c.MainSections == nil { p.c.MainSections = []string{} } } return nil }, }, "module": { key: "module", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Module, err = modules.DecodeConfig(p.p) return err }, }, "permalinks": { key: "permalinks", decode: func(d decodeWeight, p decodeConfig) error { p.c.Permalinks = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, }, "sitemap": { key: "sitemap", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Sitemap, err = config.DecodeSitemap(config.SitemapConfig{Priority: -1, Filename: "sitemap.xml"}, p.p.GetStringMap(d.key)) return err }, }, "taxonomies": { key: "taxonomies", decode: func(d decodeWeight, p decodeConfig) error { p.c.Taxonomies = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, }, "related": { key: "related", weight: 100, // This needs to be decoded after taxonomies. decode: func(d decodeWeight, p decodeConfig) error { if p.p.IsSet(d.key) { var err error p.c.Related, err = related.DecodeConfig(p.p.GetParams(d.key)) if err != nil { return fmt.Errorf("failed to decode related config: %w", err) } } else { p.c.Related = related.DefaultConfig if _, found := p.c.Taxonomies["tag"]; found { p.c.Related.Add(related.IndexConfig{Name: "tags", Weight: 80}) } } return nil }, }, "languages": { key: "languages", decode: func(d decodeWeight, p decodeConfig) error { var err error m := p.p.GetStringMap(d.key) if len(m) == 1 { // In v0.112.4 we moved this to the language config, but it's very commmon for mono language sites to have this at the top level. var first maps.Params var ok bool for _, v := range m { first, ok = v.(maps.Params) if ok { break } } if first != nil { if _, found := first["languagecode"]; !found { first["languagecode"] = p.p.GetString("languagecode") } } } p.c.Languages, err = langs.DecodeConfig(m) if err != nil { return err } // Validate defaultContentLanguage. var found bool for lang := range p.c.Languages { if lang == p.c.DefaultContentLanguage { found = true break } } if !found { return fmt.Errorf("config value %q for defaultContentLanguage does not match any language definition", p.c.DefaultContentLanguage) } return nil }, }, "cascade": { key: "cascade", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Cascade, err = page.DecodeCascadeConfig(p.p.Get(d.key)) return err }, }, "menus": { key: "menus", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Menus, err = navigation.DecodeConfig(p.p.Get(d.key)) return err }, }, "privacy": { key: "privacy", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Privacy, err = privacy.DecodeConfig(p.p) return err }, }, "security": { key: "security", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Security, err = security.DecodeConfig(p.p) return err }, }, "services": { key: "services", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Services, err = services.DecodeConfig(p.p) return err }, }, "deployment": { key: "deployment", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Deployment, err = deploy.DecodeConfig(p.p) return err }, }, "author": { key: "author", decode: func(d decodeWeight, p decodeConfig) error { p.c.Author = maps.CleanConfigStringMap(p.p.GetStringMap(d.key)) return nil }, }, "social": { key: "social", decode: func(d decodeWeight, p decodeConfig) error { p.c.Social = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, }, "uglyurls": { key: "uglyurls", decode: func(d decodeWeight, p decodeConfig) error { v := p.p.Get(d.key) switch vv := v.(type) { case bool: p.c.UglyURLs = vv case string: p.c.UglyURLs = vv == "true" default: p.c.UglyURLs = cast.ToStringMapBool(v) } return nil }, }, "internal": { key: "internal", decode: func(d decodeWeight, p decodeConfig) error { return mapstructure.WeakDecode(p.p.GetStringMap(d.key), &p.c.Internal) }, }, }
// Copyright 2023 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 allconfig import ( "fmt" "strings" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/privacy" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/config/services" "github.com/gohugoio/hugo/deploy" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/minifiers" "github.com/gohugoio/hugo/modules" "github.com/gohugoio/hugo/navigation" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/related" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/mitchellh/mapstructure" "github.com/spf13/afero" "github.com/spf13/cast" ) type decodeConfig struct { p config.Provider c *Config fs afero.Fs bcfg config.BaseConfig } type decodeWeight struct { key string decode func(decodeWeight, decodeConfig) error getCompiler func(c *Config) configCompiler weight int } var allDecoderSetups = map[string]decodeWeight{ "": { key: "", weight: -100, // Always first. decode: func(d decodeWeight, p decodeConfig) error { if err := mapstructure.WeakDecode(p.p.Get(""), &p.c.RootConfig); err != nil { return err } // This need to match with Lang which is always lower case. p.c.RootConfig.DefaultContentLanguage = strings.ToLower(p.c.RootConfig.DefaultContentLanguage) return nil }, }, "imaging": { key: "imaging", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Imaging, err = images.DecodeConfig(p.p.GetStringMap(d.key)) return err }, }, "caches": { key: "caches", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Caches, err = filecache.DecodeConfig(p.fs, p.bcfg, p.p.GetStringMap(d.key)) if p.c.IgnoreCache { // Set MaxAge in all caches to 0. for k, cache := range p.c.Caches { cache.MaxAge = 0 p.c.Caches[k] = cache } } return err }, }, "build": { key: "build", decode: func(d decodeWeight, p decodeConfig) error { p.c.Build = config.DecodeBuildConfig(p.p) return nil }, getCompiler: func(c *Config) configCompiler { return &c.Build }, }, "frontmatter": { key: "frontmatter", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Frontmatter, err = pagemeta.DecodeFrontMatterConfig(p.p) return err }, }, "markup": { key: "markup", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Markup, err = markup_config.Decode(p.p) return err }, }, "server": { key: "server", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Server, err = config.DecodeServer(p.p) return err }, getCompiler: func(c *Config) configCompiler { return &c.Server }, }, "minify": { key: "minify", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Minify, err = minifiers.DecodeConfig(p.p.Get(d.key)) return err }, }, "mediaTypes": { key: "mediaTypes", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.MediaTypes, err = media.DecodeTypes(p.p.GetStringMap(d.key)) return err }, }, "outputs": { key: "outputs", decode: func(d decodeWeight, p decodeConfig) error { defaults := createDefaultOutputFormats(p.c.OutputFormats.Config) m := p.p.GetStringMap("outputs") p.c.Outputs = make(map[string][]string) for k, v := range m { s := types.ToStringSlicePreserveString(v) for i, v := range s { s[i] = strings.ToLower(v) } p.c.Outputs[k] = s } // Apply defaults. for k, v := range defaults { if _, found := p.c.Outputs[k]; !found { p.c.Outputs[k] = v } } return nil }, }, "outputFormats": { key: "outputFormats", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.OutputFormats, err = output.DecodeConfig(p.c.MediaTypes.Config, p.p.Get(d.key)) return err }, }, "params": { key: "params", decode: func(d decodeWeight, p decodeConfig) error { p.c.Params = maps.CleanConfigStringMap(p.p.GetStringMap("params")) if p.c.Params == nil { p.c.Params = make(map[string]any) } // Before Hugo 0.112.0 this was configured via site Params. if mainSections, found := p.c.Params["mainsections"]; found { p.c.MainSections = types.ToStringSlicePreserveString(mainSections) if p.c.MainSections == nil { p.c.MainSections = []string{} } } return nil }, }, "module": { key: "module", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Module, err = modules.DecodeConfig(p.p) return err }, }, "permalinks": { key: "permalinks", decode: func(d decodeWeight, p decodeConfig) error { p.c.Permalinks = make(map[string]map[string]string) p.c.Permalinks["page"] = make(map[string]string) p.c.Permalinks["section"] = make(map[string]string) p.c.Permalinks["taxonomy"] = make(map[string]string) p.c.Permalinks["term"] = make(map[string]string) config := maps.CleanConfigStringMap(p.p.GetStringMap(d.key)) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term p.c.Permalinks["page"][k] = v; p.c.Permalinks["term"][k] = v; case maps.Params: // [permalinks.key] // xyz = ??? if (k == "page") || (k == "section") || (k == "taxonomy") || (k == "term") { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: p.c.Permalinks[k][k2] = v2 default: return fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return fmt.Errorf("permalinks configuration only allows per-kind configuration 'page', 'section', 'taxonomy' and 'term'; unknown kind: %q", k) } default: return fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return nil }, }, "sitemap": { key: "sitemap", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Sitemap, err = config.DecodeSitemap(config.SitemapConfig{Priority: -1, Filename: "sitemap.xml"}, p.p.GetStringMap(d.key)) return err }, }, "taxonomies": { key: "taxonomies", decode: func(d decodeWeight, p decodeConfig) error { p.c.Taxonomies = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, }, "related": { key: "related", weight: 100, // This needs to be decoded after taxonomies. decode: func(d decodeWeight, p decodeConfig) error { if p.p.IsSet(d.key) { var err error p.c.Related, err = related.DecodeConfig(p.p.GetParams(d.key)) if err != nil { return fmt.Errorf("failed to decode related config: %w", err) } } else { p.c.Related = related.DefaultConfig if _, found := p.c.Taxonomies["tag"]; found { p.c.Related.Add(related.IndexConfig{Name: "tags", Weight: 80}) } } return nil }, }, "languages": { key: "languages", decode: func(d decodeWeight, p decodeConfig) error { var err error m := p.p.GetStringMap(d.key) if len(m) == 1 { // In v0.112.4 we moved this to the language config, but it's very commmon for mono language sites to have this at the top level. var first maps.Params var ok bool for _, v := range m { first, ok = v.(maps.Params) if ok { break } } if first != nil { if _, found := first["languagecode"]; !found { first["languagecode"] = p.p.GetString("languagecode") } } } p.c.Languages, err = langs.DecodeConfig(m) if err != nil { return err } // Validate defaultContentLanguage. var found bool for lang := range p.c.Languages { if lang == p.c.DefaultContentLanguage { found = true break } } if !found { return fmt.Errorf("config value %q for defaultContentLanguage does not match any language definition", p.c.DefaultContentLanguage) } return nil }, }, "cascade": { key: "cascade", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Cascade, err = page.DecodeCascadeConfig(p.p.Get(d.key)) return err }, }, "menus": { key: "menus", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Menus, err = navigation.DecodeConfig(p.p.Get(d.key)) return err }, }, "privacy": { key: "privacy", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Privacy, err = privacy.DecodeConfig(p.p) return err }, }, "security": { key: "security", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Security, err = security.DecodeConfig(p.p) return err }, }, "services": { key: "services", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Services, err = services.DecodeConfig(p.p) return err }, }, "deployment": { key: "deployment", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Deployment, err = deploy.DecodeConfig(p.p) return err }, }, "author": { key: "author", decode: func(d decodeWeight, p decodeConfig) error { p.c.Author = maps.CleanConfigStringMap(p.p.GetStringMap(d.key)) return nil }, }, "social": { key: "social", decode: func(d decodeWeight, p decodeConfig) error { p.c.Social = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, }, "uglyurls": { key: "uglyurls", decode: func(d decodeWeight, p decodeConfig) error { v := p.p.Get(d.key) switch vv := v.(type) { case bool: p.c.UglyURLs = vv case string: p.c.UglyURLs = vv == "true" default: p.c.UglyURLs = cast.ToStringMapBool(v) } return nil }, }, "internal": { key: "internal", decode: func(d decodeWeight, p decodeConfig) error { return mapstructure.WeakDecode(p.p.GetStringMap(d.key), &p.c.Internal) }, }, }
Mai-Lapyst
e3308a0bbc2de1cb4d7571521abeab07049ce31f
cc14c6a52c215fc43716f7b266c4c340b3d28230
I think you can use the constants in `pagekinds.Page` etc.
bep
65
gohugoio/hugo
10,847
resources/page: Allow section&taxonomy pages to have a permalink configuration
Allows using permalink configuration for sections (branch bundles) and also for taxonomy pages. Extends the current permalink configuration to be able to specified per page kind while also staying backward compatible: all permalink patterns not dedicated to a certain kind, get automatically added for both normal pages and term pages. Fixes #8523 Example config: ```toml [permalinks] docs = "/docs/1.0/:sections[1:]/:filename" # Will get added to both page & term permalinks [permalinks.section] docs = "/docs/1.0/:sections[1:]" [permalinks.page] [permalinks.term] [permalinks.taxonomy] ```
null
2023-03-17 23:56:51+00:00
2023-06-26 13:31:01+00:00
config/allconfig/alldecoders.go
// Copyright 2023 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 allconfig import ( "fmt" "strings" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/privacy" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/config/services" "github.com/gohugoio/hugo/deploy" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/minifiers" "github.com/gohugoio/hugo/modules" "github.com/gohugoio/hugo/navigation" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/related" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/mitchellh/mapstructure" "github.com/spf13/afero" "github.com/spf13/cast" ) type decodeConfig struct { p config.Provider c *Config fs afero.Fs bcfg config.BaseConfig } type decodeWeight struct { key string decode func(decodeWeight, decodeConfig) error getCompiler func(c *Config) configCompiler weight int } var allDecoderSetups = map[string]decodeWeight{ "": { key: "", weight: -100, // Always first. decode: func(d decodeWeight, p decodeConfig) error { if err := mapstructure.WeakDecode(p.p.Get(""), &p.c.RootConfig); err != nil { return err } // This need to match with Lang which is always lower case. p.c.RootConfig.DefaultContentLanguage = strings.ToLower(p.c.RootConfig.DefaultContentLanguage) return nil }, }, "imaging": { key: "imaging", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Imaging, err = images.DecodeConfig(p.p.GetStringMap(d.key)) return err }, }, "caches": { key: "caches", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Caches, err = filecache.DecodeConfig(p.fs, p.bcfg, p.p.GetStringMap(d.key)) if p.c.IgnoreCache { // Set MaxAge in all caches to 0. for k, cache := range p.c.Caches { cache.MaxAge = 0 p.c.Caches[k] = cache } } return err }, }, "build": { key: "build", decode: func(d decodeWeight, p decodeConfig) error { p.c.Build = config.DecodeBuildConfig(p.p) return nil }, getCompiler: func(c *Config) configCompiler { return &c.Build }, }, "frontmatter": { key: "frontmatter", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Frontmatter, err = pagemeta.DecodeFrontMatterConfig(p.p) return err }, }, "markup": { key: "markup", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Markup, err = markup_config.Decode(p.p) return err }, }, "server": { key: "server", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Server, err = config.DecodeServer(p.p) return err }, getCompiler: func(c *Config) configCompiler { return &c.Server }, }, "minify": { key: "minify", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Minify, err = minifiers.DecodeConfig(p.p.Get(d.key)) return err }, }, "mediaTypes": { key: "mediaTypes", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.MediaTypes, err = media.DecodeTypes(p.p.GetStringMap(d.key)) return err }, }, "outputs": { key: "outputs", decode: func(d decodeWeight, p decodeConfig) error { defaults := createDefaultOutputFormats(p.c.OutputFormats.Config) m := p.p.GetStringMap("outputs") p.c.Outputs = make(map[string][]string) for k, v := range m { s := types.ToStringSlicePreserveString(v) for i, v := range s { s[i] = strings.ToLower(v) } p.c.Outputs[k] = s } // Apply defaults. for k, v := range defaults { if _, found := p.c.Outputs[k]; !found { p.c.Outputs[k] = v } } return nil }, }, "outputFormats": { key: "outputFormats", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.OutputFormats, err = output.DecodeConfig(p.c.MediaTypes.Config, p.p.Get(d.key)) return err }, }, "params": { key: "params", decode: func(d decodeWeight, p decodeConfig) error { p.c.Params = maps.CleanConfigStringMap(p.p.GetStringMap("params")) if p.c.Params == nil { p.c.Params = make(map[string]any) } // Before Hugo 0.112.0 this was configured via site Params. if mainSections, found := p.c.Params["mainsections"]; found { p.c.MainSections = types.ToStringSlicePreserveString(mainSections) if p.c.MainSections == nil { p.c.MainSections = []string{} } } return nil }, }, "module": { key: "module", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Module, err = modules.DecodeConfig(p.p) return err }, }, "permalinks": { key: "permalinks", decode: func(d decodeWeight, p decodeConfig) error { p.c.Permalinks = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, }, "sitemap": { key: "sitemap", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Sitemap, err = config.DecodeSitemap(config.SitemapConfig{Priority: -1, Filename: "sitemap.xml"}, p.p.GetStringMap(d.key)) return err }, }, "taxonomies": { key: "taxonomies", decode: func(d decodeWeight, p decodeConfig) error { p.c.Taxonomies = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, }, "related": { key: "related", weight: 100, // This needs to be decoded after taxonomies. decode: func(d decodeWeight, p decodeConfig) error { if p.p.IsSet(d.key) { var err error p.c.Related, err = related.DecodeConfig(p.p.GetParams(d.key)) if err != nil { return fmt.Errorf("failed to decode related config: %w", err) } } else { p.c.Related = related.DefaultConfig if _, found := p.c.Taxonomies["tag"]; found { p.c.Related.Add(related.IndexConfig{Name: "tags", Weight: 80}) } } return nil }, }, "languages": { key: "languages", decode: func(d decodeWeight, p decodeConfig) error { var err error m := p.p.GetStringMap(d.key) if len(m) == 1 { // In v0.112.4 we moved this to the language config, but it's very commmon for mono language sites to have this at the top level. var first maps.Params var ok bool for _, v := range m { first, ok = v.(maps.Params) if ok { break } } if first != nil { if _, found := first["languagecode"]; !found { first["languagecode"] = p.p.GetString("languagecode") } } } p.c.Languages, err = langs.DecodeConfig(m) if err != nil { return err } // Validate defaultContentLanguage. var found bool for lang := range p.c.Languages { if lang == p.c.DefaultContentLanguage { found = true break } } if !found { return fmt.Errorf("config value %q for defaultContentLanguage does not match any language definition", p.c.DefaultContentLanguage) } return nil }, }, "cascade": { key: "cascade", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Cascade, err = page.DecodeCascadeConfig(p.p.Get(d.key)) return err }, }, "menus": { key: "menus", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Menus, err = navigation.DecodeConfig(p.p.Get(d.key)) return err }, }, "privacy": { key: "privacy", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Privacy, err = privacy.DecodeConfig(p.p) return err }, }, "security": { key: "security", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Security, err = security.DecodeConfig(p.p) return err }, }, "services": { key: "services", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Services, err = services.DecodeConfig(p.p) return err }, }, "deployment": { key: "deployment", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Deployment, err = deploy.DecodeConfig(p.p) return err }, }, "author": { key: "author", decode: func(d decodeWeight, p decodeConfig) error { p.c.Author = maps.CleanConfigStringMap(p.p.GetStringMap(d.key)) return nil }, }, "social": { key: "social", decode: func(d decodeWeight, p decodeConfig) error { p.c.Social = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, }, "uglyurls": { key: "uglyurls", decode: func(d decodeWeight, p decodeConfig) error { v := p.p.Get(d.key) switch vv := v.(type) { case bool: p.c.UglyURLs = vv case string: p.c.UglyURLs = vv == "true" default: p.c.UglyURLs = cast.ToStringMapBool(v) } return nil }, }, "internal": { key: "internal", decode: func(d decodeWeight, p decodeConfig) error { return mapstructure.WeakDecode(p.p.GetStringMap(d.key), &p.c.Internal) }, }, }
// Copyright 2023 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 allconfig import ( "fmt" "strings" "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config/privacy" "github.com/gohugoio/hugo/config/security" "github.com/gohugoio/hugo/config/services" "github.com/gohugoio/hugo/deploy" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/markup/markup_config" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/minifiers" "github.com/gohugoio/hugo/modules" "github.com/gohugoio/hugo/navigation" "github.com/gohugoio/hugo/output" "github.com/gohugoio/hugo/related" "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/mitchellh/mapstructure" "github.com/spf13/afero" "github.com/spf13/cast" ) type decodeConfig struct { p config.Provider c *Config fs afero.Fs bcfg config.BaseConfig } type decodeWeight struct { key string decode func(decodeWeight, decodeConfig) error getCompiler func(c *Config) configCompiler weight int } var allDecoderSetups = map[string]decodeWeight{ "": { key: "", weight: -100, // Always first. decode: func(d decodeWeight, p decodeConfig) error { if err := mapstructure.WeakDecode(p.p.Get(""), &p.c.RootConfig); err != nil { return err } // This need to match with Lang which is always lower case. p.c.RootConfig.DefaultContentLanguage = strings.ToLower(p.c.RootConfig.DefaultContentLanguage) return nil }, }, "imaging": { key: "imaging", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Imaging, err = images.DecodeConfig(p.p.GetStringMap(d.key)) return err }, }, "caches": { key: "caches", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Caches, err = filecache.DecodeConfig(p.fs, p.bcfg, p.p.GetStringMap(d.key)) if p.c.IgnoreCache { // Set MaxAge in all caches to 0. for k, cache := range p.c.Caches { cache.MaxAge = 0 p.c.Caches[k] = cache } } return err }, }, "build": { key: "build", decode: func(d decodeWeight, p decodeConfig) error { p.c.Build = config.DecodeBuildConfig(p.p) return nil }, getCompiler: func(c *Config) configCompiler { return &c.Build }, }, "frontmatter": { key: "frontmatter", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Frontmatter, err = pagemeta.DecodeFrontMatterConfig(p.p) return err }, }, "markup": { key: "markup", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Markup, err = markup_config.Decode(p.p) return err }, }, "server": { key: "server", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Server, err = config.DecodeServer(p.p) return err }, getCompiler: func(c *Config) configCompiler { return &c.Server }, }, "minify": { key: "minify", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Minify, err = minifiers.DecodeConfig(p.p.Get(d.key)) return err }, }, "mediaTypes": { key: "mediaTypes", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.MediaTypes, err = media.DecodeTypes(p.p.GetStringMap(d.key)) return err }, }, "outputs": { key: "outputs", decode: func(d decodeWeight, p decodeConfig) error { defaults := createDefaultOutputFormats(p.c.OutputFormats.Config) m := p.p.GetStringMap("outputs") p.c.Outputs = make(map[string][]string) for k, v := range m { s := types.ToStringSlicePreserveString(v) for i, v := range s { s[i] = strings.ToLower(v) } p.c.Outputs[k] = s } // Apply defaults. for k, v := range defaults { if _, found := p.c.Outputs[k]; !found { p.c.Outputs[k] = v } } return nil }, }, "outputFormats": { key: "outputFormats", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.OutputFormats, err = output.DecodeConfig(p.c.MediaTypes.Config, p.p.Get(d.key)) return err }, }, "params": { key: "params", decode: func(d decodeWeight, p decodeConfig) error { p.c.Params = maps.CleanConfigStringMap(p.p.GetStringMap("params")) if p.c.Params == nil { p.c.Params = make(map[string]any) } // Before Hugo 0.112.0 this was configured via site Params. if mainSections, found := p.c.Params["mainsections"]; found { p.c.MainSections = types.ToStringSlicePreserveString(mainSections) if p.c.MainSections == nil { p.c.MainSections = []string{} } } return nil }, }, "module": { key: "module", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Module, err = modules.DecodeConfig(p.p) return err }, }, "permalinks": { key: "permalinks", decode: func(d decodeWeight, p decodeConfig) error { p.c.Permalinks = make(map[string]map[string]string) p.c.Permalinks["page"] = make(map[string]string) p.c.Permalinks["section"] = make(map[string]string) p.c.Permalinks["taxonomy"] = make(map[string]string) p.c.Permalinks["term"] = make(map[string]string) config := maps.CleanConfigStringMap(p.p.GetStringMap(d.key)) for k, v := range config { switch v := v.(type) { case string: // [permalinks] // key = '...' // To sucessfully be backward compatible, "default" patterns need to be set for both page and term p.c.Permalinks["page"][k] = v; p.c.Permalinks["term"][k] = v; case maps.Params: // [permalinks.key] // xyz = ??? if (k == "page") || (k == "section") || (k == "taxonomy") || (k == "term") { // TODO: warn if we overwrite an already set value for k2, v2 := range v { switch v2 := v2.(type) { case string: p.c.Permalinks[k][k2] = v2 default: return fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q for kind %q", v2, k2, k) } } } else { return fmt.Errorf("permalinks configuration only allows per-kind configuration 'page', 'section', 'taxonomy' and 'term'; unknown kind: %q", k) } default: return fmt.Errorf("permalinks configuration invalid: unknown value %q for key %q", v, k) } } return nil }, }, "sitemap": { key: "sitemap", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Sitemap, err = config.DecodeSitemap(config.SitemapConfig{Priority: -1, Filename: "sitemap.xml"}, p.p.GetStringMap(d.key)) return err }, }, "taxonomies": { key: "taxonomies", decode: func(d decodeWeight, p decodeConfig) error { p.c.Taxonomies = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, }, "related": { key: "related", weight: 100, // This needs to be decoded after taxonomies. decode: func(d decodeWeight, p decodeConfig) error { if p.p.IsSet(d.key) { var err error p.c.Related, err = related.DecodeConfig(p.p.GetParams(d.key)) if err != nil { return fmt.Errorf("failed to decode related config: %w", err) } } else { p.c.Related = related.DefaultConfig if _, found := p.c.Taxonomies["tag"]; found { p.c.Related.Add(related.IndexConfig{Name: "tags", Weight: 80}) } } return nil }, }, "languages": { key: "languages", decode: func(d decodeWeight, p decodeConfig) error { var err error m := p.p.GetStringMap(d.key) if len(m) == 1 { // In v0.112.4 we moved this to the language config, but it's very commmon for mono language sites to have this at the top level. var first maps.Params var ok bool for _, v := range m { first, ok = v.(maps.Params) if ok { break } } if first != nil { if _, found := first["languagecode"]; !found { first["languagecode"] = p.p.GetString("languagecode") } } } p.c.Languages, err = langs.DecodeConfig(m) if err != nil { return err } // Validate defaultContentLanguage. var found bool for lang := range p.c.Languages { if lang == p.c.DefaultContentLanguage { found = true break } } if !found { return fmt.Errorf("config value %q for defaultContentLanguage does not match any language definition", p.c.DefaultContentLanguage) } return nil }, }, "cascade": { key: "cascade", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Cascade, err = page.DecodeCascadeConfig(p.p.Get(d.key)) return err }, }, "menus": { key: "menus", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Menus, err = navigation.DecodeConfig(p.p.Get(d.key)) return err }, }, "privacy": { key: "privacy", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Privacy, err = privacy.DecodeConfig(p.p) return err }, }, "security": { key: "security", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Security, err = security.DecodeConfig(p.p) return err }, }, "services": { key: "services", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Services, err = services.DecodeConfig(p.p) return err }, }, "deployment": { key: "deployment", decode: func(d decodeWeight, p decodeConfig) error { var err error p.c.Deployment, err = deploy.DecodeConfig(p.p) return err }, }, "author": { key: "author", decode: func(d decodeWeight, p decodeConfig) error { p.c.Author = maps.CleanConfigStringMap(p.p.GetStringMap(d.key)) return nil }, }, "social": { key: "social", decode: func(d decodeWeight, p decodeConfig) error { p.c.Social = maps.CleanConfigStringMapString(p.p.GetStringMapString(d.key)) return nil }, }, "uglyurls": { key: "uglyurls", decode: func(d decodeWeight, p decodeConfig) error { v := p.p.Get(d.key) switch vv := v.(type) { case bool: p.c.UglyURLs = vv case string: p.c.UglyURLs = vv == "true" default: p.c.UglyURLs = cast.ToStringMapBool(v) } return nil }, }, "internal": { key: "internal", decode: func(d decodeWeight, p decodeConfig) error { return mapstructure.WeakDecode(p.p.GetStringMap(d.key), &p.c.Internal) }, }, }
Mai-Lapyst
e3308a0bbc2de1cb4d7571521abeab07049ce31f
cc14c6a52c215fc43716f7b266c4c340b3d28230
pagekinds.Page etc.
bep
66
gohugoio/hugo
10,847
resources/page: Allow section&taxonomy pages to have a permalink configuration
Allows using permalink configuration for sections (branch bundles) and also for taxonomy pages. Extends the current permalink configuration to be able to specified per page kind while also staying backward compatible: all permalink patterns not dedicated to a certain kind, get automatically added for both normal pages and term pages. Fixes #8523 Example config: ```toml [permalinks] docs = "/docs/1.0/:sections[1:]/:filename" # Will get added to both page & term permalinks [permalinks.section] docs = "/docs/1.0/:sections[1:]" [permalinks.page] [permalinks.term] [permalinks.taxonomy] ```
null
2023-03-17 23:56:51+00:00
2023-06-26 13:31:01+00:00
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 ( "bufio" "fmt" "io" "os" "path/filepath" "sort" "strings" "unicode" "github.com/spf13/afero" ) const ( // The NPM package.json "template" file. FilenamePackageHugoJSON = "package.hugo.json" // The NPM package file. FilenamePackageJSON = "package.json" ) var ( // This should be the only list of valid extensions for content files. contentFileExtensions = []string{ "html", "htm", "mdown", "markdown", "md", "asciidoc", "adoc", "ad", "rest", "rst", "org", "pandoc", "pdc", } contentFileExtensionsSet map[string]bool htmlFileExtensions = []string{ "html", "htm", } htmlFileExtensionsSet map[string]bool ) func init() { contentFileExtensionsSet = make(map[string]bool) for _, ext := range contentFileExtensions { contentFileExtensionsSet[ext] = true } htmlFileExtensionsSet = make(map[string]bool) for _, ext := range htmlFileExtensions { htmlFileExtensionsSet[ext] = true } } func IsContentFile(filename string) bool { return contentFileExtensionsSet[strings.TrimPrefix(filepath.Ext(filename), ".")] } func IsIndexContentFile(filename string) bool { if !IsContentFile(filename) { return false } base := filepath.Base(filename) return strings.HasPrefix(base, "index.") || strings.HasPrefix(base, "_index.") } func IsHTMLFile(filename string) bool { return htmlFileExtensionsSet[strings.TrimPrefix(filepath.Ext(filename), ".")] } func IsContentExt(ext string) bool { return contentFileExtensionsSet[ext] } type ContentClass string const ( ContentClassLeaf ContentClass = "leaf" ContentClassBranch ContentClass = "branch" ContentClassFile ContentClass = "zfile" // Sort below ContentClassContent ContentClass = "zcontent" ) func (c ContentClass) IsBundle() bool { return c == ContentClassLeaf || c == ContentClassBranch } func ClassifyContentFile(filename string, open func() (afero.File, error)) ContentClass { if !IsContentFile(filename) { return ContentClassFile } if IsHTMLFile(filename) { // We need to look inside the file. If the first non-whitespace // character is a "<", then we treat it as a regular file. // Eearlier we created pages for these files, but that had all sorts // of troubles, and isn't what it says in the documentation. // See https://github.com/gohugoio/hugo/issues/7030 if open == nil { panic(fmt.Sprintf("no file opener provided for %q", filename)) } f, err := open() if err != nil { return ContentClassFile } ishtml := isHTMLContent(f) f.Close() if ishtml { return ContentClassFile } } if strings.HasPrefix(filename, "_index.") { return ContentClassBranch } if strings.HasPrefix(filename, "index.") { return ContentClassLeaf } return ContentClassContent } var htmlComment = []rune{'<', '!', '-', '-'} func isHTMLContent(r io.Reader) bool { br := bufio.NewReader(r) i := 0 for { c, _, err := br.ReadRune() if err != nil { break } if i > 0 { if i >= len(htmlComment) { return false } if c != htmlComment[i] { return true } i++ continue } if !unicode.IsSpace(c) { if i == 0 && c != '<' { return false } i++ } } return true } 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. ) 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] }
// 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 ( "bufio" "fmt" "io" "os" "path/filepath" "sort" "strings" "unicode" "github.com/spf13/afero" ) const ( // The NPM package.json "template" file. FilenamePackageHugoJSON = "package.hugo.json" // The NPM package file. FilenamePackageJSON = "package.json" ) var ( // This should be the only list of valid extensions for content files. contentFileExtensions = []string{ "html", "htm", "mdown", "markdown", "md", "asciidoc", "adoc", "ad", "rest", "rst", "org", "pandoc", "pdc", } contentFileExtensionsSet map[string]bool htmlFileExtensions = []string{ "html", "htm", } htmlFileExtensionsSet map[string]bool ) func init() { contentFileExtensionsSet = make(map[string]bool) for _, ext := range contentFileExtensions { contentFileExtensionsSet[ext] = true } htmlFileExtensionsSet = make(map[string]bool) for _, ext := range htmlFileExtensions { htmlFileExtensionsSet[ext] = true } } func IsContentFile(filename string) bool { return contentFileExtensionsSet[strings.TrimPrefix(filepath.Ext(filename), ".")] } func IsIndexContentFile(filename string) bool { if !IsContentFile(filename) { return false } base := filepath.Base(filename) return strings.HasPrefix(base, "index.") || strings.HasPrefix(base, "_index.") } func IsHTMLFile(filename string) bool { return htmlFileExtensionsSet[strings.TrimPrefix(filepath.Ext(filename), ".")] } func IsContentExt(ext string) bool { return contentFileExtensionsSet[ext] } type ContentClass string const ( ContentClassLeaf ContentClass = "leaf" ContentClassBranch ContentClass = "branch" ContentClassFile ContentClass = "zfile" // Sort below ContentClassContent ContentClass = "zcontent" ContentClassZero ContentClass = "zero" // Special value for zeroFile ) func (c ContentClass) IsBundle() bool { return c == ContentClassLeaf || c == ContentClassBranch } func ClassifyContentFile(filename string, open func() (afero.File, error)) ContentClass { if !IsContentFile(filename) { return ContentClassFile } if IsHTMLFile(filename) { // We need to look inside the file. If the first non-whitespace // character is a "<", then we treat it as a regular file. // Eearlier we created pages for these files, but that had all sorts // of troubles, and isn't what it says in the documentation. // See https://github.com/gohugoio/hugo/issues/7030 if open == nil { panic(fmt.Sprintf("no file opener provided for %q", filename)) } f, err := open() if err != nil { return ContentClassFile } ishtml := isHTMLContent(f) f.Close() if ishtml { return ContentClassFile } } if strings.HasPrefix(filename, "_index.") { return ContentClassBranch } if strings.HasPrefix(filename, "index.") { return ContentClassLeaf } return ContentClassContent } var htmlComment = []rune{'<', '!', '-', '-'} func isHTMLContent(r io.Reader) bool { br := bufio.NewReader(r) i := 0 for { c, _, err := br.ReadRune() if err != nil { break } if i > 0 { if i >= len(htmlComment) { return false } if c != htmlComment[i] { return true } i++ continue } if !unicode.IsSpace(c) { if i == 0 && c != '<' { return false } i++ } } return true } 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. ) 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] }
Mai-Lapyst
e3308a0bbc2de1cb4d7571521abeab07049ce31f
cc14c6a52c215fc43716f7b266c4c340b3d28230
I don't think we need/want this. A zero file would have an empty ContentClass string, which is the natural zero value, no need to make one up.
bep
67
gohugoio/hugo
10,847
resources/page: Allow section&taxonomy pages to have a permalink configuration
Allows using permalink configuration for sections (branch bundles) and also for taxonomy pages. Extends the current permalink configuration to be able to specified per page kind while also staying backward compatible: all permalink patterns not dedicated to a certain kind, get automatically added for both normal pages and term pages. Fixes #8523 Example config: ```toml [permalinks] docs = "/docs/1.0/:sections[1:]/:filename" # Will get added to both page & term permalinks [permalinks.section] docs = "/docs/1.0/:sections[1:]" [permalinks.page] [permalinks.term] [permalinks.taxonomy] ```
null
2023-03-17 23:56:51+00:00
2023-06-26 13:31:01+00:00
hugolib/page__paths.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 hugolib import ( "net/url" "strings" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/page" ) func newPagePaths( s *Site, p page.Page, pm *pageMeta) (pagePaths, error) { targetPathDescriptor, err := createTargetPathDescriptor(s, p, pm) if err != nil { return pagePaths{}, err } outputFormats := pm.outputFormats() if len(outputFormats) == 0 { return pagePaths{}, nil } if pm.noRender() { outputFormats = outputFormats[:1] } pageOutputFormats := make(page.OutputFormats, len(outputFormats)) targets := make(map[string]targetPathsHolder) for i, f := range outputFormats { desc := targetPathDescriptor desc.Type = f paths := page.CreateTargetPaths(desc) var relPermalink, permalink string // If a page is headless or bundled in another, // it will not get published on its own and it will have no links. // We also check the build options if it's set to not render or have // a link. if !pm.noLink() && !pm.bundled { relPermalink = paths.RelPermalink(s.PathSpec) permalink = paths.PermalinkForOutputFormat(s.PathSpec, f) } pageOutputFormats[i] = page.NewOutputFormat(relPermalink, permalink, len(outputFormats) == 1, f) // Use the main format for permalinks, usually HTML. permalinksIndex := 0 if f.Permalinkable { // Unless it's permalinkable permalinksIndex = i } targets[f.Name] = targetPathsHolder{ paths: paths, OutputFormat: pageOutputFormats[permalinksIndex], } } var out page.OutputFormats if !pm.noLink() { out = pageOutputFormats } return pagePaths{ outputFormats: out, firstOutputFormat: pageOutputFormats[0], targetPaths: targets, targetPathDescriptor: targetPathDescriptor, }, nil } type pagePaths struct { outputFormats page.OutputFormats firstOutputFormat page.OutputFormat targetPaths map[string]targetPathsHolder targetPathDescriptor page.TargetPathDescriptor } func (l pagePaths) OutputFormats() page.OutputFormats { return l.outputFormats } func createTargetPathDescriptor(s *Site, p page.Page, pm *pageMeta) (page.TargetPathDescriptor, error) { var ( dir string baseName string contentBaseName string ) d := s.Deps if !p.File().IsZero() { dir = p.File().Dir() baseName = p.File().TranslationBaseName() contentBaseName = p.File().ContentBaseName() } if baseName != contentBaseName { // See https://github.com/gohugoio/hugo/issues/4870 // A leaf bundle dir = strings.TrimSuffix(dir, contentBaseName+helpers.FilePathSeparator) baseName = contentBaseName } alwaysInSubDir := p.Kind() == kindSitemap desc := page.TargetPathDescriptor{ PathSpec: d.PathSpec, Kind: p.Kind(), Sections: p.SectionsEntries(), UglyURLs: s.h.Conf.IsUglyURLs(p.Section()), ForcePrefix: s.h.Conf.IsMultihost() || alwaysInSubDir, Dir: dir, URL: pm.urlPaths.URL, } if pm.Slug() != "" { desc.BaseName = pm.Slug() } else { desc.BaseName = baseName } desc.PrefixFilePath = s.getLanguageTargetPathLang(alwaysInSubDir) desc.PrefixLink = s.getLanguagePermalinkLang(alwaysInSubDir) // Expand only page.KindPage and page.KindTaxonomy; don't expand other Kinds of Pages // like page.KindSection or page.KindTaxonomyTerm because they are "shallower" and // the permalink configuration values are likely to be redundant, e.g. // naively expanding /category/:slug/ would give /category/categories/ for // the "categories" page.KindTaxonomyTerm. if p.Kind() == page.KindPage || p.Kind() == page.KindTerm { opath, err := d.ResourceSpec.Permalinks.Expand(p.Section(), p) if err != nil { return desc, err } if opath != "" { opath, _ = url.QueryUnescape(opath) desc.ExpandedPermalink = opath } } return desc, nil }
// 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 hugolib import ( "net/url" "strings" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/resources/page" ) func newPagePaths( s *Site, p page.Page, pm *pageMeta) (pagePaths, error) { targetPathDescriptor, err := createTargetPathDescriptor(s, p, pm) if err != nil { return pagePaths{}, err } outputFormats := pm.outputFormats() if len(outputFormats) == 0 { return pagePaths{}, nil } if pm.noRender() { outputFormats = outputFormats[:1] } pageOutputFormats := make(page.OutputFormats, len(outputFormats)) targets := make(map[string]targetPathsHolder) for i, f := range outputFormats { desc := targetPathDescriptor desc.Type = f paths := page.CreateTargetPaths(desc) var relPermalink, permalink string // If a page is headless or bundled in another, // it will not get published on its own and it will have no links. // We also check the build options if it's set to not render or have // a link. if !pm.noLink() && !pm.bundled { relPermalink = paths.RelPermalink(s.PathSpec) permalink = paths.PermalinkForOutputFormat(s.PathSpec, f) } pageOutputFormats[i] = page.NewOutputFormat(relPermalink, permalink, len(outputFormats) == 1, f) // Use the main format for permalinks, usually HTML. permalinksIndex := 0 if f.Permalinkable { // Unless it's permalinkable permalinksIndex = i } targets[f.Name] = targetPathsHolder{ paths: paths, OutputFormat: pageOutputFormats[permalinksIndex], } } var out page.OutputFormats if !pm.noLink() { out = pageOutputFormats } return pagePaths{ outputFormats: out, firstOutputFormat: pageOutputFormats[0], targetPaths: targets, targetPathDescriptor: targetPathDescriptor, }, nil } type pagePaths struct { outputFormats page.OutputFormats firstOutputFormat page.OutputFormat targetPaths map[string]targetPathsHolder targetPathDescriptor page.TargetPathDescriptor } func (l pagePaths) OutputFormats() page.OutputFormats { return l.outputFormats } func createTargetPathDescriptor(s *Site, p page.Page, pm *pageMeta) (page.TargetPathDescriptor, error) { var ( dir string baseName string contentBaseName string ) d := s.Deps classifier := files.ContentClassZero if !p.File().IsZero() { dir = p.File().Dir() baseName = p.File().TranslationBaseName() contentBaseName = p.File().ContentBaseName() classifier = p.File().Classifier() } if classifier == files.ContentClassLeaf { // See https://github.com/gohugoio/hugo/issues/4870 // A leaf bundle dir = strings.TrimSuffix(dir, contentBaseName+helpers.FilePathSeparator) baseName = contentBaseName } alwaysInSubDir := p.Kind() == kindSitemap desc := page.TargetPathDescriptor{ PathSpec: d.PathSpec, Kind: p.Kind(), Sections: p.SectionsEntries(), UglyURLs: s.h.Conf.IsUglyURLs(p.Section()), ForcePrefix: s.h.Conf.IsMultihost() || alwaysInSubDir, Dir: dir, URL: pm.urlPaths.URL, } if pm.Slug() != "" { desc.BaseName = pm.Slug() } else { desc.BaseName = baseName } desc.PrefixFilePath = s.getLanguageTargetPathLang(alwaysInSubDir) desc.PrefixLink = s.getLanguagePermalinkLang(alwaysInSubDir) opath, err := d.ResourceSpec.Permalinks.Expand(p.Section(), p) if err != nil { return desc, err } if opath != "" { opath, _ = url.QueryUnescape(opath) if strings.HasSuffix(opath, "//") { // When rewriting the _index of the section the permalink config is applied to, // we get douple slashes at the end sometimes; clear them up here opath = strings.TrimSuffix(opath, "/") } desc.ExpandedPermalink = opath if !p.File().IsZero() { s.Log.Debugf("Set expanded permalink path for %s %s to %#v", p.Kind(), p.File().Path(), opath) } else { s.Log.Debugf("Set expanded permalink path for %s in %v to %#v", p.Kind(), desc.Sections, opath) } } return desc, nil }
Mai-Lapyst
e3308a0bbc2de1cb4d7571521abeab07049ce31f
cc14c6a52c215fc43716f7b266c4c340b3d28230
Can you remove these debug statement, it makes the debug log very busy,.
bep
68
gohugoio/hugo
10,847
resources/page: Allow section&taxonomy pages to have a permalink configuration
Allows using permalink configuration for sections (branch bundles) and also for taxonomy pages. Extends the current permalink configuration to be able to specified per page kind while also staying backward compatible: all permalink patterns not dedicated to a certain kind, get automatically added for both normal pages and term pages. Fixes #8523 Example config: ```toml [permalinks] docs = "/docs/1.0/:sections[1:]/:filename" # Will get added to both page & term permalinks [permalinks.section] docs = "/docs/1.0/:sections[1:]" [permalinks.page] [permalinks.term] [permalinks.taxonomy] ```
null
2023-03-17 23:56:51+00:00
2023-06-26 13:31:01+00:00
resources/page/permalinks_test.go
// Copyright 2023 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 page import ( "fmt" "regexp" "strings" "sync" "testing" "time" qt "github.com/frankban/quicktest" ) // testdataPermalinks is used by a couple of tests; the expandsTo content is // subject to the data in simplePageJSON. var testdataPermalinks = []struct { spec string valid bool expandsTo string }{ {":title", true, "spf13-vim-3.0-release-and-new-website"}, {"/:year-:month-:title", true, "/2012-04-spf13-vim-3.0-release-and-new-website"}, {"/:year/:yearday/:month/:monthname/:day/:weekday/:weekdayname/", true, "/2012/97/04/April/06/5/Friday/"}, // Dates {"/:section/", true, "/blue/"}, // Section {"/:title/", true, "/spf13-vim-3.0-release-and-new-website/"}, // Title {"/:slug/", true, "/the-slug/"}, // Slug {"/:slugorfilename/", true, "/the-slug/"}, // Slug or filename {"/:filename/", true, "/test-page/"}, // Filename {"/:06-:1-:2-:Monday", true, "/12-4-6-Friday"}, // Dates with Go formatting {"/:2006_01_02_15_04_05.000", true, "/2012_04_06_03_01_59.000"}, // Complicated custom date format {"/:sections/", true, "/a/b/c/"}, // Sections {"/:sections[last]/", true, "/c/"}, // Sections {"/:sections[0]/:sections[last]/", true, "/a/c/"}, // Sections // Failures {"/blog/:fred", false, ""}, {"/:year//:title", false, ""}, {"/:TITLE", false, ""}, // case is not normalized {"/:2017", false, ""}, // invalid date format {"/:2006-01-02", false, ""}, // valid date format but invalid attribute name } func urlize(uri string) string { // This is just an approximation of the real urlize function. return strings.ToLower(strings.ReplaceAll(uri, " ", "-")) } func TestPermalinkExpansion(t *testing.T) { t.Parallel() c := qt.New(t) page := newTestPageWithFile("/test-page/index.md") page.title = "Spf13 Vim 3.0 Release and new website" d, _ := time.Parse("2006-01-02 15:04:05", "2012-04-06 03:01:59") page.date = d page.section = "blue" page.slug = "The Slug" for _, item := range testdataPermalinks { if !item.valid { continue } specNameCleaner := regexp.MustCompile(`[\:\/\[\]]`) name := specNameCleaner.ReplaceAllString(item.spec, "") c.Run(name, func(c *qt.C) { patterns := map[string]string{ "posts": item.spec, } expander, err := NewPermalinkExpander(urlize, patterns) c.Assert(err, qt.IsNil) expanded, err := expander.Expand("posts", page) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, item.expandsTo) }) } } func TestPermalinkExpansionMultiSection(t *testing.T) { t.Parallel() c := qt.New(t) page := newTestPage() page.title = "Page Title" d, _ := time.Parse("2006-01-02", "2012-04-06") page.date = d page.section = "blue" page.slug = "The Slug" page_slug_fallback := newTestPageWithFile("/page-filename/index.md") page_slug_fallback.title = "Page Title" permalinksConfig := map[string]string{ "posts": "/:slug", "blog": "/:section/:year", "recipes": "/:slugorfilename", } expander, err := NewPermalinkExpander(urlize, permalinksConfig) c.Assert(err, qt.IsNil) expanded, err := expander.Expand("posts", page) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, "/the-slug") expanded, err = expander.Expand("blog", page) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, "/blue/2012") expanded, err = expander.Expand("posts", page_slug_fallback) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, "/page-title") expanded, err = expander.Expand("recipes", page_slug_fallback) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, "/page-filename") } func TestPermalinkExpansionConcurrent(t *testing.T) { t.Parallel() c := qt.New(t) permalinksConfig := map[string]string{ "posts": "/:slug/", } expander, err := NewPermalinkExpander(urlize, permalinksConfig) c.Assert(err, qt.IsNil) var wg sync.WaitGroup for i := 1; i < 20; i++ { wg.Add(1) go func(i int) { defer wg.Done() page := newTestPage() for j := 1; j < 20; j++ { page.slug = fmt.Sprintf("slug%d", i+j) expanded, err := expander.Expand("posts", page) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, fmt.Sprintf("/%s/", page.slug)) } }(i) } wg.Wait() } func TestPermalinkExpansionSliceSyntax(t *testing.T) { t.Parallel() c := qt.New(t) exp, err := NewPermalinkExpander(urlize, nil) c.Assert(err, qt.IsNil) slice := []string{"a", "b", "c", "d"} fn := func(s string) []string { return exp.toSliceFunc(s)(slice) } c.Run("Basic", func(c *qt.C) { c.Assert(fn("[1:3]"), qt.DeepEquals, []string{"b", "c"}) c.Assert(fn("[1:]"), qt.DeepEquals, []string{"b", "c", "d"}) c.Assert(fn("[:2]"), qt.DeepEquals, []string{"a", "b"}) c.Assert(fn("[0:2]"), qt.DeepEquals, []string{"a", "b"}) c.Assert(fn("[:]"), qt.DeepEquals, []string{"a", "b", "c", "d"}) c.Assert(fn(""), qt.DeepEquals, []string{"a", "b", "c", "d"}) c.Assert(fn("[last]"), qt.DeepEquals, []string{"d"}) c.Assert(fn("[:last]"), qt.DeepEquals, []string{"a", "b", "c"}) }) c.Run("Out of bounds", func(c *qt.C) { c.Assert(fn("[1:5]"), qt.DeepEquals, []string{"b", "c", "d"}) c.Assert(fn("[-1:5]"), qt.DeepEquals, []string{"a", "b", "c", "d"}) c.Assert(fn("[5:]"), qt.DeepEquals, []string{}) c.Assert(fn("[5:]"), qt.DeepEquals, []string{}) c.Assert(fn("[5:32]"), qt.DeepEquals, []string{}) c.Assert(exp.toSliceFunc("[:1]")(nil), qt.DeepEquals, []string(nil)) c.Assert(exp.toSliceFunc("[:1]")([]string{}), qt.DeepEquals, []string(nil)) // These all return nil c.Assert(fn("[]"), qt.IsNil) c.Assert(fn("[1:}"), qt.IsNil) c.Assert(fn("foo"), qt.IsNil) }) } func BenchmarkPermalinkExpand(b *testing.B) { page := newTestPage() page.title = "Hugo Rocks" d, _ := time.Parse("2006-01-02", "2019-02-28") page.date = d permalinksConfig := map[string]string{ "posts": "/:year-:month-:title", } expander, err := NewPermalinkExpander(urlize, permalinksConfig) if err != nil { b.Fatal(err) } b.ResetTimer() for i := 0; i < b.N; i++ { s, err := expander.Expand("posts", page) if err != nil { b.Fatal(err) } if s != "/2019-02-hugo-rocks" { b.Fatal(s) } } }
// Copyright 2023 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 page import ( "fmt" "regexp" "strings" "sync" "testing" "time" qt "github.com/frankban/quicktest" ) // testdataPermalinks is used by a couple of tests; the expandsTo content is // subject to the data in simplePageJSON. var testdataPermalinks = []struct { spec string valid bool expandsTo string }{ {":title", true, "spf13-vim-3.0-release-and-new-website"}, {"/:year-:month-:title", true, "/2012-04-spf13-vim-3.0-release-and-new-website"}, {"/:year/:yearday/:month/:monthname/:day/:weekday/:weekdayname/", true, "/2012/97/04/April/06/5/Friday/"}, // Dates {"/:section/", true, "/blue/"}, // Section {"/:title/", true, "/spf13-vim-3.0-release-and-new-website/"}, // Title {"/:slug/", true, "/the-slug/"}, // Slug {"/:slugorfilename/", true, "/the-slug/"}, // Slug or filename {"/:filename/", true, "/test-page/"}, // Filename {"/:06-:1-:2-:Monday", true, "/12-4-6-Friday"}, // Dates with Go formatting {"/:2006_01_02_15_04_05.000", true, "/2012_04_06_03_01_59.000"}, // Complicated custom date format {"/:sections/", true, "/a/b/c/"}, // Sections {"/:sections[last]/", true, "/c/"}, // Sections {"/:sections[0]/:sections[last]/", true, "/a/c/"}, // Sections // Failures {"/blog/:fred", false, ""}, {"/:year//:title", false, ""}, {"/:TITLE", false, ""}, // case is not normalized {"/:2017", false, ""}, // invalid date format {"/:2006-01-02", false, ""}, // valid date format but invalid attribute name } func urlize(uri string) string { // This is just an approximation of the real urlize function. return strings.ToLower(strings.ReplaceAll(uri, " ", "-")) } func TestPermalinkExpansion(t *testing.T) { t.Parallel() c := qt.New(t) page := newTestPageWithFile("/test-page/index.md") page.title = "Spf13 Vim 3.0 Release and new website" d, _ := time.Parse("2006-01-02 15:04:05", "2012-04-06 03:01:59") page.date = d page.section = "blue" page.slug = "The Slug" page.kind = "page" for _, item := range testdataPermalinks { if !item.valid { continue } specNameCleaner := regexp.MustCompile(`[\:\/\[\]]`) name := specNameCleaner.ReplaceAllString(item.spec, "") c.Run(name, func(c *qt.C) { patterns := map[string]map[string]string{ "page": { "posts": item.spec, }, } expander, err := NewPermalinkExpander(urlize, patterns) c.Assert(err, qt.IsNil) expanded, err := expander.Expand("posts", page) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, item.expandsTo) }) } } func TestPermalinkExpansionMultiSection(t *testing.T) { t.Parallel() c := qt.New(t) page := newTestPage() page.title = "Page Title" d, _ := time.Parse("2006-01-02", "2012-04-06") page.date = d page.section = "blue" page.slug = "The Slug" page.kind = "page" page_slug_fallback := newTestPageWithFile("/page-filename/index.md") page_slug_fallback.title = "Page Title" page_slug_fallback.kind = "page" permalinksConfig := map[string]map[string]string{ "page": { "posts": "/:slug", "blog": "/:section/:year", "recipes": "/:slugorfilename", }, } expander, err := NewPermalinkExpander(urlize, permalinksConfig) c.Assert(err, qt.IsNil) expanded, err := expander.Expand("posts", page) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, "/the-slug") expanded, err = expander.Expand("blog", page) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, "/blue/2012") expanded, err = expander.Expand("posts", page_slug_fallback) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, "/page-title") expanded, err = expander.Expand("recipes", page_slug_fallback) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, "/page-filename") } func TestPermalinkExpansionConcurrent(t *testing.T) { t.Parallel() c := qt.New(t) permalinksConfig := map[string]map[string]string{ "page": { "posts": "/:slug/", }, } expander, err := NewPermalinkExpander(urlize, permalinksConfig) c.Assert(err, qt.IsNil) var wg sync.WaitGroup for i := 1; i < 20; i++ { wg.Add(1) go func(i int) { defer wg.Done() page := newTestPage() page.kind = "page" for j := 1; j < 20; j++ { page.slug = fmt.Sprintf("slug%d", i+j) expanded, err := expander.Expand("posts", page) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, fmt.Sprintf("/%s/", page.slug)) } }(i) } wg.Wait() } func TestPermalinkExpansionSliceSyntax(t *testing.T) { t.Parallel() c := qt.New(t) exp, err := NewPermalinkExpander(urlize, nil) c.Assert(err, qt.IsNil) slice := []string{"a", "b", "c", "d"} fn := func(s string) []string { return exp.toSliceFunc(s)(slice) } c.Run("Basic", func(c *qt.C) { c.Assert(fn("[1:3]"), qt.DeepEquals, []string{"b", "c"}) c.Assert(fn("[1:]"), qt.DeepEquals, []string{"b", "c", "d"}) c.Assert(fn("[:2]"), qt.DeepEquals, []string{"a", "b"}) c.Assert(fn("[0:2]"), qt.DeepEquals, []string{"a", "b"}) c.Assert(fn("[:]"), qt.DeepEquals, []string{"a", "b", "c", "d"}) c.Assert(fn(""), qt.DeepEquals, []string{"a", "b", "c", "d"}) c.Assert(fn("[last]"), qt.DeepEquals, []string{"d"}) c.Assert(fn("[:last]"), qt.DeepEquals, []string{"a", "b", "c"}) }) c.Run("Out of bounds", func(c *qt.C) { c.Assert(fn("[1:5]"), qt.DeepEquals, []string{"b", "c", "d"}) c.Assert(fn("[-1:5]"), qt.DeepEquals, []string{"a", "b", "c", "d"}) c.Assert(fn("[5:]"), qt.DeepEquals, []string{}) c.Assert(fn("[5:]"), qt.DeepEquals, []string{}) c.Assert(fn("[5:32]"), qt.DeepEquals, []string{}) c.Assert(exp.toSliceFunc("[:1]")(nil), qt.DeepEquals, []string(nil)) c.Assert(exp.toSliceFunc("[:1]")([]string{}), qt.DeepEquals, []string(nil)) // These all return nil c.Assert(fn("[]"), qt.IsNil) c.Assert(fn("[1:}"), qt.IsNil) c.Assert(fn("foo"), qt.IsNil) }) } func BenchmarkPermalinkExpand(b *testing.B) { page := newTestPage() page.title = "Hugo Rocks" d, _ := time.Parse("2006-01-02", "2019-02-28") page.date = d page.kind = "page" permalinksConfig := map[string]map[string]string{ "page": { "posts": "/:year-:month-:title", }, } expander, err := NewPermalinkExpander(urlize, permalinksConfig) if err != nil { b.Fatal(err) } b.ResetTimer() for i := 0; i < b.N; i++ { s, err := expander.Expand("posts", page) if err != nil { b.Fatal(err) } if s != "/2019-02-hugo-rocks" { b.Fatal(s) } } }
Mai-Lapyst
e3308a0bbc2de1cb4d7571521abeab07049ce31f
cc14c6a52c215fc43716f7b266c4c340b3d28230
This all looks good, but I think we need a test that shows the new setup working. I suggest you create a new `permalink_integration_test.go` and follow the the cue of similar tests (using the NewIntegrationTest...) that tests the new permalink setup in a site build.
bep
69
gohugoio/hugo
10,828
fix: math (must provide at least two values)
resolve #10827
null
2023-03-12 17:40:39+00:00
2023-03-14 08:28:39+00:00
tpl/math/math.go
// Copyright 2017 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 math provides template functions for mathematical operations. package math import ( "errors" "math" "sync/atomic" _math "github.com/gohugoio/hugo/common/math" "github.com/spf13/cast" ) // New returns a new instance of the math-namespaced template functions. func New() *Namespace { return &Namespace{} } // Namespace provides template functions for the "math" namespace. type Namespace struct{} // Add adds the multivalued addends n1 and n2 or more values. func (ns *Namespace) Add(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '+') } // Ceil returns the least integer value greater than or equal to n. func (ns *Namespace) Ceil(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Ceil operator can't be used with non-float value") } return math.Ceil(xf), nil } // Div divides n1 by n2. func (ns *Namespace) Div(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '/') } // Floor returns the greatest integer value less than or equal to n. func (ns *Namespace) Floor(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Floor operator can't be used with non-float value") } return math.Floor(xf), nil } // Log returns the natural logarithm of the number n. func (ns *Namespace) Log(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Log operator can't be used with non integer or float value") } return math.Log(af), nil } // Max returns the greater of the multivalued numbers n1 and n2 or more values. func (ns *Namespace) Max(inputs ...any) (maximum float64, err error) { var value float64 for index, input := range inputs { value, err = cast.ToFloat64E(input) if err != nil { err = errors.New("Max operator can't be used with non-float value") return } if index == 0 { maximum = value continue } maximum = math.Max(value, maximum) } return } // Min returns the smaller of multivalued numbers n1 and n2 or more values. func (ns *Namespace) Min(inputs ...any) (minimum float64, err error) { var value float64 for index, input := range inputs { value, err = cast.ToFloat64E(input) if err != nil { err = errors.New("Max operator can't be used with non-float value") return } if index == 0 { minimum = value continue } minimum = math.Min(value, minimum) } return } // Mod returns n1 % n2. func (ns *Namespace) Mod(n1, n2 any) (int64, error) { ai, erra := cast.ToInt64E(n1) bi, errb := cast.ToInt64E(n2) if erra != nil || errb != nil { return 0, errors.New("modulo operator can't be used with non integer value") } if bi == 0 { return 0, errors.New("the number can't be divided by zero at modulo operation") } return ai % bi, nil } // ModBool returns the boolean of n1 % n2. If n1 % n2 == 0, return true. func (ns *Namespace) ModBool(n1, n2 any) (bool, error) { res, err := ns.Mod(n1, n2) if err != nil { return false, err } return res == int64(0), nil } // Mul multiplies the multivalued numbers n1 and n2 or more values. func (ns *Namespace) Mul(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '*') } // Pow returns n1 raised to the power of n2. func (ns *Namespace) Pow(n1, n2 any) (float64, error) { af, erra := cast.ToFloat64E(n1) bf, errb := cast.ToFloat64E(n2) if erra != nil || errb != nil { return 0, errors.New("Pow operator can't be used with non-float value") } return math.Pow(af, bf), nil } // Round returns the integer nearest to n, rounding half away from zero. func (ns *Namespace) Round(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Round operator can't be used with non-float value") } return _round(xf), nil } // Sqrt returns the square root of the number n. func (ns *Namespace) Sqrt(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Sqrt operator can't be used with non integer or float value") } return math.Sqrt(af), nil } // Sub subtracts multivalued. func (ns *Namespace) Sub(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '-') } func (ns *Namespace) doArithmetic(inputs []any, operation rune) (value any, err error) { value = inputs[0] for i := 1; i < len(inputs); i++ { value, err = _math.DoArithmetic(value, inputs[i], operation) if err != nil { return } } return } var counter uint64 // Counter increments and returns a global counter. // This was originally added to be used in tests where now.UnixNano did not // have the needed precision (especially on Windows). // Note that given the parallel nature of Hugo, you cannot use this to get sequences of numbers, // and the counter will reset on new builds. func (ns *Namespace) Counter() uint64 { return atomic.AddUint64(&counter, uint64(1)) }
// Copyright 2017 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 math provides template functions for mathematical operations. package math import ( "errors" "math" "sync/atomic" _math "github.com/gohugoio/hugo/common/math" "github.com/spf13/cast" ) var ( errMustTwoNumbersError = errors.New("must provide at least two numbers") ) // New returns a new instance of the math-namespaced template functions. func New() *Namespace { return &Namespace{} } // Namespace provides template functions for the "math" namespace. type Namespace struct{} // Add adds the multivalued addends n1 and n2 or more values. func (ns *Namespace) Add(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '+') } // Ceil returns the least integer value greater than or equal to n. func (ns *Namespace) Ceil(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Ceil operator can't be used with non-float value") } return math.Ceil(xf), nil } // Div divides n1 by n2. func (ns *Namespace) Div(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '/') } // Floor returns the greatest integer value less than or equal to n. func (ns *Namespace) Floor(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Floor operator can't be used with non-float value") } return math.Floor(xf), nil } // Log returns the natural logarithm of the number n. func (ns *Namespace) Log(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Log operator can't be used with non integer or float value") } return math.Log(af), nil } // Max returns the greater of the multivalued numbers n1 and n2 or more values. func (ns *Namespace) Max(inputs ...any) (maximum float64, err error) { if len(inputs) < 2 { err = errMustTwoNumbersError return } var value float64 for index, input := range inputs { value, err = cast.ToFloat64E(input) if err != nil { err = errors.New("Max operator can't be used with non-float value") return } if index == 0 { maximum = value continue } maximum = math.Max(value, maximum) } return } // Min returns the smaller of multivalued numbers n1 and n2 or more values. func (ns *Namespace) Min(inputs ...any) (minimum float64, err error) { if len(inputs) < 2 { err = errMustTwoNumbersError return } var value float64 for index, input := range inputs { value, err = cast.ToFloat64E(input) if err != nil { err = errors.New("Max operator can't be used with non-float value") return } if index == 0 { minimum = value continue } minimum = math.Min(value, minimum) } return } // Mod returns n1 % n2. func (ns *Namespace) Mod(n1, n2 any) (int64, error) { ai, erra := cast.ToInt64E(n1) bi, errb := cast.ToInt64E(n2) if erra != nil || errb != nil { return 0, errors.New("modulo operator can't be used with non integer value") } if bi == 0 { return 0, errors.New("the number can't be divided by zero at modulo operation") } return ai % bi, nil } // ModBool returns the boolean of n1 % n2. If n1 % n2 == 0, return true. func (ns *Namespace) ModBool(n1, n2 any) (bool, error) { res, err := ns.Mod(n1, n2) if err != nil { return false, err } return res == int64(0), nil } // Mul multiplies the multivalued numbers n1 and n2 or more values. func (ns *Namespace) Mul(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '*') } // Pow returns n1 raised to the power of n2. func (ns *Namespace) Pow(n1, n2 any) (float64, error) { af, erra := cast.ToFloat64E(n1) bf, errb := cast.ToFloat64E(n2) if erra != nil || errb != nil { return 0, errors.New("Pow operator can't be used with non-float value") } return math.Pow(af, bf), nil } // Round returns the integer nearest to n, rounding half away from zero. func (ns *Namespace) Round(n any) (float64, error) { xf, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Round operator can't be used with non-float value") } return _round(xf), nil } // Sqrt returns the square root of the number n. func (ns *Namespace) Sqrt(n any) (float64, error) { af, err := cast.ToFloat64E(n) if err != nil { return 0, errors.New("Sqrt operator can't be used with non integer or float value") } return math.Sqrt(af), nil } // Sub subtracts multivalued. func (ns *Namespace) Sub(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '-') } func (ns *Namespace) doArithmetic(inputs []any, operation rune) (value any, err error) { if len(inputs) < 2 { return nil, errMustTwoNumbersError } value = inputs[0] for i := 1; i < len(inputs); i++ { value, err = _math.DoArithmetic(value, inputs[i], operation) if err != nil { return } } return } var counter uint64 // Counter increments and returns a global counter. // This was originally added to be used in tests where now.UnixNano did not // have the needed precision (especially on Windows). // Note that given the parallel nature of Hugo, you cannot use this to get sequences of numbers, // and the counter will reset on new builds. func (ns *Namespace) Counter() uint64 { return atomic.AddUint64(&counter, uint64(1)) }
septs
0e8ab20a841ccf86eba9128fd3712026b206abc7
f5eddf89bf6c8ea9571c16f301f6b449259e6187
Can you change the error message to: ``` must provide at least two numbers ``` And note that all error strings should start with a lower case char.
bep
70
gohugoio/hugo
10,779
Hugo deploy customize parallel transfer count
### What is the purpose? The current hugo deploy limits the number of parallel requests by 10 with `nParallel = 10` This PR allows customization of this value by providing another flag called transfers ### Why? It can sometimes be useful to set this to a smaller number if the remote is giving a lot of timeouts or bigger if you have lots of bandwidth and a fast remote. In my testing setting this to 100 in one of our bigger deployment runners reduced our time to deploy to s3 from `1min 50s` to `32s` ### Existing users Exiting users should see no change as it will default to 10 ### Example Usage ```bash hugo deploy --target foo --workers 20 ```
null
2023-03-03 19:59:34+00:00
2023-03-07 14:38:27+00:00
docs/content/en/commands/hugo_deploy.md
--- title: "hugo deploy" slug: hugo_deploy url: /commands/hugo_deploy/ --- ## hugo deploy Deploy your site to a Cloud provider. ### Synopsis Deploy your site to a Cloud provider. See https://gohugo.io/hosting-and-deployment/hugo-deploy/ for detailed documentation. ``` hugo deploy [flags] ``` ### Options ``` --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 --confirm ask for confirmation before making changes to the target --dryRun dry run -e, --environment string build environment --force force upload of all files -h, --help help for deploy --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern --invalidateCDN invalidate the CDN cache listed in the deployment target (default true) --maxDeletes int maximum # of files to delete, or -1 to disable (default 256) --workers int number of workers to transfer files. (default 10) -s, --source string filesystem path to read files relative from --target string target deployment from deployments section in config file; defaults to the first one --themesDir string filesystem path to themes directory ``` ### Options inherited from parent commands ``` --config string config file (default is hugo.yaml|json|toml) --configDir string config dir (default "config") --debug debug output --log enable Logging --logFile string log File path (if set, logging enabled automatically) --quiet build in quiet mode -v, --verbose verbose output --verboseLog verbose logging ``` ### SEE ALSO * [hugo](/commands/hugo/) - hugo builds your site
--- title: "hugo deploy" slug: hugo_deploy url: /commands/hugo_deploy/ --- ## hugo deploy Deploy your site to a Cloud provider. ### Synopsis Deploy your site to a Cloud provider. See https://gohugo.io/hosting-and-deployment/hugo-deploy/ for detailed documentation. ``` hugo deploy [flags] ``` ### Options ``` --clock string set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00 --confirm ask for confirmation before making changes to the target --dryRun dry run -e, --environment string build environment --force force upload of all files -h, --help help for deploy --ignoreVendorPaths string ignores any _vendor for module paths matching the given Glob pattern --invalidateCDN invalidate the CDN cache listed in the deployment target (default true) --maxDeletes int maximum # of files to delete, or -1 to disable (default 256) --workers int number of workers to transfer files. (default 10) -s, --source string filesystem path to read files relative from --target string target deployment from deployments section in config file; defaults to the first one --themesDir string filesystem path to themes directory ``` ### Options inherited from parent commands ``` --config string config file (default is hugo.yaml|json|toml) --configDir string config dir (default "config") --debug debug output --log enable Logging --logFile string log File path (if set, logging enabled automatically) --quiet build in quiet mode -v, --verbose verbose output --verboseLog verbose logging ``` ### SEE ALSO * [hugo](/commands/hugo/) - hugo builds your site
davidejones
bebb2b8d0a0a15350c492b13ce878ac5b01d488c
873be9f90aa0e23c1ec8cd99e9753742d9c4a36d
looks like `.` is not needed, for consistency with other options ```suggestion --workers int number of workers to transfer files (default 10) ```
alexandear
71
gohugoio/hugo
10,676
Add some shortcode testcases
Updates #10671
null
2023-01-31 08:28:49+00:00
2023-02-23 08:36:15+00:00
hugolib/shortcode_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 hugolib import ( "context" "fmt" "path/filepath" "reflect" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources/page" qt "github.com/frankban/quicktest" ) func TestExtractShortcodes(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithTemplates( "default/single.html", `EMPTY`, "_internal/shortcodes/tag.html", `tag`, "_internal/shortcodes/legacytag.html", `{{ $_hugo_config := "{ \"version\": 1 }" }}tag`, "_internal/shortcodes/sc1.html", `sc1`, "_internal/shortcodes/sc2.html", `sc2`, "_internal/shortcodes/inner.html", `{{with .Inner }}{{ . }}{{ end }}`, "_internal/shortcodes/inner2.html", `{{.Inner}}`, "_internal/shortcodes/inner3.html", `{{.Inner}}`, ).WithContent("page.md", `--- title: "Shortcodes Galore!" --- `) b.CreateSites().Build(BuildCfg{}) s := b.H.Sites[0] // Make it more regexp friendly strReplacer := strings.NewReplacer("[", "{", "]", "}") str := func(s *shortcode) string { if s == nil { return "<nil>" } var version int if s.info != nil { version = s.info.ParseInfo().Config.Version } return strReplacer.Replace(fmt.Sprintf("%s;inline:%t;closing:%t;inner:%v;params:%v;ordinal:%d;markup:%t;version:%d;pos:%d", s.name, s.isInline, s.isClosing, s.inner, s.params, s.ordinal, s.doMarkup, version, s.pos)) } regexpCheck := func(re string) func(c *qt.C, shortcode *shortcode, err error) { return func(c *qt.C, shortcode *shortcode, err error) { c.Assert(err, qt.IsNil) c.Assert(str(shortcode), qt.Matches, ".*"+re+".*") } } for _, test := range []struct { name string input string check func(c *qt.C, shortcode *shortcode, err error) }{ {"one shortcode, no markup", "{{< tag >}}", regexpCheck("tag.*closing:false.*markup:false")}, {"one shortcode, markup", "{{% tag %}}", regexpCheck("tag.*closing:false.*markup:true;version:2")}, {"one shortcode, markup, legacy", "{{% legacytag %}}", regexpCheck("tag.*closing:false.*markup:true;version:1")}, {"outer shortcode markup", "{{% inner %}}{{< tag >}}{{% /inner %}}", regexpCheck("inner.*closing:true.*markup:true")}, {"inner shortcode markup", "{{< inner >}}{{% tag %}}{{< /inner >}}", regexpCheck("inner.*closing:true.*;markup:false;version:2")}, {"one pos param", "{{% tag param1 %}}", regexpCheck("tag.*params:{param1}")}, {"two pos params", "{{< tag param1 param2>}}", regexpCheck("tag.*params:{param1 param2}")}, {"one named param", `{{% tag param1="value" %}}`, regexpCheck("tag.*params:map{param1:value}")}, {"two named params", `{{< tag param1="value1" param2="value2" >}}`, regexpCheck("tag.*params:map{param\\d:value\\d param\\d:value\\d}")}, {"inner", `{{< inner >}}Inner Content{{< / inner >}}`, regexpCheck("inner;inline:false;closing:true;inner:{Inner Content};")}, // issue #934 {"inner self-closing", `{{< inner />}}`, regexpCheck("inner;.*inner:{}")}, { "nested inner", `{{< inner >}}Inner Content->{{% inner2 param1 %}}inner2txt{{% /inner2 %}}Inner close->{{< / inner >}}`, regexpCheck("inner;.*inner:{Inner Content->.*Inner close->}"), }, { "nested, nested inner", `{{< inner >}}inner2->{{% inner2 param1 %}}inner2txt->inner3{{< inner3>}}inner3txt{{</ inner3 >}}{{% /inner2 %}}final close->{{< / inner >}}`, regexpCheck("inner:{inner2-> inner2.*{{inner2txt->inner3.*final close->}"), }, {"closed without content", `{{< inner param1 >}}{{< / inner >}}`, regexpCheck("inner.*inner:{}")}, {"inline", `{{< my.inline >}}Hi{{< /my.inline >}}`, regexpCheck("my.inline;inline:true;closing:true;inner:{Hi};")}, } { test := test t.Run(test.name, func(t *testing.T) { t.Parallel() c := qt.New(t) p, err := pageparser.ParseMain(strings.NewReader(test.input), pageparser.Config{}) c.Assert(err, qt.IsNil) handler := newShortcodeHandler(nil, s) iter := p.Iterator() short, err := handler.extractShortcode(0, 0, p.Input(), iter) test.check(c, short, err) }) } } func TestShortcodeMultipleOutputFormats(t *testing.T) { t.Parallel() siteConfig := ` baseURL = "http://example.com/blog" paginate = 1 disableKinds = ["section", "term", "taxonomy", "RSS", "sitemap", "robotsTXT", "404"] [outputs] home = [ "HTML", "AMP", "Calendar" ] page = [ "HTML", "AMP", "JSON" ] ` pageTemplate := `--- title: "%s" --- # Doc {{< myShort >}} {{< noExt >}} {{%% onlyHTML %%}} {{< myInner >}}{{< myShort >}}{{< /myInner >}} ` pageTemplateCSVOnly := `--- title: "%s" outputs: ["CSV"] --- # Doc CSV: {{< myShort >}} ` b := newTestSitesBuilder(t).WithConfigFile("toml", siteConfig) b.WithTemplates( "layouts/_default/single.html", `Single HTML: {{ .Title }}|{{ .Content }}`, "layouts/_default/single.json", `Single JSON: {{ .Title }}|{{ .Content }}`, "layouts/_default/single.csv", `Single CSV: {{ .Title }}|{{ .Content }}`, "layouts/index.html", `Home HTML: {{ .Title }}|{{ .Content }}`, "layouts/index.amp.html", `Home AMP: {{ .Title }}|{{ .Content }}`, "layouts/index.ics", `Home Calendar: {{ .Title }}|{{ .Content }}`, "layouts/shortcodes/myShort.html", `ShortHTML`, "layouts/shortcodes/myShort.amp.html", `ShortAMP`, "layouts/shortcodes/myShort.csv", `ShortCSV`, "layouts/shortcodes/myShort.ics", `ShortCalendar`, "layouts/shortcodes/myShort.json", `ShortJSON`, "layouts/shortcodes/noExt", `ShortNoExt`, "layouts/shortcodes/onlyHTML.html", `ShortOnlyHTML`, "layouts/shortcodes/myInner.html", `myInner:--{{- .Inner -}}--`, ) b.WithContent("_index.md", fmt.Sprintf(pageTemplate, "Home"), "sect/mypage.md", fmt.Sprintf(pageTemplate, "Single"), "sect/mycsvpage.md", fmt.Sprintf(pageTemplateCSVOnly, "Single CSV"), ) b.Build(BuildCfg{}) h := b.H b.Assert(len(h.Sites), qt.Equals, 1) s := h.Sites[0] home := s.getPage(page.KindHome) b.Assert(home, qt.Not(qt.IsNil)) b.Assert(len(home.OutputFormats()), qt.Equals, 3) b.AssertFileContent("public/index.html", "Home HTML", "ShortHTML", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortHTML--", ) b.AssertFileContent("public/amp/index.html", "Home AMP", "ShortAMP", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortAMP--", ) b.AssertFileContent("public/index.ics", "Home Calendar", "ShortCalendar", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortCalendar--", ) b.AssertFileContent("public/sect/mypage/index.html", "Single HTML", "ShortHTML", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortHTML--", ) b.AssertFileContent("public/sect/mypage/index.json", "Single JSON", "ShortJSON", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortJSON--", ) b.AssertFileContent("public/amp/sect/mypage/index.html", // No special AMP template "Single HTML", "ShortAMP", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortAMP--", ) b.AssertFileContent("public/sect/mycsvpage/index.csv", "Single CSV", "ShortCSV", ) } func BenchmarkReplaceShortcodeTokens(b *testing.B) { type input struct { in []byte tokenHandler func(ctx context.Context, token string) ([]byte, error) expect []byte } data := []struct { input string replacements map[string]string expect []byte }{ {"Hello HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, []byte("Hello World.")}, {strings.Repeat("A", 100) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A", 100) + " Hello World.")}, {strings.Repeat("A", 500) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A", 500) + " Hello World.")}, {strings.Repeat("ABCD ", 500) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("ABCD ", 500) + " Hello World.")}, {strings.Repeat("A ", 3000) + " HAHAHUGOSHORTCODE-1HBHB." + strings.Repeat("BC ", 1000) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A ", 3000) + " Hello World." + strings.Repeat("BC ", 1000) + " Hello World.")}, } cnt := 0 in := make([]input, b.N*len(data)) for i := 0; i < b.N; i++ { for _, this := range data { replacements := make(map[string]shortcodeRenderer) for k, v := range this.replacements { replacements[k] = prerenderedShortcode{s: v} } tokenHandler := func(ctx context.Context, token string) ([]byte, error) { return []byte(this.replacements[token]), nil } in[cnt] = input{[]byte(this.input), tokenHandler, this.expect} cnt++ } } b.ResetTimer() cnt = 0 ctx := context.Background() for i := 0; i < b.N; i++ { for j := range data { currIn := in[cnt] cnt++ results, err := expandShortcodeTokens(ctx, currIn.in, currIn.tokenHandler) if err != nil { b.Fatalf("[%d] failed: %s", i, err) continue } if len(results) != len(currIn.expect) { b.Fatalf("[%d] replaceShortcodeTokens, got \n%q but expected \n%q", j, results, currIn.expect) } } } } func BenchmarkShortcodesInSite(b *testing.B) { files := ` -- config.toml -- -- layouts/shortcodes/mark1.md -- {{ .Inner }} -- layouts/shortcodes/mark2.md -- 1. Item Mark2 1 1. Item Mark2 2 1. Item Mark2 2-1 1. Item Mark2 3 -- layouts/_default/single.html -- {{ .Content }} ` content := ` --- title: "Markdown Shortcode" --- ## List 1. List 1 {{§ mark1 §}} 1. Item Mark1 1 1. Item Mark1 2 {{§ mark2 §}} {{§ /mark1 §}} ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } files = strings.ReplaceAll(files, "§", "%") cfg := IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*IntegrationTestBuilder, b.N) for i := range builders { builders[i] = NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func TestReplaceShortcodeTokens(t *testing.T) { t.Parallel() for i, this := range []struct { input string prefix string replacements map[string]string expect any }{ {"Hello HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello World."}, {"Hello HAHAHUGOSHORTCODE-1@}@.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, false}, {"HAHAHUGOSHORTCODE2-1HBHB", "PREFIX2", map[string]string{"HAHAHUGOSHORTCODE2-1HBHB": "World"}, "World"}, {"Hello World!", "PREFIX2", map[string]string{}, "Hello World!"}, {"!HAHAHUGOSHORTCODE-1HBHB", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "!World"}, {"HAHAHUGOSHORTCODE-1HBHB!", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "World!"}, {"!HAHAHUGOSHORTCODE-1HBHB!", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "!World!"}, {"_{_PREFIX-1HBHB", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "_{_PREFIX-1HBHB"}, {"Hello HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "To You My Old Friend Who Told Me This Fantastic Story"}, "Hello To You My Old Friend Who Told Me This Fantastic Story."}, {"A HAHAHUGOSHORTCODE-1HBHB asdf HAHAHUGOSHORTCODE-2HBHB.", "A", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "v1", "HAHAHUGOSHORTCODE-2HBHB": "v2"}, "A v1 asdf v2."}, {"Hello HAHAHUGOSHORTCODE2-1HBHB. Go HAHAHUGOSHORTCODE2-2HBHB, Go, Go HAHAHUGOSHORTCODE2-3HBHB Go Go!.", "PREFIX2", map[string]string{"HAHAHUGOSHORTCODE2-1HBHB": "Europe", "HAHAHUGOSHORTCODE2-2HBHB": "Jonny", "HAHAHUGOSHORTCODE2-3HBHB": "Johnny"}, "Hello Europe. Go Jonny, Go, Go Johnny Go Go!."}, {"A HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "A B A."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A"}, false}, {"A HAHAHUGOSHORTCODE-1HBHB but not the second.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "A A but not the second."}, {"An HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "An A."}, {"An HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "An A B."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-3HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-3HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B", "HAHAHUGOSHORTCODE-3HBHB": "C"}, "A A B C A C."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-3HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-3HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B", "HAHAHUGOSHORTCODE-3HBHB": "C"}, "A A B C A C."}, // Issue #1148 remove p-tags 10 => {"Hello <p>HAHAHUGOSHORTCODE-1HBHB</p>. END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello World. END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB</p>. <p>HAHAHUGOSHORTCODE-2HBHB</p> END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World", "HAHAHUGOSHORTCODE-2HBHB": "THE"}, "Hello World. THE END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB. END</p>.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello <p>World. END</p>."}, {"<p>Hello HAHAHUGOSHORTCODE-1HBHB</p>. END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "<p>Hello World</p>. END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB12", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello <p>World12"}, { "Hello HAHAHUGOSHORTCODE-1HBHB. HAHAHUGOSHORTCODE-1HBHB-HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB END", "P", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": strings.Repeat("BC", 100)}, fmt.Sprintf("Hello %s. %s-%s %s %s %s END", strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100)), }, } { replacements := make(map[string]shortcodeRenderer) for k, v := range this.replacements { replacements[k] = prerenderedShortcode{s: v} } tokenHandler := func(ctx context.Context, token string) ([]byte, error) { return []byte(this.replacements[token]), nil } ctx := context.Background() results, err := expandShortcodeTokens(ctx, []byte(this.input), tokenHandler) if b, ok := this.expect.(bool); ok && !b { if err == nil { t.Errorf("[%d] replaceShortcodeTokens didn't return an expected error", i) } } else { if err != nil { t.Errorf("[%d] failed: %s", i, err) continue } if !reflect.DeepEqual(results, []byte(this.expect.(string))) { t.Errorf("[%d] replaceShortcodeTokens, got \n%q but expected \n%q", i, results, this.expect) } } } } func TestShortcodeGetContent(t *testing.T) { t.Parallel() contentShortcode := ` {{- $t := .Get 0 -}} {{- $p := .Get 1 -}} {{- $k := .Get 2 -}} {{- $page := $.Page.Site.GetPage "page" $p -}} {{ if $page }} {{- if eq $t "bundle" -}} {{- .Scratch.Set "p" ($page.Resources.GetMatch (printf "%s*" $k)) -}} {{- else -}} {{- $.Scratch.Set "p" $page -}} {{- end -}}P1:{{ .Page.Content }}|P2:{{ $p := ($.Scratch.Get "p") }}{{ $p.Title }}/{{ $p.Content }}| {{- else -}} {{- errorf "Page %s is nil" $p -}} {{- end -}} ` var templates []string var content []string contentWithShortcodeTemplate := `--- title: doc%s weight: %d --- Logo:{{< c "bundle" "b1" "logo.png" >}}:P1: {{< c "page" "section1/p1" "" >}}:BP1:{{< c "bundle" "b1" "bp1" >}}` simpleContentTemplate := `--- title: doc%s weight: %d --- C-%s` templates = append(templates, []string{"shortcodes/c.html", contentShortcode}...) templates = append(templates, []string{"_default/single.html", "Single Content: {{ .Content }}"}...) templates = append(templates, []string{"_default/list.html", "List Content: {{ .Content }}"}...) content = append(content, []string{"b1/index.md", fmt.Sprintf(contentWithShortcodeTemplate, "b1", 1)}...) content = append(content, []string{"b1/logo.png", "PNG logo"}...) content = append(content, []string{"b1/bp1.md", fmt.Sprintf(simpleContentTemplate, "bp1", 1, "bp1")}...) content = append(content, []string{"section1/_index.md", fmt.Sprintf(contentWithShortcodeTemplate, "s1", 2)}...) content = append(content, []string{"section1/p1.md", fmt.Sprintf(simpleContentTemplate, "s1p1", 2, "s1p1")}...) content = append(content, []string{"section2/_index.md", fmt.Sprintf(simpleContentTemplate, "b1", 1, "b1")}...) content = append(content, []string{"section2/s2p1.md", fmt.Sprintf(contentWithShortcodeTemplate, "bp1", 1)}...) builder := newTestSitesBuilder(t).WithDefaultMultiSiteConfig() builder.WithContent(content...).WithTemplates(templates...).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] builder.Assert(len(s.RegularPages()), qt.Equals, 3) builder.AssertFileContent("public/en/section1/index.html", "List Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "BP1:P1:|P2:docbp1/<p>C-bp1</p>", ) builder.AssertFileContent("public/en/b1/index.html", "Single Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "P2:docbp1/<p>C-bp1</p>", ) builder.AssertFileContent("public/en/section2/s2p1/index.html", "Single Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "P2:docbp1/<p>C-bp1</p>", ) } // https://github.com/gohugoio/hugo/issues/5833 func TestShortcodeParentResourcesOnRebuild(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).Running().WithSimpleConfigFile() b.WithTemplatesAdded( "index.html", ` {{ $b := .Site.GetPage "b1" }} b1 Content: {{ $b.Content }} {{$p := $b.Resources.GetMatch "p1*" }} Content: {{ $p.Content }} {{ $article := .Site.GetPage "blog/article" }} Article Content: {{ $article.Content }} `, "shortcodes/c.html", ` {{ range .Page.Parent.Resources }} * Parent resource: {{ .Name }}: {{ .RelPermalink }} {{ end }} `) pageContent := ` --- title: MyPage --- SHORTCODE: {{< c >}} ` b.WithContent("b1/index.md", pageContent, "b1/logo.png", "PNG logo", "b1/p1.md", pageContent, "blog/_index.md", pageContent, "blog/logo-article.png", "PNG logo", "blog/article.md", pageContent, ) b.Build(BuildCfg{}) assert := func(matchers ...string) { allMatchers := append(matchers, "Parent resource: logo.png: /b1/logo.png", "Article Content: <p>SHORTCODE: \n\n* Parent resource: logo-article.png: /blog/logo-article.png", ) b.AssertFileContent("public/index.html", allMatchers..., ) } assert() b.EditFiles("content/b1/index.md", pageContent+" Edit.") b.Build(BuildCfg{}) assert("Edit.") } func TestShortcodePreserveOrder(t *testing.T) { t.Parallel() c := qt.New(t) contentTemplate := `--- title: doc%d weight: %d --- # doc {{< s1 >}}{{< s2 >}}{{< s3 >}}{{< s4 >}}{{< s5 >}} {{< nested >}} {{< ordinal >}} {{< scratch >}} {{< ordinal >}} {{< scratch >}} {{< ordinal >}} {{< scratch >}} {{< /nested >}} ` ordinalShortcodeTemplate := `ordinal: {{ .Ordinal }}{{ .Page.Scratch.Set "ordinal" .Ordinal }}` nestedShortcode := `outer ordinal: {{ .Ordinal }} inner: {{ .Inner }}` scratchGetShortcode := `scratch ordinal: {{ .Ordinal }} scratch get ordinal: {{ .Page.Scratch.Get "ordinal" }}` shortcodeTemplate := `v%d: {{ .Ordinal }} sgo: {{ .Page.Scratch.Get "o2" }}{{ .Page.Scratch.Set "o2" .Ordinal }}|` var shortcodes []string var content []string shortcodes = append(shortcodes, []string{"shortcodes/nested.html", nestedShortcode}...) shortcodes = append(shortcodes, []string{"shortcodes/ordinal.html", ordinalShortcodeTemplate}...) shortcodes = append(shortcodes, []string{"shortcodes/scratch.html", scratchGetShortcode}...) for i := 1; i <= 5; i++ { sc := fmt.Sprintf(shortcodeTemplate, i) sc = strings.Replace(sc, "%%", "%", -1) shortcodes = append(shortcodes, []string{fmt.Sprintf("shortcodes/s%d.html", i), sc}...) } for i := 1; i <= 3; i++ { content = append(content, []string{fmt.Sprintf("p%d.md", i), fmt.Sprintf(contentTemplate, i, i)}...) } builder := newTestSitesBuilder(t).WithDefaultMultiSiteConfig() builder.WithContent(content...).WithTemplatesAdded(shortcodes...).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 3) builder.AssertFileContent("public/en/p1/index.html", `v1: 0 sgo: |v2: 1 sgo: 0|v3: 2 sgo: 1|v4: 3 sgo: 2|v5: 4 sgo: 3`) builder.AssertFileContent("public/en/p1/index.html", `outer ordinal: 5 inner: ordinal: 0 scratch ordinal: 1 scratch get ordinal: 0 ordinal: 2 scratch ordinal: 3 scratch get ordinal: 2 ordinal: 4 scratch ordinal: 5 scratch get ordinal: 4`) } func TestShortcodeVariables(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc {{< s1 >}} `).WithTemplatesAdded("layouts/shortcodes/s1.html", ` Name: {{ .Name }} {{ with .Position }} File: {{ .Filename }} Offset: {{ .Offset }} Line: {{ .LineNumber }} Column: {{ .ColumnNumber }} String: {{ . | safeHTML }} {{ end }} `).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", filepath.FromSlash("File: content/page.md"), "Line: 7", "Column: 4", "Offset: 40", filepath.FromSlash("String: \"content/page.md:7:4\""), "Name: s1", ) } func TestInlineShortcodes(t *testing.T) { for _, enableInlineShortcodes := range []bool{true, false} { enableInlineShortcodes := enableInlineShortcodes t.Run(fmt.Sprintf("enableInlineShortcodes=%t", enableInlineShortcodes), func(t *testing.T) { t.Parallel() conf := fmt.Sprintf(` baseURL = "https://example.com" enableInlineShortcodes = %t `, enableInlineShortcodes) b := newTestSitesBuilder(t) b.WithConfigFile("toml", conf) shortcodeContent := `FIRST:{{< myshort.inline "first" >}} Page: {{ .Page.Title }} Seq: {{ seq 3 }} Param: {{ .Get 0 }} {{< /myshort.inline >}}:END: SECOND:{{< myshort.inline "second" />}}:END NEW INLINE: {{< n1.inline "5" >}}W1: {{ seq (.Get 0) }}{{< /n1.inline >}}:END: INLINE IN INNER: {{< outer >}}{{< n2.inline >}}W2: {{ seq 4 }}{{< /n2.inline >}}{{< /outer >}}:END: REUSED INLINE IN INNER: {{< outer >}}{{< n1.inline "3" />}}{{< /outer >}}:END: ## MARKDOWN DELIMITER: {{% mymarkdown.inline %}}**Hugo Rocks!**{{% /mymarkdown.inline %}} ` b.WithContent("page-md-shortcode.md", `--- title: "Hugo" --- `+shortcodeContent) b.WithContent("_index.md", `--- title: "Hugo Home" --- `+shortcodeContent) b.WithTemplatesAdded("layouts/_default/single.html", ` CONTENT:{{ .Content }} TOC: {{ .TableOfContents }} `) b.WithTemplatesAdded("layouts/index.html", ` CONTENT:{{ .Content }} TOC: {{ .TableOfContents }} `) b.WithTemplatesAdded("layouts/shortcodes/outer.html", `Inner: {{ .Inner }}`) b.CreateSites().Build(BuildCfg{}) shouldContain := []string{ "Seq: [1 2 3]", "Param: first", "Param: second", "NEW INLINE: W1: [1 2 3 4 5]", "INLINE IN INNER: Inner: W2: [1 2 3 4]", "REUSED INLINE IN INNER: Inner: W1: [1 2 3]", `<li><a href="#markdown-delimiter-hugo-rocks">MARKDOWN DELIMITER: <strong>Hugo Rocks!</strong></a></li>`, } if enableInlineShortcodes { b.AssertFileContent("public/page-md-shortcode/index.html", shouldContain..., ) b.AssertFileContent("public/index.html", shouldContain..., ) } else { b.AssertFileContent("public/page-md-shortcode/index.html", "FIRST::END", "SECOND::END", "NEW INLINE: :END", "INLINE IN INNER: Inner: :END:", "REUSED INLINE IN INNER: Inner: :END:", ) } }) } } // https://github.com/gohugoio/hugo/issues/5863 func TestShortcodeNamespaced(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc hello: {{< hello >}} test/hello: {{< test/hello >}} `).WithTemplatesAdded( "layouts/shortcodes/hello.html", `hello`, "layouts/shortcodes/test/hello.html", `test/hello`).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", "hello: hello", "test/hello: test/hello", ) } // https://github.com/gohugoio/hugo/issues/6504 func TestShortcodeEmoji(t *testing.T) { t.Parallel() v := config.NewWithTestDefaults() v.Set("enableEmoji", true) builder := newTestSitesBuilder(t).WithViper(v) builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc {{< event >}}10:30-11:00 My :smile: Event {{< /event >}} `).WithTemplatesAdded( "layouts/shortcodes/event.html", `<div>{{ "\u29BE" }} {{ .Inner }} </div>`) builder.Build(BuildCfg{}) builder.AssertFileContent("public/page/index.html", "⦾ 10:30-11:00 My 😄 Event", ) } func TestShortcodeParams(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc types positional: {{< hello true false 33 3.14 >}} types named: {{< hello b1=true b2=false i1=33 f1=3.14 >}} types string: {{< hello "true" trues "33" "3.14" >}} escaped quoute: {{< hello "hello \"world\"." >}} `).WithTemplatesAdded( "layouts/shortcodes/hello.html", `{{ range $i, $v := .Params }} - {{ printf "%v: %v (%T)" $i $v $v }} {{ end }} {{ $b1 := .Get "b1" }} Get: {{ printf "%v (%T)" $b1 $b1 | safeHTML }} `).Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", "types positional: - 0: true (bool) - 1: false (bool) - 2: 33 (int) - 3: 3.14 (float64)", "types named: - b1: true (bool) - b2: false (bool) - f1: 3.14 (float64) - i1: 33 (int) Get: true (bool) ", "types string: - 0: true (string) - 1: trues (string) - 2: 33 (string) - 3: 3.14 (string) ", "hello &#34;world&#34;. (string)", ) } func TestShortcodeRef(t *testing.T) { t.Parallel() v := config.NewWithTestDefaults() v.Set("baseURL", "https://example.org") builder := newTestSitesBuilder(t).WithViper(v) for i := 1; i <= 2; i++ { builder.WithContent(fmt.Sprintf("page%d.md", i), `--- title: "Hugo Rocks!" --- [Page 1]({{< ref "page1.md" >}}) [Page 1 with anchor]({{< relref "page1.md#doc" >}}) [Page 2]({{< ref "page2.md" >}}) [Page 2 with anchor]({{< relref "page2.md#doc" >}}) ## Doc `) } builder.Build(BuildCfg{}) builder.AssertFileContent("public/page2/index.html", ` <a href="/page1/#doc">Page 1 with anchor</a> <a href="https://example.org/page2/">Page 2</a> <a href="/page2/#doc">Page 2 with anchor</a></p> <h2 id="doc">Doc</h2> `, ) } // https://github.com/gohugoio/hugo/issues/6857 func TestShortcodeNoInner(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("mypage.md", `--- title: "No Inner!" --- {{< noinner >}}{{< /noinner >}} `).WithTemplatesAdded( "layouts/shortcodes/noinner.html", `No inner here.`) err := b.BuildE(BuildCfg{}) b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`"content/mypage.md:4:21": failed to extract shortcode: shortcode "noinner" has no .Inner, yet a closing tag was provided`)) } func TestShortcodeStableOutputFormatTemplates(t *testing.T) { t.Parallel() for i := 0; i < 5; i++ { b := newTestSitesBuilder(t) const numPages = 10 for i := 0; i < numPages; i++ { b.WithContent(fmt.Sprintf("page%d.md", i), `--- title: "Page" outputs: ["html", "css", "csv", "json"] --- {{< myshort >}} `) } b.WithTemplates( "_default/single.html", "{{ .Content }}", "_default/single.css", "{{ .Content }}", "_default/single.csv", "{{ .Content }}", "_default/single.json", "{{ .Content }}", "shortcodes/myshort.html", `Short-HTML`, "shortcodes/myshort.csv", `Short-CSV`, ) b.Build(BuildCfg{}) // helpers.PrintFs(b.Fs.Destination, "public", os.Stdout) for i := 0; i < numPages; i++ { b.AssertFileContent(fmt.Sprintf("public/page%d/index.html", i), "Short-HTML") b.AssertFileContent(fmt.Sprintf("public/page%d/index.csv", i), "Short-CSV") b.AssertFileContent(fmt.Sprintf("public/page%d/index.json", i), "Short-HTML") } for i := 0; i < numPages; i++ { b.AssertFileContent(fmt.Sprintf("public/page%d/styles.css", i), "Short-HTML") } } } // #9821 func TestShortcodeMarkdownOutputFormat(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- {{< foo >}} -- layouts/shortcodes/foo.md -- §§§ <x §§§ -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <x `) } func TestShortcodePreserveIndentation(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## List With Indented Shortcodes 1. List 1 {{% mark1 %}} 1. Item Mark1 1 1. Item Mark1 2 {{% mark2 %}} {{% /mark1 %}} -- layouts/shortcodes/mark1.md -- {{ .Inner }} -- layouts/shortcodes/mark2.md -- 1. Item Mark2 1 1. Item Mark2 2 1. Item Mark2 2-1 1. Item Mark2 3 -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", "<ol>\n<li>\n<p>List 1</p>\n<ol>\n<li>Item Mark1 1</li>\n<li>Item Mark1 2</li>\n<li>Item Mark2 1</li>\n<li>Item Mark2 2\n<ol>\n<li>Item Mark2 2-1</li>\n</ol>\n</li>\n<li>Item Mark2 3</li>\n</ol>\n</li>\n</ol>") } func TestShortcodeCodeblockIndent(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code block {{% code %}} -- layouts/shortcodes/code.md -- echo "foo"; -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", "<pre><code>echo &quot;foo&quot;;\n</code></pre>") } func TestShortcodeHighlightDeindent(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] codeFences = true noClasses = false -- content/p1.md -- --- title: "p1" --- ## Indent 5 Spaces {{< highlight bash >}} line 1; line 2; line 3; {{< /highlight >}} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <pre><code> <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">line 1<span class="p">;</span> </span></span><span class="line"><span class="cl">line 2<span class="p">;</span> </span></span><span class="line"><span class="cl">line 3<span class="p">;</span></span></span></code></pre></div> </code></pre> `) } // Issue 10236. func TestShortcodeParamEscapedQuote(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- {{< figure src="/media/spf13.jpg" title="Steve \"Francia\"." >}} -- layouts/shortcodes/figure.html -- Title: {{ .Get "title" | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/p1/index.html", `Title: Steve "Francia".`) } // Issue 10391. func TestNestedShortcodeCustomOutputFormat(t *testing.T) { t.Parallel() files := ` -- config.toml -- [outputFormats.Foobar] baseName = "foobar" isPlainText = true mediaType = "application/json" notAlternative = true [languages.en] languageName = "English" [languages.en.outputs] home = [ "HTML", "RSS", "Foobar" ] [languages.fr] languageName = "Français" [[module.mounts]] source = "content/en" target = "content" lang = "en" [[module.mounts]] source = "content/fr" target = "content" lang = "fr" -- layouts/_default/list.foobar.json -- {{- $.Scratch.Add "data" slice -}} {{- range (where .Site.AllPages "Kind" "!=" "home") -}} {{- $.Scratch.Add "data" (dict "content" (.Plain | truncate 10000) "type" .Type "full_url" .Permalink) -}} {{- end -}} {{- $.Scratch.Get "data" | jsonify -}} -- content/en/p1.md -- --- title: "p1" --- ### More information {{< tabs >}} {{% tab "Test" %}} It's a test {{% /tab %}} {{< /tabs >}} -- content/fr/p2.md -- --- title: Test --- ### Plus d'informations {{< tabs >}} {{% tab "Test" %}} C'est un test {{% /tab %}} {{< /tabs >}} -- layouts/shortcodes/tabs.html -- <div> <div class="tab-content">{{ .Inner }}</div> </div> -- layouts/shortcodes/tab.html -- <div>{{ .Inner }}</div> -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/fr/p2/index.html", `plus-dinformations`) } // Issue 10671. func TestShortcodeInnerShouldBeEmptyWhenNotClosed(t *testing.T) { t.Parallel() files := ` -- config.toml -- disableKinds = ["home", "taxonomy", "term"] -- content/p1.md -- --- title: "p1" --- {{< sc "self-closing" />}} Text. {{< sc "closing-no-newline" >}}{{< /sc >}} -- layouts/shortcodes/sc.html -- Inner: {{ .Get 0 }}: {{ len .Inner }} InnerDeindent: {{ .Get 0 }}: {{ len .InnerDeindent }} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` Inner: self-closing: 0 InnerDeindent: self-closing: 0 Inner: closing-no-newline: 0 InnerDeindent: closing-no-newline: 0 `) } // Issue 10675. func TestShortcodeErrorWhenItShouldBeClosed(t *testing.T) { t.Parallel() files := ` -- config.toml -- disableKinds = ["home", "taxonomy", "term"] -- content/p1.md -- --- title: "p1" --- {{< sc >}} Text. -- layouts/shortcodes/sc.html -- Inner: {{ .Get 0 }}: {{ len .Inner }} -- layouts/_default/single.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).BuildE() b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, `p1.md:5:1": failed to extract shortcode: unclosed shortcode "sc"`) }
// 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 hugolib import ( "context" "fmt" "path/filepath" "reflect" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources/page" qt "github.com/frankban/quicktest" ) func TestExtractShortcodes(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithTemplates( "default/single.html", `EMPTY`, "_internal/shortcodes/tag.html", `tag`, "_internal/shortcodes/legacytag.html", `{{ $_hugo_config := "{ \"version\": 1 }" }}tag`, "_internal/shortcodes/sc1.html", `sc1`, "_internal/shortcodes/sc2.html", `sc2`, "_internal/shortcodes/inner.html", `{{with .Inner }}{{ . }}{{ end }}`, "_internal/shortcodes/inner2.html", `{{.Inner}}`, "_internal/shortcodes/inner3.html", `{{.Inner}}`, ).WithContent("page.md", `--- title: "Shortcodes Galore!" --- `) b.CreateSites().Build(BuildCfg{}) s := b.H.Sites[0] // Make it more regexp friendly strReplacer := strings.NewReplacer("[", "{", "]", "}") str := func(s *shortcode) string { if s == nil { return "<nil>" } var version int if s.info != nil { version = s.info.ParseInfo().Config.Version } return strReplacer.Replace(fmt.Sprintf("%s;inline:%t;closing:%t;inner:%v;params:%v;ordinal:%d;markup:%t;version:%d;pos:%d", s.name, s.isInline, s.isClosing, s.inner, s.params, s.ordinal, s.doMarkup, version, s.pos)) } regexpCheck := func(re string) func(c *qt.C, shortcode *shortcode, err error) { return func(c *qt.C, shortcode *shortcode, err error) { c.Assert(err, qt.IsNil) c.Assert(str(shortcode), qt.Matches, ".*"+re+".*") } } for _, test := range []struct { name string input string check func(c *qt.C, shortcode *shortcode, err error) }{ {"one shortcode, no markup", "{{< tag >}}", regexpCheck("tag.*closing:false.*markup:false")}, {"one shortcode, markup", "{{% tag %}}", regexpCheck("tag.*closing:false.*markup:true;version:2")}, {"one shortcode, markup, legacy", "{{% legacytag %}}", regexpCheck("tag.*closing:false.*markup:true;version:1")}, {"outer shortcode markup", "{{% inner %}}{{< tag >}}{{% /inner %}}", regexpCheck("inner.*closing:true.*markup:true")}, {"inner shortcode markup", "{{< inner >}}{{% tag %}}{{< /inner >}}", regexpCheck("inner.*closing:true.*;markup:false;version:2")}, {"one pos param", "{{% tag param1 %}}", regexpCheck("tag.*params:{param1}")}, {"two pos params", "{{< tag param1 param2>}}", regexpCheck("tag.*params:{param1 param2}")}, {"one named param", `{{% tag param1="value" %}}`, regexpCheck("tag.*params:map{param1:value}")}, {"two named params", `{{< tag param1="value1" param2="value2" >}}`, regexpCheck("tag.*params:map{param\\d:value\\d param\\d:value\\d}")}, {"inner", `{{< inner >}}Inner Content{{< / inner >}}`, regexpCheck("inner;inline:false;closing:true;inner:{Inner Content};")}, // issue #934 {"inner self-closing", `{{< inner />}}`, regexpCheck("inner;.*inner:{}")}, { "nested inner", `{{< inner >}}Inner Content->{{% inner2 param1 %}}inner2txt{{% /inner2 %}}Inner close->{{< / inner >}}`, regexpCheck("inner;.*inner:{Inner Content->.*Inner close->}"), }, { "nested, nested inner", `{{< inner >}}inner2->{{% inner2 param1 %}}inner2txt->inner3{{< inner3>}}inner3txt{{</ inner3 >}}{{% /inner2 %}}final close->{{< / inner >}}`, regexpCheck("inner:{inner2-> inner2.*{{inner2txt->inner3.*final close->}"), }, {"closed without content", `{{< inner param1 >}}{{< / inner >}}`, regexpCheck("inner.*inner:{}")}, {"inline", `{{< my.inline >}}Hi{{< /my.inline >}}`, regexpCheck("my.inline;inline:true;closing:true;inner:{Hi};")}, } { test := test t.Run(test.name, func(t *testing.T) { t.Parallel() c := qt.New(t) p, err := pageparser.ParseMain(strings.NewReader(test.input), pageparser.Config{}) c.Assert(err, qt.IsNil) handler := newShortcodeHandler(nil, s) iter := p.Iterator() short, err := handler.extractShortcode(0, 0, p.Input(), iter) test.check(c, short, err) }) } } func TestShortcodeMultipleOutputFormats(t *testing.T) { t.Parallel() siteConfig := ` baseURL = "http://example.com/blog" paginate = 1 disableKinds = ["section", "term", "taxonomy", "RSS", "sitemap", "robotsTXT", "404"] [outputs] home = [ "HTML", "AMP", "Calendar" ] page = [ "HTML", "AMP", "JSON" ] ` pageTemplate := `--- title: "%s" --- # Doc {{< myShort >}} {{< noExt >}} {{%% onlyHTML %%}} {{< myInner >}}{{< myShort >}}{{< /myInner >}} ` pageTemplateCSVOnly := `--- title: "%s" outputs: ["CSV"] --- # Doc CSV: {{< myShort >}} ` b := newTestSitesBuilder(t).WithConfigFile("toml", siteConfig) b.WithTemplates( "layouts/_default/single.html", `Single HTML: {{ .Title }}|{{ .Content }}`, "layouts/_default/single.json", `Single JSON: {{ .Title }}|{{ .Content }}`, "layouts/_default/single.csv", `Single CSV: {{ .Title }}|{{ .Content }}`, "layouts/index.html", `Home HTML: {{ .Title }}|{{ .Content }}`, "layouts/index.amp.html", `Home AMP: {{ .Title }}|{{ .Content }}`, "layouts/index.ics", `Home Calendar: {{ .Title }}|{{ .Content }}`, "layouts/shortcodes/myShort.html", `ShortHTML`, "layouts/shortcodes/myShort.amp.html", `ShortAMP`, "layouts/shortcodes/myShort.csv", `ShortCSV`, "layouts/shortcodes/myShort.ics", `ShortCalendar`, "layouts/shortcodes/myShort.json", `ShortJSON`, "layouts/shortcodes/noExt", `ShortNoExt`, "layouts/shortcodes/onlyHTML.html", `ShortOnlyHTML`, "layouts/shortcodes/myInner.html", `myInner:--{{- .Inner -}}--`, ) b.WithContent("_index.md", fmt.Sprintf(pageTemplate, "Home"), "sect/mypage.md", fmt.Sprintf(pageTemplate, "Single"), "sect/mycsvpage.md", fmt.Sprintf(pageTemplateCSVOnly, "Single CSV"), ) b.Build(BuildCfg{}) h := b.H b.Assert(len(h.Sites), qt.Equals, 1) s := h.Sites[0] home := s.getPage(page.KindHome) b.Assert(home, qt.Not(qt.IsNil)) b.Assert(len(home.OutputFormats()), qt.Equals, 3) b.AssertFileContent("public/index.html", "Home HTML", "ShortHTML", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortHTML--", ) b.AssertFileContent("public/amp/index.html", "Home AMP", "ShortAMP", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortAMP--", ) b.AssertFileContent("public/index.ics", "Home Calendar", "ShortCalendar", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortCalendar--", ) b.AssertFileContent("public/sect/mypage/index.html", "Single HTML", "ShortHTML", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortHTML--", ) b.AssertFileContent("public/sect/mypage/index.json", "Single JSON", "ShortJSON", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortJSON--", ) b.AssertFileContent("public/amp/sect/mypage/index.html", // No special AMP template "Single HTML", "ShortAMP", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortAMP--", ) b.AssertFileContent("public/sect/mycsvpage/index.csv", "Single CSV", "ShortCSV", ) } func BenchmarkReplaceShortcodeTokens(b *testing.B) { type input struct { in []byte tokenHandler func(ctx context.Context, token string) ([]byte, error) expect []byte } data := []struct { input string replacements map[string]string expect []byte }{ {"Hello HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, []byte("Hello World.")}, {strings.Repeat("A", 100) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A", 100) + " Hello World.")}, {strings.Repeat("A", 500) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A", 500) + " Hello World.")}, {strings.Repeat("ABCD ", 500) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("ABCD ", 500) + " Hello World.")}, {strings.Repeat("A ", 3000) + " HAHAHUGOSHORTCODE-1HBHB." + strings.Repeat("BC ", 1000) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A ", 3000) + " Hello World." + strings.Repeat("BC ", 1000) + " Hello World.")}, } cnt := 0 in := make([]input, b.N*len(data)) for i := 0; i < b.N; i++ { for _, this := range data { replacements := make(map[string]shortcodeRenderer) for k, v := range this.replacements { replacements[k] = prerenderedShortcode{s: v} } tokenHandler := func(ctx context.Context, token string) ([]byte, error) { return []byte(this.replacements[token]), nil } in[cnt] = input{[]byte(this.input), tokenHandler, this.expect} cnt++ } } b.ResetTimer() cnt = 0 ctx := context.Background() for i := 0; i < b.N; i++ { for j := range data { currIn := in[cnt] cnt++ results, err := expandShortcodeTokens(ctx, currIn.in, currIn.tokenHandler) if err != nil { b.Fatalf("[%d] failed: %s", i, err) continue } if len(results) != len(currIn.expect) { b.Fatalf("[%d] replaceShortcodeTokens, got \n%q but expected \n%q", j, results, currIn.expect) } } } } func BenchmarkShortcodesInSite(b *testing.B) { files := ` -- config.toml -- -- layouts/shortcodes/mark1.md -- {{ .Inner }} -- layouts/shortcodes/mark2.md -- 1. Item Mark2 1 1. Item Mark2 2 1. Item Mark2 2-1 1. Item Mark2 3 -- layouts/_default/single.html -- {{ .Content }} ` content := ` --- title: "Markdown Shortcode" --- ## List 1. List 1 {{§ mark1 §}} 1. Item Mark1 1 1. Item Mark1 2 {{§ mark2 §}} {{§ /mark1 §}} ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } files = strings.ReplaceAll(files, "§", "%") cfg := IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*IntegrationTestBuilder, b.N) for i := range builders { builders[i] = NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func TestReplaceShortcodeTokens(t *testing.T) { t.Parallel() for i, this := range []struct { input string prefix string replacements map[string]string expect any }{ {"Hello HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello World."}, {"Hello HAHAHUGOSHORTCODE-1@}@.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, false}, {"HAHAHUGOSHORTCODE2-1HBHB", "PREFIX2", map[string]string{"HAHAHUGOSHORTCODE2-1HBHB": "World"}, "World"}, {"Hello World!", "PREFIX2", map[string]string{}, "Hello World!"}, {"!HAHAHUGOSHORTCODE-1HBHB", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "!World"}, {"HAHAHUGOSHORTCODE-1HBHB!", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "World!"}, {"!HAHAHUGOSHORTCODE-1HBHB!", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "!World!"}, {"_{_PREFIX-1HBHB", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "_{_PREFIX-1HBHB"}, {"Hello HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "To You My Old Friend Who Told Me This Fantastic Story"}, "Hello To You My Old Friend Who Told Me This Fantastic Story."}, {"A HAHAHUGOSHORTCODE-1HBHB asdf HAHAHUGOSHORTCODE-2HBHB.", "A", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "v1", "HAHAHUGOSHORTCODE-2HBHB": "v2"}, "A v1 asdf v2."}, {"Hello HAHAHUGOSHORTCODE2-1HBHB. Go HAHAHUGOSHORTCODE2-2HBHB, Go, Go HAHAHUGOSHORTCODE2-3HBHB Go Go!.", "PREFIX2", map[string]string{"HAHAHUGOSHORTCODE2-1HBHB": "Europe", "HAHAHUGOSHORTCODE2-2HBHB": "Jonny", "HAHAHUGOSHORTCODE2-3HBHB": "Johnny"}, "Hello Europe. Go Jonny, Go, Go Johnny Go Go!."}, {"A HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "A B A."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A"}, false}, {"A HAHAHUGOSHORTCODE-1HBHB but not the second.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "A A but not the second."}, {"An HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "An A."}, {"An HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "An A B."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-3HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-3HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B", "HAHAHUGOSHORTCODE-3HBHB": "C"}, "A A B C A C."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-3HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-3HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B", "HAHAHUGOSHORTCODE-3HBHB": "C"}, "A A B C A C."}, // Issue #1148 remove p-tags 10 => {"Hello <p>HAHAHUGOSHORTCODE-1HBHB</p>. END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello World. END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB</p>. <p>HAHAHUGOSHORTCODE-2HBHB</p> END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World", "HAHAHUGOSHORTCODE-2HBHB": "THE"}, "Hello World. THE END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB. END</p>.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello <p>World. END</p>."}, {"<p>Hello HAHAHUGOSHORTCODE-1HBHB</p>. END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "<p>Hello World</p>. END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB12", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello <p>World12"}, { "Hello HAHAHUGOSHORTCODE-1HBHB. HAHAHUGOSHORTCODE-1HBHB-HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB END", "P", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": strings.Repeat("BC", 100)}, fmt.Sprintf("Hello %s. %s-%s %s %s %s END", strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100)), }, } { replacements := make(map[string]shortcodeRenderer) for k, v := range this.replacements { replacements[k] = prerenderedShortcode{s: v} } tokenHandler := func(ctx context.Context, token string) ([]byte, error) { return []byte(this.replacements[token]), nil } ctx := context.Background() results, err := expandShortcodeTokens(ctx, []byte(this.input), tokenHandler) if b, ok := this.expect.(bool); ok && !b { if err == nil { t.Errorf("[%d] replaceShortcodeTokens didn't return an expected error", i) } } else { if err != nil { t.Errorf("[%d] failed: %s", i, err) continue } if !reflect.DeepEqual(results, []byte(this.expect.(string))) { t.Errorf("[%d] replaceShortcodeTokens, got \n%q but expected \n%q", i, results, this.expect) } } } } func TestShortcodeGetContent(t *testing.T) { t.Parallel() contentShortcode := ` {{- $t := .Get 0 -}} {{- $p := .Get 1 -}} {{- $k := .Get 2 -}} {{- $page := $.Page.Site.GetPage "page" $p -}} {{ if $page }} {{- if eq $t "bundle" -}} {{- .Scratch.Set "p" ($page.Resources.GetMatch (printf "%s*" $k)) -}} {{- else -}} {{- $.Scratch.Set "p" $page -}} {{- end -}}P1:{{ .Page.Content }}|P2:{{ $p := ($.Scratch.Get "p") }}{{ $p.Title }}/{{ $p.Content }}| {{- else -}} {{- errorf "Page %s is nil" $p -}} {{- end -}} ` var templates []string var content []string contentWithShortcodeTemplate := `--- title: doc%s weight: %d --- Logo:{{< c "bundle" "b1" "logo.png" >}}:P1: {{< c "page" "section1/p1" "" >}}:BP1:{{< c "bundle" "b1" "bp1" >}}` simpleContentTemplate := `--- title: doc%s weight: %d --- C-%s` templates = append(templates, []string{"shortcodes/c.html", contentShortcode}...) templates = append(templates, []string{"_default/single.html", "Single Content: {{ .Content }}"}...) templates = append(templates, []string{"_default/list.html", "List Content: {{ .Content }}"}...) content = append(content, []string{"b1/index.md", fmt.Sprintf(contentWithShortcodeTemplate, "b1", 1)}...) content = append(content, []string{"b1/logo.png", "PNG logo"}...) content = append(content, []string{"b1/bp1.md", fmt.Sprintf(simpleContentTemplate, "bp1", 1, "bp1")}...) content = append(content, []string{"section1/_index.md", fmt.Sprintf(contentWithShortcodeTemplate, "s1", 2)}...) content = append(content, []string{"section1/p1.md", fmt.Sprintf(simpleContentTemplate, "s1p1", 2, "s1p1")}...) content = append(content, []string{"section2/_index.md", fmt.Sprintf(simpleContentTemplate, "b1", 1, "b1")}...) content = append(content, []string{"section2/s2p1.md", fmt.Sprintf(contentWithShortcodeTemplate, "bp1", 1)}...) builder := newTestSitesBuilder(t).WithDefaultMultiSiteConfig() builder.WithContent(content...).WithTemplates(templates...).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] builder.Assert(len(s.RegularPages()), qt.Equals, 3) builder.AssertFileContent("public/en/section1/index.html", "List Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "BP1:P1:|P2:docbp1/<p>C-bp1</p>", ) builder.AssertFileContent("public/en/b1/index.html", "Single Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "P2:docbp1/<p>C-bp1</p>", ) builder.AssertFileContent("public/en/section2/s2p1/index.html", "Single Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "P2:docbp1/<p>C-bp1</p>", ) } // https://github.com/gohugoio/hugo/issues/5833 func TestShortcodeParentResourcesOnRebuild(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).Running().WithSimpleConfigFile() b.WithTemplatesAdded( "index.html", ` {{ $b := .Site.GetPage "b1" }} b1 Content: {{ $b.Content }} {{$p := $b.Resources.GetMatch "p1*" }} Content: {{ $p.Content }} {{ $article := .Site.GetPage "blog/article" }} Article Content: {{ $article.Content }} `, "shortcodes/c.html", ` {{ range .Page.Parent.Resources }} * Parent resource: {{ .Name }}: {{ .RelPermalink }} {{ end }} `) pageContent := ` --- title: MyPage --- SHORTCODE: {{< c >}} ` b.WithContent("b1/index.md", pageContent, "b1/logo.png", "PNG logo", "b1/p1.md", pageContent, "blog/_index.md", pageContent, "blog/logo-article.png", "PNG logo", "blog/article.md", pageContent, ) b.Build(BuildCfg{}) assert := func(matchers ...string) { allMatchers := append(matchers, "Parent resource: logo.png: /b1/logo.png", "Article Content: <p>SHORTCODE: \n\n* Parent resource: logo-article.png: /blog/logo-article.png", ) b.AssertFileContent("public/index.html", allMatchers..., ) } assert() b.EditFiles("content/b1/index.md", pageContent+" Edit.") b.Build(BuildCfg{}) assert("Edit.") } func TestShortcodePreserveOrder(t *testing.T) { t.Parallel() c := qt.New(t) contentTemplate := `--- title: doc%d weight: %d --- # doc {{< s1 >}}{{< s2 >}}{{< s3 >}}{{< s4 >}}{{< s5 >}} {{< nested >}} {{< ordinal >}} {{< scratch >}} {{< ordinal >}} {{< scratch >}} {{< ordinal >}} {{< scratch >}} {{< /nested >}} ` ordinalShortcodeTemplate := `ordinal: {{ .Ordinal }}{{ .Page.Scratch.Set "ordinal" .Ordinal }}` nestedShortcode := `outer ordinal: {{ .Ordinal }} inner: {{ .Inner }}` scratchGetShortcode := `scratch ordinal: {{ .Ordinal }} scratch get ordinal: {{ .Page.Scratch.Get "ordinal" }}` shortcodeTemplate := `v%d: {{ .Ordinal }} sgo: {{ .Page.Scratch.Get "o2" }}{{ .Page.Scratch.Set "o2" .Ordinal }}|` var shortcodes []string var content []string shortcodes = append(shortcodes, []string{"shortcodes/nested.html", nestedShortcode}...) shortcodes = append(shortcodes, []string{"shortcodes/ordinal.html", ordinalShortcodeTemplate}...) shortcodes = append(shortcodes, []string{"shortcodes/scratch.html", scratchGetShortcode}...) for i := 1; i <= 5; i++ { sc := fmt.Sprintf(shortcodeTemplate, i) sc = strings.Replace(sc, "%%", "%", -1) shortcodes = append(shortcodes, []string{fmt.Sprintf("shortcodes/s%d.html", i), sc}...) } for i := 1; i <= 3; i++ { content = append(content, []string{fmt.Sprintf("p%d.md", i), fmt.Sprintf(contentTemplate, i, i)}...) } builder := newTestSitesBuilder(t).WithDefaultMultiSiteConfig() builder.WithContent(content...).WithTemplatesAdded(shortcodes...).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 3) builder.AssertFileContent("public/en/p1/index.html", `v1: 0 sgo: |v2: 1 sgo: 0|v3: 2 sgo: 1|v4: 3 sgo: 2|v5: 4 sgo: 3`) builder.AssertFileContent("public/en/p1/index.html", `outer ordinal: 5 inner: ordinal: 0 scratch ordinal: 1 scratch get ordinal: 0 ordinal: 2 scratch ordinal: 3 scratch get ordinal: 2 ordinal: 4 scratch ordinal: 5 scratch get ordinal: 4`) } func TestShortcodeVariables(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc {{< s1 >}} `).WithTemplatesAdded("layouts/shortcodes/s1.html", ` Name: {{ .Name }} {{ with .Position }} File: {{ .Filename }} Offset: {{ .Offset }} Line: {{ .LineNumber }} Column: {{ .ColumnNumber }} String: {{ . | safeHTML }} {{ end }} `).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", filepath.FromSlash("File: content/page.md"), "Line: 7", "Column: 4", "Offset: 40", filepath.FromSlash("String: \"content/page.md:7:4\""), "Name: s1", ) } func TestInlineShortcodes(t *testing.T) { for _, enableInlineShortcodes := range []bool{true, false} { enableInlineShortcodes := enableInlineShortcodes t.Run(fmt.Sprintf("enableInlineShortcodes=%t", enableInlineShortcodes), func(t *testing.T) { t.Parallel() conf := fmt.Sprintf(` baseURL = "https://example.com" enableInlineShortcodes = %t `, enableInlineShortcodes) b := newTestSitesBuilder(t) b.WithConfigFile("toml", conf) shortcodeContent := `FIRST:{{< myshort.inline "first" >}} Page: {{ .Page.Title }} Seq: {{ seq 3 }} Param: {{ .Get 0 }} {{< /myshort.inline >}}:END: SECOND:{{< myshort.inline "second" />}}:END NEW INLINE: {{< n1.inline "5" >}}W1: {{ seq (.Get 0) }}{{< /n1.inline >}}:END: INLINE IN INNER: {{< outer >}}{{< n2.inline >}}W2: {{ seq 4 }}{{< /n2.inline >}}{{< /outer >}}:END: REUSED INLINE IN INNER: {{< outer >}}{{< n1.inline "3" />}}{{< /outer >}}:END: ## MARKDOWN DELIMITER: {{% mymarkdown.inline %}}**Hugo Rocks!**{{% /mymarkdown.inline %}} ` b.WithContent("page-md-shortcode.md", `--- title: "Hugo" --- `+shortcodeContent) b.WithContent("_index.md", `--- title: "Hugo Home" --- `+shortcodeContent) b.WithTemplatesAdded("layouts/_default/single.html", ` CONTENT:{{ .Content }} TOC: {{ .TableOfContents }} `) b.WithTemplatesAdded("layouts/index.html", ` CONTENT:{{ .Content }} TOC: {{ .TableOfContents }} `) b.WithTemplatesAdded("layouts/shortcodes/outer.html", `Inner: {{ .Inner }}`) b.CreateSites().Build(BuildCfg{}) shouldContain := []string{ "Seq: [1 2 3]", "Param: first", "Param: second", "NEW INLINE: W1: [1 2 3 4 5]", "INLINE IN INNER: Inner: W2: [1 2 3 4]", "REUSED INLINE IN INNER: Inner: W1: [1 2 3]", `<li><a href="#markdown-delimiter-hugo-rocks">MARKDOWN DELIMITER: <strong>Hugo Rocks!</strong></a></li>`, } if enableInlineShortcodes { b.AssertFileContent("public/page-md-shortcode/index.html", shouldContain..., ) b.AssertFileContent("public/index.html", shouldContain..., ) } else { b.AssertFileContent("public/page-md-shortcode/index.html", "FIRST::END", "SECOND::END", "NEW INLINE: :END", "INLINE IN INNER: Inner: :END:", "REUSED INLINE IN INNER: Inner: :END:", ) } }) } } // https://github.com/gohugoio/hugo/issues/5863 func TestShortcodeNamespaced(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc hello: {{< hello >}} test/hello: {{< test/hello >}} `).WithTemplatesAdded( "layouts/shortcodes/hello.html", `hello`, "layouts/shortcodes/test/hello.html", `test/hello`).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", "hello: hello", "test/hello: test/hello", ) } // https://github.com/gohugoio/hugo/issues/6504 func TestShortcodeEmoji(t *testing.T) { t.Parallel() v := config.NewWithTestDefaults() v.Set("enableEmoji", true) builder := newTestSitesBuilder(t).WithViper(v) builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc {{< event >}}10:30-11:00 My :smile: Event {{< /event >}} `).WithTemplatesAdded( "layouts/shortcodes/event.html", `<div>{{ "\u29BE" }} {{ .Inner }} </div>`) builder.Build(BuildCfg{}) builder.AssertFileContent("public/page/index.html", "⦾ 10:30-11:00 My 😄 Event", ) } func TestShortcodeParams(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc types positional: {{< hello true false 33 3.14 >}} types named: {{< hello b1=true b2=false i1=33 f1=3.14 >}} types string: {{< hello "true" trues "33" "3.14" >}} escaped quoute: {{< hello "hello \"world\"." >}} `).WithTemplatesAdded( "layouts/shortcodes/hello.html", `{{ range $i, $v := .Params }} - {{ printf "%v: %v (%T)" $i $v $v }} {{ end }} {{ $b1 := .Get "b1" }} Get: {{ printf "%v (%T)" $b1 $b1 | safeHTML }} `).Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", "types positional: - 0: true (bool) - 1: false (bool) - 2: 33 (int) - 3: 3.14 (float64)", "types named: - b1: true (bool) - b2: false (bool) - f1: 3.14 (float64) - i1: 33 (int) Get: true (bool) ", "types string: - 0: true (string) - 1: trues (string) - 2: 33 (string) - 3: 3.14 (string) ", "hello &#34;world&#34;. (string)", ) } func TestShortcodeRef(t *testing.T) { t.Parallel() v := config.NewWithTestDefaults() v.Set("baseURL", "https://example.org") builder := newTestSitesBuilder(t).WithViper(v) for i := 1; i <= 2; i++ { builder.WithContent(fmt.Sprintf("page%d.md", i), `--- title: "Hugo Rocks!" --- [Page 1]({{< ref "page1.md" >}}) [Page 1 with anchor]({{< relref "page1.md#doc" >}}) [Page 2]({{< ref "page2.md" >}}) [Page 2 with anchor]({{< relref "page2.md#doc" >}}) ## Doc `) } builder.Build(BuildCfg{}) builder.AssertFileContent("public/page2/index.html", ` <a href="/page1/#doc">Page 1 with anchor</a> <a href="https://example.org/page2/">Page 2</a> <a href="/page2/#doc">Page 2 with anchor</a></p> <h2 id="doc">Doc</h2> `, ) } // https://github.com/gohugoio/hugo/issues/6857 func TestShortcodeNoInner(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("mypage.md", `--- title: "No Inner!" --- {{< noinner >}}{{< /noinner >}} `).WithTemplatesAdded( "layouts/shortcodes/noinner.html", `No inner here.`) err := b.BuildE(BuildCfg{}) b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`"content/mypage.md:4:16": failed to extract shortcode: shortcode "noinner" does not evaluate .Inner or .InnerDeindent, yet a closing tag was provided`)) } func TestShortcodeStableOutputFormatTemplates(t *testing.T) { t.Parallel() for i := 0; i < 5; i++ { b := newTestSitesBuilder(t) const numPages = 10 for i := 0; i < numPages; i++ { b.WithContent(fmt.Sprintf("page%d.md", i), `--- title: "Page" outputs: ["html", "css", "csv", "json"] --- {{< myshort >}} `) } b.WithTemplates( "_default/single.html", "{{ .Content }}", "_default/single.css", "{{ .Content }}", "_default/single.csv", "{{ .Content }}", "_default/single.json", "{{ .Content }}", "shortcodes/myshort.html", `Short-HTML`, "shortcodes/myshort.csv", `Short-CSV`, ) b.Build(BuildCfg{}) // helpers.PrintFs(b.Fs.Destination, "public", os.Stdout) for i := 0; i < numPages; i++ { b.AssertFileContent(fmt.Sprintf("public/page%d/index.html", i), "Short-HTML") b.AssertFileContent(fmt.Sprintf("public/page%d/index.csv", i), "Short-CSV") b.AssertFileContent(fmt.Sprintf("public/page%d/index.json", i), "Short-HTML") } for i := 0; i < numPages; i++ { b.AssertFileContent(fmt.Sprintf("public/page%d/styles.css", i), "Short-HTML") } } } // #9821 func TestShortcodeMarkdownOutputFormat(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- {{< foo >}} -- layouts/shortcodes/foo.md -- §§§ <x §§§ -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <x `) } func TestShortcodePreserveIndentation(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## List With Indented Shortcodes 1. List 1 {{% mark1 %}} 1. Item Mark1 1 1. Item Mark1 2 {{% mark2 %}} {{% /mark1 %}} -- layouts/shortcodes/mark1.md -- {{ .Inner }} -- layouts/shortcodes/mark2.md -- 1. Item Mark2 1 1. Item Mark2 2 1. Item Mark2 2-1 1. Item Mark2 3 -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", "<ol>\n<li>\n<p>List 1</p>\n<ol>\n<li>Item Mark1 1</li>\n<li>Item Mark1 2</li>\n<li>Item Mark2 1</li>\n<li>Item Mark2 2\n<ol>\n<li>Item Mark2 2-1</li>\n</ol>\n</li>\n<li>Item Mark2 3</li>\n</ol>\n</li>\n</ol>") } func TestShortcodeCodeblockIndent(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code block {{% code %}} -- layouts/shortcodes/code.md -- echo "foo"; -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", "<pre><code>echo &quot;foo&quot;;\n</code></pre>") } func TestShortcodeHighlightDeindent(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] codeFences = true noClasses = false -- content/p1.md -- --- title: "p1" --- ## Indent 5 Spaces {{< highlight bash >}} line 1; line 2; line 3; {{< /highlight >}} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <pre><code> <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">line 1<span class="p">;</span> </span></span><span class="line"><span class="cl">line 2<span class="p">;</span> </span></span><span class="line"><span class="cl">line 3<span class="p">;</span></span></span></code></pre></div> </code></pre> `) } // Issue 10236. func TestShortcodeParamEscapedQuote(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- {{< figure src="/media/spf13.jpg" title="Steve \"Francia\"." >}} -- layouts/shortcodes/figure.html -- Title: {{ .Get "title" | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/p1/index.html", `Title: Steve "Francia".`) } // Issue 10391. func TestNestedShortcodeCustomOutputFormat(t *testing.T) { t.Parallel() files := ` -- config.toml -- [outputFormats.Foobar] baseName = "foobar" isPlainText = true mediaType = "application/json" notAlternative = true [languages.en] languageName = "English" [languages.en.outputs] home = [ "HTML", "RSS", "Foobar" ] [languages.fr] languageName = "Français" [[module.mounts]] source = "content/en" target = "content" lang = "en" [[module.mounts]] source = "content/fr" target = "content" lang = "fr" -- layouts/_default/list.foobar.json -- {{- $.Scratch.Add "data" slice -}} {{- range (where .Site.AllPages "Kind" "!=" "home") -}} {{- $.Scratch.Add "data" (dict "content" (.Plain | truncate 10000) "type" .Type "full_url" .Permalink) -}} {{- end -}} {{- $.Scratch.Get "data" | jsonify -}} -- content/en/p1.md -- --- title: "p1" --- ### More information {{< tabs >}} {{% tab "Test" %}} It's a test {{% /tab %}} {{< /tabs >}} -- content/fr/p2.md -- --- title: Test --- ### Plus d'informations {{< tabs >}} {{% tab "Test" %}} C'est un test {{% /tab %}} {{< /tabs >}} -- layouts/shortcodes/tabs.html -- <div> <div class="tab-content">{{ .Inner }}</div> </div> -- layouts/shortcodes/tab.html -- <div>{{ .Inner }}</div> -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/fr/p2/index.html", `plus-dinformations`) } // Issue 10671. func TestShortcodeInnerShouldBeEmptyWhenNotClosed(t *testing.T) { t.Parallel() files := ` -- config.toml -- disableKinds = ["home", "taxonomy", "term"] -- content/p1.md -- --- title: "p1" --- {{< sc "self-closing" />}} Text. {{< sc "closing-no-newline" >}}{{< /sc >}} -- layouts/shortcodes/sc.html -- Inner: {{ .Get 0 }}: {{ len .Inner }} InnerDeindent: {{ .Get 0 }}: {{ len .InnerDeindent }} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` Inner: self-closing: 0 InnerDeindent: self-closing: 0 Inner: closing-no-newline: 0 InnerDeindent: closing-no-newline: 0 `) } // Issue 10675. func TestShortcodeErrorWhenItShouldBeClosed(t *testing.T) { t.Parallel() files := ` -- config.toml -- disableKinds = ["home", "taxonomy", "term"] -- content/p1.md -- --- title: "p1" --- {{< sc >}} Text. -- layouts/shortcodes/sc.html -- Inner: {{ .Get 0 }}: {{ len .Inner }} -- layouts/_default/single.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).BuildE() b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, `p1.md:5:1": failed to extract shortcode: unclosed shortcode "sc"`) }
bep
7d78a498e19c2331a325fa43dd46f4da2b0443a6
ae48507d66db1fbe9b8fd5e3589941bee362a7ec
@jmooring the 2 test cases above passes. In my head that then leaves us with #10675 and #10673 ...?
bep
72
gohugoio/hugo
10,676
Add some shortcode testcases
Updates #10671
null
2023-01-31 08:28:49+00:00
2023-02-23 08:36:15+00:00
hugolib/shortcode_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 hugolib import ( "context" "fmt" "path/filepath" "reflect" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources/page" qt "github.com/frankban/quicktest" ) func TestExtractShortcodes(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithTemplates( "default/single.html", `EMPTY`, "_internal/shortcodes/tag.html", `tag`, "_internal/shortcodes/legacytag.html", `{{ $_hugo_config := "{ \"version\": 1 }" }}tag`, "_internal/shortcodes/sc1.html", `sc1`, "_internal/shortcodes/sc2.html", `sc2`, "_internal/shortcodes/inner.html", `{{with .Inner }}{{ . }}{{ end }}`, "_internal/shortcodes/inner2.html", `{{.Inner}}`, "_internal/shortcodes/inner3.html", `{{.Inner}}`, ).WithContent("page.md", `--- title: "Shortcodes Galore!" --- `) b.CreateSites().Build(BuildCfg{}) s := b.H.Sites[0] // Make it more regexp friendly strReplacer := strings.NewReplacer("[", "{", "]", "}") str := func(s *shortcode) string { if s == nil { return "<nil>" } var version int if s.info != nil { version = s.info.ParseInfo().Config.Version } return strReplacer.Replace(fmt.Sprintf("%s;inline:%t;closing:%t;inner:%v;params:%v;ordinal:%d;markup:%t;version:%d;pos:%d", s.name, s.isInline, s.isClosing, s.inner, s.params, s.ordinal, s.doMarkup, version, s.pos)) } regexpCheck := func(re string) func(c *qt.C, shortcode *shortcode, err error) { return func(c *qt.C, shortcode *shortcode, err error) { c.Assert(err, qt.IsNil) c.Assert(str(shortcode), qt.Matches, ".*"+re+".*") } } for _, test := range []struct { name string input string check func(c *qt.C, shortcode *shortcode, err error) }{ {"one shortcode, no markup", "{{< tag >}}", regexpCheck("tag.*closing:false.*markup:false")}, {"one shortcode, markup", "{{% tag %}}", regexpCheck("tag.*closing:false.*markup:true;version:2")}, {"one shortcode, markup, legacy", "{{% legacytag %}}", regexpCheck("tag.*closing:false.*markup:true;version:1")}, {"outer shortcode markup", "{{% inner %}}{{< tag >}}{{% /inner %}}", regexpCheck("inner.*closing:true.*markup:true")}, {"inner shortcode markup", "{{< inner >}}{{% tag %}}{{< /inner >}}", regexpCheck("inner.*closing:true.*;markup:false;version:2")}, {"one pos param", "{{% tag param1 %}}", regexpCheck("tag.*params:{param1}")}, {"two pos params", "{{< tag param1 param2>}}", regexpCheck("tag.*params:{param1 param2}")}, {"one named param", `{{% tag param1="value" %}}`, regexpCheck("tag.*params:map{param1:value}")}, {"two named params", `{{< tag param1="value1" param2="value2" >}}`, regexpCheck("tag.*params:map{param\\d:value\\d param\\d:value\\d}")}, {"inner", `{{< inner >}}Inner Content{{< / inner >}}`, regexpCheck("inner;inline:false;closing:true;inner:{Inner Content};")}, // issue #934 {"inner self-closing", `{{< inner />}}`, regexpCheck("inner;.*inner:{}")}, { "nested inner", `{{< inner >}}Inner Content->{{% inner2 param1 %}}inner2txt{{% /inner2 %}}Inner close->{{< / inner >}}`, regexpCheck("inner;.*inner:{Inner Content->.*Inner close->}"), }, { "nested, nested inner", `{{< inner >}}inner2->{{% inner2 param1 %}}inner2txt->inner3{{< inner3>}}inner3txt{{</ inner3 >}}{{% /inner2 %}}final close->{{< / inner >}}`, regexpCheck("inner:{inner2-> inner2.*{{inner2txt->inner3.*final close->}"), }, {"closed without content", `{{< inner param1 >}}{{< / inner >}}`, regexpCheck("inner.*inner:{}")}, {"inline", `{{< my.inline >}}Hi{{< /my.inline >}}`, regexpCheck("my.inline;inline:true;closing:true;inner:{Hi};")}, } { test := test t.Run(test.name, func(t *testing.T) { t.Parallel() c := qt.New(t) p, err := pageparser.ParseMain(strings.NewReader(test.input), pageparser.Config{}) c.Assert(err, qt.IsNil) handler := newShortcodeHandler(nil, s) iter := p.Iterator() short, err := handler.extractShortcode(0, 0, p.Input(), iter) test.check(c, short, err) }) } } func TestShortcodeMultipleOutputFormats(t *testing.T) { t.Parallel() siteConfig := ` baseURL = "http://example.com/blog" paginate = 1 disableKinds = ["section", "term", "taxonomy", "RSS", "sitemap", "robotsTXT", "404"] [outputs] home = [ "HTML", "AMP", "Calendar" ] page = [ "HTML", "AMP", "JSON" ] ` pageTemplate := `--- title: "%s" --- # Doc {{< myShort >}} {{< noExt >}} {{%% onlyHTML %%}} {{< myInner >}}{{< myShort >}}{{< /myInner >}} ` pageTemplateCSVOnly := `--- title: "%s" outputs: ["CSV"] --- # Doc CSV: {{< myShort >}} ` b := newTestSitesBuilder(t).WithConfigFile("toml", siteConfig) b.WithTemplates( "layouts/_default/single.html", `Single HTML: {{ .Title }}|{{ .Content }}`, "layouts/_default/single.json", `Single JSON: {{ .Title }}|{{ .Content }}`, "layouts/_default/single.csv", `Single CSV: {{ .Title }}|{{ .Content }}`, "layouts/index.html", `Home HTML: {{ .Title }}|{{ .Content }}`, "layouts/index.amp.html", `Home AMP: {{ .Title }}|{{ .Content }}`, "layouts/index.ics", `Home Calendar: {{ .Title }}|{{ .Content }}`, "layouts/shortcodes/myShort.html", `ShortHTML`, "layouts/shortcodes/myShort.amp.html", `ShortAMP`, "layouts/shortcodes/myShort.csv", `ShortCSV`, "layouts/shortcodes/myShort.ics", `ShortCalendar`, "layouts/shortcodes/myShort.json", `ShortJSON`, "layouts/shortcodes/noExt", `ShortNoExt`, "layouts/shortcodes/onlyHTML.html", `ShortOnlyHTML`, "layouts/shortcodes/myInner.html", `myInner:--{{- .Inner -}}--`, ) b.WithContent("_index.md", fmt.Sprintf(pageTemplate, "Home"), "sect/mypage.md", fmt.Sprintf(pageTemplate, "Single"), "sect/mycsvpage.md", fmt.Sprintf(pageTemplateCSVOnly, "Single CSV"), ) b.Build(BuildCfg{}) h := b.H b.Assert(len(h.Sites), qt.Equals, 1) s := h.Sites[0] home := s.getPage(page.KindHome) b.Assert(home, qt.Not(qt.IsNil)) b.Assert(len(home.OutputFormats()), qt.Equals, 3) b.AssertFileContent("public/index.html", "Home HTML", "ShortHTML", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortHTML--", ) b.AssertFileContent("public/amp/index.html", "Home AMP", "ShortAMP", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortAMP--", ) b.AssertFileContent("public/index.ics", "Home Calendar", "ShortCalendar", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortCalendar--", ) b.AssertFileContent("public/sect/mypage/index.html", "Single HTML", "ShortHTML", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortHTML--", ) b.AssertFileContent("public/sect/mypage/index.json", "Single JSON", "ShortJSON", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortJSON--", ) b.AssertFileContent("public/amp/sect/mypage/index.html", // No special AMP template "Single HTML", "ShortAMP", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortAMP--", ) b.AssertFileContent("public/sect/mycsvpage/index.csv", "Single CSV", "ShortCSV", ) } func BenchmarkReplaceShortcodeTokens(b *testing.B) { type input struct { in []byte tokenHandler func(ctx context.Context, token string) ([]byte, error) expect []byte } data := []struct { input string replacements map[string]string expect []byte }{ {"Hello HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, []byte("Hello World.")}, {strings.Repeat("A", 100) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A", 100) + " Hello World.")}, {strings.Repeat("A", 500) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A", 500) + " Hello World.")}, {strings.Repeat("ABCD ", 500) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("ABCD ", 500) + " Hello World.")}, {strings.Repeat("A ", 3000) + " HAHAHUGOSHORTCODE-1HBHB." + strings.Repeat("BC ", 1000) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A ", 3000) + " Hello World." + strings.Repeat("BC ", 1000) + " Hello World.")}, } cnt := 0 in := make([]input, b.N*len(data)) for i := 0; i < b.N; i++ { for _, this := range data { replacements := make(map[string]shortcodeRenderer) for k, v := range this.replacements { replacements[k] = prerenderedShortcode{s: v} } tokenHandler := func(ctx context.Context, token string) ([]byte, error) { return []byte(this.replacements[token]), nil } in[cnt] = input{[]byte(this.input), tokenHandler, this.expect} cnt++ } } b.ResetTimer() cnt = 0 ctx := context.Background() for i := 0; i < b.N; i++ { for j := range data { currIn := in[cnt] cnt++ results, err := expandShortcodeTokens(ctx, currIn.in, currIn.tokenHandler) if err != nil { b.Fatalf("[%d] failed: %s", i, err) continue } if len(results) != len(currIn.expect) { b.Fatalf("[%d] replaceShortcodeTokens, got \n%q but expected \n%q", j, results, currIn.expect) } } } } func BenchmarkShortcodesInSite(b *testing.B) { files := ` -- config.toml -- -- layouts/shortcodes/mark1.md -- {{ .Inner }} -- layouts/shortcodes/mark2.md -- 1. Item Mark2 1 1. Item Mark2 2 1. Item Mark2 2-1 1. Item Mark2 3 -- layouts/_default/single.html -- {{ .Content }} ` content := ` --- title: "Markdown Shortcode" --- ## List 1. List 1 {{§ mark1 §}} 1. Item Mark1 1 1. Item Mark1 2 {{§ mark2 §}} {{§ /mark1 §}} ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } files = strings.ReplaceAll(files, "§", "%") cfg := IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*IntegrationTestBuilder, b.N) for i := range builders { builders[i] = NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func TestReplaceShortcodeTokens(t *testing.T) { t.Parallel() for i, this := range []struct { input string prefix string replacements map[string]string expect any }{ {"Hello HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello World."}, {"Hello HAHAHUGOSHORTCODE-1@}@.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, false}, {"HAHAHUGOSHORTCODE2-1HBHB", "PREFIX2", map[string]string{"HAHAHUGOSHORTCODE2-1HBHB": "World"}, "World"}, {"Hello World!", "PREFIX2", map[string]string{}, "Hello World!"}, {"!HAHAHUGOSHORTCODE-1HBHB", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "!World"}, {"HAHAHUGOSHORTCODE-1HBHB!", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "World!"}, {"!HAHAHUGOSHORTCODE-1HBHB!", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "!World!"}, {"_{_PREFIX-1HBHB", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "_{_PREFIX-1HBHB"}, {"Hello HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "To You My Old Friend Who Told Me This Fantastic Story"}, "Hello To You My Old Friend Who Told Me This Fantastic Story."}, {"A HAHAHUGOSHORTCODE-1HBHB asdf HAHAHUGOSHORTCODE-2HBHB.", "A", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "v1", "HAHAHUGOSHORTCODE-2HBHB": "v2"}, "A v1 asdf v2."}, {"Hello HAHAHUGOSHORTCODE2-1HBHB. Go HAHAHUGOSHORTCODE2-2HBHB, Go, Go HAHAHUGOSHORTCODE2-3HBHB Go Go!.", "PREFIX2", map[string]string{"HAHAHUGOSHORTCODE2-1HBHB": "Europe", "HAHAHUGOSHORTCODE2-2HBHB": "Jonny", "HAHAHUGOSHORTCODE2-3HBHB": "Johnny"}, "Hello Europe. Go Jonny, Go, Go Johnny Go Go!."}, {"A HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "A B A."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A"}, false}, {"A HAHAHUGOSHORTCODE-1HBHB but not the second.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "A A but not the second."}, {"An HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "An A."}, {"An HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "An A B."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-3HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-3HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B", "HAHAHUGOSHORTCODE-3HBHB": "C"}, "A A B C A C."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-3HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-3HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B", "HAHAHUGOSHORTCODE-3HBHB": "C"}, "A A B C A C."}, // Issue #1148 remove p-tags 10 => {"Hello <p>HAHAHUGOSHORTCODE-1HBHB</p>. END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello World. END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB</p>. <p>HAHAHUGOSHORTCODE-2HBHB</p> END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World", "HAHAHUGOSHORTCODE-2HBHB": "THE"}, "Hello World. THE END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB. END</p>.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello <p>World. END</p>."}, {"<p>Hello HAHAHUGOSHORTCODE-1HBHB</p>. END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "<p>Hello World</p>. END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB12", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello <p>World12"}, { "Hello HAHAHUGOSHORTCODE-1HBHB. HAHAHUGOSHORTCODE-1HBHB-HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB END", "P", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": strings.Repeat("BC", 100)}, fmt.Sprintf("Hello %s. %s-%s %s %s %s END", strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100)), }, } { replacements := make(map[string]shortcodeRenderer) for k, v := range this.replacements { replacements[k] = prerenderedShortcode{s: v} } tokenHandler := func(ctx context.Context, token string) ([]byte, error) { return []byte(this.replacements[token]), nil } ctx := context.Background() results, err := expandShortcodeTokens(ctx, []byte(this.input), tokenHandler) if b, ok := this.expect.(bool); ok && !b { if err == nil { t.Errorf("[%d] replaceShortcodeTokens didn't return an expected error", i) } } else { if err != nil { t.Errorf("[%d] failed: %s", i, err) continue } if !reflect.DeepEqual(results, []byte(this.expect.(string))) { t.Errorf("[%d] replaceShortcodeTokens, got \n%q but expected \n%q", i, results, this.expect) } } } } func TestShortcodeGetContent(t *testing.T) { t.Parallel() contentShortcode := ` {{- $t := .Get 0 -}} {{- $p := .Get 1 -}} {{- $k := .Get 2 -}} {{- $page := $.Page.Site.GetPage "page" $p -}} {{ if $page }} {{- if eq $t "bundle" -}} {{- .Scratch.Set "p" ($page.Resources.GetMatch (printf "%s*" $k)) -}} {{- else -}} {{- $.Scratch.Set "p" $page -}} {{- end -}}P1:{{ .Page.Content }}|P2:{{ $p := ($.Scratch.Get "p") }}{{ $p.Title }}/{{ $p.Content }}| {{- else -}} {{- errorf "Page %s is nil" $p -}} {{- end -}} ` var templates []string var content []string contentWithShortcodeTemplate := `--- title: doc%s weight: %d --- Logo:{{< c "bundle" "b1" "logo.png" >}}:P1: {{< c "page" "section1/p1" "" >}}:BP1:{{< c "bundle" "b1" "bp1" >}}` simpleContentTemplate := `--- title: doc%s weight: %d --- C-%s` templates = append(templates, []string{"shortcodes/c.html", contentShortcode}...) templates = append(templates, []string{"_default/single.html", "Single Content: {{ .Content }}"}...) templates = append(templates, []string{"_default/list.html", "List Content: {{ .Content }}"}...) content = append(content, []string{"b1/index.md", fmt.Sprintf(contentWithShortcodeTemplate, "b1", 1)}...) content = append(content, []string{"b1/logo.png", "PNG logo"}...) content = append(content, []string{"b1/bp1.md", fmt.Sprintf(simpleContentTemplate, "bp1", 1, "bp1")}...) content = append(content, []string{"section1/_index.md", fmt.Sprintf(contentWithShortcodeTemplate, "s1", 2)}...) content = append(content, []string{"section1/p1.md", fmt.Sprintf(simpleContentTemplate, "s1p1", 2, "s1p1")}...) content = append(content, []string{"section2/_index.md", fmt.Sprintf(simpleContentTemplate, "b1", 1, "b1")}...) content = append(content, []string{"section2/s2p1.md", fmt.Sprintf(contentWithShortcodeTemplate, "bp1", 1)}...) builder := newTestSitesBuilder(t).WithDefaultMultiSiteConfig() builder.WithContent(content...).WithTemplates(templates...).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] builder.Assert(len(s.RegularPages()), qt.Equals, 3) builder.AssertFileContent("public/en/section1/index.html", "List Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "BP1:P1:|P2:docbp1/<p>C-bp1</p>", ) builder.AssertFileContent("public/en/b1/index.html", "Single Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "P2:docbp1/<p>C-bp1</p>", ) builder.AssertFileContent("public/en/section2/s2p1/index.html", "Single Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "P2:docbp1/<p>C-bp1</p>", ) } // https://github.com/gohugoio/hugo/issues/5833 func TestShortcodeParentResourcesOnRebuild(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).Running().WithSimpleConfigFile() b.WithTemplatesAdded( "index.html", ` {{ $b := .Site.GetPage "b1" }} b1 Content: {{ $b.Content }} {{$p := $b.Resources.GetMatch "p1*" }} Content: {{ $p.Content }} {{ $article := .Site.GetPage "blog/article" }} Article Content: {{ $article.Content }} `, "shortcodes/c.html", ` {{ range .Page.Parent.Resources }} * Parent resource: {{ .Name }}: {{ .RelPermalink }} {{ end }} `) pageContent := ` --- title: MyPage --- SHORTCODE: {{< c >}} ` b.WithContent("b1/index.md", pageContent, "b1/logo.png", "PNG logo", "b1/p1.md", pageContent, "blog/_index.md", pageContent, "blog/logo-article.png", "PNG logo", "blog/article.md", pageContent, ) b.Build(BuildCfg{}) assert := func(matchers ...string) { allMatchers := append(matchers, "Parent resource: logo.png: /b1/logo.png", "Article Content: <p>SHORTCODE: \n\n* Parent resource: logo-article.png: /blog/logo-article.png", ) b.AssertFileContent("public/index.html", allMatchers..., ) } assert() b.EditFiles("content/b1/index.md", pageContent+" Edit.") b.Build(BuildCfg{}) assert("Edit.") } func TestShortcodePreserveOrder(t *testing.T) { t.Parallel() c := qt.New(t) contentTemplate := `--- title: doc%d weight: %d --- # doc {{< s1 >}}{{< s2 >}}{{< s3 >}}{{< s4 >}}{{< s5 >}} {{< nested >}} {{< ordinal >}} {{< scratch >}} {{< ordinal >}} {{< scratch >}} {{< ordinal >}} {{< scratch >}} {{< /nested >}} ` ordinalShortcodeTemplate := `ordinal: {{ .Ordinal }}{{ .Page.Scratch.Set "ordinal" .Ordinal }}` nestedShortcode := `outer ordinal: {{ .Ordinal }} inner: {{ .Inner }}` scratchGetShortcode := `scratch ordinal: {{ .Ordinal }} scratch get ordinal: {{ .Page.Scratch.Get "ordinal" }}` shortcodeTemplate := `v%d: {{ .Ordinal }} sgo: {{ .Page.Scratch.Get "o2" }}{{ .Page.Scratch.Set "o2" .Ordinal }}|` var shortcodes []string var content []string shortcodes = append(shortcodes, []string{"shortcodes/nested.html", nestedShortcode}...) shortcodes = append(shortcodes, []string{"shortcodes/ordinal.html", ordinalShortcodeTemplate}...) shortcodes = append(shortcodes, []string{"shortcodes/scratch.html", scratchGetShortcode}...) for i := 1; i <= 5; i++ { sc := fmt.Sprintf(shortcodeTemplate, i) sc = strings.Replace(sc, "%%", "%", -1) shortcodes = append(shortcodes, []string{fmt.Sprintf("shortcodes/s%d.html", i), sc}...) } for i := 1; i <= 3; i++ { content = append(content, []string{fmt.Sprintf("p%d.md", i), fmt.Sprintf(contentTemplate, i, i)}...) } builder := newTestSitesBuilder(t).WithDefaultMultiSiteConfig() builder.WithContent(content...).WithTemplatesAdded(shortcodes...).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 3) builder.AssertFileContent("public/en/p1/index.html", `v1: 0 sgo: |v2: 1 sgo: 0|v3: 2 sgo: 1|v4: 3 sgo: 2|v5: 4 sgo: 3`) builder.AssertFileContent("public/en/p1/index.html", `outer ordinal: 5 inner: ordinal: 0 scratch ordinal: 1 scratch get ordinal: 0 ordinal: 2 scratch ordinal: 3 scratch get ordinal: 2 ordinal: 4 scratch ordinal: 5 scratch get ordinal: 4`) } func TestShortcodeVariables(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc {{< s1 >}} `).WithTemplatesAdded("layouts/shortcodes/s1.html", ` Name: {{ .Name }} {{ with .Position }} File: {{ .Filename }} Offset: {{ .Offset }} Line: {{ .LineNumber }} Column: {{ .ColumnNumber }} String: {{ . | safeHTML }} {{ end }} `).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", filepath.FromSlash("File: content/page.md"), "Line: 7", "Column: 4", "Offset: 40", filepath.FromSlash("String: \"content/page.md:7:4\""), "Name: s1", ) } func TestInlineShortcodes(t *testing.T) { for _, enableInlineShortcodes := range []bool{true, false} { enableInlineShortcodes := enableInlineShortcodes t.Run(fmt.Sprintf("enableInlineShortcodes=%t", enableInlineShortcodes), func(t *testing.T) { t.Parallel() conf := fmt.Sprintf(` baseURL = "https://example.com" enableInlineShortcodes = %t `, enableInlineShortcodes) b := newTestSitesBuilder(t) b.WithConfigFile("toml", conf) shortcodeContent := `FIRST:{{< myshort.inline "first" >}} Page: {{ .Page.Title }} Seq: {{ seq 3 }} Param: {{ .Get 0 }} {{< /myshort.inline >}}:END: SECOND:{{< myshort.inline "second" />}}:END NEW INLINE: {{< n1.inline "5" >}}W1: {{ seq (.Get 0) }}{{< /n1.inline >}}:END: INLINE IN INNER: {{< outer >}}{{< n2.inline >}}W2: {{ seq 4 }}{{< /n2.inline >}}{{< /outer >}}:END: REUSED INLINE IN INNER: {{< outer >}}{{< n1.inline "3" />}}{{< /outer >}}:END: ## MARKDOWN DELIMITER: {{% mymarkdown.inline %}}**Hugo Rocks!**{{% /mymarkdown.inline %}} ` b.WithContent("page-md-shortcode.md", `--- title: "Hugo" --- `+shortcodeContent) b.WithContent("_index.md", `--- title: "Hugo Home" --- `+shortcodeContent) b.WithTemplatesAdded("layouts/_default/single.html", ` CONTENT:{{ .Content }} TOC: {{ .TableOfContents }} `) b.WithTemplatesAdded("layouts/index.html", ` CONTENT:{{ .Content }} TOC: {{ .TableOfContents }} `) b.WithTemplatesAdded("layouts/shortcodes/outer.html", `Inner: {{ .Inner }}`) b.CreateSites().Build(BuildCfg{}) shouldContain := []string{ "Seq: [1 2 3]", "Param: first", "Param: second", "NEW INLINE: W1: [1 2 3 4 5]", "INLINE IN INNER: Inner: W2: [1 2 3 4]", "REUSED INLINE IN INNER: Inner: W1: [1 2 3]", `<li><a href="#markdown-delimiter-hugo-rocks">MARKDOWN DELIMITER: <strong>Hugo Rocks!</strong></a></li>`, } if enableInlineShortcodes { b.AssertFileContent("public/page-md-shortcode/index.html", shouldContain..., ) b.AssertFileContent("public/index.html", shouldContain..., ) } else { b.AssertFileContent("public/page-md-shortcode/index.html", "FIRST::END", "SECOND::END", "NEW INLINE: :END", "INLINE IN INNER: Inner: :END:", "REUSED INLINE IN INNER: Inner: :END:", ) } }) } } // https://github.com/gohugoio/hugo/issues/5863 func TestShortcodeNamespaced(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc hello: {{< hello >}} test/hello: {{< test/hello >}} `).WithTemplatesAdded( "layouts/shortcodes/hello.html", `hello`, "layouts/shortcodes/test/hello.html", `test/hello`).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", "hello: hello", "test/hello: test/hello", ) } // https://github.com/gohugoio/hugo/issues/6504 func TestShortcodeEmoji(t *testing.T) { t.Parallel() v := config.NewWithTestDefaults() v.Set("enableEmoji", true) builder := newTestSitesBuilder(t).WithViper(v) builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc {{< event >}}10:30-11:00 My :smile: Event {{< /event >}} `).WithTemplatesAdded( "layouts/shortcodes/event.html", `<div>{{ "\u29BE" }} {{ .Inner }} </div>`) builder.Build(BuildCfg{}) builder.AssertFileContent("public/page/index.html", "⦾ 10:30-11:00 My 😄 Event", ) } func TestShortcodeParams(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc types positional: {{< hello true false 33 3.14 >}} types named: {{< hello b1=true b2=false i1=33 f1=3.14 >}} types string: {{< hello "true" trues "33" "3.14" >}} escaped quoute: {{< hello "hello \"world\"." >}} `).WithTemplatesAdded( "layouts/shortcodes/hello.html", `{{ range $i, $v := .Params }} - {{ printf "%v: %v (%T)" $i $v $v }} {{ end }} {{ $b1 := .Get "b1" }} Get: {{ printf "%v (%T)" $b1 $b1 | safeHTML }} `).Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", "types positional: - 0: true (bool) - 1: false (bool) - 2: 33 (int) - 3: 3.14 (float64)", "types named: - b1: true (bool) - b2: false (bool) - f1: 3.14 (float64) - i1: 33 (int) Get: true (bool) ", "types string: - 0: true (string) - 1: trues (string) - 2: 33 (string) - 3: 3.14 (string) ", "hello &#34;world&#34;. (string)", ) } func TestShortcodeRef(t *testing.T) { t.Parallel() v := config.NewWithTestDefaults() v.Set("baseURL", "https://example.org") builder := newTestSitesBuilder(t).WithViper(v) for i := 1; i <= 2; i++ { builder.WithContent(fmt.Sprintf("page%d.md", i), `--- title: "Hugo Rocks!" --- [Page 1]({{< ref "page1.md" >}}) [Page 1 with anchor]({{< relref "page1.md#doc" >}}) [Page 2]({{< ref "page2.md" >}}) [Page 2 with anchor]({{< relref "page2.md#doc" >}}) ## Doc `) } builder.Build(BuildCfg{}) builder.AssertFileContent("public/page2/index.html", ` <a href="/page1/#doc">Page 1 with anchor</a> <a href="https://example.org/page2/">Page 2</a> <a href="/page2/#doc">Page 2 with anchor</a></p> <h2 id="doc">Doc</h2> `, ) } // https://github.com/gohugoio/hugo/issues/6857 func TestShortcodeNoInner(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("mypage.md", `--- title: "No Inner!" --- {{< noinner >}}{{< /noinner >}} `).WithTemplatesAdded( "layouts/shortcodes/noinner.html", `No inner here.`) err := b.BuildE(BuildCfg{}) b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`"content/mypage.md:4:21": failed to extract shortcode: shortcode "noinner" has no .Inner, yet a closing tag was provided`)) } func TestShortcodeStableOutputFormatTemplates(t *testing.T) { t.Parallel() for i := 0; i < 5; i++ { b := newTestSitesBuilder(t) const numPages = 10 for i := 0; i < numPages; i++ { b.WithContent(fmt.Sprintf("page%d.md", i), `--- title: "Page" outputs: ["html", "css", "csv", "json"] --- {{< myshort >}} `) } b.WithTemplates( "_default/single.html", "{{ .Content }}", "_default/single.css", "{{ .Content }}", "_default/single.csv", "{{ .Content }}", "_default/single.json", "{{ .Content }}", "shortcodes/myshort.html", `Short-HTML`, "shortcodes/myshort.csv", `Short-CSV`, ) b.Build(BuildCfg{}) // helpers.PrintFs(b.Fs.Destination, "public", os.Stdout) for i := 0; i < numPages; i++ { b.AssertFileContent(fmt.Sprintf("public/page%d/index.html", i), "Short-HTML") b.AssertFileContent(fmt.Sprintf("public/page%d/index.csv", i), "Short-CSV") b.AssertFileContent(fmt.Sprintf("public/page%d/index.json", i), "Short-HTML") } for i := 0; i < numPages; i++ { b.AssertFileContent(fmt.Sprintf("public/page%d/styles.css", i), "Short-HTML") } } } // #9821 func TestShortcodeMarkdownOutputFormat(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- {{< foo >}} -- layouts/shortcodes/foo.md -- §§§ <x §§§ -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <x `) } func TestShortcodePreserveIndentation(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## List With Indented Shortcodes 1. List 1 {{% mark1 %}} 1. Item Mark1 1 1. Item Mark1 2 {{% mark2 %}} {{% /mark1 %}} -- layouts/shortcodes/mark1.md -- {{ .Inner }} -- layouts/shortcodes/mark2.md -- 1. Item Mark2 1 1. Item Mark2 2 1. Item Mark2 2-1 1. Item Mark2 3 -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", "<ol>\n<li>\n<p>List 1</p>\n<ol>\n<li>Item Mark1 1</li>\n<li>Item Mark1 2</li>\n<li>Item Mark2 1</li>\n<li>Item Mark2 2\n<ol>\n<li>Item Mark2 2-1</li>\n</ol>\n</li>\n<li>Item Mark2 3</li>\n</ol>\n</li>\n</ol>") } func TestShortcodeCodeblockIndent(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code block {{% code %}} -- layouts/shortcodes/code.md -- echo "foo"; -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", "<pre><code>echo &quot;foo&quot;;\n</code></pre>") } func TestShortcodeHighlightDeindent(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] codeFences = true noClasses = false -- content/p1.md -- --- title: "p1" --- ## Indent 5 Spaces {{< highlight bash >}} line 1; line 2; line 3; {{< /highlight >}} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <pre><code> <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">line 1<span class="p">;</span> </span></span><span class="line"><span class="cl">line 2<span class="p">;</span> </span></span><span class="line"><span class="cl">line 3<span class="p">;</span></span></span></code></pre></div> </code></pre> `) } // Issue 10236. func TestShortcodeParamEscapedQuote(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- {{< figure src="/media/spf13.jpg" title="Steve \"Francia\"." >}} -- layouts/shortcodes/figure.html -- Title: {{ .Get "title" | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/p1/index.html", `Title: Steve "Francia".`) } // Issue 10391. func TestNestedShortcodeCustomOutputFormat(t *testing.T) { t.Parallel() files := ` -- config.toml -- [outputFormats.Foobar] baseName = "foobar" isPlainText = true mediaType = "application/json" notAlternative = true [languages.en] languageName = "English" [languages.en.outputs] home = [ "HTML", "RSS", "Foobar" ] [languages.fr] languageName = "Français" [[module.mounts]] source = "content/en" target = "content" lang = "en" [[module.mounts]] source = "content/fr" target = "content" lang = "fr" -- layouts/_default/list.foobar.json -- {{- $.Scratch.Add "data" slice -}} {{- range (where .Site.AllPages "Kind" "!=" "home") -}} {{- $.Scratch.Add "data" (dict "content" (.Plain | truncate 10000) "type" .Type "full_url" .Permalink) -}} {{- end -}} {{- $.Scratch.Get "data" | jsonify -}} -- content/en/p1.md -- --- title: "p1" --- ### More information {{< tabs >}} {{% tab "Test" %}} It's a test {{% /tab %}} {{< /tabs >}} -- content/fr/p2.md -- --- title: Test --- ### Plus d'informations {{< tabs >}} {{% tab "Test" %}} C'est un test {{% /tab %}} {{< /tabs >}} -- layouts/shortcodes/tabs.html -- <div> <div class="tab-content">{{ .Inner }}</div> </div> -- layouts/shortcodes/tab.html -- <div>{{ .Inner }}</div> -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/fr/p2/index.html", `plus-dinformations`) } // Issue 10671. func TestShortcodeInnerShouldBeEmptyWhenNotClosed(t *testing.T) { t.Parallel() files := ` -- config.toml -- disableKinds = ["home", "taxonomy", "term"] -- content/p1.md -- --- title: "p1" --- {{< sc "self-closing" />}} Text. {{< sc "closing-no-newline" >}}{{< /sc >}} -- layouts/shortcodes/sc.html -- Inner: {{ .Get 0 }}: {{ len .Inner }} InnerDeindent: {{ .Get 0 }}: {{ len .InnerDeindent }} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` Inner: self-closing: 0 InnerDeindent: self-closing: 0 Inner: closing-no-newline: 0 InnerDeindent: closing-no-newline: 0 `) } // Issue 10675. func TestShortcodeErrorWhenItShouldBeClosed(t *testing.T) { t.Parallel() files := ` -- config.toml -- disableKinds = ["home", "taxonomy", "term"] -- content/p1.md -- --- title: "p1" --- {{< sc >}} Text. -- layouts/shortcodes/sc.html -- Inner: {{ .Get 0 }}: {{ len .Inner }} -- layouts/_default/single.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).BuildE() b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, `p1.md:5:1": failed to extract shortcode: unclosed shortcode "sc"`) }
// 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 hugolib import ( "context" "fmt" "path/filepath" "reflect" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources/page" qt "github.com/frankban/quicktest" ) func TestExtractShortcodes(t *testing.T) { b := newTestSitesBuilder(t).WithSimpleConfigFile() b.WithTemplates( "default/single.html", `EMPTY`, "_internal/shortcodes/tag.html", `tag`, "_internal/shortcodes/legacytag.html", `{{ $_hugo_config := "{ \"version\": 1 }" }}tag`, "_internal/shortcodes/sc1.html", `sc1`, "_internal/shortcodes/sc2.html", `sc2`, "_internal/shortcodes/inner.html", `{{with .Inner }}{{ . }}{{ end }}`, "_internal/shortcodes/inner2.html", `{{.Inner}}`, "_internal/shortcodes/inner3.html", `{{.Inner}}`, ).WithContent("page.md", `--- title: "Shortcodes Galore!" --- `) b.CreateSites().Build(BuildCfg{}) s := b.H.Sites[0] // Make it more regexp friendly strReplacer := strings.NewReplacer("[", "{", "]", "}") str := func(s *shortcode) string { if s == nil { return "<nil>" } var version int if s.info != nil { version = s.info.ParseInfo().Config.Version } return strReplacer.Replace(fmt.Sprintf("%s;inline:%t;closing:%t;inner:%v;params:%v;ordinal:%d;markup:%t;version:%d;pos:%d", s.name, s.isInline, s.isClosing, s.inner, s.params, s.ordinal, s.doMarkup, version, s.pos)) } regexpCheck := func(re string) func(c *qt.C, shortcode *shortcode, err error) { return func(c *qt.C, shortcode *shortcode, err error) { c.Assert(err, qt.IsNil) c.Assert(str(shortcode), qt.Matches, ".*"+re+".*") } } for _, test := range []struct { name string input string check func(c *qt.C, shortcode *shortcode, err error) }{ {"one shortcode, no markup", "{{< tag >}}", regexpCheck("tag.*closing:false.*markup:false")}, {"one shortcode, markup", "{{% tag %}}", regexpCheck("tag.*closing:false.*markup:true;version:2")}, {"one shortcode, markup, legacy", "{{% legacytag %}}", regexpCheck("tag.*closing:false.*markup:true;version:1")}, {"outer shortcode markup", "{{% inner %}}{{< tag >}}{{% /inner %}}", regexpCheck("inner.*closing:true.*markup:true")}, {"inner shortcode markup", "{{< inner >}}{{% tag %}}{{< /inner >}}", regexpCheck("inner.*closing:true.*;markup:false;version:2")}, {"one pos param", "{{% tag param1 %}}", regexpCheck("tag.*params:{param1}")}, {"two pos params", "{{< tag param1 param2>}}", regexpCheck("tag.*params:{param1 param2}")}, {"one named param", `{{% tag param1="value" %}}`, regexpCheck("tag.*params:map{param1:value}")}, {"two named params", `{{< tag param1="value1" param2="value2" >}}`, regexpCheck("tag.*params:map{param\\d:value\\d param\\d:value\\d}")}, {"inner", `{{< inner >}}Inner Content{{< / inner >}}`, regexpCheck("inner;inline:false;closing:true;inner:{Inner Content};")}, // issue #934 {"inner self-closing", `{{< inner />}}`, regexpCheck("inner;.*inner:{}")}, { "nested inner", `{{< inner >}}Inner Content->{{% inner2 param1 %}}inner2txt{{% /inner2 %}}Inner close->{{< / inner >}}`, regexpCheck("inner;.*inner:{Inner Content->.*Inner close->}"), }, { "nested, nested inner", `{{< inner >}}inner2->{{% inner2 param1 %}}inner2txt->inner3{{< inner3>}}inner3txt{{</ inner3 >}}{{% /inner2 %}}final close->{{< / inner >}}`, regexpCheck("inner:{inner2-> inner2.*{{inner2txt->inner3.*final close->}"), }, {"closed without content", `{{< inner param1 >}}{{< / inner >}}`, regexpCheck("inner.*inner:{}")}, {"inline", `{{< my.inline >}}Hi{{< /my.inline >}}`, regexpCheck("my.inline;inline:true;closing:true;inner:{Hi};")}, } { test := test t.Run(test.name, func(t *testing.T) { t.Parallel() c := qt.New(t) p, err := pageparser.ParseMain(strings.NewReader(test.input), pageparser.Config{}) c.Assert(err, qt.IsNil) handler := newShortcodeHandler(nil, s) iter := p.Iterator() short, err := handler.extractShortcode(0, 0, p.Input(), iter) test.check(c, short, err) }) } } func TestShortcodeMultipleOutputFormats(t *testing.T) { t.Parallel() siteConfig := ` baseURL = "http://example.com/blog" paginate = 1 disableKinds = ["section", "term", "taxonomy", "RSS", "sitemap", "robotsTXT", "404"] [outputs] home = [ "HTML", "AMP", "Calendar" ] page = [ "HTML", "AMP", "JSON" ] ` pageTemplate := `--- title: "%s" --- # Doc {{< myShort >}} {{< noExt >}} {{%% onlyHTML %%}} {{< myInner >}}{{< myShort >}}{{< /myInner >}} ` pageTemplateCSVOnly := `--- title: "%s" outputs: ["CSV"] --- # Doc CSV: {{< myShort >}} ` b := newTestSitesBuilder(t).WithConfigFile("toml", siteConfig) b.WithTemplates( "layouts/_default/single.html", `Single HTML: {{ .Title }}|{{ .Content }}`, "layouts/_default/single.json", `Single JSON: {{ .Title }}|{{ .Content }}`, "layouts/_default/single.csv", `Single CSV: {{ .Title }}|{{ .Content }}`, "layouts/index.html", `Home HTML: {{ .Title }}|{{ .Content }}`, "layouts/index.amp.html", `Home AMP: {{ .Title }}|{{ .Content }}`, "layouts/index.ics", `Home Calendar: {{ .Title }}|{{ .Content }}`, "layouts/shortcodes/myShort.html", `ShortHTML`, "layouts/shortcodes/myShort.amp.html", `ShortAMP`, "layouts/shortcodes/myShort.csv", `ShortCSV`, "layouts/shortcodes/myShort.ics", `ShortCalendar`, "layouts/shortcodes/myShort.json", `ShortJSON`, "layouts/shortcodes/noExt", `ShortNoExt`, "layouts/shortcodes/onlyHTML.html", `ShortOnlyHTML`, "layouts/shortcodes/myInner.html", `myInner:--{{- .Inner -}}--`, ) b.WithContent("_index.md", fmt.Sprintf(pageTemplate, "Home"), "sect/mypage.md", fmt.Sprintf(pageTemplate, "Single"), "sect/mycsvpage.md", fmt.Sprintf(pageTemplateCSVOnly, "Single CSV"), ) b.Build(BuildCfg{}) h := b.H b.Assert(len(h.Sites), qt.Equals, 1) s := h.Sites[0] home := s.getPage(page.KindHome) b.Assert(home, qt.Not(qt.IsNil)) b.Assert(len(home.OutputFormats()), qt.Equals, 3) b.AssertFileContent("public/index.html", "Home HTML", "ShortHTML", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortHTML--", ) b.AssertFileContent("public/amp/index.html", "Home AMP", "ShortAMP", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortAMP--", ) b.AssertFileContent("public/index.ics", "Home Calendar", "ShortCalendar", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortCalendar--", ) b.AssertFileContent("public/sect/mypage/index.html", "Single HTML", "ShortHTML", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortHTML--", ) b.AssertFileContent("public/sect/mypage/index.json", "Single JSON", "ShortJSON", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortJSON--", ) b.AssertFileContent("public/amp/sect/mypage/index.html", // No special AMP template "Single HTML", "ShortAMP", "ShortNoExt", "ShortOnlyHTML", "myInner:--ShortAMP--", ) b.AssertFileContent("public/sect/mycsvpage/index.csv", "Single CSV", "ShortCSV", ) } func BenchmarkReplaceShortcodeTokens(b *testing.B) { type input struct { in []byte tokenHandler func(ctx context.Context, token string) ([]byte, error) expect []byte } data := []struct { input string replacements map[string]string expect []byte }{ {"Hello HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, []byte("Hello World.")}, {strings.Repeat("A", 100) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A", 100) + " Hello World.")}, {strings.Repeat("A", 500) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A", 500) + " Hello World.")}, {strings.Repeat("ABCD ", 500) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("ABCD ", 500) + " Hello World.")}, {strings.Repeat("A ", 3000) + " HAHAHUGOSHORTCODE-1HBHB." + strings.Repeat("BC ", 1000) + " HAHAHUGOSHORTCODE-1HBHB.", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "Hello World"}, []byte(strings.Repeat("A ", 3000) + " Hello World." + strings.Repeat("BC ", 1000) + " Hello World.")}, } cnt := 0 in := make([]input, b.N*len(data)) for i := 0; i < b.N; i++ { for _, this := range data { replacements := make(map[string]shortcodeRenderer) for k, v := range this.replacements { replacements[k] = prerenderedShortcode{s: v} } tokenHandler := func(ctx context.Context, token string) ([]byte, error) { return []byte(this.replacements[token]), nil } in[cnt] = input{[]byte(this.input), tokenHandler, this.expect} cnt++ } } b.ResetTimer() cnt = 0 ctx := context.Background() for i := 0; i < b.N; i++ { for j := range data { currIn := in[cnt] cnt++ results, err := expandShortcodeTokens(ctx, currIn.in, currIn.tokenHandler) if err != nil { b.Fatalf("[%d] failed: %s", i, err) continue } if len(results) != len(currIn.expect) { b.Fatalf("[%d] replaceShortcodeTokens, got \n%q but expected \n%q", j, results, currIn.expect) } } } } func BenchmarkShortcodesInSite(b *testing.B) { files := ` -- config.toml -- -- layouts/shortcodes/mark1.md -- {{ .Inner }} -- layouts/shortcodes/mark2.md -- 1. Item Mark2 1 1. Item Mark2 2 1. Item Mark2 2-1 1. Item Mark2 3 -- layouts/_default/single.html -- {{ .Content }} ` content := ` --- title: "Markdown Shortcode" --- ## List 1. List 1 {{§ mark1 §}} 1. Item Mark1 1 1. Item Mark1 2 {{§ mark2 §}} {{§ /mark1 §}} ` for i := 1; i < 100; i++ { files += fmt.Sprintf("\n-- content/posts/p%d.md --\n"+content, i+1) } files = strings.ReplaceAll(files, "§", "%") cfg := IntegrationTestConfig{ T: b, TxtarString: files, } builders := make([]*IntegrationTestBuilder, b.N) for i := range builders { builders[i] = NewIntegrationTestBuilder(cfg) } b.ResetTimer() for i := 0; i < b.N; i++ { builders[i].Build() } } func TestReplaceShortcodeTokens(t *testing.T) { t.Parallel() for i, this := range []struct { input string prefix string replacements map[string]string expect any }{ {"Hello HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello World."}, {"Hello HAHAHUGOSHORTCODE-1@}@.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, false}, {"HAHAHUGOSHORTCODE2-1HBHB", "PREFIX2", map[string]string{"HAHAHUGOSHORTCODE2-1HBHB": "World"}, "World"}, {"Hello World!", "PREFIX2", map[string]string{}, "Hello World!"}, {"!HAHAHUGOSHORTCODE-1HBHB", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "!World"}, {"HAHAHUGOSHORTCODE-1HBHB!", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "World!"}, {"!HAHAHUGOSHORTCODE-1HBHB!", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "!World!"}, {"_{_PREFIX-1HBHB", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "_{_PREFIX-1HBHB"}, {"Hello HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "To You My Old Friend Who Told Me This Fantastic Story"}, "Hello To You My Old Friend Who Told Me This Fantastic Story."}, {"A HAHAHUGOSHORTCODE-1HBHB asdf HAHAHUGOSHORTCODE-2HBHB.", "A", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "v1", "HAHAHUGOSHORTCODE-2HBHB": "v2"}, "A v1 asdf v2."}, {"Hello HAHAHUGOSHORTCODE2-1HBHB. Go HAHAHUGOSHORTCODE2-2HBHB, Go, Go HAHAHUGOSHORTCODE2-3HBHB Go Go!.", "PREFIX2", map[string]string{"HAHAHUGOSHORTCODE2-1HBHB": "Europe", "HAHAHUGOSHORTCODE2-2HBHB": "Jonny", "HAHAHUGOSHORTCODE2-3HBHB": "Johnny"}, "Hello Europe. Go Jonny, Go, Go Johnny Go Go!."}, {"A HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "A B A."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A"}, false}, {"A HAHAHUGOSHORTCODE-1HBHB but not the second.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "A A but not the second."}, {"An HAHAHUGOSHORTCODE-1HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "An A."}, {"An HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B"}, "An A B."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-3HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-3HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B", "HAHAHUGOSHORTCODE-3HBHB": "C"}, "A A B C A C."}, {"A HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-2HBHB HAHAHUGOSHORTCODE-3HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-3HBHB.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "A", "HAHAHUGOSHORTCODE-2HBHB": "B", "HAHAHUGOSHORTCODE-3HBHB": "C"}, "A A B C A C."}, // Issue #1148 remove p-tags 10 => {"Hello <p>HAHAHUGOSHORTCODE-1HBHB</p>. END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello World. END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB</p>. <p>HAHAHUGOSHORTCODE-2HBHB</p> END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World", "HAHAHUGOSHORTCODE-2HBHB": "THE"}, "Hello World. THE END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB. END</p>.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello <p>World. END</p>."}, {"<p>Hello HAHAHUGOSHORTCODE-1HBHB</p>. END.", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "<p>Hello World</p>. END."}, {"Hello <p>HAHAHUGOSHORTCODE-1HBHB12", "PREFIX", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": "World"}, "Hello <p>World12"}, { "Hello HAHAHUGOSHORTCODE-1HBHB. HAHAHUGOSHORTCODE-1HBHB-HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB HAHAHUGOSHORTCODE-1HBHB END", "P", map[string]string{"HAHAHUGOSHORTCODE-1HBHB": strings.Repeat("BC", 100)}, fmt.Sprintf("Hello %s. %s-%s %s %s %s END", strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100), strings.Repeat("BC", 100)), }, } { replacements := make(map[string]shortcodeRenderer) for k, v := range this.replacements { replacements[k] = prerenderedShortcode{s: v} } tokenHandler := func(ctx context.Context, token string) ([]byte, error) { return []byte(this.replacements[token]), nil } ctx := context.Background() results, err := expandShortcodeTokens(ctx, []byte(this.input), tokenHandler) if b, ok := this.expect.(bool); ok && !b { if err == nil { t.Errorf("[%d] replaceShortcodeTokens didn't return an expected error", i) } } else { if err != nil { t.Errorf("[%d] failed: %s", i, err) continue } if !reflect.DeepEqual(results, []byte(this.expect.(string))) { t.Errorf("[%d] replaceShortcodeTokens, got \n%q but expected \n%q", i, results, this.expect) } } } } func TestShortcodeGetContent(t *testing.T) { t.Parallel() contentShortcode := ` {{- $t := .Get 0 -}} {{- $p := .Get 1 -}} {{- $k := .Get 2 -}} {{- $page := $.Page.Site.GetPage "page" $p -}} {{ if $page }} {{- if eq $t "bundle" -}} {{- .Scratch.Set "p" ($page.Resources.GetMatch (printf "%s*" $k)) -}} {{- else -}} {{- $.Scratch.Set "p" $page -}} {{- end -}}P1:{{ .Page.Content }}|P2:{{ $p := ($.Scratch.Get "p") }}{{ $p.Title }}/{{ $p.Content }}| {{- else -}} {{- errorf "Page %s is nil" $p -}} {{- end -}} ` var templates []string var content []string contentWithShortcodeTemplate := `--- title: doc%s weight: %d --- Logo:{{< c "bundle" "b1" "logo.png" >}}:P1: {{< c "page" "section1/p1" "" >}}:BP1:{{< c "bundle" "b1" "bp1" >}}` simpleContentTemplate := `--- title: doc%s weight: %d --- C-%s` templates = append(templates, []string{"shortcodes/c.html", contentShortcode}...) templates = append(templates, []string{"_default/single.html", "Single Content: {{ .Content }}"}...) templates = append(templates, []string{"_default/list.html", "List Content: {{ .Content }}"}...) content = append(content, []string{"b1/index.md", fmt.Sprintf(contentWithShortcodeTemplate, "b1", 1)}...) content = append(content, []string{"b1/logo.png", "PNG logo"}...) content = append(content, []string{"b1/bp1.md", fmt.Sprintf(simpleContentTemplate, "bp1", 1, "bp1")}...) content = append(content, []string{"section1/_index.md", fmt.Sprintf(contentWithShortcodeTemplate, "s1", 2)}...) content = append(content, []string{"section1/p1.md", fmt.Sprintf(simpleContentTemplate, "s1p1", 2, "s1p1")}...) content = append(content, []string{"section2/_index.md", fmt.Sprintf(simpleContentTemplate, "b1", 1, "b1")}...) content = append(content, []string{"section2/s2p1.md", fmt.Sprintf(contentWithShortcodeTemplate, "bp1", 1)}...) builder := newTestSitesBuilder(t).WithDefaultMultiSiteConfig() builder.WithContent(content...).WithTemplates(templates...).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] builder.Assert(len(s.RegularPages()), qt.Equals, 3) builder.AssertFileContent("public/en/section1/index.html", "List Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "BP1:P1:|P2:docbp1/<p>C-bp1</p>", ) builder.AssertFileContent("public/en/b1/index.html", "Single Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "P2:docbp1/<p>C-bp1</p>", ) builder.AssertFileContent("public/en/section2/s2p1/index.html", "Single Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "P2:docbp1/<p>C-bp1</p>", ) } // https://github.com/gohugoio/hugo/issues/5833 func TestShortcodeParentResourcesOnRebuild(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t).Running().WithSimpleConfigFile() b.WithTemplatesAdded( "index.html", ` {{ $b := .Site.GetPage "b1" }} b1 Content: {{ $b.Content }} {{$p := $b.Resources.GetMatch "p1*" }} Content: {{ $p.Content }} {{ $article := .Site.GetPage "blog/article" }} Article Content: {{ $article.Content }} `, "shortcodes/c.html", ` {{ range .Page.Parent.Resources }} * Parent resource: {{ .Name }}: {{ .RelPermalink }} {{ end }} `) pageContent := ` --- title: MyPage --- SHORTCODE: {{< c >}} ` b.WithContent("b1/index.md", pageContent, "b1/logo.png", "PNG logo", "b1/p1.md", pageContent, "blog/_index.md", pageContent, "blog/logo-article.png", "PNG logo", "blog/article.md", pageContent, ) b.Build(BuildCfg{}) assert := func(matchers ...string) { allMatchers := append(matchers, "Parent resource: logo.png: /b1/logo.png", "Article Content: <p>SHORTCODE: \n\n* Parent resource: logo-article.png: /blog/logo-article.png", ) b.AssertFileContent("public/index.html", allMatchers..., ) } assert() b.EditFiles("content/b1/index.md", pageContent+" Edit.") b.Build(BuildCfg{}) assert("Edit.") } func TestShortcodePreserveOrder(t *testing.T) { t.Parallel() c := qt.New(t) contentTemplate := `--- title: doc%d weight: %d --- # doc {{< s1 >}}{{< s2 >}}{{< s3 >}}{{< s4 >}}{{< s5 >}} {{< nested >}} {{< ordinal >}} {{< scratch >}} {{< ordinal >}} {{< scratch >}} {{< ordinal >}} {{< scratch >}} {{< /nested >}} ` ordinalShortcodeTemplate := `ordinal: {{ .Ordinal }}{{ .Page.Scratch.Set "ordinal" .Ordinal }}` nestedShortcode := `outer ordinal: {{ .Ordinal }} inner: {{ .Inner }}` scratchGetShortcode := `scratch ordinal: {{ .Ordinal }} scratch get ordinal: {{ .Page.Scratch.Get "ordinal" }}` shortcodeTemplate := `v%d: {{ .Ordinal }} sgo: {{ .Page.Scratch.Get "o2" }}{{ .Page.Scratch.Set "o2" .Ordinal }}|` var shortcodes []string var content []string shortcodes = append(shortcodes, []string{"shortcodes/nested.html", nestedShortcode}...) shortcodes = append(shortcodes, []string{"shortcodes/ordinal.html", ordinalShortcodeTemplate}...) shortcodes = append(shortcodes, []string{"shortcodes/scratch.html", scratchGetShortcode}...) for i := 1; i <= 5; i++ { sc := fmt.Sprintf(shortcodeTemplate, i) sc = strings.Replace(sc, "%%", "%", -1) shortcodes = append(shortcodes, []string{fmt.Sprintf("shortcodes/s%d.html", i), sc}...) } for i := 1; i <= 3; i++ { content = append(content, []string{fmt.Sprintf("p%d.md", i), fmt.Sprintf(contentTemplate, i, i)}...) } builder := newTestSitesBuilder(t).WithDefaultMultiSiteConfig() builder.WithContent(content...).WithTemplatesAdded(shortcodes...).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 3) builder.AssertFileContent("public/en/p1/index.html", `v1: 0 sgo: |v2: 1 sgo: 0|v3: 2 sgo: 1|v4: 3 sgo: 2|v5: 4 sgo: 3`) builder.AssertFileContent("public/en/p1/index.html", `outer ordinal: 5 inner: ordinal: 0 scratch ordinal: 1 scratch get ordinal: 0 ordinal: 2 scratch ordinal: 3 scratch get ordinal: 2 ordinal: 4 scratch ordinal: 5 scratch get ordinal: 4`) } func TestShortcodeVariables(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc {{< s1 >}} `).WithTemplatesAdded("layouts/shortcodes/s1.html", ` Name: {{ .Name }} {{ with .Position }} File: {{ .Filename }} Offset: {{ .Offset }} Line: {{ .LineNumber }} Column: {{ .ColumnNumber }} String: {{ . | safeHTML }} {{ end }} `).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", filepath.FromSlash("File: content/page.md"), "Line: 7", "Column: 4", "Offset: 40", filepath.FromSlash("String: \"content/page.md:7:4\""), "Name: s1", ) } func TestInlineShortcodes(t *testing.T) { for _, enableInlineShortcodes := range []bool{true, false} { enableInlineShortcodes := enableInlineShortcodes t.Run(fmt.Sprintf("enableInlineShortcodes=%t", enableInlineShortcodes), func(t *testing.T) { t.Parallel() conf := fmt.Sprintf(` baseURL = "https://example.com" enableInlineShortcodes = %t `, enableInlineShortcodes) b := newTestSitesBuilder(t) b.WithConfigFile("toml", conf) shortcodeContent := `FIRST:{{< myshort.inline "first" >}} Page: {{ .Page.Title }} Seq: {{ seq 3 }} Param: {{ .Get 0 }} {{< /myshort.inline >}}:END: SECOND:{{< myshort.inline "second" />}}:END NEW INLINE: {{< n1.inline "5" >}}W1: {{ seq (.Get 0) }}{{< /n1.inline >}}:END: INLINE IN INNER: {{< outer >}}{{< n2.inline >}}W2: {{ seq 4 }}{{< /n2.inline >}}{{< /outer >}}:END: REUSED INLINE IN INNER: {{< outer >}}{{< n1.inline "3" />}}{{< /outer >}}:END: ## MARKDOWN DELIMITER: {{% mymarkdown.inline %}}**Hugo Rocks!**{{% /mymarkdown.inline %}} ` b.WithContent("page-md-shortcode.md", `--- title: "Hugo" --- `+shortcodeContent) b.WithContent("_index.md", `--- title: "Hugo Home" --- `+shortcodeContent) b.WithTemplatesAdded("layouts/_default/single.html", ` CONTENT:{{ .Content }} TOC: {{ .TableOfContents }} `) b.WithTemplatesAdded("layouts/index.html", ` CONTENT:{{ .Content }} TOC: {{ .TableOfContents }} `) b.WithTemplatesAdded("layouts/shortcodes/outer.html", `Inner: {{ .Inner }}`) b.CreateSites().Build(BuildCfg{}) shouldContain := []string{ "Seq: [1 2 3]", "Param: first", "Param: second", "NEW INLINE: W1: [1 2 3 4 5]", "INLINE IN INNER: Inner: W2: [1 2 3 4]", "REUSED INLINE IN INNER: Inner: W1: [1 2 3]", `<li><a href="#markdown-delimiter-hugo-rocks">MARKDOWN DELIMITER: <strong>Hugo Rocks!</strong></a></li>`, } if enableInlineShortcodes { b.AssertFileContent("public/page-md-shortcode/index.html", shouldContain..., ) b.AssertFileContent("public/index.html", shouldContain..., ) } else { b.AssertFileContent("public/page-md-shortcode/index.html", "FIRST::END", "SECOND::END", "NEW INLINE: :END", "INLINE IN INNER: Inner: :END:", "REUSED INLINE IN INNER: Inner: :END:", ) } }) } } // https://github.com/gohugoio/hugo/issues/5863 func TestShortcodeNamespaced(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc hello: {{< hello >}} test/hello: {{< test/hello >}} `).WithTemplatesAdded( "layouts/shortcodes/hello.html", `hello`, "layouts/shortcodes/test/hello.html", `test/hello`).CreateSites().Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", "hello: hello", "test/hello: test/hello", ) } // https://github.com/gohugoio/hugo/issues/6504 func TestShortcodeEmoji(t *testing.T) { t.Parallel() v := config.NewWithTestDefaults() v.Set("enableEmoji", true) builder := newTestSitesBuilder(t).WithViper(v) builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc {{< event >}}10:30-11:00 My :smile: Event {{< /event >}} `).WithTemplatesAdded( "layouts/shortcodes/event.html", `<div>{{ "\u29BE" }} {{ .Inner }} </div>`) builder.Build(BuildCfg{}) builder.AssertFileContent("public/page/index.html", "⦾ 10:30-11:00 My 😄 Event", ) } func TestShortcodeParams(t *testing.T) { t.Parallel() c := qt.New(t) builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder.WithContent("page.md", `--- title: "Hugo Rocks!" --- # doc types positional: {{< hello true false 33 3.14 >}} types named: {{< hello b1=true b2=false i1=33 f1=3.14 >}} types string: {{< hello "true" trues "33" "3.14" >}} escaped quoute: {{< hello "hello \"world\"." >}} `).WithTemplatesAdded( "layouts/shortcodes/hello.html", `{{ range $i, $v := .Params }} - {{ printf "%v: %v (%T)" $i $v $v }} {{ end }} {{ $b1 := .Get "b1" }} Get: {{ printf "%v (%T)" $b1 $b1 | safeHTML }} `).Build(BuildCfg{}) s := builder.H.Sites[0] c.Assert(len(s.RegularPages()), qt.Equals, 1) builder.AssertFileContent("public/page/index.html", "types positional: - 0: true (bool) - 1: false (bool) - 2: 33 (int) - 3: 3.14 (float64)", "types named: - b1: true (bool) - b2: false (bool) - f1: 3.14 (float64) - i1: 33 (int) Get: true (bool) ", "types string: - 0: true (string) - 1: trues (string) - 2: 33 (string) - 3: 3.14 (string) ", "hello &#34;world&#34;. (string)", ) } func TestShortcodeRef(t *testing.T) { t.Parallel() v := config.NewWithTestDefaults() v.Set("baseURL", "https://example.org") builder := newTestSitesBuilder(t).WithViper(v) for i := 1; i <= 2; i++ { builder.WithContent(fmt.Sprintf("page%d.md", i), `--- title: "Hugo Rocks!" --- [Page 1]({{< ref "page1.md" >}}) [Page 1 with anchor]({{< relref "page1.md#doc" >}}) [Page 2]({{< ref "page2.md" >}}) [Page 2 with anchor]({{< relref "page2.md#doc" >}}) ## Doc `) } builder.Build(BuildCfg{}) builder.AssertFileContent("public/page2/index.html", ` <a href="/page1/#doc">Page 1 with anchor</a> <a href="https://example.org/page2/">Page 2</a> <a href="/page2/#doc">Page 2 with anchor</a></p> <h2 id="doc">Doc</h2> `, ) } // https://github.com/gohugoio/hugo/issues/6857 func TestShortcodeNoInner(t *testing.T) { t.Parallel() b := newTestSitesBuilder(t) b.WithContent("mypage.md", `--- title: "No Inner!" --- {{< noinner >}}{{< /noinner >}} `).WithTemplatesAdded( "layouts/shortcodes/noinner.html", `No inner here.`) err := b.BuildE(BuildCfg{}) b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`"content/mypage.md:4:16": failed to extract shortcode: shortcode "noinner" does not evaluate .Inner or .InnerDeindent, yet a closing tag was provided`)) } func TestShortcodeStableOutputFormatTemplates(t *testing.T) { t.Parallel() for i := 0; i < 5; i++ { b := newTestSitesBuilder(t) const numPages = 10 for i := 0; i < numPages; i++ { b.WithContent(fmt.Sprintf("page%d.md", i), `--- title: "Page" outputs: ["html", "css", "csv", "json"] --- {{< myshort >}} `) } b.WithTemplates( "_default/single.html", "{{ .Content }}", "_default/single.css", "{{ .Content }}", "_default/single.csv", "{{ .Content }}", "_default/single.json", "{{ .Content }}", "shortcodes/myshort.html", `Short-HTML`, "shortcodes/myshort.csv", `Short-CSV`, ) b.Build(BuildCfg{}) // helpers.PrintFs(b.Fs.Destination, "public", os.Stdout) for i := 0; i < numPages; i++ { b.AssertFileContent(fmt.Sprintf("public/page%d/index.html", i), "Short-HTML") b.AssertFileContent(fmt.Sprintf("public/page%d/index.csv", i), "Short-CSV") b.AssertFileContent(fmt.Sprintf("public/page%d/index.json", i), "Short-HTML") } for i := 0; i < numPages; i++ { b.AssertFileContent(fmt.Sprintf("public/page%d/styles.css", i), "Short-HTML") } } } // #9821 func TestShortcodeMarkdownOutputFormat(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- {{< foo >}} -- layouts/shortcodes/foo.md -- §§§ <x §§§ -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <x `) } func TestShortcodePreserveIndentation(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## List With Indented Shortcodes 1. List 1 {{% mark1 %}} 1. Item Mark1 1 1. Item Mark1 2 {{% mark2 %}} {{% /mark1 %}} -- layouts/shortcodes/mark1.md -- {{ .Inner }} -- layouts/shortcodes/mark2.md -- 1. Item Mark2 1 1. Item Mark2 2 1. Item Mark2 2-1 1. Item Mark2 3 -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", "<ol>\n<li>\n<p>List 1</p>\n<ol>\n<li>Item Mark1 1</li>\n<li>Item Mark1 2</li>\n<li>Item Mark2 1</li>\n<li>Item Mark2 2\n<ol>\n<li>Item Mark2 2-1</li>\n</ol>\n</li>\n<li>Item Mark2 3</li>\n</ol>\n</li>\n</ol>") } func TestShortcodeCodeblockIndent(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code block {{% code %}} -- layouts/shortcodes/code.md -- echo "foo"; -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", "<pre><code>echo &quot;foo&quot;;\n</code></pre>") } func TestShortcodeHighlightDeindent(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] [markup.highlight] codeFences = true noClasses = false -- content/p1.md -- --- title: "p1" --- ## Indent 5 Spaces {{< highlight bash >}} line 1; line 2; line 3; {{< /highlight >}} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` <pre><code> <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">line 1<span class="p">;</span> </span></span><span class="line"><span class="cl">line 2<span class="p">;</span> </span></span><span class="line"><span class="cl">line 3<span class="p">;</span></span></span></code></pre></div> </code></pre> `) } // Issue 10236. func TestShortcodeParamEscapedQuote(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- {{< figure src="/media/spf13.jpg" title="Steve \"Francia\"." >}} -- layouts/shortcodes/figure.html -- Title: {{ .Get "title" | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/p1/index.html", `Title: Steve "Francia".`) } // Issue 10391. func TestNestedShortcodeCustomOutputFormat(t *testing.T) { t.Parallel() files := ` -- config.toml -- [outputFormats.Foobar] baseName = "foobar" isPlainText = true mediaType = "application/json" notAlternative = true [languages.en] languageName = "English" [languages.en.outputs] home = [ "HTML", "RSS", "Foobar" ] [languages.fr] languageName = "Français" [[module.mounts]] source = "content/en" target = "content" lang = "en" [[module.mounts]] source = "content/fr" target = "content" lang = "fr" -- layouts/_default/list.foobar.json -- {{- $.Scratch.Add "data" slice -}} {{- range (where .Site.AllPages "Kind" "!=" "home") -}} {{- $.Scratch.Add "data" (dict "content" (.Plain | truncate 10000) "type" .Type "full_url" .Permalink) -}} {{- end -}} {{- $.Scratch.Get "data" | jsonify -}} -- content/en/p1.md -- --- title: "p1" --- ### More information {{< tabs >}} {{% tab "Test" %}} It's a test {{% /tab %}} {{< /tabs >}} -- content/fr/p2.md -- --- title: Test --- ### Plus d'informations {{< tabs >}} {{% tab "Test" %}} C'est un test {{% /tab %}} {{< /tabs >}} -- layouts/shortcodes/tabs.html -- <div> <div class="tab-content">{{ .Inner }}</div> </div> -- layouts/shortcodes/tab.html -- <div>{{ .Inner }}</div> -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/fr/p2/index.html", `plus-dinformations`) } // Issue 10671. func TestShortcodeInnerShouldBeEmptyWhenNotClosed(t *testing.T) { t.Parallel() files := ` -- config.toml -- disableKinds = ["home", "taxonomy", "term"] -- content/p1.md -- --- title: "p1" --- {{< sc "self-closing" />}} Text. {{< sc "closing-no-newline" >}}{{< /sc >}} -- layouts/shortcodes/sc.html -- Inner: {{ .Get 0 }}: {{ len .Inner }} InnerDeindent: {{ .Get 0 }}: {{ len .InnerDeindent }} -- layouts/_default/single.html -- {{ .Content }} ` b := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).Build() b.AssertFileContent("public/p1/index.html", ` Inner: self-closing: 0 InnerDeindent: self-closing: 0 Inner: closing-no-newline: 0 InnerDeindent: closing-no-newline: 0 `) } // Issue 10675. func TestShortcodeErrorWhenItShouldBeClosed(t *testing.T) { t.Parallel() files := ` -- config.toml -- disableKinds = ["home", "taxonomy", "term"] -- content/p1.md -- --- title: "p1" --- {{< sc >}} Text. -- layouts/shortcodes/sc.html -- Inner: {{ .Get 0 }}: {{ len .Inner }} -- layouts/_default/single.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, Running: true, Verbose: true, }, ).BuildE() b.Assert(err, qt.Not(qt.IsNil)) b.Assert(err.Error(), qt.Contains, `p1.md:5:1": failed to extract shortcode: unclosed shortcode "sc"`) }
bep
7d78a498e19c2331a325fa43dd46f4da2b0443a6
ae48507d66db1fbe9b8fd5e3589941bee362a7ec
> In my head that then leaves us with https://github.com/gohugoio/hugo/issues/10675 and https://github.com/gohugoio/hugo/issues/10673 And https://github.com/gohugoio/hugo/issues/10672
jmooring
73
gohugoio/hugo
10,621
Make hugo.toml the new config.toml
Both will of course work, but hugo.toml will win if both are set. We should have done this a long time ago, of course, but the reason I'm picking this up now is that my VS Code setup by default picks up some JSON config schema from some random other software which also names its config files config.toml. Fixes #8979
null
2023-01-16 08:39:47+00:00
2023-01-16 14:34:16+00:00
hugolib/config_test.go
// Copyright 2016-present 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 hugolib import ( "bytes" "fmt" "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/google/go-cmp/cmp" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/maps" "github.com/spf13/afero" ) func TestLoadConfig(t *testing.T) { c := qt.New(t) loadConfig := func(c *qt.C, configContent string, fromDir bool) config.Provider { mm := afero.NewMemMapFs() filename := "config.toml" descriptor := ConfigSourceDescriptor{Fs: mm} if fromDir { filename = filepath.Join("config", "_default", filename) descriptor.AbsConfigDir = "config" } writeToFs(t, mm, filename, configContent) cfg, _, err := LoadConfig(descriptor) c.Assert(err, qt.IsNil) return cfg } c.Run("Basic", func(c *qt.C) { c.Parallel() // Add a random config variable for testing. // side = page in Norwegian. cfg := loadConfig(c, `PaginatePath = "side"`, false) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "side") }) // Issue #8763 for _, fromDir := range []bool{false, true} { testName := "Taxonomy overrides" if fromDir { testName += " from dir" } c.Run(testName, func(c *qt.C) { c.Parallel() cfg := loadConfig(c, `[taxonomies] appellation = "appellations" vigneron = "vignerons"`, fromDir) c.Assert(cfg.Get("taxonomies"), qt.DeepEquals, maps.Params{ "appellation": "appellations", "vigneron": "vignerons", }) }) } } func TestLoadMultiConfig(t *testing.T) { t.Parallel() c := qt.New(t) // Add a random config variable for testing. // side = page in Norwegian. configContentBase := ` DontChange = "same" PaginatePath = "side" ` configContentSub := ` PaginatePath = "top" ` mm := afero.NewMemMapFs() writeToFs(t, mm, "base.toml", configContentBase) writeToFs(t, mm, "override.toml", configContentSub) cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "base.toml,override.toml"}) c.Assert(err, qt.IsNil) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "top") c.Assert(cfg.GetString("DontChange"), qt.Equals, "same") } func TestLoadConfigFromThemes(t *testing.T) { t.Parallel() c := qt.New(t) mainConfigTemplate := ` theme = "test-theme" baseURL = "https://example.com/" [frontmatter] date = ["date","publishDate"] [params] MERGE_PARAMS p1 = "p1 main" [params.b] b1 = "b1 main" [params.b.c] bc1 = "bc1 main" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1main"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1main" [languages] [languages.en] languageName = "English" [languages.en.params] pl1 = "p1-en-main" [languages.nb] languageName = "Norsk" [languages.nb.params] pl1 = "p1-nb-main" [[menu.main]] name = "menu-main-main" [[menu.top]] name = "menu-top-main" ` themeConfig := ` baseURL = "http://bep.is/" # Can not be set in theme. disableKinds = ["taxonomy", "term"] # Can not be set in theme. [frontmatter] expiryDate = ["date"] [params] p1 = "p1 theme" p2 = "p2 theme" [params.b] b1 = "b1 theme" b2 = "b2 theme" [params.b.c] bc1 = "bc1 theme" bc2 = "bc2 theme" [params.b.c.d] bcd1 = "bcd1 theme" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1theme"] [mediaTypes."text/m2"] suffixes = ["m2theme"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1theme" [outputFormats.o2] mediaType = "text/m2" baseName = "o2theme" [languages] [languages.en] languageName = "English2" [languages.en.params] pl1 = "p1-en-theme" pl2 = "p2-en-theme" [[languages.en.menu.main]] name = "menu-lang-en-main" [[languages.en.menu.theme]] name = "menu-lang-en-theme" [languages.nb] languageName = "Norsk2" [languages.nb.params] pl1 = "p1-nb-theme" pl2 = "p2-nb-theme" top = "top-nb-theme" [[languages.nb.menu.main]] name = "menu-lang-nb-main" [[languages.nb.menu.theme]] name = "menu-lang-nb-theme" [[languages.nb.menu.top]] name = "menu-lang-nb-top" [[menu.main]] name = "menu-main-theme" [[menu.thememenu]] name = "menu-theme" ` buildForConfig := func(t testing.TB, mainConfig, themeConfig string) *sitesBuilder { b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) return b.Build(BuildCfg{}) } buildForStrategy := func(t testing.TB, s string) *sitesBuilder { mainConfig := strings.ReplaceAll(mainConfigTemplate, "MERGE_PARAMS", s) return buildForConfig(t, mainConfig, themeConfig) } c.Run("Merge default", func(c *qt.C) { b := buildForStrategy(c, "") got := b.Cfg.Get("").(maps.Params) // Issue #8866 b.Assert(b.Cfg.Get("disableKinds"), qt.IsNil) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", "bc2": "bc2 theme", "d": maps.Params{"bcd1": string("bcd1 theme")}, }, "b2": "b2 theme", }, "p2": "p2 theme", "p1": "p1 main", }) b.Assert(got["mediatypes"], qt.DeepEquals, maps.Params{ "text/m2": maps.Params{ "suffixes": []any{ "m2theme", }, }, "text/m1": maps.Params{ "suffixes": []any{ "m1main", }, }, }) var eq = qt.CmpEquals( cmp.Comparer(func(m1, m2 media.Type) bool { if m1.SubType != m2.SubType { return false } return m1.FirstSuffix == m2.FirstSuffix }), ) mediaTypes := b.H.Sites[0].mediaTypesConfig m1, _ := mediaTypes.GetByType("text/m1") m2, _ := mediaTypes.GetByType("text/m2") b.Assert(got["outputformats"], eq, maps.Params{ "o1": maps.Params{ "mediatype": m1, "basename": "o1main", }, "o2": maps.Params{ "basename": "o2theme", "mediatype": m2, }, }) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "params": maps.Params{ "pl2": "p2-en-theme", "pl1": "p1-en-main", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-en-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-en-theme", }, }, }, }, "nb": maps.Params{ "languagename": "Norsk", "params": maps.Params{ "top": "top-nb-theme", "pl1": "p1-nb-main", "pl2": "p2-nb-theme", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-nb-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-nb-theme", }, }, "top": []any{ map[string]any{ "name": "menu-lang-nb-top", }, }, }, }, }) c.Assert(got["baseurl"], qt.Equals, "https://example.com/") }) c.Run("Merge shallow", func(c *qt.C) { b := buildForStrategy(c, fmt.Sprintf("_merge=%q", "shallow")) got := b.Cfg.Get("").(maps.Params) // Shallow merge, only add new keys to params. b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 main", "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", }, }, "p2": "p2 theme", }) }) c.Run("Merge no params in project", func(c *qt.C) { b := buildForConfig( c, "baseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", "[params]\np1 = \"p1 theme\"\n", ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 theme", }) }) c.Run("Merge language no menus or params in project", func(c *qt.C) { b := buildForConfig( c, ` theme = "test-theme" baseURL = "https://example.com/" [languages] [languages.en] languageName = "English" `, ` [languages] [languages.en] languageName = "EnglishTheme" [languages.en.params] p1="themep1" [[languages.en.menus.main]] name = "menu-theme" `, ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-theme", }, }, }, "params": maps.Params{ "p1": "themep1", }, }, }, ) }) // Issue #8724 for _, mergeStrategy := range []string{"none", "shallow"} { c.Run(fmt.Sprintf("Merge with sitemap config in theme, mergestrategy %s", mergeStrategy), func(c *qt.C) { smapConfigTempl := `[sitemap] changefreq = %q filename = "sitemap.xml" priority = 0.5` b := buildForConfig( c, fmt.Sprintf("_merge=%q\nbaseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", mergeStrategy), "baseURL=\"http://example.com\"\n"+fmt.Sprintf(smapConfigTempl, "monthly"), ) got := b.Cfg.Get("").(maps.Params) if mergeStrategy == "none" { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", }) b.AssertFileContent("public/sitemap.xml", "schemas/sitemap") } else { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", "changefreq": "monthly", }) b.AssertFileContent("public/sitemap.xml", "<changefreq>monthly</changefreq>") } }) } } func TestLoadConfigFromThemeDir(t *testing.T) { t.Parallel() mainConfig := ` theme = "test-theme" [params] m1 = "mv1" ` themeConfig := ` [params] t1 = "tv1" t2 = "tv2" ` themeConfigDir := filepath.Join("themes", "test-theme", "config") themeConfigDirDefault := filepath.Join(themeConfigDir, "_default") themeConfigDirProduction := filepath.Join(themeConfigDir, "production") projectConfigDir := "config" b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirDefault, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirProduction, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(projectConfigDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(projectConfigDir, "config.toml"), `[params] m2 = "mv2" `) b.WithSourceFile(filepath.Join(themeConfigDirDefault, "config.toml"), `[params] t2 = "tv2d" t3 = "tv3d" `) b.WithSourceFile(filepath.Join(themeConfigDirProduction, "config.toml"), `[params] t3 = "tv3p" `) b.Build(BuildCfg{}) got := b.Cfg.Get("params").(maps.Params) b.Assert(got, qt.DeepEquals, maps.Params{ "t3": "tv3p", "m1": "mv1", "t1": "tv1", "t2": "tv2d", }) } func TestPrivacyConfig(t *testing.T) { t.Parallel() c := qt.New(t) tomlConfig := ` someOtherValue = "foo" [privacy] [privacy.youtube] privacyEnhanced = true ` b := newTestSitesBuilder(t) b.WithConfigFile("toml", tomlConfig) b.Build(BuildCfg{SkipRender: true}) c.Assert(b.H.Sites[0].Info.Config().Privacy.YouTube.PrivacyEnhanced, qt.Equals, true) } func TestLoadConfigModules(t *testing.T) { t.Parallel() c := qt.New(t) // https://github.com/gohugoio/hugoThemes#themetoml const ( // Before Hugo 0.56 each theme/component could have its own theme.toml // with some settings, mostly used on the Hugo themes site. // To preserve combability we read these files into the new "modules" // section in config.toml. o1t = ` name = "Component o1" license = "MIT" min_version = 0.38 ` // This is the component's config.toml, using the old theme syntax. o1c = ` theme = ["n2"] ` n1 = ` title = "Component n1" [module] description = "Component n1 description" [module.hugoVersion] min = "0.40.0" max = "0.50.0" extended = true [[module.imports]] path="o1" [[module.imports]] path="n3" ` n2 = ` title = "Component n2" ` n3 = ` title = "Component n3" ` n4 = ` title = "Component n4" ` ) b := newTestSitesBuilder(t) writeThemeFiles := func(name, configTOML, themeTOML string) { b.WithSourceFile(filepath.Join("themes", name, "data", "module.toml"), fmt.Sprintf("name=%q", name)) if configTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "config.toml"), configTOML) } if themeTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "theme.toml"), themeTOML) } } writeThemeFiles("n1", n1, "") writeThemeFiles("n2", n2, "") writeThemeFiles("n3", n3, "") writeThemeFiles("n4", n4, "") writeThemeFiles("o1", o1c, o1t) b.WithConfigFile("toml", ` [module] [[module.imports]] path="n1" [[module.imports]] path="n4" `) b.Build(BuildCfg{}) modulesClient := b.H.Paths.ModulesClient var graphb bytes.Buffer modulesClient.Graph(&graphb) expected := `project n1 n1 o1 o1 n2 n1 n3 project n4 ` c.Assert(graphb.String(), qt.Equals, expected) } func TestLoadConfigWithOsEnvOverrides(t *testing.T) { c := qt.New(t) baseConfig := ` theme = "mytheme" environment = "production" enableGitInfo = true intSlice = [5,7,9] floatSlice = [3.14, 5.19] stringSlice = ["a", "b"] [outputFormats] [outputFormats.ofbase] mediaType = "text/plain" [params] paramWithNoEnvOverride="nooverride" [params.api_config] api_key="default_key" another_key="default another_key" [imaging] anchor = "smart" quality = 75 ` newB := func(t testing.TB) *sitesBuilder { b := newTestSitesBuilder(t).WithConfigFile("toml", baseConfig) b.WithSourceFile("themes/mytheme/config.toml", ` [outputFormats] [outputFormats.oftheme] mediaType = "text/plain" [outputFormats.ofbase] mediaType = "application/xml" [params] [params.mytheme_section] theme_param="themevalue" theme_param_nooverride="nooverride" [params.mytheme_section2] theme_param="themevalue2" `) return b } c.Run("Variations", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENVIRONMENT", "test", "HUGO_NEW", "new", // key not in config.toml "HUGO_ENABLEGITINFO", "false", "HUGO_IMAGING_ANCHOR", "top", "HUGO_IMAGING_RESAMPLEFILTER", "CatmullRom", "HUGO_STRINGSLICE", `["c", "d"]`, "HUGO_INTSLICE", `[5, 8, 9]`, "HUGO_FLOATSLICE", `[5.32]`, // Issue #7829 "HUGOxPARAMSxAPI_CONFIGxAPI_KEY", "new_key", // Delimiters are case sensitive. "HUGOxPARAMSxAPI_CONFIGXANOTHER_KEY", "another_key", // Issue #8346 "HUGOxPARAMSxMYTHEME_SECTIONxTHEME_PARAM", "themevalue_changed", "HUGOxPARAMSxMYTHEME_SECTION2xTHEME_PARAM", "themevalue2_changed", "HUGO_PARAMS_EMPTY", ``, "HUGO_PARAMS_HTML", `<a target="_blank" />`, // Issue #8618 "HUGO_SERVICES_GOOGLEANALYTICS_ID", `gaid`, "HUGO_PARAMS_A_B_C", "abc", ) b.Build(BuildCfg{}) cfg := b.H.Cfg s := b.H.Sites[0] scfg := s.siteConfigConfig.Services c.Assert(cfg.Get("environment"), qt.Equals, "test") c.Assert(cfg.GetBool("enablegitinfo"), qt.Equals, false) c.Assert(cfg.Get("new"), qt.Equals, "new") c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "top") c.Assert(cfg.Get("imaging.quality"), qt.Equals, int64(75)) c.Assert(cfg.Get("imaging.resamplefilter"), qt.Equals, "CatmullRom") c.Assert(cfg.Get("stringSlice"), qt.DeepEquals, []any{"c", "d"}) c.Assert(cfg.Get("floatSlice"), qt.DeepEquals, []any{5.32}) c.Assert(cfg.Get("intSlice"), qt.DeepEquals, []any{5, 8, 9}) c.Assert(cfg.Get("params.api_config.api_key"), qt.Equals, "new_key") c.Assert(cfg.Get("params.api_config.another_key"), qt.Equals, "default another_key") c.Assert(cfg.Get("params.mytheme_section.theme_param"), qt.Equals, "themevalue_changed") c.Assert(cfg.Get("params.mytheme_section.theme_param_nooverride"), qt.Equals, "nooverride") c.Assert(cfg.Get("params.mytheme_section2.theme_param"), qt.Equals, "themevalue2_changed") c.Assert(cfg.Get("params.empty"), qt.Equals, ``) c.Assert(cfg.Get("params.html"), qt.Equals, `<a target="_blank" />`) params := cfg.Get("params").(maps.Params) c.Assert(params["paramwithnoenvoverride"], qt.Equals, "nooverride") c.Assert(cfg.Get("params.paramwithnoenvoverride"), qt.Equals, "nooverride") c.Assert(scfg.GoogleAnalytics.ID, qt.Equals, "gaid") c.Assert(cfg.Get("params.a.b"), qt.DeepEquals, maps.Params{ "c": "abc", }) ofBase, _ := s.outputFormatsConfig.GetByName("ofbase") ofTheme, _ := s.outputFormatsConfig.GetByName("oftheme") c.Assert(ofBase.MediaType, qt.Equals, media.TextType) c.Assert(ofTheme.MediaType, qt.Equals, media.TextType) }) // Issue #8709 c.Run("Set in string", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENABLEGITINFO", "false", // imaging.anchor is a string, and it's not possible // to set a child attribute. "HUGO_IMAGING_ANCHOR_FOO", "top", ) b.Build(BuildCfg{}) cfg := b.H.Cfg c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "smart") }) } func TestInvalidDefaultMarkdownHandler(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] defaultMarkdownHandler = 'blackfriday' -- content/_index.md -- ## Foo -- layouts/index.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "Configured defaultMarkdownHandler \"blackfriday\" not found. Did you mean to use goldmark? Blackfriday was removed in Hugo v0.100.0.") }
// Copyright 2016-present 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 hugolib import ( "bytes" "fmt" "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/google/go-cmp/cmp" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/maps" "github.com/spf13/afero" ) func TestLoadConfig(t *testing.T) { c := qt.New(t) loadConfig := func(c *qt.C, configContent string, fromDir bool) config.Provider { mm := afero.NewMemMapFs() filename := "config.toml" descriptor := ConfigSourceDescriptor{Fs: mm} if fromDir { filename = filepath.Join("config", "_default", filename) descriptor.AbsConfigDir = "config" } writeToFs(t, mm, filename, configContent) cfg, _, err := LoadConfig(descriptor) c.Assert(err, qt.IsNil) return cfg } c.Run("Basic", func(c *qt.C) { c.Parallel() // Add a random config variable for testing. // side = page in Norwegian. cfg := loadConfig(c, `PaginatePath = "side"`, false) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "side") }) // Issue #8763 for _, fromDir := range []bool{false, true} { testName := "Taxonomy overrides" if fromDir { testName += " from dir" } c.Run(testName, func(c *qt.C) { c.Parallel() cfg := loadConfig(c, `[taxonomies] appellation = "appellations" vigneron = "vignerons"`, fromDir) c.Assert(cfg.Get("taxonomies"), qt.DeepEquals, maps.Params{ "appellation": "appellations", "vigneron": "vignerons", }) }) } } func TestLoadMultiConfig(t *testing.T) { t.Parallel() c := qt.New(t) // Add a random config variable for testing. // side = page in Norwegian. configContentBase := ` DontChange = "same" PaginatePath = "side" ` configContentSub := ` PaginatePath = "top" ` mm := afero.NewMemMapFs() writeToFs(t, mm, "base.toml", configContentBase) writeToFs(t, mm, "override.toml", configContentSub) cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "base.toml,override.toml"}) c.Assert(err, qt.IsNil) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "top") c.Assert(cfg.GetString("DontChange"), qt.Equals, "same") } func TestLoadConfigFromThemes(t *testing.T) { t.Parallel() c := qt.New(t) mainConfigTemplate := ` theme = "test-theme" baseURL = "https://example.com/" [frontmatter] date = ["date","publishDate"] [params] MERGE_PARAMS p1 = "p1 main" [params.b] b1 = "b1 main" [params.b.c] bc1 = "bc1 main" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1main"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1main" [languages] [languages.en] languageName = "English" [languages.en.params] pl1 = "p1-en-main" [languages.nb] languageName = "Norsk" [languages.nb.params] pl1 = "p1-nb-main" [[menu.main]] name = "menu-main-main" [[menu.top]] name = "menu-top-main" ` themeConfig := ` baseURL = "http://bep.is/" # Can not be set in theme. disableKinds = ["taxonomy", "term"] # Can not be set in theme. [frontmatter] expiryDate = ["date"] [params] p1 = "p1 theme" p2 = "p2 theme" [params.b] b1 = "b1 theme" b2 = "b2 theme" [params.b.c] bc1 = "bc1 theme" bc2 = "bc2 theme" [params.b.c.d] bcd1 = "bcd1 theme" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1theme"] [mediaTypes."text/m2"] suffixes = ["m2theme"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1theme" [outputFormats.o2] mediaType = "text/m2" baseName = "o2theme" [languages] [languages.en] languageName = "English2" [languages.en.params] pl1 = "p1-en-theme" pl2 = "p2-en-theme" [[languages.en.menu.main]] name = "menu-lang-en-main" [[languages.en.menu.theme]] name = "menu-lang-en-theme" [languages.nb] languageName = "Norsk2" [languages.nb.params] pl1 = "p1-nb-theme" pl2 = "p2-nb-theme" top = "top-nb-theme" [[languages.nb.menu.main]] name = "menu-lang-nb-main" [[languages.nb.menu.theme]] name = "menu-lang-nb-theme" [[languages.nb.menu.top]] name = "menu-lang-nb-top" [[menu.main]] name = "menu-main-theme" [[menu.thememenu]] name = "menu-theme" ` buildForConfig := func(t testing.TB, mainConfig, themeConfig string) *sitesBuilder { b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) return b.Build(BuildCfg{}) } buildForStrategy := func(t testing.TB, s string) *sitesBuilder { mainConfig := strings.ReplaceAll(mainConfigTemplate, "MERGE_PARAMS", s) return buildForConfig(t, mainConfig, themeConfig) } c.Run("Merge default", func(c *qt.C) { b := buildForStrategy(c, "") got := b.Cfg.Get("").(maps.Params) // Issue #8866 b.Assert(b.Cfg.Get("disableKinds"), qt.IsNil) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", "bc2": "bc2 theme", "d": maps.Params{"bcd1": string("bcd1 theme")}, }, "b2": "b2 theme", }, "p2": "p2 theme", "p1": "p1 main", }) b.Assert(got["mediatypes"], qt.DeepEquals, maps.Params{ "text/m2": maps.Params{ "suffixes": []any{ "m2theme", }, }, "text/m1": maps.Params{ "suffixes": []any{ "m1main", }, }, }) var eq = qt.CmpEquals( cmp.Comparer(func(m1, m2 media.Type) bool { if m1.SubType != m2.SubType { return false } return m1.FirstSuffix == m2.FirstSuffix }), ) mediaTypes := b.H.Sites[0].mediaTypesConfig m1, _ := mediaTypes.GetByType("text/m1") m2, _ := mediaTypes.GetByType("text/m2") b.Assert(got["outputformats"], eq, maps.Params{ "o1": maps.Params{ "mediatype": m1, "basename": "o1main", }, "o2": maps.Params{ "basename": "o2theme", "mediatype": m2, }, }) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "params": maps.Params{ "pl2": "p2-en-theme", "pl1": "p1-en-main", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-en-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-en-theme", }, }, }, }, "nb": maps.Params{ "languagename": "Norsk", "params": maps.Params{ "top": "top-nb-theme", "pl1": "p1-nb-main", "pl2": "p2-nb-theme", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-nb-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-nb-theme", }, }, "top": []any{ map[string]any{ "name": "menu-lang-nb-top", }, }, }, }, }) c.Assert(got["baseurl"], qt.Equals, "https://example.com/") }) c.Run("Merge shallow", func(c *qt.C) { b := buildForStrategy(c, fmt.Sprintf("_merge=%q", "shallow")) got := b.Cfg.Get("").(maps.Params) // Shallow merge, only add new keys to params. b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 main", "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", }, }, "p2": "p2 theme", }) }) c.Run("Merge no params in project", func(c *qt.C) { b := buildForConfig( c, "baseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", "[params]\np1 = \"p1 theme\"\n", ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 theme", }) }) c.Run("Merge language no menus or params in project", func(c *qt.C) { b := buildForConfig( c, ` theme = "test-theme" baseURL = "https://example.com/" [languages] [languages.en] languageName = "English" `, ` [languages] [languages.en] languageName = "EnglishTheme" [languages.en.params] p1="themep1" [[languages.en.menus.main]] name = "menu-theme" `, ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-theme", }, }, }, "params": maps.Params{ "p1": "themep1", }, }, }, ) }) // Issue #8724 for _, mergeStrategy := range []string{"none", "shallow"} { c.Run(fmt.Sprintf("Merge with sitemap config in theme, mergestrategy %s", mergeStrategy), func(c *qt.C) { smapConfigTempl := `[sitemap] changefreq = %q filename = "sitemap.xml" priority = 0.5` b := buildForConfig( c, fmt.Sprintf("_merge=%q\nbaseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", mergeStrategy), "baseURL=\"http://example.com\"\n"+fmt.Sprintf(smapConfigTempl, "monthly"), ) got := b.Cfg.Get("").(maps.Params) if mergeStrategy == "none" { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", }) b.AssertFileContent("public/sitemap.xml", "schemas/sitemap") } else { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", "changefreq": "monthly", }) b.AssertFileContent("public/sitemap.xml", "<changefreq>monthly</changefreq>") } }) } } func TestLoadConfigFromThemeDir(t *testing.T) { t.Parallel() mainConfig := ` theme = "test-theme" [params] m1 = "mv1" ` themeConfig := ` [params] t1 = "tv1" t2 = "tv2" ` themeConfigDir := filepath.Join("themes", "test-theme", "config") themeConfigDirDefault := filepath.Join(themeConfigDir, "_default") themeConfigDirProduction := filepath.Join(themeConfigDir, "production") projectConfigDir := "config" b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirDefault, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirProduction, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(projectConfigDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(projectConfigDir, "config.toml"), `[params] m2 = "mv2" `) b.WithSourceFile(filepath.Join(themeConfigDirDefault, "config.toml"), `[params] t2 = "tv2d" t3 = "tv3d" `) b.WithSourceFile(filepath.Join(themeConfigDirProduction, "config.toml"), `[params] t3 = "tv3p" `) b.Build(BuildCfg{}) got := b.Cfg.Get("params").(maps.Params) b.Assert(got, qt.DeepEquals, maps.Params{ "t3": "tv3p", "m1": "mv1", "t1": "tv1", "t2": "tv2d", }) } func TestPrivacyConfig(t *testing.T) { t.Parallel() c := qt.New(t) tomlConfig := ` someOtherValue = "foo" [privacy] [privacy.youtube] privacyEnhanced = true ` b := newTestSitesBuilder(t) b.WithConfigFile("toml", tomlConfig) b.Build(BuildCfg{SkipRender: true}) c.Assert(b.H.Sites[0].Info.Config().Privacy.YouTube.PrivacyEnhanced, qt.Equals, true) } func TestLoadConfigModules(t *testing.T) { t.Parallel() c := qt.New(t) // https://github.com/gohugoio/hugoThemes#themetoml const ( // Before Hugo 0.56 each theme/component could have its own theme.toml // with some settings, mostly used on the Hugo themes site. // To preserve combability we read these files into the new "modules" // section in config.toml. o1t = ` name = "Component o1" license = "MIT" min_version = 0.38 ` // This is the component's config.toml, using the old theme syntax. o1c = ` theme = ["n2"] ` n1 = ` title = "Component n1" [module] description = "Component n1 description" [module.hugoVersion] min = "0.40.0" max = "0.50.0" extended = true [[module.imports]] path="o1" [[module.imports]] path="n3" ` n2 = ` title = "Component n2" ` n3 = ` title = "Component n3" ` n4 = ` title = "Component n4" ` ) b := newTestSitesBuilder(t) writeThemeFiles := func(name, configTOML, themeTOML string) { b.WithSourceFile(filepath.Join("themes", name, "data", "module.toml"), fmt.Sprintf("name=%q", name)) if configTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "config.toml"), configTOML) } if themeTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "theme.toml"), themeTOML) } } writeThemeFiles("n1", n1, "") writeThemeFiles("n2", n2, "") writeThemeFiles("n3", n3, "") writeThemeFiles("n4", n4, "") writeThemeFiles("o1", o1c, o1t) b.WithConfigFile("toml", ` [module] [[module.imports]] path="n1" [[module.imports]] path="n4" `) b.Build(BuildCfg{}) modulesClient := b.H.Paths.ModulesClient var graphb bytes.Buffer modulesClient.Graph(&graphb) expected := `project n1 n1 o1 o1 n2 n1 n3 project n4 ` c.Assert(graphb.String(), qt.Equals, expected) } func TestLoadConfigWithOsEnvOverrides(t *testing.T) { c := qt.New(t) baseConfig := ` theme = "mytheme" environment = "production" enableGitInfo = true intSlice = [5,7,9] floatSlice = [3.14, 5.19] stringSlice = ["a", "b"] [outputFormats] [outputFormats.ofbase] mediaType = "text/plain" [params] paramWithNoEnvOverride="nooverride" [params.api_config] api_key="default_key" another_key="default another_key" [imaging] anchor = "smart" quality = 75 ` newB := func(t testing.TB) *sitesBuilder { b := newTestSitesBuilder(t).WithConfigFile("toml", baseConfig) b.WithSourceFile("themes/mytheme/config.toml", ` [outputFormats] [outputFormats.oftheme] mediaType = "text/plain" [outputFormats.ofbase] mediaType = "application/xml" [params] [params.mytheme_section] theme_param="themevalue" theme_param_nooverride="nooverride" [params.mytheme_section2] theme_param="themevalue2" `) return b } c.Run("Variations", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENVIRONMENT", "test", "HUGO_NEW", "new", // key not in config.toml "HUGO_ENABLEGITINFO", "false", "HUGO_IMAGING_ANCHOR", "top", "HUGO_IMAGING_RESAMPLEFILTER", "CatmullRom", "HUGO_STRINGSLICE", `["c", "d"]`, "HUGO_INTSLICE", `[5, 8, 9]`, "HUGO_FLOATSLICE", `[5.32]`, // Issue #7829 "HUGOxPARAMSxAPI_CONFIGxAPI_KEY", "new_key", // Delimiters are case sensitive. "HUGOxPARAMSxAPI_CONFIGXANOTHER_KEY", "another_key", // Issue #8346 "HUGOxPARAMSxMYTHEME_SECTIONxTHEME_PARAM", "themevalue_changed", "HUGOxPARAMSxMYTHEME_SECTION2xTHEME_PARAM", "themevalue2_changed", "HUGO_PARAMS_EMPTY", ``, "HUGO_PARAMS_HTML", `<a target="_blank" />`, // Issue #8618 "HUGO_SERVICES_GOOGLEANALYTICS_ID", `gaid`, "HUGO_PARAMS_A_B_C", "abc", ) b.Build(BuildCfg{}) cfg := b.H.Cfg s := b.H.Sites[0] scfg := s.siteConfigConfig.Services c.Assert(cfg.Get("environment"), qt.Equals, "test") c.Assert(cfg.GetBool("enablegitinfo"), qt.Equals, false) c.Assert(cfg.Get("new"), qt.Equals, "new") c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "top") c.Assert(cfg.Get("imaging.quality"), qt.Equals, int64(75)) c.Assert(cfg.Get("imaging.resamplefilter"), qt.Equals, "CatmullRom") c.Assert(cfg.Get("stringSlice"), qt.DeepEquals, []any{"c", "d"}) c.Assert(cfg.Get("floatSlice"), qt.DeepEquals, []any{5.32}) c.Assert(cfg.Get("intSlice"), qt.DeepEquals, []any{5, 8, 9}) c.Assert(cfg.Get("params.api_config.api_key"), qt.Equals, "new_key") c.Assert(cfg.Get("params.api_config.another_key"), qt.Equals, "default another_key") c.Assert(cfg.Get("params.mytheme_section.theme_param"), qt.Equals, "themevalue_changed") c.Assert(cfg.Get("params.mytheme_section.theme_param_nooverride"), qt.Equals, "nooverride") c.Assert(cfg.Get("params.mytheme_section2.theme_param"), qt.Equals, "themevalue2_changed") c.Assert(cfg.Get("params.empty"), qt.Equals, ``) c.Assert(cfg.Get("params.html"), qt.Equals, `<a target="_blank" />`) params := cfg.Get("params").(maps.Params) c.Assert(params["paramwithnoenvoverride"], qt.Equals, "nooverride") c.Assert(cfg.Get("params.paramwithnoenvoverride"), qt.Equals, "nooverride") c.Assert(scfg.GoogleAnalytics.ID, qt.Equals, "gaid") c.Assert(cfg.Get("params.a.b"), qt.DeepEquals, maps.Params{ "c": "abc", }) ofBase, _ := s.outputFormatsConfig.GetByName("ofbase") ofTheme, _ := s.outputFormatsConfig.GetByName("oftheme") c.Assert(ofBase.MediaType, qt.Equals, media.TextType) c.Assert(ofTheme.MediaType, qt.Equals, media.TextType) }) // Issue #8709 c.Run("Set in string", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENABLEGITINFO", "false", // imaging.anchor is a string, and it's not possible // to set a child attribute. "HUGO_IMAGING_ANCHOR_FOO", "top", ) b.Build(BuildCfg{}) cfg := b.H.Cfg c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "smart") }) } func TestInvalidDefaultMarkdownHandler(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] defaultMarkdownHandler = 'blackfriday' -- content/_index.md -- ## Foo -- layouts/index.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "Configured defaultMarkdownHandler \"blackfriday\" not found. Did you mean to use goldmark? Blackfriday was removed in Hugo v0.100.0.") } // Issue 8979 func TestHugoConfig(t *testing.T) { filesTemplate := ` -- hugo.toml -- theme = "mytheme" [params] rootparam = "rootvalue" -- config/_default/hugo.toml -- [params] rootconfigparam = "rootconfigvalue" -- themes/mytheme/config/_default/hugo.toml -- [params] themeconfigdirparam = "themeconfigdirvalue" -- themes/mytheme/hugo.toml -- [params] themeparam = "themevalue" -- layouts/index.html -- rootparam: {{ site.Params.rootparam }} rootconfigparam: {{ site.Params.rootconfigparam }} themeparam: {{ site.Params.themeparam }} themeconfigdirparam: {{ site.Params.themeconfigdirparam }} ` for _, configName := range []string{"hugo.toml", "config.toml"} { configName := configName t.Run(configName, func(t *testing.T) { t.Parallel() files := strings.ReplaceAll(filesTemplate, "hugo.toml", configName) b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNil) b.AssertFileContent("public/index.html", "rootparam: rootvalue", "rootconfigparam: rootconfigvalue", "themeparam: themevalue", "themeconfigdirparam: themeconfigdirvalue", ) }) } }
bep
6a579ebac3a81df61f22988e3eb55f7cb35ce523
f38a2fbd2e4de7f095a833b448cb8bc053955ce2
@jmooring do you see any problems with this test case? Note that * For the main config file in the root, we will pick the first. For the config.toml inside /config, I have made it simple so you can in theory have both, but that should not be a problem... * I will wait a little before changing the behaviour of hugo new site Also note that the main motivation behind me doing this now is VS Code starting to pick some other random config schema and is throwing these validation errors for me when doing config edits. I'm able to change this inside VS Code, but it's rather annoying, and I suspect this will improve when having a distinct filename,
bep
74
gohugoio/hugo
10,621
Make hugo.toml the new config.toml
Both will of course work, but hugo.toml will win if both are set. We should have done this a long time ago, of course, but the reason I'm picking this up now is that my VS Code setup by default picks up some JSON config schema from some random other software which also names its config files config.toml. Fixes #8979
null
2023-01-16 08:39:47+00:00
2023-01-16 14:34:16+00:00
hugolib/config_test.go
// Copyright 2016-present 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 hugolib import ( "bytes" "fmt" "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/google/go-cmp/cmp" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/maps" "github.com/spf13/afero" ) func TestLoadConfig(t *testing.T) { c := qt.New(t) loadConfig := func(c *qt.C, configContent string, fromDir bool) config.Provider { mm := afero.NewMemMapFs() filename := "config.toml" descriptor := ConfigSourceDescriptor{Fs: mm} if fromDir { filename = filepath.Join("config", "_default", filename) descriptor.AbsConfigDir = "config" } writeToFs(t, mm, filename, configContent) cfg, _, err := LoadConfig(descriptor) c.Assert(err, qt.IsNil) return cfg } c.Run("Basic", func(c *qt.C) { c.Parallel() // Add a random config variable for testing. // side = page in Norwegian. cfg := loadConfig(c, `PaginatePath = "side"`, false) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "side") }) // Issue #8763 for _, fromDir := range []bool{false, true} { testName := "Taxonomy overrides" if fromDir { testName += " from dir" } c.Run(testName, func(c *qt.C) { c.Parallel() cfg := loadConfig(c, `[taxonomies] appellation = "appellations" vigneron = "vignerons"`, fromDir) c.Assert(cfg.Get("taxonomies"), qt.DeepEquals, maps.Params{ "appellation": "appellations", "vigneron": "vignerons", }) }) } } func TestLoadMultiConfig(t *testing.T) { t.Parallel() c := qt.New(t) // Add a random config variable for testing. // side = page in Norwegian. configContentBase := ` DontChange = "same" PaginatePath = "side" ` configContentSub := ` PaginatePath = "top" ` mm := afero.NewMemMapFs() writeToFs(t, mm, "base.toml", configContentBase) writeToFs(t, mm, "override.toml", configContentSub) cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "base.toml,override.toml"}) c.Assert(err, qt.IsNil) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "top") c.Assert(cfg.GetString("DontChange"), qt.Equals, "same") } func TestLoadConfigFromThemes(t *testing.T) { t.Parallel() c := qt.New(t) mainConfigTemplate := ` theme = "test-theme" baseURL = "https://example.com/" [frontmatter] date = ["date","publishDate"] [params] MERGE_PARAMS p1 = "p1 main" [params.b] b1 = "b1 main" [params.b.c] bc1 = "bc1 main" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1main"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1main" [languages] [languages.en] languageName = "English" [languages.en.params] pl1 = "p1-en-main" [languages.nb] languageName = "Norsk" [languages.nb.params] pl1 = "p1-nb-main" [[menu.main]] name = "menu-main-main" [[menu.top]] name = "menu-top-main" ` themeConfig := ` baseURL = "http://bep.is/" # Can not be set in theme. disableKinds = ["taxonomy", "term"] # Can not be set in theme. [frontmatter] expiryDate = ["date"] [params] p1 = "p1 theme" p2 = "p2 theme" [params.b] b1 = "b1 theme" b2 = "b2 theme" [params.b.c] bc1 = "bc1 theme" bc2 = "bc2 theme" [params.b.c.d] bcd1 = "bcd1 theme" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1theme"] [mediaTypes."text/m2"] suffixes = ["m2theme"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1theme" [outputFormats.o2] mediaType = "text/m2" baseName = "o2theme" [languages] [languages.en] languageName = "English2" [languages.en.params] pl1 = "p1-en-theme" pl2 = "p2-en-theme" [[languages.en.menu.main]] name = "menu-lang-en-main" [[languages.en.menu.theme]] name = "menu-lang-en-theme" [languages.nb] languageName = "Norsk2" [languages.nb.params] pl1 = "p1-nb-theme" pl2 = "p2-nb-theme" top = "top-nb-theme" [[languages.nb.menu.main]] name = "menu-lang-nb-main" [[languages.nb.menu.theme]] name = "menu-lang-nb-theme" [[languages.nb.menu.top]] name = "menu-lang-nb-top" [[menu.main]] name = "menu-main-theme" [[menu.thememenu]] name = "menu-theme" ` buildForConfig := func(t testing.TB, mainConfig, themeConfig string) *sitesBuilder { b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) return b.Build(BuildCfg{}) } buildForStrategy := func(t testing.TB, s string) *sitesBuilder { mainConfig := strings.ReplaceAll(mainConfigTemplate, "MERGE_PARAMS", s) return buildForConfig(t, mainConfig, themeConfig) } c.Run("Merge default", func(c *qt.C) { b := buildForStrategy(c, "") got := b.Cfg.Get("").(maps.Params) // Issue #8866 b.Assert(b.Cfg.Get("disableKinds"), qt.IsNil) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", "bc2": "bc2 theme", "d": maps.Params{"bcd1": string("bcd1 theme")}, }, "b2": "b2 theme", }, "p2": "p2 theme", "p1": "p1 main", }) b.Assert(got["mediatypes"], qt.DeepEquals, maps.Params{ "text/m2": maps.Params{ "suffixes": []any{ "m2theme", }, }, "text/m1": maps.Params{ "suffixes": []any{ "m1main", }, }, }) var eq = qt.CmpEquals( cmp.Comparer(func(m1, m2 media.Type) bool { if m1.SubType != m2.SubType { return false } return m1.FirstSuffix == m2.FirstSuffix }), ) mediaTypes := b.H.Sites[0].mediaTypesConfig m1, _ := mediaTypes.GetByType("text/m1") m2, _ := mediaTypes.GetByType("text/m2") b.Assert(got["outputformats"], eq, maps.Params{ "o1": maps.Params{ "mediatype": m1, "basename": "o1main", }, "o2": maps.Params{ "basename": "o2theme", "mediatype": m2, }, }) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "params": maps.Params{ "pl2": "p2-en-theme", "pl1": "p1-en-main", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-en-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-en-theme", }, }, }, }, "nb": maps.Params{ "languagename": "Norsk", "params": maps.Params{ "top": "top-nb-theme", "pl1": "p1-nb-main", "pl2": "p2-nb-theme", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-nb-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-nb-theme", }, }, "top": []any{ map[string]any{ "name": "menu-lang-nb-top", }, }, }, }, }) c.Assert(got["baseurl"], qt.Equals, "https://example.com/") }) c.Run("Merge shallow", func(c *qt.C) { b := buildForStrategy(c, fmt.Sprintf("_merge=%q", "shallow")) got := b.Cfg.Get("").(maps.Params) // Shallow merge, only add new keys to params. b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 main", "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", }, }, "p2": "p2 theme", }) }) c.Run("Merge no params in project", func(c *qt.C) { b := buildForConfig( c, "baseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", "[params]\np1 = \"p1 theme\"\n", ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 theme", }) }) c.Run("Merge language no menus or params in project", func(c *qt.C) { b := buildForConfig( c, ` theme = "test-theme" baseURL = "https://example.com/" [languages] [languages.en] languageName = "English" `, ` [languages] [languages.en] languageName = "EnglishTheme" [languages.en.params] p1="themep1" [[languages.en.menus.main]] name = "menu-theme" `, ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-theme", }, }, }, "params": maps.Params{ "p1": "themep1", }, }, }, ) }) // Issue #8724 for _, mergeStrategy := range []string{"none", "shallow"} { c.Run(fmt.Sprintf("Merge with sitemap config in theme, mergestrategy %s", mergeStrategy), func(c *qt.C) { smapConfigTempl := `[sitemap] changefreq = %q filename = "sitemap.xml" priority = 0.5` b := buildForConfig( c, fmt.Sprintf("_merge=%q\nbaseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", mergeStrategy), "baseURL=\"http://example.com\"\n"+fmt.Sprintf(smapConfigTempl, "monthly"), ) got := b.Cfg.Get("").(maps.Params) if mergeStrategy == "none" { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", }) b.AssertFileContent("public/sitemap.xml", "schemas/sitemap") } else { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", "changefreq": "monthly", }) b.AssertFileContent("public/sitemap.xml", "<changefreq>monthly</changefreq>") } }) } } func TestLoadConfigFromThemeDir(t *testing.T) { t.Parallel() mainConfig := ` theme = "test-theme" [params] m1 = "mv1" ` themeConfig := ` [params] t1 = "tv1" t2 = "tv2" ` themeConfigDir := filepath.Join("themes", "test-theme", "config") themeConfigDirDefault := filepath.Join(themeConfigDir, "_default") themeConfigDirProduction := filepath.Join(themeConfigDir, "production") projectConfigDir := "config" b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirDefault, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirProduction, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(projectConfigDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(projectConfigDir, "config.toml"), `[params] m2 = "mv2" `) b.WithSourceFile(filepath.Join(themeConfigDirDefault, "config.toml"), `[params] t2 = "tv2d" t3 = "tv3d" `) b.WithSourceFile(filepath.Join(themeConfigDirProduction, "config.toml"), `[params] t3 = "tv3p" `) b.Build(BuildCfg{}) got := b.Cfg.Get("params").(maps.Params) b.Assert(got, qt.DeepEquals, maps.Params{ "t3": "tv3p", "m1": "mv1", "t1": "tv1", "t2": "tv2d", }) } func TestPrivacyConfig(t *testing.T) { t.Parallel() c := qt.New(t) tomlConfig := ` someOtherValue = "foo" [privacy] [privacy.youtube] privacyEnhanced = true ` b := newTestSitesBuilder(t) b.WithConfigFile("toml", tomlConfig) b.Build(BuildCfg{SkipRender: true}) c.Assert(b.H.Sites[0].Info.Config().Privacy.YouTube.PrivacyEnhanced, qt.Equals, true) } func TestLoadConfigModules(t *testing.T) { t.Parallel() c := qt.New(t) // https://github.com/gohugoio/hugoThemes#themetoml const ( // Before Hugo 0.56 each theme/component could have its own theme.toml // with some settings, mostly used on the Hugo themes site. // To preserve combability we read these files into the new "modules" // section in config.toml. o1t = ` name = "Component o1" license = "MIT" min_version = 0.38 ` // This is the component's config.toml, using the old theme syntax. o1c = ` theme = ["n2"] ` n1 = ` title = "Component n1" [module] description = "Component n1 description" [module.hugoVersion] min = "0.40.0" max = "0.50.0" extended = true [[module.imports]] path="o1" [[module.imports]] path="n3" ` n2 = ` title = "Component n2" ` n3 = ` title = "Component n3" ` n4 = ` title = "Component n4" ` ) b := newTestSitesBuilder(t) writeThemeFiles := func(name, configTOML, themeTOML string) { b.WithSourceFile(filepath.Join("themes", name, "data", "module.toml"), fmt.Sprintf("name=%q", name)) if configTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "config.toml"), configTOML) } if themeTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "theme.toml"), themeTOML) } } writeThemeFiles("n1", n1, "") writeThemeFiles("n2", n2, "") writeThemeFiles("n3", n3, "") writeThemeFiles("n4", n4, "") writeThemeFiles("o1", o1c, o1t) b.WithConfigFile("toml", ` [module] [[module.imports]] path="n1" [[module.imports]] path="n4" `) b.Build(BuildCfg{}) modulesClient := b.H.Paths.ModulesClient var graphb bytes.Buffer modulesClient.Graph(&graphb) expected := `project n1 n1 o1 o1 n2 n1 n3 project n4 ` c.Assert(graphb.String(), qt.Equals, expected) } func TestLoadConfigWithOsEnvOverrides(t *testing.T) { c := qt.New(t) baseConfig := ` theme = "mytheme" environment = "production" enableGitInfo = true intSlice = [5,7,9] floatSlice = [3.14, 5.19] stringSlice = ["a", "b"] [outputFormats] [outputFormats.ofbase] mediaType = "text/plain" [params] paramWithNoEnvOverride="nooverride" [params.api_config] api_key="default_key" another_key="default another_key" [imaging] anchor = "smart" quality = 75 ` newB := func(t testing.TB) *sitesBuilder { b := newTestSitesBuilder(t).WithConfigFile("toml", baseConfig) b.WithSourceFile("themes/mytheme/config.toml", ` [outputFormats] [outputFormats.oftheme] mediaType = "text/plain" [outputFormats.ofbase] mediaType = "application/xml" [params] [params.mytheme_section] theme_param="themevalue" theme_param_nooverride="nooverride" [params.mytheme_section2] theme_param="themevalue2" `) return b } c.Run("Variations", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENVIRONMENT", "test", "HUGO_NEW", "new", // key not in config.toml "HUGO_ENABLEGITINFO", "false", "HUGO_IMAGING_ANCHOR", "top", "HUGO_IMAGING_RESAMPLEFILTER", "CatmullRom", "HUGO_STRINGSLICE", `["c", "d"]`, "HUGO_INTSLICE", `[5, 8, 9]`, "HUGO_FLOATSLICE", `[5.32]`, // Issue #7829 "HUGOxPARAMSxAPI_CONFIGxAPI_KEY", "new_key", // Delimiters are case sensitive. "HUGOxPARAMSxAPI_CONFIGXANOTHER_KEY", "another_key", // Issue #8346 "HUGOxPARAMSxMYTHEME_SECTIONxTHEME_PARAM", "themevalue_changed", "HUGOxPARAMSxMYTHEME_SECTION2xTHEME_PARAM", "themevalue2_changed", "HUGO_PARAMS_EMPTY", ``, "HUGO_PARAMS_HTML", `<a target="_blank" />`, // Issue #8618 "HUGO_SERVICES_GOOGLEANALYTICS_ID", `gaid`, "HUGO_PARAMS_A_B_C", "abc", ) b.Build(BuildCfg{}) cfg := b.H.Cfg s := b.H.Sites[0] scfg := s.siteConfigConfig.Services c.Assert(cfg.Get("environment"), qt.Equals, "test") c.Assert(cfg.GetBool("enablegitinfo"), qt.Equals, false) c.Assert(cfg.Get("new"), qt.Equals, "new") c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "top") c.Assert(cfg.Get("imaging.quality"), qt.Equals, int64(75)) c.Assert(cfg.Get("imaging.resamplefilter"), qt.Equals, "CatmullRom") c.Assert(cfg.Get("stringSlice"), qt.DeepEquals, []any{"c", "d"}) c.Assert(cfg.Get("floatSlice"), qt.DeepEquals, []any{5.32}) c.Assert(cfg.Get("intSlice"), qt.DeepEquals, []any{5, 8, 9}) c.Assert(cfg.Get("params.api_config.api_key"), qt.Equals, "new_key") c.Assert(cfg.Get("params.api_config.another_key"), qt.Equals, "default another_key") c.Assert(cfg.Get("params.mytheme_section.theme_param"), qt.Equals, "themevalue_changed") c.Assert(cfg.Get("params.mytheme_section.theme_param_nooverride"), qt.Equals, "nooverride") c.Assert(cfg.Get("params.mytheme_section2.theme_param"), qt.Equals, "themevalue2_changed") c.Assert(cfg.Get("params.empty"), qt.Equals, ``) c.Assert(cfg.Get("params.html"), qt.Equals, `<a target="_blank" />`) params := cfg.Get("params").(maps.Params) c.Assert(params["paramwithnoenvoverride"], qt.Equals, "nooverride") c.Assert(cfg.Get("params.paramwithnoenvoverride"), qt.Equals, "nooverride") c.Assert(scfg.GoogleAnalytics.ID, qt.Equals, "gaid") c.Assert(cfg.Get("params.a.b"), qt.DeepEquals, maps.Params{ "c": "abc", }) ofBase, _ := s.outputFormatsConfig.GetByName("ofbase") ofTheme, _ := s.outputFormatsConfig.GetByName("oftheme") c.Assert(ofBase.MediaType, qt.Equals, media.TextType) c.Assert(ofTheme.MediaType, qt.Equals, media.TextType) }) // Issue #8709 c.Run("Set in string", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENABLEGITINFO", "false", // imaging.anchor is a string, and it's not possible // to set a child attribute. "HUGO_IMAGING_ANCHOR_FOO", "top", ) b.Build(BuildCfg{}) cfg := b.H.Cfg c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "smart") }) } func TestInvalidDefaultMarkdownHandler(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] defaultMarkdownHandler = 'blackfriday' -- content/_index.md -- ## Foo -- layouts/index.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "Configured defaultMarkdownHandler \"blackfriday\" not found. Did you mean to use goldmark? Blackfriday was removed in Hugo v0.100.0.") }
// Copyright 2016-present 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 hugolib import ( "bytes" "fmt" "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/google/go-cmp/cmp" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/maps" "github.com/spf13/afero" ) func TestLoadConfig(t *testing.T) { c := qt.New(t) loadConfig := func(c *qt.C, configContent string, fromDir bool) config.Provider { mm := afero.NewMemMapFs() filename := "config.toml" descriptor := ConfigSourceDescriptor{Fs: mm} if fromDir { filename = filepath.Join("config", "_default", filename) descriptor.AbsConfigDir = "config" } writeToFs(t, mm, filename, configContent) cfg, _, err := LoadConfig(descriptor) c.Assert(err, qt.IsNil) return cfg } c.Run("Basic", func(c *qt.C) { c.Parallel() // Add a random config variable for testing. // side = page in Norwegian. cfg := loadConfig(c, `PaginatePath = "side"`, false) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "side") }) // Issue #8763 for _, fromDir := range []bool{false, true} { testName := "Taxonomy overrides" if fromDir { testName += " from dir" } c.Run(testName, func(c *qt.C) { c.Parallel() cfg := loadConfig(c, `[taxonomies] appellation = "appellations" vigneron = "vignerons"`, fromDir) c.Assert(cfg.Get("taxonomies"), qt.DeepEquals, maps.Params{ "appellation": "appellations", "vigneron": "vignerons", }) }) } } func TestLoadMultiConfig(t *testing.T) { t.Parallel() c := qt.New(t) // Add a random config variable for testing. // side = page in Norwegian. configContentBase := ` DontChange = "same" PaginatePath = "side" ` configContentSub := ` PaginatePath = "top" ` mm := afero.NewMemMapFs() writeToFs(t, mm, "base.toml", configContentBase) writeToFs(t, mm, "override.toml", configContentSub) cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "base.toml,override.toml"}) c.Assert(err, qt.IsNil) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "top") c.Assert(cfg.GetString("DontChange"), qt.Equals, "same") } func TestLoadConfigFromThemes(t *testing.T) { t.Parallel() c := qt.New(t) mainConfigTemplate := ` theme = "test-theme" baseURL = "https://example.com/" [frontmatter] date = ["date","publishDate"] [params] MERGE_PARAMS p1 = "p1 main" [params.b] b1 = "b1 main" [params.b.c] bc1 = "bc1 main" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1main"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1main" [languages] [languages.en] languageName = "English" [languages.en.params] pl1 = "p1-en-main" [languages.nb] languageName = "Norsk" [languages.nb.params] pl1 = "p1-nb-main" [[menu.main]] name = "menu-main-main" [[menu.top]] name = "menu-top-main" ` themeConfig := ` baseURL = "http://bep.is/" # Can not be set in theme. disableKinds = ["taxonomy", "term"] # Can not be set in theme. [frontmatter] expiryDate = ["date"] [params] p1 = "p1 theme" p2 = "p2 theme" [params.b] b1 = "b1 theme" b2 = "b2 theme" [params.b.c] bc1 = "bc1 theme" bc2 = "bc2 theme" [params.b.c.d] bcd1 = "bcd1 theme" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1theme"] [mediaTypes."text/m2"] suffixes = ["m2theme"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1theme" [outputFormats.o2] mediaType = "text/m2" baseName = "o2theme" [languages] [languages.en] languageName = "English2" [languages.en.params] pl1 = "p1-en-theme" pl2 = "p2-en-theme" [[languages.en.menu.main]] name = "menu-lang-en-main" [[languages.en.menu.theme]] name = "menu-lang-en-theme" [languages.nb] languageName = "Norsk2" [languages.nb.params] pl1 = "p1-nb-theme" pl2 = "p2-nb-theme" top = "top-nb-theme" [[languages.nb.menu.main]] name = "menu-lang-nb-main" [[languages.nb.menu.theme]] name = "menu-lang-nb-theme" [[languages.nb.menu.top]] name = "menu-lang-nb-top" [[menu.main]] name = "menu-main-theme" [[menu.thememenu]] name = "menu-theme" ` buildForConfig := func(t testing.TB, mainConfig, themeConfig string) *sitesBuilder { b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) return b.Build(BuildCfg{}) } buildForStrategy := func(t testing.TB, s string) *sitesBuilder { mainConfig := strings.ReplaceAll(mainConfigTemplate, "MERGE_PARAMS", s) return buildForConfig(t, mainConfig, themeConfig) } c.Run("Merge default", func(c *qt.C) { b := buildForStrategy(c, "") got := b.Cfg.Get("").(maps.Params) // Issue #8866 b.Assert(b.Cfg.Get("disableKinds"), qt.IsNil) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", "bc2": "bc2 theme", "d": maps.Params{"bcd1": string("bcd1 theme")}, }, "b2": "b2 theme", }, "p2": "p2 theme", "p1": "p1 main", }) b.Assert(got["mediatypes"], qt.DeepEquals, maps.Params{ "text/m2": maps.Params{ "suffixes": []any{ "m2theme", }, }, "text/m1": maps.Params{ "suffixes": []any{ "m1main", }, }, }) var eq = qt.CmpEquals( cmp.Comparer(func(m1, m2 media.Type) bool { if m1.SubType != m2.SubType { return false } return m1.FirstSuffix == m2.FirstSuffix }), ) mediaTypes := b.H.Sites[0].mediaTypesConfig m1, _ := mediaTypes.GetByType("text/m1") m2, _ := mediaTypes.GetByType("text/m2") b.Assert(got["outputformats"], eq, maps.Params{ "o1": maps.Params{ "mediatype": m1, "basename": "o1main", }, "o2": maps.Params{ "basename": "o2theme", "mediatype": m2, }, }) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "params": maps.Params{ "pl2": "p2-en-theme", "pl1": "p1-en-main", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-en-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-en-theme", }, }, }, }, "nb": maps.Params{ "languagename": "Norsk", "params": maps.Params{ "top": "top-nb-theme", "pl1": "p1-nb-main", "pl2": "p2-nb-theme", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-nb-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-nb-theme", }, }, "top": []any{ map[string]any{ "name": "menu-lang-nb-top", }, }, }, }, }) c.Assert(got["baseurl"], qt.Equals, "https://example.com/") }) c.Run("Merge shallow", func(c *qt.C) { b := buildForStrategy(c, fmt.Sprintf("_merge=%q", "shallow")) got := b.Cfg.Get("").(maps.Params) // Shallow merge, only add new keys to params. b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 main", "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", }, }, "p2": "p2 theme", }) }) c.Run("Merge no params in project", func(c *qt.C) { b := buildForConfig( c, "baseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", "[params]\np1 = \"p1 theme\"\n", ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 theme", }) }) c.Run("Merge language no menus or params in project", func(c *qt.C) { b := buildForConfig( c, ` theme = "test-theme" baseURL = "https://example.com/" [languages] [languages.en] languageName = "English" `, ` [languages] [languages.en] languageName = "EnglishTheme" [languages.en.params] p1="themep1" [[languages.en.menus.main]] name = "menu-theme" `, ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-theme", }, }, }, "params": maps.Params{ "p1": "themep1", }, }, }, ) }) // Issue #8724 for _, mergeStrategy := range []string{"none", "shallow"} { c.Run(fmt.Sprintf("Merge with sitemap config in theme, mergestrategy %s", mergeStrategy), func(c *qt.C) { smapConfigTempl := `[sitemap] changefreq = %q filename = "sitemap.xml" priority = 0.5` b := buildForConfig( c, fmt.Sprintf("_merge=%q\nbaseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", mergeStrategy), "baseURL=\"http://example.com\"\n"+fmt.Sprintf(smapConfigTempl, "monthly"), ) got := b.Cfg.Get("").(maps.Params) if mergeStrategy == "none" { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", }) b.AssertFileContent("public/sitemap.xml", "schemas/sitemap") } else { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", "changefreq": "monthly", }) b.AssertFileContent("public/sitemap.xml", "<changefreq>monthly</changefreq>") } }) } } func TestLoadConfigFromThemeDir(t *testing.T) { t.Parallel() mainConfig := ` theme = "test-theme" [params] m1 = "mv1" ` themeConfig := ` [params] t1 = "tv1" t2 = "tv2" ` themeConfigDir := filepath.Join("themes", "test-theme", "config") themeConfigDirDefault := filepath.Join(themeConfigDir, "_default") themeConfigDirProduction := filepath.Join(themeConfigDir, "production") projectConfigDir := "config" b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirDefault, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirProduction, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(projectConfigDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(projectConfigDir, "config.toml"), `[params] m2 = "mv2" `) b.WithSourceFile(filepath.Join(themeConfigDirDefault, "config.toml"), `[params] t2 = "tv2d" t3 = "tv3d" `) b.WithSourceFile(filepath.Join(themeConfigDirProduction, "config.toml"), `[params] t3 = "tv3p" `) b.Build(BuildCfg{}) got := b.Cfg.Get("params").(maps.Params) b.Assert(got, qt.DeepEquals, maps.Params{ "t3": "tv3p", "m1": "mv1", "t1": "tv1", "t2": "tv2d", }) } func TestPrivacyConfig(t *testing.T) { t.Parallel() c := qt.New(t) tomlConfig := ` someOtherValue = "foo" [privacy] [privacy.youtube] privacyEnhanced = true ` b := newTestSitesBuilder(t) b.WithConfigFile("toml", tomlConfig) b.Build(BuildCfg{SkipRender: true}) c.Assert(b.H.Sites[0].Info.Config().Privacy.YouTube.PrivacyEnhanced, qt.Equals, true) } func TestLoadConfigModules(t *testing.T) { t.Parallel() c := qt.New(t) // https://github.com/gohugoio/hugoThemes#themetoml const ( // Before Hugo 0.56 each theme/component could have its own theme.toml // with some settings, mostly used on the Hugo themes site. // To preserve combability we read these files into the new "modules" // section in config.toml. o1t = ` name = "Component o1" license = "MIT" min_version = 0.38 ` // This is the component's config.toml, using the old theme syntax. o1c = ` theme = ["n2"] ` n1 = ` title = "Component n1" [module] description = "Component n1 description" [module.hugoVersion] min = "0.40.0" max = "0.50.0" extended = true [[module.imports]] path="o1" [[module.imports]] path="n3" ` n2 = ` title = "Component n2" ` n3 = ` title = "Component n3" ` n4 = ` title = "Component n4" ` ) b := newTestSitesBuilder(t) writeThemeFiles := func(name, configTOML, themeTOML string) { b.WithSourceFile(filepath.Join("themes", name, "data", "module.toml"), fmt.Sprintf("name=%q", name)) if configTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "config.toml"), configTOML) } if themeTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "theme.toml"), themeTOML) } } writeThemeFiles("n1", n1, "") writeThemeFiles("n2", n2, "") writeThemeFiles("n3", n3, "") writeThemeFiles("n4", n4, "") writeThemeFiles("o1", o1c, o1t) b.WithConfigFile("toml", ` [module] [[module.imports]] path="n1" [[module.imports]] path="n4" `) b.Build(BuildCfg{}) modulesClient := b.H.Paths.ModulesClient var graphb bytes.Buffer modulesClient.Graph(&graphb) expected := `project n1 n1 o1 o1 n2 n1 n3 project n4 ` c.Assert(graphb.String(), qt.Equals, expected) } func TestLoadConfigWithOsEnvOverrides(t *testing.T) { c := qt.New(t) baseConfig := ` theme = "mytheme" environment = "production" enableGitInfo = true intSlice = [5,7,9] floatSlice = [3.14, 5.19] stringSlice = ["a", "b"] [outputFormats] [outputFormats.ofbase] mediaType = "text/plain" [params] paramWithNoEnvOverride="nooverride" [params.api_config] api_key="default_key" another_key="default another_key" [imaging] anchor = "smart" quality = 75 ` newB := func(t testing.TB) *sitesBuilder { b := newTestSitesBuilder(t).WithConfigFile("toml", baseConfig) b.WithSourceFile("themes/mytheme/config.toml", ` [outputFormats] [outputFormats.oftheme] mediaType = "text/plain" [outputFormats.ofbase] mediaType = "application/xml" [params] [params.mytheme_section] theme_param="themevalue" theme_param_nooverride="nooverride" [params.mytheme_section2] theme_param="themevalue2" `) return b } c.Run("Variations", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENVIRONMENT", "test", "HUGO_NEW", "new", // key not in config.toml "HUGO_ENABLEGITINFO", "false", "HUGO_IMAGING_ANCHOR", "top", "HUGO_IMAGING_RESAMPLEFILTER", "CatmullRom", "HUGO_STRINGSLICE", `["c", "d"]`, "HUGO_INTSLICE", `[5, 8, 9]`, "HUGO_FLOATSLICE", `[5.32]`, // Issue #7829 "HUGOxPARAMSxAPI_CONFIGxAPI_KEY", "new_key", // Delimiters are case sensitive. "HUGOxPARAMSxAPI_CONFIGXANOTHER_KEY", "another_key", // Issue #8346 "HUGOxPARAMSxMYTHEME_SECTIONxTHEME_PARAM", "themevalue_changed", "HUGOxPARAMSxMYTHEME_SECTION2xTHEME_PARAM", "themevalue2_changed", "HUGO_PARAMS_EMPTY", ``, "HUGO_PARAMS_HTML", `<a target="_blank" />`, // Issue #8618 "HUGO_SERVICES_GOOGLEANALYTICS_ID", `gaid`, "HUGO_PARAMS_A_B_C", "abc", ) b.Build(BuildCfg{}) cfg := b.H.Cfg s := b.H.Sites[0] scfg := s.siteConfigConfig.Services c.Assert(cfg.Get("environment"), qt.Equals, "test") c.Assert(cfg.GetBool("enablegitinfo"), qt.Equals, false) c.Assert(cfg.Get("new"), qt.Equals, "new") c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "top") c.Assert(cfg.Get("imaging.quality"), qt.Equals, int64(75)) c.Assert(cfg.Get("imaging.resamplefilter"), qt.Equals, "CatmullRom") c.Assert(cfg.Get("stringSlice"), qt.DeepEquals, []any{"c", "d"}) c.Assert(cfg.Get("floatSlice"), qt.DeepEquals, []any{5.32}) c.Assert(cfg.Get("intSlice"), qt.DeepEquals, []any{5, 8, 9}) c.Assert(cfg.Get("params.api_config.api_key"), qt.Equals, "new_key") c.Assert(cfg.Get("params.api_config.another_key"), qt.Equals, "default another_key") c.Assert(cfg.Get("params.mytheme_section.theme_param"), qt.Equals, "themevalue_changed") c.Assert(cfg.Get("params.mytheme_section.theme_param_nooverride"), qt.Equals, "nooverride") c.Assert(cfg.Get("params.mytheme_section2.theme_param"), qt.Equals, "themevalue2_changed") c.Assert(cfg.Get("params.empty"), qt.Equals, ``) c.Assert(cfg.Get("params.html"), qt.Equals, `<a target="_blank" />`) params := cfg.Get("params").(maps.Params) c.Assert(params["paramwithnoenvoverride"], qt.Equals, "nooverride") c.Assert(cfg.Get("params.paramwithnoenvoverride"), qt.Equals, "nooverride") c.Assert(scfg.GoogleAnalytics.ID, qt.Equals, "gaid") c.Assert(cfg.Get("params.a.b"), qt.DeepEquals, maps.Params{ "c": "abc", }) ofBase, _ := s.outputFormatsConfig.GetByName("ofbase") ofTheme, _ := s.outputFormatsConfig.GetByName("oftheme") c.Assert(ofBase.MediaType, qt.Equals, media.TextType) c.Assert(ofTheme.MediaType, qt.Equals, media.TextType) }) // Issue #8709 c.Run("Set in string", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENABLEGITINFO", "false", // imaging.anchor is a string, and it's not possible // to set a child attribute. "HUGO_IMAGING_ANCHOR_FOO", "top", ) b.Build(BuildCfg{}) cfg := b.H.Cfg c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "smart") }) } func TestInvalidDefaultMarkdownHandler(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] defaultMarkdownHandler = 'blackfriday' -- content/_index.md -- ## Foo -- layouts/index.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "Configured defaultMarkdownHandler \"blackfriday\" not found. Did you mean to use goldmark? Blackfriday was removed in Hugo v0.100.0.") } // Issue 8979 func TestHugoConfig(t *testing.T) { filesTemplate := ` -- hugo.toml -- theme = "mytheme" [params] rootparam = "rootvalue" -- config/_default/hugo.toml -- [params] rootconfigparam = "rootconfigvalue" -- themes/mytheme/config/_default/hugo.toml -- [params] themeconfigdirparam = "themeconfigdirvalue" -- themes/mytheme/hugo.toml -- [params] themeparam = "themevalue" -- layouts/index.html -- rootparam: {{ site.Params.rootparam }} rootconfigparam: {{ site.Params.rootconfigparam }} themeparam: {{ site.Params.themeparam }} themeconfigdirparam: {{ site.Params.themeconfigdirparam }} ` for _, configName := range []string{"hugo.toml", "config.toml"} { configName := configName t.Run(configName, func(t *testing.T) { t.Parallel() files := strings.ReplaceAll(filesTemplate, "hugo.toml", configName) b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNil) b.AssertFileContent("public/index.html", "rootparam: rootvalue", "rootconfigparam: rootconfigvalue", "themeparam: themevalue", "themeconfigdirparam: themeconfigdirvalue", ) }) } }
bep
6a579ebac3a81df61f22988e3eb55f7cb35ce523
f38a2fbd2e4de7f095a833b448cb8bc053955ce2
I tested various combinations of having both `config.xxx` and `hugo.xxx` in all 4 directories, making sure that the files in root or theme root are not merged, and files in the config root or theme config root _are_ merged. Looks good to me.
jmooring
75
gohugoio/hugo
10,621
Make hugo.toml the new config.toml
Both will of course work, but hugo.toml will win if both are set. We should have done this a long time ago, of course, but the reason I'm picking this up now is that my VS Code setup by default picks up some JSON config schema from some random other software which also names its config files config.toml. Fixes #8979
null
2023-01-16 08:39:47+00:00
2023-01-16 14:34:16+00:00
hugolib/config_test.go
// Copyright 2016-present 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 hugolib import ( "bytes" "fmt" "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/google/go-cmp/cmp" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/maps" "github.com/spf13/afero" ) func TestLoadConfig(t *testing.T) { c := qt.New(t) loadConfig := func(c *qt.C, configContent string, fromDir bool) config.Provider { mm := afero.NewMemMapFs() filename := "config.toml" descriptor := ConfigSourceDescriptor{Fs: mm} if fromDir { filename = filepath.Join("config", "_default", filename) descriptor.AbsConfigDir = "config" } writeToFs(t, mm, filename, configContent) cfg, _, err := LoadConfig(descriptor) c.Assert(err, qt.IsNil) return cfg } c.Run("Basic", func(c *qt.C) { c.Parallel() // Add a random config variable for testing. // side = page in Norwegian. cfg := loadConfig(c, `PaginatePath = "side"`, false) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "side") }) // Issue #8763 for _, fromDir := range []bool{false, true} { testName := "Taxonomy overrides" if fromDir { testName += " from dir" } c.Run(testName, func(c *qt.C) { c.Parallel() cfg := loadConfig(c, `[taxonomies] appellation = "appellations" vigneron = "vignerons"`, fromDir) c.Assert(cfg.Get("taxonomies"), qt.DeepEquals, maps.Params{ "appellation": "appellations", "vigneron": "vignerons", }) }) } } func TestLoadMultiConfig(t *testing.T) { t.Parallel() c := qt.New(t) // Add a random config variable for testing. // side = page in Norwegian. configContentBase := ` DontChange = "same" PaginatePath = "side" ` configContentSub := ` PaginatePath = "top" ` mm := afero.NewMemMapFs() writeToFs(t, mm, "base.toml", configContentBase) writeToFs(t, mm, "override.toml", configContentSub) cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "base.toml,override.toml"}) c.Assert(err, qt.IsNil) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "top") c.Assert(cfg.GetString("DontChange"), qt.Equals, "same") } func TestLoadConfigFromThemes(t *testing.T) { t.Parallel() c := qt.New(t) mainConfigTemplate := ` theme = "test-theme" baseURL = "https://example.com/" [frontmatter] date = ["date","publishDate"] [params] MERGE_PARAMS p1 = "p1 main" [params.b] b1 = "b1 main" [params.b.c] bc1 = "bc1 main" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1main"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1main" [languages] [languages.en] languageName = "English" [languages.en.params] pl1 = "p1-en-main" [languages.nb] languageName = "Norsk" [languages.nb.params] pl1 = "p1-nb-main" [[menu.main]] name = "menu-main-main" [[menu.top]] name = "menu-top-main" ` themeConfig := ` baseURL = "http://bep.is/" # Can not be set in theme. disableKinds = ["taxonomy", "term"] # Can not be set in theme. [frontmatter] expiryDate = ["date"] [params] p1 = "p1 theme" p2 = "p2 theme" [params.b] b1 = "b1 theme" b2 = "b2 theme" [params.b.c] bc1 = "bc1 theme" bc2 = "bc2 theme" [params.b.c.d] bcd1 = "bcd1 theme" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1theme"] [mediaTypes."text/m2"] suffixes = ["m2theme"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1theme" [outputFormats.o2] mediaType = "text/m2" baseName = "o2theme" [languages] [languages.en] languageName = "English2" [languages.en.params] pl1 = "p1-en-theme" pl2 = "p2-en-theme" [[languages.en.menu.main]] name = "menu-lang-en-main" [[languages.en.menu.theme]] name = "menu-lang-en-theme" [languages.nb] languageName = "Norsk2" [languages.nb.params] pl1 = "p1-nb-theme" pl2 = "p2-nb-theme" top = "top-nb-theme" [[languages.nb.menu.main]] name = "menu-lang-nb-main" [[languages.nb.menu.theme]] name = "menu-lang-nb-theme" [[languages.nb.menu.top]] name = "menu-lang-nb-top" [[menu.main]] name = "menu-main-theme" [[menu.thememenu]] name = "menu-theme" ` buildForConfig := func(t testing.TB, mainConfig, themeConfig string) *sitesBuilder { b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) return b.Build(BuildCfg{}) } buildForStrategy := func(t testing.TB, s string) *sitesBuilder { mainConfig := strings.ReplaceAll(mainConfigTemplate, "MERGE_PARAMS", s) return buildForConfig(t, mainConfig, themeConfig) } c.Run("Merge default", func(c *qt.C) { b := buildForStrategy(c, "") got := b.Cfg.Get("").(maps.Params) // Issue #8866 b.Assert(b.Cfg.Get("disableKinds"), qt.IsNil) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", "bc2": "bc2 theme", "d": maps.Params{"bcd1": string("bcd1 theme")}, }, "b2": "b2 theme", }, "p2": "p2 theme", "p1": "p1 main", }) b.Assert(got["mediatypes"], qt.DeepEquals, maps.Params{ "text/m2": maps.Params{ "suffixes": []any{ "m2theme", }, }, "text/m1": maps.Params{ "suffixes": []any{ "m1main", }, }, }) var eq = qt.CmpEquals( cmp.Comparer(func(m1, m2 media.Type) bool { if m1.SubType != m2.SubType { return false } return m1.FirstSuffix == m2.FirstSuffix }), ) mediaTypes := b.H.Sites[0].mediaTypesConfig m1, _ := mediaTypes.GetByType("text/m1") m2, _ := mediaTypes.GetByType("text/m2") b.Assert(got["outputformats"], eq, maps.Params{ "o1": maps.Params{ "mediatype": m1, "basename": "o1main", }, "o2": maps.Params{ "basename": "o2theme", "mediatype": m2, }, }) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "params": maps.Params{ "pl2": "p2-en-theme", "pl1": "p1-en-main", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-en-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-en-theme", }, }, }, }, "nb": maps.Params{ "languagename": "Norsk", "params": maps.Params{ "top": "top-nb-theme", "pl1": "p1-nb-main", "pl2": "p2-nb-theme", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-nb-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-nb-theme", }, }, "top": []any{ map[string]any{ "name": "menu-lang-nb-top", }, }, }, }, }) c.Assert(got["baseurl"], qt.Equals, "https://example.com/") }) c.Run("Merge shallow", func(c *qt.C) { b := buildForStrategy(c, fmt.Sprintf("_merge=%q", "shallow")) got := b.Cfg.Get("").(maps.Params) // Shallow merge, only add new keys to params. b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 main", "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", }, }, "p2": "p2 theme", }) }) c.Run("Merge no params in project", func(c *qt.C) { b := buildForConfig( c, "baseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", "[params]\np1 = \"p1 theme\"\n", ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 theme", }) }) c.Run("Merge language no menus or params in project", func(c *qt.C) { b := buildForConfig( c, ` theme = "test-theme" baseURL = "https://example.com/" [languages] [languages.en] languageName = "English" `, ` [languages] [languages.en] languageName = "EnglishTheme" [languages.en.params] p1="themep1" [[languages.en.menus.main]] name = "menu-theme" `, ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-theme", }, }, }, "params": maps.Params{ "p1": "themep1", }, }, }, ) }) // Issue #8724 for _, mergeStrategy := range []string{"none", "shallow"} { c.Run(fmt.Sprintf("Merge with sitemap config in theme, mergestrategy %s", mergeStrategy), func(c *qt.C) { smapConfigTempl := `[sitemap] changefreq = %q filename = "sitemap.xml" priority = 0.5` b := buildForConfig( c, fmt.Sprintf("_merge=%q\nbaseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", mergeStrategy), "baseURL=\"http://example.com\"\n"+fmt.Sprintf(smapConfigTempl, "monthly"), ) got := b.Cfg.Get("").(maps.Params) if mergeStrategy == "none" { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", }) b.AssertFileContent("public/sitemap.xml", "schemas/sitemap") } else { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", "changefreq": "monthly", }) b.AssertFileContent("public/sitemap.xml", "<changefreq>monthly</changefreq>") } }) } } func TestLoadConfigFromThemeDir(t *testing.T) { t.Parallel() mainConfig := ` theme = "test-theme" [params] m1 = "mv1" ` themeConfig := ` [params] t1 = "tv1" t2 = "tv2" ` themeConfigDir := filepath.Join("themes", "test-theme", "config") themeConfigDirDefault := filepath.Join(themeConfigDir, "_default") themeConfigDirProduction := filepath.Join(themeConfigDir, "production") projectConfigDir := "config" b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirDefault, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirProduction, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(projectConfigDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(projectConfigDir, "config.toml"), `[params] m2 = "mv2" `) b.WithSourceFile(filepath.Join(themeConfigDirDefault, "config.toml"), `[params] t2 = "tv2d" t3 = "tv3d" `) b.WithSourceFile(filepath.Join(themeConfigDirProduction, "config.toml"), `[params] t3 = "tv3p" `) b.Build(BuildCfg{}) got := b.Cfg.Get("params").(maps.Params) b.Assert(got, qt.DeepEquals, maps.Params{ "t3": "tv3p", "m1": "mv1", "t1": "tv1", "t2": "tv2d", }) } func TestPrivacyConfig(t *testing.T) { t.Parallel() c := qt.New(t) tomlConfig := ` someOtherValue = "foo" [privacy] [privacy.youtube] privacyEnhanced = true ` b := newTestSitesBuilder(t) b.WithConfigFile("toml", tomlConfig) b.Build(BuildCfg{SkipRender: true}) c.Assert(b.H.Sites[0].Info.Config().Privacy.YouTube.PrivacyEnhanced, qt.Equals, true) } func TestLoadConfigModules(t *testing.T) { t.Parallel() c := qt.New(t) // https://github.com/gohugoio/hugoThemes#themetoml const ( // Before Hugo 0.56 each theme/component could have its own theme.toml // with some settings, mostly used on the Hugo themes site. // To preserve combability we read these files into the new "modules" // section in config.toml. o1t = ` name = "Component o1" license = "MIT" min_version = 0.38 ` // This is the component's config.toml, using the old theme syntax. o1c = ` theme = ["n2"] ` n1 = ` title = "Component n1" [module] description = "Component n1 description" [module.hugoVersion] min = "0.40.0" max = "0.50.0" extended = true [[module.imports]] path="o1" [[module.imports]] path="n3" ` n2 = ` title = "Component n2" ` n3 = ` title = "Component n3" ` n4 = ` title = "Component n4" ` ) b := newTestSitesBuilder(t) writeThemeFiles := func(name, configTOML, themeTOML string) { b.WithSourceFile(filepath.Join("themes", name, "data", "module.toml"), fmt.Sprintf("name=%q", name)) if configTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "config.toml"), configTOML) } if themeTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "theme.toml"), themeTOML) } } writeThemeFiles("n1", n1, "") writeThemeFiles("n2", n2, "") writeThemeFiles("n3", n3, "") writeThemeFiles("n4", n4, "") writeThemeFiles("o1", o1c, o1t) b.WithConfigFile("toml", ` [module] [[module.imports]] path="n1" [[module.imports]] path="n4" `) b.Build(BuildCfg{}) modulesClient := b.H.Paths.ModulesClient var graphb bytes.Buffer modulesClient.Graph(&graphb) expected := `project n1 n1 o1 o1 n2 n1 n3 project n4 ` c.Assert(graphb.String(), qt.Equals, expected) } func TestLoadConfigWithOsEnvOverrides(t *testing.T) { c := qt.New(t) baseConfig := ` theme = "mytheme" environment = "production" enableGitInfo = true intSlice = [5,7,9] floatSlice = [3.14, 5.19] stringSlice = ["a", "b"] [outputFormats] [outputFormats.ofbase] mediaType = "text/plain" [params] paramWithNoEnvOverride="nooverride" [params.api_config] api_key="default_key" another_key="default another_key" [imaging] anchor = "smart" quality = 75 ` newB := func(t testing.TB) *sitesBuilder { b := newTestSitesBuilder(t).WithConfigFile("toml", baseConfig) b.WithSourceFile("themes/mytheme/config.toml", ` [outputFormats] [outputFormats.oftheme] mediaType = "text/plain" [outputFormats.ofbase] mediaType = "application/xml" [params] [params.mytheme_section] theme_param="themevalue" theme_param_nooverride="nooverride" [params.mytheme_section2] theme_param="themevalue2" `) return b } c.Run("Variations", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENVIRONMENT", "test", "HUGO_NEW", "new", // key not in config.toml "HUGO_ENABLEGITINFO", "false", "HUGO_IMAGING_ANCHOR", "top", "HUGO_IMAGING_RESAMPLEFILTER", "CatmullRom", "HUGO_STRINGSLICE", `["c", "d"]`, "HUGO_INTSLICE", `[5, 8, 9]`, "HUGO_FLOATSLICE", `[5.32]`, // Issue #7829 "HUGOxPARAMSxAPI_CONFIGxAPI_KEY", "new_key", // Delimiters are case sensitive. "HUGOxPARAMSxAPI_CONFIGXANOTHER_KEY", "another_key", // Issue #8346 "HUGOxPARAMSxMYTHEME_SECTIONxTHEME_PARAM", "themevalue_changed", "HUGOxPARAMSxMYTHEME_SECTION2xTHEME_PARAM", "themevalue2_changed", "HUGO_PARAMS_EMPTY", ``, "HUGO_PARAMS_HTML", `<a target="_blank" />`, // Issue #8618 "HUGO_SERVICES_GOOGLEANALYTICS_ID", `gaid`, "HUGO_PARAMS_A_B_C", "abc", ) b.Build(BuildCfg{}) cfg := b.H.Cfg s := b.H.Sites[0] scfg := s.siteConfigConfig.Services c.Assert(cfg.Get("environment"), qt.Equals, "test") c.Assert(cfg.GetBool("enablegitinfo"), qt.Equals, false) c.Assert(cfg.Get("new"), qt.Equals, "new") c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "top") c.Assert(cfg.Get("imaging.quality"), qt.Equals, int64(75)) c.Assert(cfg.Get("imaging.resamplefilter"), qt.Equals, "CatmullRom") c.Assert(cfg.Get("stringSlice"), qt.DeepEquals, []any{"c", "d"}) c.Assert(cfg.Get("floatSlice"), qt.DeepEquals, []any{5.32}) c.Assert(cfg.Get("intSlice"), qt.DeepEquals, []any{5, 8, 9}) c.Assert(cfg.Get("params.api_config.api_key"), qt.Equals, "new_key") c.Assert(cfg.Get("params.api_config.another_key"), qt.Equals, "default another_key") c.Assert(cfg.Get("params.mytheme_section.theme_param"), qt.Equals, "themevalue_changed") c.Assert(cfg.Get("params.mytheme_section.theme_param_nooverride"), qt.Equals, "nooverride") c.Assert(cfg.Get("params.mytheme_section2.theme_param"), qt.Equals, "themevalue2_changed") c.Assert(cfg.Get("params.empty"), qt.Equals, ``) c.Assert(cfg.Get("params.html"), qt.Equals, `<a target="_blank" />`) params := cfg.Get("params").(maps.Params) c.Assert(params["paramwithnoenvoverride"], qt.Equals, "nooverride") c.Assert(cfg.Get("params.paramwithnoenvoverride"), qt.Equals, "nooverride") c.Assert(scfg.GoogleAnalytics.ID, qt.Equals, "gaid") c.Assert(cfg.Get("params.a.b"), qt.DeepEquals, maps.Params{ "c": "abc", }) ofBase, _ := s.outputFormatsConfig.GetByName("ofbase") ofTheme, _ := s.outputFormatsConfig.GetByName("oftheme") c.Assert(ofBase.MediaType, qt.Equals, media.TextType) c.Assert(ofTheme.MediaType, qt.Equals, media.TextType) }) // Issue #8709 c.Run("Set in string", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENABLEGITINFO", "false", // imaging.anchor is a string, and it's not possible // to set a child attribute. "HUGO_IMAGING_ANCHOR_FOO", "top", ) b.Build(BuildCfg{}) cfg := b.H.Cfg c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "smart") }) } func TestInvalidDefaultMarkdownHandler(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] defaultMarkdownHandler = 'blackfriday' -- content/_index.md -- ## Foo -- layouts/index.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "Configured defaultMarkdownHandler \"blackfriday\" not found. Did you mean to use goldmark? Blackfriday was removed in Hugo v0.100.0.") }
// Copyright 2016-present 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 hugolib import ( "bytes" "fmt" "path/filepath" "strings" "testing" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/media" "github.com/google/go-cmp/cmp" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/maps" "github.com/spf13/afero" ) func TestLoadConfig(t *testing.T) { c := qt.New(t) loadConfig := func(c *qt.C, configContent string, fromDir bool) config.Provider { mm := afero.NewMemMapFs() filename := "config.toml" descriptor := ConfigSourceDescriptor{Fs: mm} if fromDir { filename = filepath.Join("config", "_default", filename) descriptor.AbsConfigDir = "config" } writeToFs(t, mm, filename, configContent) cfg, _, err := LoadConfig(descriptor) c.Assert(err, qt.IsNil) return cfg } c.Run("Basic", func(c *qt.C) { c.Parallel() // Add a random config variable for testing. // side = page in Norwegian. cfg := loadConfig(c, `PaginatePath = "side"`, false) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "side") }) // Issue #8763 for _, fromDir := range []bool{false, true} { testName := "Taxonomy overrides" if fromDir { testName += " from dir" } c.Run(testName, func(c *qt.C) { c.Parallel() cfg := loadConfig(c, `[taxonomies] appellation = "appellations" vigneron = "vignerons"`, fromDir) c.Assert(cfg.Get("taxonomies"), qt.DeepEquals, maps.Params{ "appellation": "appellations", "vigneron": "vignerons", }) }) } } func TestLoadMultiConfig(t *testing.T) { t.Parallel() c := qt.New(t) // Add a random config variable for testing. // side = page in Norwegian. configContentBase := ` DontChange = "same" PaginatePath = "side" ` configContentSub := ` PaginatePath = "top" ` mm := afero.NewMemMapFs() writeToFs(t, mm, "base.toml", configContentBase) writeToFs(t, mm, "override.toml", configContentSub) cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "base.toml,override.toml"}) c.Assert(err, qt.IsNil) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "top") c.Assert(cfg.GetString("DontChange"), qt.Equals, "same") } func TestLoadConfigFromThemes(t *testing.T) { t.Parallel() c := qt.New(t) mainConfigTemplate := ` theme = "test-theme" baseURL = "https://example.com/" [frontmatter] date = ["date","publishDate"] [params] MERGE_PARAMS p1 = "p1 main" [params.b] b1 = "b1 main" [params.b.c] bc1 = "bc1 main" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1main"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1main" [languages] [languages.en] languageName = "English" [languages.en.params] pl1 = "p1-en-main" [languages.nb] languageName = "Norsk" [languages.nb.params] pl1 = "p1-nb-main" [[menu.main]] name = "menu-main-main" [[menu.top]] name = "menu-top-main" ` themeConfig := ` baseURL = "http://bep.is/" # Can not be set in theme. disableKinds = ["taxonomy", "term"] # Can not be set in theme. [frontmatter] expiryDate = ["date"] [params] p1 = "p1 theme" p2 = "p2 theme" [params.b] b1 = "b1 theme" b2 = "b2 theme" [params.b.c] bc1 = "bc1 theme" bc2 = "bc2 theme" [params.b.c.d] bcd1 = "bcd1 theme" [mediaTypes] [mediaTypes."text/m1"] suffixes = ["m1theme"] [mediaTypes."text/m2"] suffixes = ["m2theme"] [outputFormats.o1] mediaType = "text/m1" baseName = "o1theme" [outputFormats.o2] mediaType = "text/m2" baseName = "o2theme" [languages] [languages.en] languageName = "English2" [languages.en.params] pl1 = "p1-en-theme" pl2 = "p2-en-theme" [[languages.en.menu.main]] name = "menu-lang-en-main" [[languages.en.menu.theme]] name = "menu-lang-en-theme" [languages.nb] languageName = "Norsk2" [languages.nb.params] pl1 = "p1-nb-theme" pl2 = "p2-nb-theme" top = "top-nb-theme" [[languages.nb.menu.main]] name = "menu-lang-nb-main" [[languages.nb.menu.theme]] name = "menu-lang-nb-theme" [[languages.nb.menu.top]] name = "menu-lang-nb-top" [[menu.main]] name = "menu-main-theme" [[menu.thememenu]] name = "menu-theme" ` buildForConfig := func(t testing.TB, mainConfig, themeConfig string) *sitesBuilder { b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) return b.Build(BuildCfg{}) } buildForStrategy := func(t testing.TB, s string) *sitesBuilder { mainConfig := strings.ReplaceAll(mainConfigTemplate, "MERGE_PARAMS", s) return buildForConfig(t, mainConfig, themeConfig) } c.Run("Merge default", func(c *qt.C) { b := buildForStrategy(c, "") got := b.Cfg.Get("").(maps.Params) // Issue #8866 b.Assert(b.Cfg.Get("disableKinds"), qt.IsNil) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", "bc2": "bc2 theme", "d": maps.Params{"bcd1": string("bcd1 theme")}, }, "b2": "b2 theme", }, "p2": "p2 theme", "p1": "p1 main", }) b.Assert(got["mediatypes"], qt.DeepEquals, maps.Params{ "text/m2": maps.Params{ "suffixes": []any{ "m2theme", }, }, "text/m1": maps.Params{ "suffixes": []any{ "m1main", }, }, }) var eq = qt.CmpEquals( cmp.Comparer(func(m1, m2 media.Type) bool { if m1.SubType != m2.SubType { return false } return m1.FirstSuffix == m2.FirstSuffix }), ) mediaTypes := b.H.Sites[0].mediaTypesConfig m1, _ := mediaTypes.GetByType("text/m1") m2, _ := mediaTypes.GetByType("text/m2") b.Assert(got["outputformats"], eq, maps.Params{ "o1": maps.Params{ "mediatype": m1, "basename": "o1main", }, "o2": maps.Params{ "basename": "o2theme", "mediatype": m2, }, }) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "params": maps.Params{ "pl2": "p2-en-theme", "pl1": "p1-en-main", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-en-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-en-theme", }, }, }, }, "nb": maps.Params{ "languagename": "Norsk", "params": maps.Params{ "top": "top-nb-theme", "pl1": "p1-nb-main", "pl2": "p2-nb-theme", }, "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-lang-nb-main", }, }, "theme": []any{ map[string]any{ "name": "menu-lang-nb-theme", }, }, "top": []any{ map[string]any{ "name": "menu-lang-nb-top", }, }, }, }, }) c.Assert(got["baseurl"], qt.Equals, "https://example.com/") }) c.Run("Merge shallow", func(c *qt.C) { b := buildForStrategy(c, fmt.Sprintf("_merge=%q", "shallow")) got := b.Cfg.Get("").(maps.Params) // Shallow merge, only add new keys to params. b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 main", "b": maps.Params{ "b1": "b1 main", "c": maps.Params{ "bc1": "bc1 main", }, }, "p2": "p2 theme", }) }) c.Run("Merge no params in project", func(c *qt.C) { b := buildForConfig( c, "baseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", "[params]\np1 = \"p1 theme\"\n", ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["params"], qt.DeepEquals, maps.Params{ "p1": "p1 theme", }) }) c.Run("Merge language no menus or params in project", func(c *qt.C) { b := buildForConfig( c, ` theme = "test-theme" baseURL = "https://example.com/" [languages] [languages.en] languageName = "English" `, ` [languages] [languages.en] languageName = "EnglishTheme" [languages.en.params] p1="themep1" [[languages.en.menus.main]] name = "menu-theme" `, ) got := b.Cfg.Get("").(maps.Params) b.Assert(got["languages"], qt.DeepEquals, maps.Params{ "en": maps.Params{ "languagename": "English", "menus": maps.Params{ "main": []any{ map[string]any{ "name": "menu-theme", }, }, }, "params": maps.Params{ "p1": "themep1", }, }, }, ) }) // Issue #8724 for _, mergeStrategy := range []string{"none", "shallow"} { c.Run(fmt.Sprintf("Merge with sitemap config in theme, mergestrategy %s", mergeStrategy), func(c *qt.C) { smapConfigTempl := `[sitemap] changefreq = %q filename = "sitemap.xml" priority = 0.5` b := buildForConfig( c, fmt.Sprintf("_merge=%q\nbaseURL=\"https://example.org\"\ntheme = \"test-theme\"\n", mergeStrategy), "baseURL=\"http://example.com\"\n"+fmt.Sprintf(smapConfigTempl, "monthly"), ) got := b.Cfg.Get("").(maps.Params) if mergeStrategy == "none" { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", }) b.AssertFileContent("public/sitemap.xml", "schemas/sitemap") } else { b.Assert(got["sitemap"], qt.DeepEquals, maps.Params{ "priority": int(-1), "filename": "sitemap.xml", "changefreq": "monthly", }) b.AssertFileContent("public/sitemap.xml", "<changefreq>monthly</changefreq>") } }) } } func TestLoadConfigFromThemeDir(t *testing.T) { t.Parallel() mainConfig := ` theme = "test-theme" [params] m1 = "mv1" ` themeConfig := ` [params] t1 = "tv1" t2 = "tv2" ` themeConfigDir := filepath.Join("themes", "test-theme", "config") themeConfigDirDefault := filepath.Join(themeConfigDir, "_default") themeConfigDirProduction := filepath.Join(themeConfigDir, "production") projectConfigDir := "config" b := newTestSitesBuilder(t) b.WithConfigFile("toml", mainConfig).WithThemeConfigFile("toml", themeConfig) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirDefault, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(themeConfigDirProduction, 0777), qt.IsNil) b.Assert(b.Fs.Source.MkdirAll(projectConfigDir, 0777), qt.IsNil) b.WithSourceFile(filepath.Join(projectConfigDir, "config.toml"), `[params] m2 = "mv2" `) b.WithSourceFile(filepath.Join(themeConfigDirDefault, "config.toml"), `[params] t2 = "tv2d" t3 = "tv3d" `) b.WithSourceFile(filepath.Join(themeConfigDirProduction, "config.toml"), `[params] t3 = "tv3p" `) b.Build(BuildCfg{}) got := b.Cfg.Get("params").(maps.Params) b.Assert(got, qt.DeepEquals, maps.Params{ "t3": "tv3p", "m1": "mv1", "t1": "tv1", "t2": "tv2d", }) } func TestPrivacyConfig(t *testing.T) { t.Parallel() c := qt.New(t) tomlConfig := ` someOtherValue = "foo" [privacy] [privacy.youtube] privacyEnhanced = true ` b := newTestSitesBuilder(t) b.WithConfigFile("toml", tomlConfig) b.Build(BuildCfg{SkipRender: true}) c.Assert(b.H.Sites[0].Info.Config().Privacy.YouTube.PrivacyEnhanced, qt.Equals, true) } func TestLoadConfigModules(t *testing.T) { t.Parallel() c := qt.New(t) // https://github.com/gohugoio/hugoThemes#themetoml const ( // Before Hugo 0.56 each theme/component could have its own theme.toml // with some settings, mostly used on the Hugo themes site. // To preserve combability we read these files into the new "modules" // section in config.toml. o1t = ` name = "Component o1" license = "MIT" min_version = 0.38 ` // This is the component's config.toml, using the old theme syntax. o1c = ` theme = ["n2"] ` n1 = ` title = "Component n1" [module] description = "Component n1 description" [module.hugoVersion] min = "0.40.0" max = "0.50.0" extended = true [[module.imports]] path="o1" [[module.imports]] path="n3" ` n2 = ` title = "Component n2" ` n3 = ` title = "Component n3" ` n4 = ` title = "Component n4" ` ) b := newTestSitesBuilder(t) writeThemeFiles := func(name, configTOML, themeTOML string) { b.WithSourceFile(filepath.Join("themes", name, "data", "module.toml"), fmt.Sprintf("name=%q", name)) if configTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "config.toml"), configTOML) } if themeTOML != "" { b.WithSourceFile(filepath.Join("themes", name, "theme.toml"), themeTOML) } } writeThemeFiles("n1", n1, "") writeThemeFiles("n2", n2, "") writeThemeFiles("n3", n3, "") writeThemeFiles("n4", n4, "") writeThemeFiles("o1", o1c, o1t) b.WithConfigFile("toml", ` [module] [[module.imports]] path="n1" [[module.imports]] path="n4" `) b.Build(BuildCfg{}) modulesClient := b.H.Paths.ModulesClient var graphb bytes.Buffer modulesClient.Graph(&graphb) expected := `project n1 n1 o1 o1 n2 n1 n3 project n4 ` c.Assert(graphb.String(), qt.Equals, expected) } func TestLoadConfigWithOsEnvOverrides(t *testing.T) { c := qt.New(t) baseConfig := ` theme = "mytheme" environment = "production" enableGitInfo = true intSlice = [5,7,9] floatSlice = [3.14, 5.19] stringSlice = ["a", "b"] [outputFormats] [outputFormats.ofbase] mediaType = "text/plain" [params] paramWithNoEnvOverride="nooverride" [params.api_config] api_key="default_key" another_key="default another_key" [imaging] anchor = "smart" quality = 75 ` newB := func(t testing.TB) *sitesBuilder { b := newTestSitesBuilder(t).WithConfigFile("toml", baseConfig) b.WithSourceFile("themes/mytheme/config.toml", ` [outputFormats] [outputFormats.oftheme] mediaType = "text/plain" [outputFormats.ofbase] mediaType = "application/xml" [params] [params.mytheme_section] theme_param="themevalue" theme_param_nooverride="nooverride" [params.mytheme_section2] theme_param="themevalue2" `) return b } c.Run("Variations", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENVIRONMENT", "test", "HUGO_NEW", "new", // key not in config.toml "HUGO_ENABLEGITINFO", "false", "HUGO_IMAGING_ANCHOR", "top", "HUGO_IMAGING_RESAMPLEFILTER", "CatmullRom", "HUGO_STRINGSLICE", `["c", "d"]`, "HUGO_INTSLICE", `[5, 8, 9]`, "HUGO_FLOATSLICE", `[5.32]`, // Issue #7829 "HUGOxPARAMSxAPI_CONFIGxAPI_KEY", "new_key", // Delimiters are case sensitive. "HUGOxPARAMSxAPI_CONFIGXANOTHER_KEY", "another_key", // Issue #8346 "HUGOxPARAMSxMYTHEME_SECTIONxTHEME_PARAM", "themevalue_changed", "HUGOxPARAMSxMYTHEME_SECTION2xTHEME_PARAM", "themevalue2_changed", "HUGO_PARAMS_EMPTY", ``, "HUGO_PARAMS_HTML", `<a target="_blank" />`, // Issue #8618 "HUGO_SERVICES_GOOGLEANALYTICS_ID", `gaid`, "HUGO_PARAMS_A_B_C", "abc", ) b.Build(BuildCfg{}) cfg := b.H.Cfg s := b.H.Sites[0] scfg := s.siteConfigConfig.Services c.Assert(cfg.Get("environment"), qt.Equals, "test") c.Assert(cfg.GetBool("enablegitinfo"), qt.Equals, false) c.Assert(cfg.Get("new"), qt.Equals, "new") c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "top") c.Assert(cfg.Get("imaging.quality"), qt.Equals, int64(75)) c.Assert(cfg.Get("imaging.resamplefilter"), qt.Equals, "CatmullRom") c.Assert(cfg.Get("stringSlice"), qt.DeepEquals, []any{"c", "d"}) c.Assert(cfg.Get("floatSlice"), qt.DeepEquals, []any{5.32}) c.Assert(cfg.Get("intSlice"), qt.DeepEquals, []any{5, 8, 9}) c.Assert(cfg.Get("params.api_config.api_key"), qt.Equals, "new_key") c.Assert(cfg.Get("params.api_config.another_key"), qt.Equals, "default another_key") c.Assert(cfg.Get("params.mytheme_section.theme_param"), qt.Equals, "themevalue_changed") c.Assert(cfg.Get("params.mytheme_section.theme_param_nooverride"), qt.Equals, "nooverride") c.Assert(cfg.Get("params.mytheme_section2.theme_param"), qt.Equals, "themevalue2_changed") c.Assert(cfg.Get("params.empty"), qt.Equals, ``) c.Assert(cfg.Get("params.html"), qt.Equals, `<a target="_blank" />`) params := cfg.Get("params").(maps.Params) c.Assert(params["paramwithnoenvoverride"], qt.Equals, "nooverride") c.Assert(cfg.Get("params.paramwithnoenvoverride"), qt.Equals, "nooverride") c.Assert(scfg.GoogleAnalytics.ID, qt.Equals, "gaid") c.Assert(cfg.Get("params.a.b"), qt.DeepEquals, maps.Params{ "c": "abc", }) ofBase, _ := s.outputFormatsConfig.GetByName("ofbase") ofTheme, _ := s.outputFormatsConfig.GetByName("oftheme") c.Assert(ofBase.MediaType, qt.Equals, media.TextType) c.Assert(ofTheme.MediaType, qt.Equals, media.TextType) }) // Issue #8709 c.Run("Set in string", func(c *qt.C) { b := newB(c) b.WithEnviron( "HUGO_ENABLEGITINFO", "false", // imaging.anchor is a string, and it's not possible // to set a child attribute. "HUGO_IMAGING_ANCHOR_FOO", "top", ) b.Build(BuildCfg{}) cfg := b.H.Cfg c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "smart") }) } func TestInvalidDefaultMarkdownHandler(t *testing.T) { t.Parallel() files := ` -- config.toml -- [markup] defaultMarkdownHandler = 'blackfriday' -- content/_index.md -- ## Foo -- layouts/index.html -- {{ .Content }} ` b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, "Configured defaultMarkdownHandler \"blackfriday\" not found. Did you mean to use goldmark? Blackfriday was removed in Hugo v0.100.0.") } // Issue 8979 func TestHugoConfig(t *testing.T) { filesTemplate := ` -- hugo.toml -- theme = "mytheme" [params] rootparam = "rootvalue" -- config/_default/hugo.toml -- [params] rootconfigparam = "rootconfigvalue" -- themes/mytheme/config/_default/hugo.toml -- [params] themeconfigdirparam = "themeconfigdirvalue" -- themes/mytheme/hugo.toml -- [params] themeparam = "themevalue" -- layouts/index.html -- rootparam: {{ site.Params.rootparam }} rootconfigparam: {{ site.Params.rootconfigparam }} themeparam: {{ site.Params.themeparam }} themeconfigdirparam: {{ site.Params.themeconfigdirparam }} ` for _, configName := range []string{"hugo.toml", "config.toml"} { configName := configName t.Run(configName, func(t *testing.T) { t.Parallel() files := strings.ReplaceAll(filesTemplate, "hugo.toml", configName) b, err := NewIntegrationTestBuilder( IntegrationTestConfig{ T: t, TxtarString: files, }, ).BuildE() b.Assert(err, qt.IsNil) b.AssertFileContent("public/index.html", "rootparam: rootvalue", "rootconfigparam: rootconfigvalue", "themeparam: themevalue", "themeconfigdirparam: themeconfigdirvalue", ) }) } }
bep
6a579ebac3a81df61f22988e3eb55f7cb35ce523
f38a2fbd2e4de7f095a833b448cb8bc053955ce2
I'm updating my Hugo-related web pages, for example https://www.ii.com/hugo-data-directory/, and discovered that `hugo new site` is still creating `config.toml` rather than `hugo.toml`. I know @bep is waiting a little to change this, but my vote is to change it ASAP because it makes it easier for those of us who want to document this new thing. Thanks!
nancym
76
gohugoio/hugo
10,591
feat/miscgodoc30dec
- Misc Godoc improvements - Make readFile return nil when file not found (note)
null
2022-12-30 13:53:46+00:00
2023-01-04 17:01:27+00:00
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 ( "io" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/common/types/hstring" "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/internal/attributes" ) var _ AttributesOptionsSliceProvider = (*attributes.AttributesHolder)(nil) type AttributesProvider interface { Attributes() map[string]any } type LinkContext interface { Page() any Destination() string Title() string Text() hstring.RenderedString PlainText() string } type ImageLinkContext interface { LinkContext IsBlock() bool Ordinal() int } type CodeblockContext interface { AttributesProvider text.Positioner Options() map[string]any Type() string Inner() string Ordinal() int Page() any } type AttributesOptionsSliceProvider interface { AttributesSlice() []attributes.Attribute OptionsSlice() []attributes.Attribute } type LinkRenderer interface { RenderLink(w io.Writer, ctx LinkContext) error identity.Provider } type CodeBlockRenderer interface { RenderCodeblock(w hugio.FlexiWriter, ctx CodeblockContext) error identity.Provider } type IsDefaultCodeBlockRendererProvider interface { IsDefaultCodeBlockRenderer() bool } // HeadingContext contains accessors to all attributes that a HeadingRenderer // can use to render a heading. type HeadingContext interface { // Page is the page containing the heading. Page() any // 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.RenderedString // PlainText is the unrendered version of Text. PlainText() string // Attributes (e.g. CSS classes) AttributesProvider } // HeadingRenderer describes a uniquely identifiable rendering hook. type HeadingRenderer interface { // Render writes the rendered content to w using the data in w. RenderHeading(w io.Writer, ctx HeadingContext) error identity.Provider } // 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 ) type GetRendererFunc func(t RendererType, id any) any
// 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 ( "io" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/common/types/hstring" "github.com/gohugoio/hugo/identity" "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 } type LinkContext interface { // The Page being rendered. Page() any // The link URL. Destination() string // The link title attribute. Title() string // The rendered (HTML) text. Text() hstring.RenderedString // The plain variant of Text. PlainText() string } 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 { AttributesProvider text.Positioner // 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 // Zero-based ordinal for all code blocks in the current document. Ordinal() int // The owning Page. Page() any } type AttributesOptionsSliceProvider interface { AttributesSlice() []attributes.Attribute OptionsSlice() []attributes.Attribute } type LinkRenderer interface { RenderLink(w io.Writer, ctx LinkContext) error identity.Provider } type CodeBlockRenderer interface { RenderCodeblock(w hugio.FlexiWriter, ctx CodeblockContext) error identity.Provider } type IsDefaultCodeBlockRendererProvider interface { IsDefaultCodeBlockRenderer() bool } // HeadingContext contains accessors to all attributes that a HeadingRenderer // can use to render a heading. type HeadingContext interface { // Page is the page containing the heading. Page() any // 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.RenderedString // PlainText is the unrendered version of Text. PlainText() string // Attributes (e.g. CSS classes) AttributesProvider } // HeadingRenderer describes a uniquely identifiable rendering hook. type HeadingRenderer interface { // Render writes the rendered content to w using the data in w. RenderHeading(w io.Writer, ctx HeadingContext) error identity.Provider } // 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 ) type GetRendererFunc func(t RendererType, id any) any
bep
3c51625c7152abca7e035fae15fc6807ca21cc86
e402d91ee199afcace8ae75da6c3587bb8089ace
The position of the code block in the page content.
jmooring
77
gohugoio/hugo
10,567
feat: add parents property on page
Add parents property on page, simplify breadcrumb navigation implementation complexity community tricks see: https://discourse.gohugo.io/search?q=breadcrumb --- in HTML: ```html {{- $page := . -} <nav class="breadcrumb"> <ul> {{- range .Parents.Reverse }} <li><a href="{{ .Permalink }}">{{ .LinkTitle }}</a></li> {{- end }} <li class="active">{{ .LinkTitle }}</li> </ul> </nav> ``` --- in JSON-LD: see https://developers.google.com/search/docs/appearance/structured-data/breadcrumb ```html {{- $breadcrumbItems := slice -}} {{- range $index, $page := append .Parents.Reverse . -}} {{- $item := dict "@type" "ListItem" "position" (add $index 1) "name" $page.Title "item" $page.Permalink -}} {{- $breadcrumbItems = append $breadcrumbItems $item -}} {{- end -}} <script type="application/ld+json"> {{- dict "@context" "https://schema.org" "@type" "BreadcrumbList" "itemListElement" $breadcrumbItems -}} </script> ```
null
2022-12-22 03:07:33+00:00
2022-12-23 09:14:54+00:00
hugolib/page__tree.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 hugolib import ( "path" "strings" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/resources/page" ) type pageTree struct { p *pageState } func (pt pageTree) IsAncestor(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref1 != nil && ref1.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } if strings.HasPrefix(ref2.key, ref1.key) { return true, nil } return strings.HasPrefix(ref2.key, ref1.key+cmBranchSeparator), nil } func (pt pageTree) CurrentSection() page.Page { p := pt.p if p.IsHome() || p.IsSection() { return p } return p.Parent() } func (pt pageTree) IsDescendant(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref2 != nil && ref2.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref2 == nil { // A 404 or other similar standalone page. return false, nil } return ref2.n.p.IsHome(), nil } if strings.HasPrefix(ref1.key, ref2.key) { return true, nil } return strings.HasPrefix(ref1.key, ref2.key+cmBranchSeparator), nil } func (pt pageTree) FirstSection() page.Page { ref := pt.p.getTreeRef() if ref == nil { return pt.p.s.home } key := ref.key if !ref.isSection() { key = path.Dir(key) } _, b := ref.m.getFirstSection(key) if b == nil { return nil } return b.p } func (pt pageTree) InSection(other any) (bool, error) { if pt.p == nil || types.IsNil(other) { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } s1, _ := ref1.getCurrentSection() s2, _ := ref2.getCurrentSection() return s1 == s2, nil } func (pt pageTree) Page() page.Page { return pt.p } func (pt pageTree) Parent() page.Page { p := pt.p if p.parent != nil { return p.parent } if pt.p.IsHome() { return nil } tree := p.getTreeRef() if tree == nil || pt.p.Kind() == page.KindTaxonomy { return pt.p.s.home } _, b := tree.getSection() if b == nil { return nil } return b.p } func (pt pageTree) Ancestors() (parents page.Pages) { parent := pt.Parent() for parent != nil { parents = append(parents, parent) parent = parent.Parent() } return } func (pt pageTree) Sections() page.Pages { if pt.p.bucket == nil { return nil } return pt.p.bucket.getSections() }
// 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 hugolib import ( "path" "strings" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/resources/page" ) type pageTree struct { p *pageState } func (pt pageTree) IsAncestor(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref1 != nil && ref1.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } if strings.HasPrefix(ref2.key, ref1.key) { return true, nil } return strings.HasPrefix(ref2.key, ref1.key+cmBranchSeparator), nil } func (pt pageTree) CurrentSection() page.Page { p := pt.p if p.IsHome() || p.IsSection() { return p } return p.Parent() } func (pt pageTree) IsDescendant(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref2 != nil && ref2.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref2 == nil { // A 404 or other similar standalone page. return false, nil } return ref2.n.p.IsHome(), nil } if strings.HasPrefix(ref1.key, ref2.key) { return true, nil } return strings.HasPrefix(ref1.key, ref2.key+cmBranchSeparator), nil } func (pt pageTree) FirstSection() page.Page { ref := pt.p.getTreeRef() if ref == nil { return pt.p.s.home } key := ref.key if !ref.isSection() { key = path.Dir(key) } _, b := ref.m.getFirstSection(key) if b == nil { return nil } return b.p } func (pt pageTree) InSection(other any) (bool, error) { if pt.p == nil || types.IsNil(other) { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } s1, _ := ref1.getCurrentSection() s2, _ := ref2.getCurrentSection() return s1 == s2, nil } func (pt pageTree) Page() page.Page { return pt.p } func (pt pageTree) Parent() page.Page { p := pt.p if p.parent != nil { return p.parent } if pt.p.IsHome() { return nil } tree := p.getTreeRef() if tree == nil || pt.p.Kind() == page.KindTaxonomy { return pt.p.s.home } _, b := tree.getSection() if b == nil { return nil } return b.p } func (pt pageTree) Ancestors() page.Pages { var ancestors page.Pages parent := pt.Parent() for parent != nil { ancestors = append(ancestors, parent) parent = parent.Parent() } return ancestors } func (pt pageTree) Sections() page.Pages { if pt.p.bucket == nil { return nil } return pt.p.bucket.getSections() }
septs
3a216186b2cfa479c250dabb64eff022a388fb40
eb0c8f9d02431aa0c2bce6f2e5fe27a4e33bf4df
Nitpicking, but * `parents` should be named something else * we only use named return values when really needed (e.g. when we need to capture a panic and assign to err), so I would prefer `Ancestors() page.Pages`
bep
78
gohugoio/hugo
10,567
feat: add parents property on page
Add parents property on page, simplify breadcrumb navigation implementation complexity community tricks see: https://discourse.gohugo.io/search?q=breadcrumb --- in HTML: ```html {{- $page := . -} <nav class="breadcrumb"> <ul> {{- range .Parents.Reverse }} <li><a href="{{ .Permalink }}">{{ .LinkTitle }}</a></li> {{- end }} <li class="active">{{ .LinkTitle }}</li> </ul> </nav> ``` --- in JSON-LD: see https://developers.google.com/search/docs/appearance/structured-data/breadcrumb ```html {{- $breadcrumbItems := slice -}} {{- range $index, $page := append .Parents.Reverse . -}} {{- $item := dict "@type" "ListItem" "position" (add $index 1) "name" $page.Title "item" $page.Permalink -}} {{- $breadcrumbItems = append $breadcrumbItems $item -}} {{- end -}} <script type="application/ld+json"> {{- dict "@context" "https://schema.org" "@type" "BreadcrumbList" "itemListElement" $breadcrumbItems -}} </script> ```
null
2022-12-22 03:07:33+00:00
2022-12-23 09:14:54+00:00
hugolib/page__tree.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 hugolib import ( "path" "strings" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/resources/page" ) type pageTree struct { p *pageState } func (pt pageTree) IsAncestor(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref1 != nil && ref1.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } if strings.HasPrefix(ref2.key, ref1.key) { return true, nil } return strings.HasPrefix(ref2.key, ref1.key+cmBranchSeparator), nil } func (pt pageTree) CurrentSection() page.Page { p := pt.p if p.IsHome() || p.IsSection() { return p } return p.Parent() } func (pt pageTree) IsDescendant(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref2 != nil && ref2.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref2 == nil { // A 404 or other similar standalone page. return false, nil } return ref2.n.p.IsHome(), nil } if strings.HasPrefix(ref1.key, ref2.key) { return true, nil } return strings.HasPrefix(ref1.key, ref2.key+cmBranchSeparator), nil } func (pt pageTree) FirstSection() page.Page { ref := pt.p.getTreeRef() if ref == nil { return pt.p.s.home } key := ref.key if !ref.isSection() { key = path.Dir(key) } _, b := ref.m.getFirstSection(key) if b == nil { return nil } return b.p } func (pt pageTree) InSection(other any) (bool, error) { if pt.p == nil || types.IsNil(other) { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } s1, _ := ref1.getCurrentSection() s2, _ := ref2.getCurrentSection() return s1 == s2, nil } func (pt pageTree) Page() page.Page { return pt.p } func (pt pageTree) Parent() page.Page { p := pt.p if p.parent != nil { return p.parent } if pt.p.IsHome() { return nil } tree := p.getTreeRef() if tree == nil || pt.p.Kind() == page.KindTaxonomy { return pt.p.s.home } _, b := tree.getSection() if b == nil { return nil } return b.p } func (pt pageTree) Ancestors() (parents page.Pages) { parent := pt.Parent() for parent != nil { parents = append(parents, parent) parent = parent.Parent() } return } func (pt pageTree) Sections() page.Pages { if pt.p.bucket == nil { return nil } return pt.p.bucket.getSections() }
// 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 hugolib import ( "path" "strings" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/resources/page" ) type pageTree struct { p *pageState } func (pt pageTree) IsAncestor(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref1 != nil && ref1.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } if strings.HasPrefix(ref2.key, ref1.key) { return true, nil } return strings.HasPrefix(ref2.key, ref1.key+cmBranchSeparator), nil } func (pt pageTree) CurrentSection() page.Page { p := pt.p if p.IsHome() || p.IsSection() { return p } return p.Parent() } func (pt pageTree) IsDescendant(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref2 != nil && ref2.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref2 == nil { // A 404 or other similar standalone page. return false, nil } return ref2.n.p.IsHome(), nil } if strings.HasPrefix(ref1.key, ref2.key) { return true, nil } return strings.HasPrefix(ref1.key, ref2.key+cmBranchSeparator), nil } func (pt pageTree) FirstSection() page.Page { ref := pt.p.getTreeRef() if ref == nil { return pt.p.s.home } key := ref.key if !ref.isSection() { key = path.Dir(key) } _, b := ref.m.getFirstSection(key) if b == nil { return nil } return b.p } func (pt pageTree) InSection(other any) (bool, error) { if pt.p == nil || types.IsNil(other) { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } s1, _ := ref1.getCurrentSection() s2, _ := ref2.getCurrentSection() return s1 == s2, nil } func (pt pageTree) Page() page.Page { return pt.p } func (pt pageTree) Parent() page.Page { p := pt.p if p.parent != nil { return p.parent } if pt.p.IsHome() { return nil } tree := p.getTreeRef() if tree == nil || pt.p.Kind() == page.KindTaxonomy { return pt.p.s.home } _, b := tree.getSection() if b == nil { return nil } return b.p } func (pt pageTree) Ancestors() page.Pages { var ancestors page.Pages parent := pt.Parent() for parent != nil { ancestors = append(ancestors, parent) parent = parent.Parent() } return ancestors } func (pt pageTree) Sections() page.Pages { if pt.p.bucket == nil { return nil } return pt.p.bucket.getSections() }
septs
3a216186b2cfa479c250dabb64eff022a388fb40
eb0c8f9d02431aa0c2bce6f2e5fe27a4e33bf4df
OK, I can do it. I need to merge this soonish, as I'm releasing today.
bep
79
gohugoio/hugo
10,567
feat: add parents property on page
Add parents property on page, simplify breadcrumb navigation implementation complexity community tricks see: https://discourse.gohugo.io/search?q=breadcrumb --- in HTML: ```html {{- $page := . -} <nav class="breadcrumb"> <ul> {{- range .Parents.Reverse }} <li><a href="{{ .Permalink }}">{{ .LinkTitle }}</a></li> {{- end }} <li class="active">{{ .LinkTitle }}</li> </ul> </nav> ``` --- in JSON-LD: see https://developers.google.com/search/docs/appearance/structured-data/breadcrumb ```html {{- $breadcrumbItems := slice -}} {{- range $index, $page := append .Parents.Reverse . -}} {{- $item := dict "@type" "ListItem" "position" (add $index 1) "name" $page.Title "item" $page.Permalink -}} {{- $breadcrumbItems = append $breadcrumbItems $item -}} {{- end -}} <script type="application/ld+json"> {{- dict "@context" "https://schema.org" "@type" "BreadcrumbList" "itemListElement" $breadcrumbItems -}} </script> ```
null
2022-12-22 03:07:33+00:00
2022-12-23 09:14:54+00:00
hugolib/page__tree.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 hugolib import ( "path" "strings" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/resources/page" ) type pageTree struct { p *pageState } func (pt pageTree) IsAncestor(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref1 != nil && ref1.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } if strings.HasPrefix(ref2.key, ref1.key) { return true, nil } return strings.HasPrefix(ref2.key, ref1.key+cmBranchSeparator), nil } func (pt pageTree) CurrentSection() page.Page { p := pt.p if p.IsHome() || p.IsSection() { return p } return p.Parent() } func (pt pageTree) IsDescendant(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref2 != nil && ref2.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref2 == nil { // A 404 or other similar standalone page. return false, nil } return ref2.n.p.IsHome(), nil } if strings.HasPrefix(ref1.key, ref2.key) { return true, nil } return strings.HasPrefix(ref1.key, ref2.key+cmBranchSeparator), nil } func (pt pageTree) FirstSection() page.Page { ref := pt.p.getTreeRef() if ref == nil { return pt.p.s.home } key := ref.key if !ref.isSection() { key = path.Dir(key) } _, b := ref.m.getFirstSection(key) if b == nil { return nil } return b.p } func (pt pageTree) InSection(other any) (bool, error) { if pt.p == nil || types.IsNil(other) { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } s1, _ := ref1.getCurrentSection() s2, _ := ref2.getCurrentSection() return s1 == s2, nil } func (pt pageTree) Page() page.Page { return pt.p } func (pt pageTree) Parent() page.Page { p := pt.p if p.parent != nil { return p.parent } if pt.p.IsHome() { return nil } tree := p.getTreeRef() if tree == nil || pt.p.Kind() == page.KindTaxonomy { return pt.p.s.home } _, b := tree.getSection() if b == nil { return nil } return b.p } func (pt pageTree) Ancestors() (parents page.Pages) { parent := pt.Parent() for parent != nil { parents = append(parents, parent) parent = parent.Parent() } return } func (pt pageTree) Sections() page.Pages { if pt.p.bucket == nil { return nil } return pt.p.bucket.getSections() }
// 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 hugolib import ( "path" "strings" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/resources/page" ) type pageTree struct { p *pageState } func (pt pageTree) IsAncestor(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref1 != nil && ref1.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } if strings.HasPrefix(ref2.key, ref1.key) { return true, nil } return strings.HasPrefix(ref2.key, ref1.key+cmBranchSeparator), nil } func (pt pageTree) CurrentSection() page.Page { p := pt.p if p.IsHome() || p.IsSection() { return p } return p.Parent() } func (pt pageTree) IsDescendant(other any) (bool, error) { if pt.p == nil { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 != nil && ref2 != nil && ref1.key == ref2.key { return false, nil } if ref2 != nil && ref2.key == "/" { return true, nil } if ref1 == nil || ref2 == nil { if ref2 == nil { // A 404 or other similar standalone page. return false, nil } return ref2.n.p.IsHome(), nil } if strings.HasPrefix(ref1.key, ref2.key) { return true, nil } return strings.HasPrefix(ref1.key, ref2.key+cmBranchSeparator), nil } func (pt pageTree) FirstSection() page.Page { ref := pt.p.getTreeRef() if ref == nil { return pt.p.s.home } key := ref.key if !ref.isSection() { key = path.Dir(key) } _, b := ref.m.getFirstSection(key) if b == nil { return nil } return b.p } func (pt pageTree) InSection(other any) (bool, error) { if pt.p == nil || types.IsNil(other) { return false, nil } tp, ok := other.(treeRefProvider) if !ok { return false, nil } ref1, ref2 := pt.p.getTreeRef(), tp.getTreeRef() if ref1 == nil || ref2 == nil { if ref1 == nil { // A 404 or other similar standalone page. return false, nil } return ref1.n.p.IsHome(), nil } s1, _ := ref1.getCurrentSection() s2, _ := ref2.getCurrentSection() return s1 == s2, nil } func (pt pageTree) Page() page.Page { return pt.p } func (pt pageTree) Parent() page.Page { p := pt.p if p.parent != nil { return p.parent } if pt.p.IsHome() { return nil } tree := p.getTreeRef() if tree == nil || pt.p.Kind() == page.KindTaxonomy { return pt.p.s.home } _, b := tree.getSection() if b == nil { return nil } return b.p } func (pt pageTree) Ancestors() page.Pages { var ancestors page.Pages parent := pt.Parent() for parent != nil { ancestors = append(ancestors, parent) parent = parent.Parent() } return ancestors } func (pt pageTree) Sections() page.Pages { if pt.p.bucket == nil { return nil } return pt.p.bucket.getSections() }
septs
3a216186b2cfa479c250dabb64eff022a388fb40
eb0c8f9d02431aa0c2bce6f2e5fe27a4e33bf4df
Sorry, I got COVID-19 and I'm fine now
septs
80
gohugoio/hugo
10,558
tocss: Add vars option
This commit adds a new `vars` option to both the Sass transpilers (Dart Sass and Libsass). This means that you can pass a map with key/value pairs to the transpiler: ```handlebars {{ $vars := dict "$color1" "blue" "$color2" "green" "$font_size" "24px" }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ``` And the the variables will be available in the `hugo:vars` namespace. Example usage for Dart Sass: ```scss @use "hugo:vars" as v; p { color: v.$color1; font-size: v.$font_size; } ``` Note that Libsass does not support the `use` keyword, so you need to `import` them as global variables: ```scss @import "hugo:vars"; p { color: $color1; font-size: $font_size; } ``` Hugo will: * Add a missing leading `$` for the variable names if needed. * Wrap the values in `unquote('VALUE')` (Sass built-in) to get proper handling of identifiers vs other strings. This means that you can pull variables directly from e.g. the site config: ```toml [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" ``` ```handlebars {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ```
null
2022-12-19 19:09:44+00:00
2022-12-20 18:36:30+00:00
resources/resource_transformers/tocss/dartsass/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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) }
// 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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) } func TestOptionVars(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $image := "images/hero.jpg" }} {{ $vars := dict "$color1" "blue" "$color2" "green" "font_size" "24px" "image" $image }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) } func TestOptionVarsParams(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- config.toml -- [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) }
bep
9a215d6950e6705f9109497e9f38cc3844172612
41a080b26877a737e74444f83fe54c46a9c9f6bc
@jmooring this is a little rough around the edges, but I think this will be the API.
bep
81
gohugoio/hugo
10,558
tocss: Add vars option
This commit adds a new `vars` option to both the Sass transpilers (Dart Sass and Libsass). This means that you can pass a map with key/value pairs to the transpiler: ```handlebars {{ $vars := dict "$color1" "blue" "$color2" "green" "$font_size" "24px" }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ``` And the the variables will be available in the `hugo:vars` namespace. Example usage for Dart Sass: ```scss @use "hugo:vars" as v; p { color: v.$color1; font-size: v.$font_size; } ``` Note that Libsass does not support the `use` keyword, so you need to `import` them as global variables: ```scss @import "hugo:vars"; p { color: $color1; font-size: $font_size; } ``` Hugo will: * Add a missing leading `$` for the variable names if needed. * Wrap the values in `unquote('VALUE')` (Sass built-in) to get proper handling of identifiers vs other strings. This means that you can pull variables directly from e.g. the site config: ```toml [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" ``` ```handlebars {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ```
null
2022-12-19 19:09:44+00:00
2022-12-20 18:36:30+00:00
resources/resource_transformers/tocss/dartsass/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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) }
// 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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) } func TestOptionVars(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $image := "images/hero.jpg" }} {{ $vars := dict "$color1" "blue" "$color2" "green" "font_size" "24px" "image" $image }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) } func TestOptionVarsParams(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- config.toml -- [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) }
bep
9a215d6950e6705f9109497e9f38cc3844172612
41a080b26877a737e74444f83fe54c46a9c9f6bc
Nice!
jmooring
82
gohugoio/hugo
10,558
tocss: Add vars option
This commit adds a new `vars` option to both the Sass transpilers (Dart Sass and Libsass). This means that you can pass a map with key/value pairs to the transpiler: ```handlebars {{ $vars := dict "$color1" "blue" "$color2" "green" "$font_size" "24px" }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ``` And the the variables will be available in the `hugo:vars` namespace. Example usage for Dart Sass: ```scss @use "hugo:vars" as v; p { color: v.$color1; font-size: v.$font_size; } ``` Note that Libsass does not support the `use` keyword, so you need to `import` them as global variables: ```scss @import "hugo:vars"; p { color: $color1; font-size: $font_size; } ``` Hugo will: * Add a missing leading `$` for the variable names if needed. * Wrap the values in `unquote('VALUE')` (Sass built-in) to get proper handling of identifiers vs other strings. This means that you can pull variables directly from e.g. the site config: ```toml [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" ``` ```handlebars {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ```
null
2022-12-19 19:09:44+00:00
2022-12-20 18:36:30+00:00
resources/resource_transformers/tocss/dartsass/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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) }
// 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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) } func TestOptionVars(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $image := "images/hero.jpg" }} {{ $vars := dict "$color1" "blue" "$color2" "green" "font_size" "24px" "image" $image }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) } func TestOptionVarsParams(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- config.toml -- [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) }
bep
9a215d6950e6705f9109497e9f38cc3844172612
41a080b26877a737e74444f83fe54c46a9c9f6bc
@jmooring if I can get your attention for a minute. My previous approach was a little bit too magic and had some side-effects vs line numbering in errors etc. Adding a custom namespace allows the user to pull them into a namespace if they care about that, or the global e.g.: ``` @use "hugo:vars"; @use "hugo:vars" as h; @import "hugo:vars"; ``` I guess `hugo:vars` is ... OK? The `:` avoids conflicts with user defined namespaces (and I think also Sass uses that for their libraries).
bep
83
gohugoio/hugo
10,558
tocss: Add vars option
This commit adds a new `vars` option to both the Sass transpilers (Dart Sass and Libsass). This means that you can pass a map with key/value pairs to the transpiler: ```handlebars {{ $vars := dict "$color1" "blue" "$color2" "green" "$font_size" "24px" }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ``` And the the variables will be available in the `hugo:vars` namespace. Example usage for Dart Sass: ```scss @use "hugo:vars" as v; p { color: v.$color1; font-size: v.$font_size; } ``` Note that Libsass does not support the `use` keyword, so you need to `import` them as global variables: ```scss @import "hugo:vars"; p { color: $color1; font-size: $font_size; } ``` Hugo will: * Add a missing leading `$` for the variable names if needed. * Wrap the values in `unquote('VALUE')` (Sass built-in) to get proper handling of identifiers vs other strings. This means that you can pull variables directly from e.g. the site config: ```toml [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" ``` ```handlebars {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ```
null
2022-12-19 19:09:44+00:00
2022-12-20 18:36:30+00:00
resources/resource_transformers/tocss/dartsass/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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) }
// 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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) } func TestOptionVars(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $image := "images/hero.jpg" }} {{ $vars := dict "$color1" "blue" "$color2" "green" "font_size" "24px" "image" $image }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) } func TestOptionVarsParams(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- config.toml -- [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) }
bep
9a215d6950e6705f9109497e9f38cc3844172612
41a080b26877a737e74444f83fe54c46a9c9f6bc
> guess hugo:vars is ... OK Yes, and that does follow existing Sass syntax for built-in modules (e.g, `@use "sass:math";`). I pulled in the latest commit and tested. Perhaps the testing is premature, but I did get an error: > Rebuild failed: TOCSS-DART: failed to transform "scss/main.scss" (text/x-scss): "vars:0:109": expected "(". Example: ```bash git clone --single-branch -b hugo-github-issue-10558 https://github.com/jmooring/hugo-testing hugo-github-issue-10558 cd hugo-github-issue-10558 hugo server ```
jmooring
84
gohugoio/hugo
10,558
tocss: Add vars option
This commit adds a new `vars` option to both the Sass transpilers (Dart Sass and Libsass). This means that you can pass a map with key/value pairs to the transpiler: ```handlebars {{ $vars := dict "$color1" "blue" "$color2" "green" "$font_size" "24px" }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ``` And the the variables will be available in the `hugo:vars` namespace. Example usage for Dart Sass: ```scss @use "hugo:vars" as v; p { color: v.$color1; font-size: v.$font_size; } ``` Note that Libsass does not support the `use` keyword, so you need to `import` them as global variables: ```scss @import "hugo:vars"; p { color: $color1; font-size: $font_size; } ``` Hugo will: * Add a missing leading `$` for the variable names if needed. * Wrap the values in `unquote('VALUE')` (Sass built-in) to get proper handling of identifiers vs other strings. This means that you can pull variables directly from e.g. the site config: ```toml [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" ``` ```handlebars {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ```
null
2022-12-19 19:09:44+00:00
2022-12-20 18:36:30+00:00
resources/resource_transformers/tocss/dartsass/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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) }
// 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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) } func TestOptionVars(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $image := "images/hero.jpg" }} {{ $vars := dict "$color1" "blue" "$color2" "green" "font_size" "24px" "image" $image }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) } func TestOptionVarsParams(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- config.toml -- [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) }
bep
9a215d6950e6705f9109497e9f38cc3844172612
41a080b26877a737e74444f83fe54c46a9c9f6bc
Yea, it's very lightly tested by me, I just wanted to get the API right first, but it's simple enough so it should be simply to get it right, I think (and I'll also make it work on both Sass implementations).
bep
85
gohugoio/hugo
10,558
tocss: Add vars option
This commit adds a new `vars` option to both the Sass transpilers (Dart Sass and Libsass). This means that you can pass a map with key/value pairs to the transpiler: ```handlebars {{ $vars := dict "$color1" "blue" "$color2" "green" "$font_size" "24px" }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ``` And the the variables will be available in the `hugo:vars` namespace. Example usage for Dart Sass: ```scss @use "hugo:vars" as v; p { color: v.$color1; font-size: v.$font_size; } ``` Note that Libsass does not support the `use` keyword, so you need to `import` them as global variables: ```scss @import "hugo:vars"; p { color: $color1; font-size: $font_size; } ``` Hugo will: * Add a missing leading `$` for the variable names if needed. * Wrap the values in `unquote('VALUE')` (Sass built-in) to get proper handling of identifiers vs other strings. This means that you can pull variables directly from e.g. the site config: ```toml [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" ``` ```handlebars {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ```
null
2022-12-19 19:09:44+00:00
2022-12-20 18:36:30+00:00
resources/resource_transformers/tocss/dartsass/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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) }
// 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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) } func TestOptionVars(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $image := "images/hero.jpg" }} {{ $vars := dict "$color1" "blue" "$color2" "green" "font_size" "24px" "image" $image }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) } func TestOptionVarsParams(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- config.toml -- [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) }
bep
9a215d6950e6705f9109497e9f38cc3844172612
41a080b26877a737e74444f83fe54c46a9c9f6bc
Re your problem; I need to apply some CSS encoding of strings or something, it seems.
bep
86
gohugoio/hugo
10,558
tocss: Add vars option
This commit adds a new `vars` option to both the Sass transpilers (Dart Sass and Libsass). This means that you can pass a map with key/value pairs to the transpiler: ```handlebars {{ $vars := dict "$color1" "blue" "$color2" "green" "$font_size" "24px" }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ``` And the the variables will be available in the `hugo:vars` namespace. Example usage for Dart Sass: ```scss @use "hugo:vars" as v; p { color: v.$color1; font-size: v.$font_size; } ``` Note that Libsass does not support the `use` keyword, so you need to `import` them as global variables: ```scss @import "hugo:vars"; p { color: $color1; font-size: $font_size; } ``` Hugo will: * Add a missing leading `$` for the variable names if needed. * Wrap the values in `unquote('VALUE')` (Sass built-in) to get proper handling of identifiers vs other strings. This means that you can pull variables directly from e.g. the site config: ```toml [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" ``` ```handlebars {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ```
null
2022-12-19 19:09:44+00:00
2022-12-20 18:36:30+00:00
resources/resource_transformers/tocss/dartsass/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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) }
// 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 dartsass_test import ( "strings" "testing" qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/hugolib" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/dartsass" jww "github.com/spf13/jwalterweatherman" ) func TestTransformIncludePaths(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @import "moo"; -- node_modules/foo/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- config.toml -- -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo") "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#fff}`) } func TestTransformImportRegularCSS(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- assets/scss/another.css -- -- assets/scss/main.scss -- @import "moo"; @import "regular.css"; @import "moo"; @import "another.css"; /* foo */ -- assets/scss/regular.css -- -- config.toml -- -- layouts/index.html -- {{ $r := resources.Get "scss/main.scss" | toCSS (dict "transpiler" "dartsass") }} T1: {{ $r.Content | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() // Dart Sass does not follow regular CSS import, but they // get pulled to the top. b.AssertFileContent("public/index.html", `T1: @import "regular.css"; @import "another.css"; moo { color: #fff; } moo { color: #fff; } /* foo */`) } func TestTransformThemeOverrides(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/components/_boo.scss -- $boolor: green; boo { color: $boolor; } -- assets/scss/components/_moo.scss -- $moolor: #ccc; moo { color: $moolor; } -- config.toml -- theme = 'mytheme' -- layouts/index.html -- {{ $cssOpts := (dict "includePaths" (slice "node_modules/foo" ) "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} -- themes/mytheme/assets/scss/components/_boo.scss -- $boolor: orange; boo { color: $boolor; } -- themes/mytheme/assets/scss/components/_imports.scss -- @import "moo"; @import "_boo"; @import "_zoo"; -- themes/mytheme/assets/scss/components/_moo.scss -- $moolor: #fff; moo { color: $moolor; } -- themes/mytheme/assets/scss/components/_zoo.scss -- $zoolor: pink; zoo { color: $zoolor; } -- themes/mytheme/assets/scss/main.scss -- @import "components/imports"; ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }, ).Build() b.AssertFileContent("public/index.html", `T1: moo{color:#ccc}boo{color:green}zoo{color:pink}`) } func TestTransformLogging(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @warn "foo"; @debug "bar"; -- config.toml -- disableKinds = ["term", "taxonomy", "section", "page"] -- layouts/index.html -- {{ $cssOpts := (dict "transpiler" "dartsass" ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, LogLevel: jww.LevelInfo, }).Build() b.AssertLogMatches(`WARN.*Dart Sass: foo`) b.AssertLogMatches(`INFO.*Dart Sass: .*assets.*main.scss:1:0: bar`) } func TestTransformErrors(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } c := qt.New(t) const filesTemplate = ` -- config.toml -- -- assets/scss/components/_foo.scss -- /* comment line 1 */ $foocolor: #ccc; foo { color: $foocolor; } -- assets/scss/main.scss -- /* comment line 1 */ /* comment line 2 */ @import "components/foo"; /* comment line 4 */ $maincolor: #eee; body { color: $maincolor; } -- layouts/index.html -- {{ $cssOpts := dict "transpiler" "dartsass" }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts | minify }} T1: {{ $r.Content }} ` c.Run("error in main", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$maincolor: #eee;", "$maincolor #eee;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `main.scss:8:13":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{" $maincolor #eee;", "", "body {", "\tcolor: $maincolor;", "}"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) c.Run("error in import", func(c *qt.C) { b, err := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: c, TxtarString: strings.Replace(filesTemplate, "$foocolor: #ccc;", "$foocolor #ccc;", 1), NeedsOsFS: true, }).BuildE() b.Assert(err, qt.IsNotNil) b.Assert(err.Error(), qt.Contains, `_foo.scss:2:10":`) b.Assert(err.Error(), qt.Contains, `: expected ":".`) fe := b.AssertIsFileError(err) b.Assert(fe.ErrorContext(), qt.IsNotNil) b.Assert(fe.ErrorContext().Lines, qt.DeepEquals, []string{"/* comment line 1 */", "$foocolor #ccc;", "", "foo {"}) b.Assert(fe.ErrorContext().ChromaLexer, qt.Equals, "scss") }) } func TestOptionVars(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $image := "images/hero.jpg" }} {{ $vars := dict "$color1" "blue" "$color2" "green" "font_size" "24px" "image" $image }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) } func TestOptionVarsParams(t *testing.T) { t.Parallel() if !dartsass.Supports() { t.Skip() } files := ` -- config.toml -- [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" -- assets/scss/main.scss -- @use "hugo:vars"; body { body { background: url(vars.$image) no-repeat center/cover; } } p { color: vars.$color1; font-size: vars.$font_size; } b { color: vars.$color2; } -- layouts/index.html -- {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} T1: {{ $r.Content }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: true, }).Build() b.AssertFileContent("public/index.html", `T1: body body{background:url(images/hero.jpg) no-repeat center/cover}p{color:blue;font-size:24px}b{color:green}`) }
bep
9a215d6950e6705f9109497e9f38cc3844172612
41a080b26877a737e74444f83fe54c46a9c9f6bc
OK, using `unquote('%s')` seems to solve the string quoting issue, at least for Dart Sass. I tested it on your failing. Have force pushed.
bep
87
gohugoio/hugo
10,558
tocss: Add vars option
This commit adds a new `vars` option to both the Sass transpilers (Dart Sass and Libsass). This means that you can pass a map with key/value pairs to the transpiler: ```handlebars {{ $vars := dict "$color1" "blue" "$color2" "green" "$font_size" "24px" }} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ``` And the the variables will be available in the `hugo:vars` namespace. Example usage for Dart Sass: ```scss @use "hugo:vars" as v; p { color: v.$color1; font-size: v.$font_size; } ``` Note that Libsass does not support the `use` keyword, so you need to `import` them as global variables: ```scss @import "hugo:vars"; p { color: $color1; font-size: $font_size; } ``` Hugo will: * Add a missing leading `$` for the variable names if needed. * Wrap the values in `unquote('VALUE')` (Sass built-in) to get proper handling of identifiers vs other strings. This means that you can pull variables directly from e.g. the site config: ```toml [params] [params.sassvars] color1 = "blue" color2 = "green" font_size = "24px" image = "images/hero.jpg" ``` ```handlebars {{ $vars := site.Params.sassvars}} {{ $cssOpts := (dict "transpiler" "dartsass" "outputStyle" "compressed" "vars" $vars ) }} {{ $r := resources.Get "scss/main.scss" | toCSS $cssOpts }} ```
null
2022-12-19 19:09:44+00:00
2022-12-20 18:36:30+00:00
resources/resource_transformers/tocss/dartsass/transform.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 dartsass import ( "fmt" "io" "path" "path/filepath" "strings" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/internal" "github.com/spf13/afero" "github.com/gohugoio/hugo/hugofs" "github.com/bep/godartsass" ) const ( dartSassEmbeddedBinaryName = "dart-sass-embedded" ) // Supports returns whether dart-sass-embedded is found in $PATH. func Supports() bool { if htesting.SupportsAll() { return true } return hexec.InPath(dartSassEmbeddedBinaryName) } type transform struct { optsm map[string]any c *Client } func (t *transform) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey(transformationName, t.optsm) } func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { ctx.OutMediaType = media.CSSType opts, err := decodeOptions(t.optsm) if err != nil { return err } if opts.TargetPath != "" { ctx.OutPath = opts.TargetPath } else { ctx.ReplaceOutPathExtension(".css") } baseDir := path.Dir(ctx.SourcePath) filename := dartSassStdinPrefix if ctx.SourcePath != "" { filename += t.c.sfs.RealFilename(ctx.SourcePath) } args := godartsass.Args{ URL: filename, IncludePaths: t.c.sfs.RealDirs(baseDir), ImportResolver: importResolver{ baseDir: baseDir, c: t.c, }, OutputStyle: godartsass.ParseOutputStyle(opts.OutputStyle), EnableSourceMap: opts.EnableSourceMap, SourceMapIncludeSources: opts.SourceMapIncludeSources, } // Append any workDir relative include paths for _, ip := range opts.IncludePaths { info, err := t.c.workFs.Stat(filepath.Clean(ip)) if err == nil { filename := info.(hugofs.FileMetaInfo).Meta().Filename args.IncludePaths = append(args.IncludePaths, filename) } } if ctx.InMediaType.SubType == media.SASSType.SubType { args.SourceSyntax = godartsass.SourceSyntaxSASS } res, err := t.c.toCSS(args, ctx.From) if err != nil { return err } out := res.CSS _, err = io.WriteString(ctx.To, out) if err != nil { return err } if opts.EnableSourceMap && res.SourceMap != "" { if err := ctx.PublishSourceMap(res.SourceMap); err != nil { return err } _, err = fmt.Fprintf(ctx.To, "\n\n/*# sourceMappingURL=%s */", path.Base(ctx.OutPath)+".map") } return err } type importResolver struct { baseDir string c *Client } func (t importResolver) CanonicalizeURL(url string) (string, error) { filePath, isURL := paths.UrlToFilename(url) var prevDir string var pathDir string if isURL { var found bool prevDir, found = t.c.sfs.MakePathRelative(filepath.Dir(filePath)) if !found { // Not a member of this filesystem, let Dart Sass handle it. return "", nil } } else { prevDir = t.baseDir pathDir = path.Dir(url) } basePath := filepath.Join(prevDir, pathDir) name := filepath.Base(filePath) // Pick the first match. var namePatterns []string if strings.Contains(name, ".") { namePatterns = []string{"_%s", "%s"} } else if strings.HasPrefix(name, "_") { namePatterns = []string{"_%s.scss", "_%s.sass"} } else { namePatterns = []string{"_%s.scss", "%s.scss", "_%s.sass", "%s.sass"} } name = strings.TrimPrefix(name, "_") for _, namePattern := range namePatterns { filenameToCheck := filepath.Join(basePath, fmt.Sprintf(namePattern, name)) fi, err := t.c.sfs.Fs.Stat(filenameToCheck) if err == nil { if fim, ok := fi.(hugofs.FileMetaInfo); ok { return "file://" + filepath.ToSlash(fim.Meta().Filename), nil } } } // Not found, let Dart Dass handle it return "", nil } func (t importResolver) Load(url string) (string, error) { filename, _ := paths.UrlToFilename(url) b, err := afero.ReadFile(hugofs.Os, filename) return string(b), err }
// Copyright 2022 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 dartsass import ( "fmt" "io" "path" "path/filepath" "strings" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/paths" "github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource_transformers/tocss/internal/sass" "github.com/spf13/afero" "github.com/gohugoio/hugo/hugofs" "github.com/bep/godartsass" ) const ( dartSassEmbeddedBinaryName = "dart-sass-embedded" ) // Supports returns whether dart-sass-embedded is found in $PATH. func Supports() bool { if htesting.SupportsAll() { return true } return hexec.InPath(dartSassEmbeddedBinaryName) } type transform struct { optsm map[string]any c *Client } func (t *transform) Key() internal.ResourceTransformationKey { return internal.NewResourceTransformationKey(transformationName, t.optsm) } func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { ctx.OutMediaType = media.CSSType opts, err := decodeOptions(t.optsm) if err != nil { return err } if opts.TargetPath != "" { ctx.OutPath = opts.TargetPath } else { ctx.ReplaceOutPathExtension(".css") } baseDir := path.Dir(ctx.SourcePath) filename := dartSassStdinPrefix if ctx.SourcePath != "" { filename += t.c.sfs.RealFilename(ctx.SourcePath) } args := godartsass.Args{ URL: filename, IncludePaths: t.c.sfs.RealDirs(baseDir), ImportResolver: importResolver{ baseDir: baseDir, c: t.c, varsStylesheet: sass.CreateVarsStyleSheet(opts.Vars), }, OutputStyle: godartsass.ParseOutputStyle(opts.OutputStyle), EnableSourceMap: opts.EnableSourceMap, SourceMapIncludeSources: opts.SourceMapIncludeSources, } // Append any workDir relative include paths for _, ip := range opts.IncludePaths { info, err := t.c.workFs.Stat(filepath.Clean(ip)) if err == nil { filename := info.(hugofs.FileMetaInfo).Meta().Filename args.IncludePaths = append(args.IncludePaths, filename) } } if ctx.InMediaType.SubType == media.SASSType.SubType { args.SourceSyntax = godartsass.SourceSyntaxSASS } res, err := t.c.toCSS(args, ctx.From) if err != nil { return err } out := res.CSS _, err = io.WriteString(ctx.To, out) if err != nil { return err } if opts.EnableSourceMap && res.SourceMap != "" { if err := ctx.PublishSourceMap(res.SourceMap); err != nil { return err } _, err = fmt.Fprintf(ctx.To, "\n\n/*# sourceMappingURL=%s */", path.Base(ctx.OutPath)+".map") } return err } type importResolver struct { baseDir string c *Client varsStylesheet string } func (t importResolver) CanonicalizeURL(url string) (string, error) { if url == sass.HugoVarsNamespace { return url, nil } filePath, isURL := paths.UrlToFilename(url) var prevDir string var pathDir string if isURL { var found bool prevDir, found = t.c.sfs.MakePathRelative(filepath.Dir(filePath)) if !found { // Not a member of this filesystem, let Dart Sass handle it. return "", nil } } else { prevDir = t.baseDir pathDir = path.Dir(url) } basePath := filepath.Join(prevDir, pathDir) name := filepath.Base(filePath) // Pick the first match. var namePatterns []string if strings.Contains(name, ".") { namePatterns = []string{"_%s", "%s"} } else if strings.HasPrefix(name, "_") { namePatterns = []string{"_%s.scss", "_%s.sass"} } else { namePatterns = []string{"_%s.scss", "%s.scss", "_%s.sass", "%s.sass"} } name = strings.TrimPrefix(name, "_") for _, namePattern := range namePatterns { filenameToCheck := filepath.Join(basePath, fmt.Sprintf(namePattern, name)) fi, err := t.c.sfs.Fs.Stat(filenameToCheck) if err == nil { if fim, ok := fi.(hugofs.FileMetaInfo); ok { return "file://" + filepath.ToSlash(fim.Meta().Filename), nil } } } // Not found, let Dart Dass handle it return "", nil } func (t importResolver) Load(url string) (string, error) { if url == sass.HugoVarsNamespace { return t.varsStylesheet, nil } filename, _ := paths.UrlToFilename(url) b, err := afero.ReadFile(hugofs.Os, filename) return string(b), err }
bep
9a215d6950e6705f9109497e9f38cc3844172612
41a080b26877a737e74444f83fe54c46a9c9f6bc
Nice.
jmooring
88
gohugoio/hugo
10,284
Allow proxy variables in subcommands
In particular for `go get`.
null
2022-09-16 14:40:06+00:00
2022-09-19 10:37:36+00:00
config/security/securityConfig.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 security import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/mitchellh/mapstructure" ) const securityConfigKey = "security" // DefaultConfig holds the default security policy. var DefaultConfig = Config{ Exec: Exec{ Allow: NewWhitelist( "^dart-sass-embedded$", "^go$", // for Go Modules "^npx$", // used by all Node tools (Babel, PostCSS). "^postcss$", ), // These have been tested to work with Hugo's external programs // on Windows, Linux and MacOS. OsEnv: NewWhitelist("(?i)^(PATH|PATHEXT|APPDATA|TMP|TEMP|TERM)$"), }, Funcs: Funcs{ Getenv: NewWhitelist("^HUGO_"), }, HTTP: HTTP{ URLs: NewWhitelist(".*"), Methods: NewWhitelist("(?i)GET|POST"), }, } // Config is the top level security config. type Config struct { // Restricts access to os.Exec. Exec Exec `json:"exec"` // Restricts access to certain template funcs. Funcs Funcs `json:"funcs"` // Restricts access to resources.Get, getJSON, getCSV. HTTP HTTP `json:"http"` // Allow inline shortcodes EnableInlineShortcodes bool `json:"enableInlineShortcodes"` } // Exec holds os/exec policies. type Exec struct { Allow Whitelist `json:"allow"` OsEnv Whitelist `json:"osEnv"` } // Funcs holds template funcs policies. type Funcs struct { // OS env keys allowed to query in os.Getenv. Getenv Whitelist `json:"getenv"` } type HTTP struct { // URLs to allow in remote HTTP (resources.Get, getJSON, getCSV). URLs Whitelist `json:"urls"` // HTTP methods to allow. Methods Whitelist `json:"methods"` } // ToTOML converts c to TOML with [security] as the root. func (c Config) ToTOML() string { sec := c.ToSecurityMap() var b bytes.Buffer if err := parser.InterfaceToConfig(sec, metadecoders.TOML, &b); err != nil { panic(err) } return strings.TrimSpace(b.String()) } func (c Config) CheckAllowedExec(name string) error { if !c.Exec.Allow.Accept(name) { return &AccessDeniedError{ name: name, path: "security.exec.allow", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedGetEnv(name string) error { if !c.Funcs.Getenv.Accept(name) { return &AccessDeniedError{ name: name, path: "security.funcs.getenv", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPURL(url string) error { if !c.HTTP.URLs.Accept(url) { return &AccessDeniedError{ name: url, path: "security.http.urls", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPMethod(method string) error { if !c.HTTP.Methods.Accept(method) { return &AccessDeniedError{ name: method, path: "security.http.method", policies: c.ToTOML(), } } return nil } // ToSecurityMap converts c to a map with 'security' as the root key. func (c Config) ToSecurityMap() map[string]any { // Take it to JSON and back to get proper casing etc. asJson, err := json.Marshal(c) herrors.Must(err) m := make(map[string]any) herrors.Must(json.Unmarshal(asJson, &m)) // Add the root sec := map[string]any{ "security": m, } return sec } // DecodeConfig creates a privacy Config from a given Hugo configuration. func DecodeConfig(cfg config.Provider) (Config, error) { sc := DefaultConfig if cfg.IsSet(securityConfigKey) { m := cfg.GetStringMap(securityConfigKey) dec, err := mapstructure.NewDecoder( &mapstructure.DecoderConfig{ WeaklyTypedInput: true, Result: &sc, DecodeHook: stringSliceToWhitelistHook(), }, ) if err != nil { return sc, err } if err = dec.Decode(m); err != nil { return sc, err } } if !sc.EnableInlineShortcodes { // Legacy sc.EnableInlineShortcodes = cfg.GetBool("enableInlineShortcodes") } return sc, nil } func stringSliceToWhitelistHook() mapstructure.DecodeHookFuncType { return func( f reflect.Type, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(Whitelist{}) { return data, nil } wl := types.ToStringSlicePreserveString(data) return NewWhitelist(wl...), nil } } // AccessDeniedError represents a security policy conflict. type AccessDeniedError struct { path string name string policies string } func (e *AccessDeniedError) Error() string { return fmt.Sprintf("access denied: %q is not whitelisted in policy %q; the current security configuration is:\n\n%s\n\n", e.name, e.path, e.policies) } // IsAccessDenied reports whether err is an AccessDeniedError func IsAccessDenied(err error) bool { var notFoundErr *AccessDeniedError return errors.As(err, &notFoundErr) }
// 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 security import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/mitchellh/mapstructure" ) const securityConfigKey = "security" // DefaultConfig holds the default security policy. var DefaultConfig = Config{ Exec: Exec{ Allow: NewWhitelist( "^dart-sass-embedded$", "^go$", // for Go Modules "^npx$", // used by all Node tools (Babel, PostCSS). "^postcss$", ), // These have been tested to work with Hugo's external programs // on Windows, Linux and MacOS. OsEnv: NewWhitelist("(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM)$"), }, Funcs: Funcs{ Getenv: NewWhitelist("^HUGO_"), }, HTTP: HTTP{ URLs: NewWhitelist(".*"), Methods: NewWhitelist("(?i)GET|POST"), }, } // Config is the top level security config. type Config struct { // Restricts access to os.Exec. Exec Exec `json:"exec"` // Restricts access to certain template funcs. Funcs Funcs `json:"funcs"` // Restricts access to resources.Get, getJSON, getCSV. HTTP HTTP `json:"http"` // Allow inline shortcodes EnableInlineShortcodes bool `json:"enableInlineShortcodes"` } // Exec holds os/exec policies. type Exec struct { Allow Whitelist `json:"allow"` OsEnv Whitelist `json:"osEnv"` } // Funcs holds template funcs policies. type Funcs struct { // OS env keys allowed to query in os.Getenv. Getenv Whitelist `json:"getenv"` } type HTTP struct { // URLs to allow in remote HTTP (resources.Get, getJSON, getCSV). URLs Whitelist `json:"urls"` // HTTP methods to allow. Methods Whitelist `json:"methods"` } // ToTOML converts c to TOML with [security] as the root. func (c Config) ToTOML() string { sec := c.ToSecurityMap() var b bytes.Buffer if err := parser.InterfaceToConfig(sec, metadecoders.TOML, &b); err != nil { panic(err) } return strings.TrimSpace(b.String()) } func (c Config) CheckAllowedExec(name string) error { if !c.Exec.Allow.Accept(name) { return &AccessDeniedError{ name: name, path: "security.exec.allow", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedGetEnv(name string) error { if !c.Funcs.Getenv.Accept(name) { return &AccessDeniedError{ name: name, path: "security.funcs.getenv", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPURL(url string) error { if !c.HTTP.URLs.Accept(url) { return &AccessDeniedError{ name: url, path: "security.http.urls", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPMethod(method string) error { if !c.HTTP.Methods.Accept(method) { return &AccessDeniedError{ name: method, path: "security.http.method", policies: c.ToTOML(), } } return nil } // ToSecurityMap converts c to a map with 'security' as the root key. func (c Config) ToSecurityMap() map[string]any { // Take it to JSON and back to get proper casing etc. asJson, err := json.Marshal(c) herrors.Must(err) m := make(map[string]any) herrors.Must(json.Unmarshal(asJson, &m)) // Add the root sec := map[string]any{ "security": m, } return sec } // DecodeConfig creates a privacy Config from a given Hugo configuration. func DecodeConfig(cfg config.Provider) (Config, error) { sc := DefaultConfig if cfg.IsSet(securityConfigKey) { m := cfg.GetStringMap(securityConfigKey) dec, err := mapstructure.NewDecoder( &mapstructure.DecoderConfig{ WeaklyTypedInput: true, Result: &sc, DecodeHook: stringSliceToWhitelistHook(), }, ) if err != nil { return sc, err } if err = dec.Decode(m); err != nil { return sc, err } } if !sc.EnableInlineShortcodes { // Legacy sc.EnableInlineShortcodes = cfg.GetBool("enableInlineShortcodes") } return sc, nil } func stringSliceToWhitelistHook() mapstructure.DecodeHookFuncType { return func( f reflect.Type, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(Whitelist{}) { return data, nil } wl := types.ToStringSlicePreserveString(data) return NewWhitelist(wl...), nil } } // AccessDeniedError represents a security policy conflict. type AccessDeniedError struct { path string name string policies string } func (e *AccessDeniedError) Error() string { return fmt.Sprintf("access denied: %q is not whitelisted in policy %q; the current security configuration is:\n\n%s\n\n", e.name, e.path, e.policies) } // IsAccessDenied reports whether err is an AccessDeniedError func IsAccessDenied(err error) bool { var notFoundErr *AccessDeniedError return errors.As(err, &notFoundErr) }
sathieu
c46d104985b185b66a4a65d02d58043a4dc0dea0
86653fa38eb43a5fabf7adc694c752ccb7721ffa
```suggestion OsEnv: NewWhitelist("(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM)$"), ```
septs
89
gohugoio/hugo
10,284
Allow proxy variables in subcommands
In particular for `go get`.
null
2022-09-16 14:40:06+00:00
2022-09-19 10:37:36+00:00
config/security/securityConfig.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 security import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/mitchellh/mapstructure" ) const securityConfigKey = "security" // DefaultConfig holds the default security policy. var DefaultConfig = Config{ Exec: Exec{ Allow: NewWhitelist( "^dart-sass-embedded$", "^go$", // for Go Modules "^npx$", // used by all Node tools (Babel, PostCSS). "^postcss$", ), // These have been tested to work with Hugo's external programs // on Windows, Linux and MacOS. OsEnv: NewWhitelist("(?i)^(PATH|PATHEXT|APPDATA|TMP|TEMP|TERM)$"), }, Funcs: Funcs{ Getenv: NewWhitelist("^HUGO_"), }, HTTP: HTTP{ URLs: NewWhitelist(".*"), Methods: NewWhitelist("(?i)GET|POST"), }, } // Config is the top level security config. type Config struct { // Restricts access to os.Exec. Exec Exec `json:"exec"` // Restricts access to certain template funcs. Funcs Funcs `json:"funcs"` // Restricts access to resources.Get, getJSON, getCSV. HTTP HTTP `json:"http"` // Allow inline shortcodes EnableInlineShortcodes bool `json:"enableInlineShortcodes"` } // Exec holds os/exec policies. type Exec struct { Allow Whitelist `json:"allow"` OsEnv Whitelist `json:"osEnv"` } // Funcs holds template funcs policies. type Funcs struct { // OS env keys allowed to query in os.Getenv. Getenv Whitelist `json:"getenv"` } type HTTP struct { // URLs to allow in remote HTTP (resources.Get, getJSON, getCSV). URLs Whitelist `json:"urls"` // HTTP methods to allow. Methods Whitelist `json:"methods"` } // ToTOML converts c to TOML with [security] as the root. func (c Config) ToTOML() string { sec := c.ToSecurityMap() var b bytes.Buffer if err := parser.InterfaceToConfig(sec, metadecoders.TOML, &b); err != nil { panic(err) } return strings.TrimSpace(b.String()) } func (c Config) CheckAllowedExec(name string) error { if !c.Exec.Allow.Accept(name) { return &AccessDeniedError{ name: name, path: "security.exec.allow", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedGetEnv(name string) error { if !c.Funcs.Getenv.Accept(name) { return &AccessDeniedError{ name: name, path: "security.funcs.getenv", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPURL(url string) error { if !c.HTTP.URLs.Accept(url) { return &AccessDeniedError{ name: url, path: "security.http.urls", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPMethod(method string) error { if !c.HTTP.Methods.Accept(method) { return &AccessDeniedError{ name: method, path: "security.http.method", policies: c.ToTOML(), } } return nil } // ToSecurityMap converts c to a map with 'security' as the root key. func (c Config) ToSecurityMap() map[string]any { // Take it to JSON and back to get proper casing etc. asJson, err := json.Marshal(c) herrors.Must(err) m := make(map[string]any) herrors.Must(json.Unmarshal(asJson, &m)) // Add the root sec := map[string]any{ "security": m, } return sec } // DecodeConfig creates a privacy Config from a given Hugo configuration. func DecodeConfig(cfg config.Provider) (Config, error) { sc := DefaultConfig if cfg.IsSet(securityConfigKey) { m := cfg.GetStringMap(securityConfigKey) dec, err := mapstructure.NewDecoder( &mapstructure.DecoderConfig{ WeaklyTypedInput: true, Result: &sc, DecodeHook: stringSliceToWhitelistHook(), }, ) if err != nil { return sc, err } if err = dec.Decode(m); err != nil { return sc, err } } if !sc.EnableInlineShortcodes { // Legacy sc.EnableInlineShortcodes = cfg.GetBool("enableInlineShortcodes") } return sc, nil } func stringSliceToWhitelistHook() mapstructure.DecodeHookFuncType { return func( f reflect.Type, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(Whitelist{}) { return data, nil } wl := types.ToStringSlicePreserveString(data) return NewWhitelist(wl...), nil } } // AccessDeniedError represents a security policy conflict. type AccessDeniedError struct { path string name string policies string } func (e *AccessDeniedError) Error() string { return fmt.Sprintf("access denied: %q is not whitelisted in policy %q; the current security configuration is:\n\n%s\n\n", e.name, e.path, e.policies) } // IsAccessDenied reports whether err is an AccessDeniedError func IsAccessDenied(err error) bool { var notFoundErr *AccessDeniedError return errors.As(err, &notFoundErr) }
// 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 security import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/mitchellh/mapstructure" ) const securityConfigKey = "security" // DefaultConfig holds the default security policy. var DefaultConfig = Config{ Exec: Exec{ Allow: NewWhitelist( "^dart-sass-embedded$", "^go$", // for Go Modules "^npx$", // used by all Node tools (Babel, PostCSS). "^postcss$", ), // These have been tested to work with Hugo's external programs // on Windows, Linux and MacOS. OsEnv: NewWhitelist("(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM)$"), }, Funcs: Funcs{ Getenv: NewWhitelist("^HUGO_"), }, HTTP: HTTP{ URLs: NewWhitelist(".*"), Methods: NewWhitelist("(?i)GET|POST"), }, } // Config is the top level security config. type Config struct { // Restricts access to os.Exec. Exec Exec `json:"exec"` // Restricts access to certain template funcs. Funcs Funcs `json:"funcs"` // Restricts access to resources.Get, getJSON, getCSV. HTTP HTTP `json:"http"` // Allow inline shortcodes EnableInlineShortcodes bool `json:"enableInlineShortcodes"` } // Exec holds os/exec policies. type Exec struct { Allow Whitelist `json:"allow"` OsEnv Whitelist `json:"osEnv"` } // Funcs holds template funcs policies. type Funcs struct { // OS env keys allowed to query in os.Getenv. Getenv Whitelist `json:"getenv"` } type HTTP struct { // URLs to allow in remote HTTP (resources.Get, getJSON, getCSV). URLs Whitelist `json:"urls"` // HTTP methods to allow. Methods Whitelist `json:"methods"` } // ToTOML converts c to TOML with [security] as the root. func (c Config) ToTOML() string { sec := c.ToSecurityMap() var b bytes.Buffer if err := parser.InterfaceToConfig(sec, metadecoders.TOML, &b); err != nil { panic(err) } return strings.TrimSpace(b.String()) } func (c Config) CheckAllowedExec(name string) error { if !c.Exec.Allow.Accept(name) { return &AccessDeniedError{ name: name, path: "security.exec.allow", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedGetEnv(name string) error { if !c.Funcs.Getenv.Accept(name) { return &AccessDeniedError{ name: name, path: "security.funcs.getenv", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPURL(url string) error { if !c.HTTP.URLs.Accept(url) { return &AccessDeniedError{ name: url, path: "security.http.urls", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPMethod(method string) error { if !c.HTTP.Methods.Accept(method) { return &AccessDeniedError{ name: method, path: "security.http.method", policies: c.ToTOML(), } } return nil } // ToSecurityMap converts c to a map with 'security' as the root key. func (c Config) ToSecurityMap() map[string]any { // Take it to JSON and back to get proper casing etc. asJson, err := json.Marshal(c) herrors.Must(err) m := make(map[string]any) herrors.Must(json.Unmarshal(asJson, &m)) // Add the root sec := map[string]any{ "security": m, } return sec } // DecodeConfig creates a privacy Config from a given Hugo configuration. func DecodeConfig(cfg config.Provider) (Config, error) { sc := DefaultConfig if cfg.IsSet(securityConfigKey) { m := cfg.GetStringMap(securityConfigKey) dec, err := mapstructure.NewDecoder( &mapstructure.DecoderConfig{ WeaklyTypedInput: true, Result: &sc, DecodeHook: stringSliceToWhitelistHook(), }, ) if err != nil { return sc, err } if err = dec.Decode(m); err != nil { return sc, err } } if !sc.EnableInlineShortcodes { // Legacy sc.EnableInlineShortcodes = cfg.GetBool("enableInlineShortcodes") } return sc, nil } func stringSliceToWhitelistHook() mapstructure.DecodeHookFuncType { return func( f reflect.Type, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(Whitelist{}) { return data, nil } wl := types.ToStringSlicePreserveString(data) return NewWhitelist(wl...), nil } } // AccessDeniedError represents a security policy conflict. type AccessDeniedError struct { path string name string policies string } func (e *AccessDeniedError) Error() string { return fmt.Sprintf("access denied: %q is not whitelisted in policy %q; the current security configuration is:\n\n%s\n\n", e.name, e.path, e.policies) } // IsAccessDenied reports whether err is an AccessDeniedError func IsAccessDenied(err error) bool { var notFoundErr *AccessDeniedError return errors.As(err, &notFoundErr) }
sathieu
c46d104985b185b66a4a65d02d58043a4dc0dea0
86653fa38eb43a5fabf7adc694c752ccb7721ffa
<img width="750" alt="image" src="https://user-images.githubusercontent.com/3842474/190704160-f73a0992-2a2d-40d0-bd0b-e1dfa0e4bb10.png"> https://regex101.com/r/irBHIT/1
septs
90
gohugoio/hugo
10,284
Allow proxy variables in subcommands
In particular for `go get`.
null
2022-09-16 14:40:06+00:00
2022-09-19 10:37:36+00:00
config/security/securityConfig.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 security import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/mitchellh/mapstructure" ) const securityConfigKey = "security" // DefaultConfig holds the default security policy. var DefaultConfig = Config{ Exec: Exec{ Allow: NewWhitelist( "^dart-sass-embedded$", "^go$", // for Go Modules "^npx$", // used by all Node tools (Babel, PostCSS). "^postcss$", ), // These have been tested to work with Hugo's external programs // on Windows, Linux and MacOS. OsEnv: NewWhitelist("(?i)^(PATH|PATHEXT|APPDATA|TMP|TEMP|TERM)$"), }, Funcs: Funcs{ Getenv: NewWhitelist("^HUGO_"), }, HTTP: HTTP{ URLs: NewWhitelist(".*"), Methods: NewWhitelist("(?i)GET|POST"), }, } // Config is the top level security config. type Config struct { // Restricts access to os.Exec. Exec Exec `json:"exec"` // Restricts access to certain template funcs. Funcs Funcs `json:"funcs"` // Restricts access to resources.Get, getJSON, getCSV. HTTP HTTP `json:"http"` // Allow inline shortcodes EnableInlineShortcodes bool `json:"enableInlineShortcodes"` } // Exec holds os/exec policies. type Exec struct { Allow Whitelist `json:"allow"` OsEnv Whitelist `json:"osEnv"` } // Funcs holds template funcs policies. type Funcs struct { // OS env keys allowed to query in os.Getenv. Getenv Whitelist `json:"getenv"` } type HTTP struct { // URLs to allow in remote HTTP (resources.Get, getJSON, getCSV). URLs Whitelist `json:"urls"` // HTTP methods to allow. Methods Whitelist `json:"methods"` } // ToTOML converts c to TOML with [security] as the root. func (c Config) ToTOML() string { sec := c.ToSecurityMap() var b bytes.Buffer if err := parser.InterfaceToConfig(sec, metadecoders.TOML, &b); err != nil { panic(err) } return strings.TrimSpace(b.String()) } func (c Config) CheckAllowedExec(name string) error { if !c.Exec.Allow.Accept(name) { return &AccessDeniedError{ name: name, path: "security.exec.allow", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedGetEnv(name string) error { if !c.Funcs.Getenv.Accept(name) { return &AccessDeniedError{ name: name, path: "security.funcs.getenv", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPURL(url string) error { if !c.HTTP.URLs.Accept(url) { return &AccessDeniedError{ name: url, path: "security.http.urls", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPMethod(method string) error { if !c.HTTP.Methods.Accept(method) { return &AccessDeniedError{ name: method, path: "security.http.method", policies: c.ToTOML(), } } return nil } // ToSecurityMap converts c to a map with 'security' as the root key. func (c Config) ToSecurityMap() map[string]any { // Take it to JSON and back to get proper casing etc. asJson, err := json.Marshal(c) herrors.Must(err) m := make(map[string]any) herrors.Must(json.Unmarshal(asJson, &m)) // Add the root sec := map[string]any{ "security": m, } return sec } // DecodeConfig creates a privacy Config from a given Hugo configuration. func DecodeConfig(cfg config.Provider) (Config, error) { sc := DefaultConfig if cfg.IsSet(securityConfigKey) { m := cfg.GetStringMap(securityConfigKey) dec, err := mapstructure.NewDecoder( &mapstructure.DecoderConfig{ WeaklyTypedInput: true, Result: &sc, DecodeHook: stringSliceToWhitelistHook(), }, ) if err != nil { return sc, err } if err = dec.Decode(m); err != nil { return sc, err } } if !sc.EnableInlineShortcodes { // Legacy sc.EnableInlineShortcodes = cfg.GetBool("enableInlineShortcodes") } return sc, nil } func stringSliceToWhitelistHook() mapstructure.DecodeHookFuncType { return func( f reflect.Type, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(Whitelist{}) { return data, nil } wl := types.ToStringSlicePreserveString(data) return NewWhitelist(wl...), nil } } // AccessDeniedError represents a security policy conflict. type AccessDeniedError struct { path string name string policies string } func (e *AccessDeniedError) Error() string { return fmt.Sprintf("access denied: %q is not whitelisted in policy %q; the current security configuration is:\n\n%s\n\n", e.name, e.path, e.policies) } // IsAccessDenied reports whether err is an AccessDeniedError func IsAccessDenied(err error) bool { var notFoundErr *AccessDeniedError return errors.As(err, &notFoundErr) }
// 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 security import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" "github.com/mitchellh/mapstructure" ) const securityConfigKey = "security" // DefaultConfig holds the default security policy. var DefaultConfig = Config{ Exec: Exec{ Allow: NewWhitelist( "^dart-sass-embedded$", "^go$", // for Go Modules "^npx$", // used by all Node tools (Babel, PostCSS). "^postcss$", ), // These have been tested to work with Hugo's external programs // on Windows, Linux and MacOS. OsEnv: NewWhitelist("(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM)$"), }, Funcs: Funcs{ Getenv: NewWhitelist("^HUGO_"), }, HTTP: HTTP{ URLs: NewWhitelist(".*"), Methods: NewWhitelist("(?i)GET|POST"), }, } // Config is the top level security config. type Config struct { // Restricts access to os.Exec. Exec Exec `json:"exec"` // Restricts access to certain template funcs. Funcs Funcs `json:"funcs"` // Restricts access to resources.Get, getJSON, getCSV. HTTP HTTP `json:"http"` // Allow inline shortcodes EnableInlineShortcodes bool `json:"enableInlineShortcodes"` } // Exec holds os/exec policies. type Exec struct { Allow Whitelist `json:"allow"` OsEnv Whitelist `json:"osEnv"` } // Funcs holds template funcs policies. type Funcs struct { // OS env keys allowed to query in os.Getenv. Getenv Whitelist `json:"getenv"` } type HTTP struct { // URLs to allow in remote HTTP (resources.Get, getJSON, getCSV). URLs Whitelist `json:"urls"` // HTTP methods to allow. Methods Whitelist `json:"methods"` } // ToTOML converts c to TOML with [security] as the root. func (c Config) ToTOML() string { sec := c.ToSecurityMap() var b bytes.Buffer if err := parser.InterfaceToConfig(sec, metadecoders.TOML, &b); err != nil { panic(err) } return strings.TrimSpace(b.String()) } func (c Config) CheckAllowedExec(name string) error { if !c.Exec.Allow.Accept(name) { return &AccessDeniedError{ name: name, path: "security.exec.allow", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedGetEnv(name string) error { if !c.Funcs.Getenv.Accept(name) { return &AccessDeniedError{ name: name, path: "security.funcs.getenv", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPURL(url string) error { if !c.HTTP.URLs.Accept(url) { return &AccessDeniedError{ name: url, path: "security.http.urls", policies: c.ToTOML(), } } return nil } func (c Config) CheckAllowedHTTPMethod(method string) error { if !c.HTTP.Methods.Accept(method) { return &AccessDeniedError{ name: method, path: "security.http.method", policies: c.ToTOML(), } } return nil } // ToSecurityMap converts c to a map with 'security' as the root key. func (c Config) ToSecurityMap() map[string]any { // Take it to JSON and back to get proper casing etc. asJson, err := json.Marshal(c) herrors.Must(err) m := make(map[string]any) herrors.Must(json.Unmarshal(asJson, &m)) // Add the root sec := map[string]any{ "security": m, } return sec } // DecodeConfig creates a privacy Config from a given Hugo configuration. func DecodeConfig(cfg config.Provider) (Config, error) { sc := DefaultConfig if cfg.IsSet(securityConfigKey) { m := cfg.GetStringMap(securityConfigKey) dec, err := mapstructure.NewDecoder( &mapstructure.DecoderConfig{ WeaklyTypedInput: true, Result: &sc, DecodeHook: stringSliceToWhitelistHook(), }, ) if err != nil { return sc, err } if err = dec.Decode(m); err != nil { return sc, err } } if !sc.EnableInlineShortcodes { // Legacy sc.EnableInlineShortcodes = cfg.GetBool("enableInlineShortcodes") } return sc, nil } func stringSliceToWhitelistHook() mapstructure.DecodeHookFuncType { return func( f reflect.Type, t reflect.Type, data any) (any, error) { if t != reflect.TypeOf(Whitelist{}) { return data, nil } wl := types.ToStringSlicePreserveString(data) return NewWhitelist(wl...), nil } } // AccessDeniedError represents a security policy conflict. type AccessDeniedError struct { path string name string policies string } func (e *AccessDeniedError) Error() string { return fmt.Sprintf("access denied: %q is not whitelisted in policy %q; the current security configuration is:\n\n%s\n\n", e.name, e.path, e.policies) } // IsAccessDenied reports whether err is an AccessDeniedError func IsAccessDenied(err error) bool { var notFoundErr *AccessDeniedError return errors.As(err, &notFoundErr) }
sathieu
c46d104985b185b66a4a65d02d58043a4dc0dea0
86653fa38eb43a5fabf7adc694c752ccb7721ffa
@septs Changed as suggested. Please review again 🙏 !
sathieu
91
gohugoio/hugo
10,237
Add `--force` to `hugo new`
Closes #9243
null
2022-08-31 15:28:34+00:00
2022-09-08 13:35:11+00:00
commands/new.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 commands import ( "bytes" "os" "path/filepath" "strings" "github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugolib" "github.com/spf13/afero" "github.com/spf13/cobra" jww "github.com/spf13/jwalterweatherman" ) var _ cmder = (*newCmd)(nil) type newCmd struct { contentEditor string contentType string force bool *baseBuilderCmd } func (b *commandsBuilder) newNewCmd() *newCmd { cmd := &cobra.Command{ Use: "new [path]", Short: "Create new content for your site", Long: `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.`, } cc := &newCmd{baseBuilderCmd: b.newBuilderCmd(cmd)} cmd.Flags().StringVarP(&cc.contentType, "kind", "k", "", "content type to create") cmd.Flags().StringVar(&cc.contentEditor, "editor", "", "edit new content with this editor, if provided") cmd.Flags().BoolVarP(&cc.force, "force", "f", false, "allow to override file") cmd.AddCommand(b.newNewSiteCmd().getCommand()) cmd.AddCommand(b.newNewThemeCmd().getCommand()) cmd.RunE = cc.newContent return cc } func (n *newCmd) newContent(cmd *cobra.Command, args []string) error { cfgInit := func(c *commandeer) error { if cmd.Flags().Changed("editor") { c.Set("newContentEditor", n.contentEditor) } return nil } c, err := initializeConfig(true, true, false, &n.hugoBuilderCommon, n, cfgInit) if err != nil { return err } if len(args) < 1 { return newUserError("path needs to be provided") } return create.NewContent(c.hugo(), n.contentType, args[0], n.force) } func mkdir(x ...string) { p := filepath.Join(x...) err := os.MkdirAll(p, 0777) // before umask if err != nil { jww.FATAL.Fatalln(err) } } func touchFile(fs afero.Fs, x ...string) { inpath := filepath.Join(x...) mkdir(filepath.Dir(inpath)) err := helpers.WriteToDisk(inpath, bytes.NewReader([]byte{}), fs) if err != nil { jww.FATAL.Fatalln(err) } } func newContentPathSection(h *hugolib.HugoSites, path string) (string, string) { // Forward slashes is used in all examples. Convert if needed. // Issue #1133 createpath := filepath.FromSlash(path) if h != nil { for _, dir := range h.BaseFs.Content.Dirs { createpath = strings.TrimPrefix(createpath, dir.Meta().Filename) } } var section string // assume the first directory is the section (kind) if strings.Contains(createpath[1:], helpers.FilePathSeparator) { parts := strings.Split(strings.TrimPrefix(createpath, helpers.FilePathSeparator), helpers.FilePathSeparator) if len(parts) > 0 { section = parts[0] } } return createpath, section }
// 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 commands import ( "bytes" "os" "path/filepath" "strings" "github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugolib" "github.com/spf13/afero" "github.com/spf13/cobra" jww "github.com/spf13/jwalterweatherman" ) var _ cmder = (*newCmd)(nil) type newCmd struct { contentEditor string contentType string force bool *baseBuilderCmd } func (b *commandsBuilder) newNewCmd() *newCmd { cmd := &cobra.Command{ Use: "new [path]", Short: "Create new content for your site", Long: `Create a new content file and automatically set the date and title. It will guess which kind of file to create based on the path provided. You can also specify the kind with ` + "`-k KIND`" + `. If archetypes are provided in your theme or site, they will be used. Ensure you run this within the root directory of your site.`, } cc := &newCmd{baseBuilderCmd: b.newBuilderCmd(cmd)} cmd.Flags().StringVarP(&cc.contentType, "kind", "k", "", "content type to create") cmd.Flags().StringVar(&cc.contentEditor, "editor", "", "edit new content with this editor, if provided") cmd.Flags().BoolVarP(&cc.force, "force", "f", false, "overwrite file if it already exists") cmd.AddCommand(b.newNewSiteCmd().getCommand()) cmd.AddCommand(b.newNewThemeCmd().getCommand()) cmd.RunE = cc.newContent return cc } func (n *newCmd) newContent(cmd *cobra.Command, args []string) error { cfgInit := func(c *commandeer) error { if cmd.Flags().Changed("editor") { c.Set("newContentEditor", n.contentEditor) } return nil } c, err := initializeConfig(true, true, false, &n.hugoBuilderCommon, n, cfgInit) if err != nil { return err } if len(args) < 1 { return newUserError("path needs to be provided") } return create.NewContent(c.hugo(), n.contentType, args[0], n.force) } func mkdir(x ...string) { p := filepath.Join(x...) err := os.MkdirAll(p, 0777) // before umask if err != nil { jww.FATAL.Fatalln(err) } } func touchFile(fs afero.Fs, x ...string) { inpath := filepath.Join(x...) mkdir(filepath.Dir(inpath)) err := helpers.WriteToDisk(inpath, bytes.NewReader([]byte{}), fs) if err != nil { jww.FATAL.Fatalln(err) } } func newContentPathSection(h *hugolib.HugoSites, path string) (string, string) { // Forward slashes is used in all examples. Convert if needed. // Issue #1133 createpath := filepath.FromSlash(path) if h != nil { for _, dir := range h.BaseFs.Content.Dirs { createpath = strings.TrimPrefix(createpath, dir.Meta().Filename) } } var section string // assume the first directory is the section (kind) if strings.Contains(createpath[1:], helpers.FilePathSeparator) { parts := strings.Split(strings.TrimPrefix(createpath, helpers.FilePathSeparator), helpers.FilePathSeparator) if len(parts) > 0 { section = parts[0] } } return createpath, section }
satotake
7d40da876c62a166bdd273209b7cd6bead9266c1
ab5ce59894520a796ca658ef0385c65c2fa45f99
I think it should say "overwrite file if it already exists".
bep
92
gohugoio/hugo
10,119
markup/goldmark/codeblock: get attribute in no language identifier in CodeBlock
Fixes #10118
null
2022-07-23 13:03:41+00:00
2022-08-03 09:32:08+00:00
markup/goldmark/codeblocks/integration_test.go
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 10118 func TestAttributes(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Issue 10118 §§§ {foo="bar"} Hello, World! §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Type: {{ .Type }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
chick-p
3fefea06b884ff905509f5854cb13bc54d092f38
cbdaff213539dff8f41ed83dabc9a3981c409797
Could you * Add a check for the `Type` and make sure it's empty. * Get the commit message title in line with the guidelines ("get" => "Get")
bep
93
gohugoio/hugo
10,119
markup/goldmark/codeblock: get attribute in no language identifier in CodeBlock
Fixes #10118
null
2022-07-23 13:03:41+00:00
2022-08-03 09:32:08+00:00
markup/goldmark/codeblocks/integration_test.go
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 10118 func TestAttributes(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Issue 10118 §§§ {foo="bar"} Hello, World! §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Type: {{ .Type }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
chick-p
3fefea06b884ff905509f5854cb13bc54d092f38
cbdaff213539dff8f41ed83dabc9a3981c409797
@bep I'd fixed the commit message, sorry. I have a question. I tried to add to check `Type`, but the `Type` returns Attributes. Because the parser returns a string of after the code fence if a language identifier is empty. <img width="1027" alt=" 2022-07-24 8 59 24" src="https://user-images.githubusercontent.com/14119304/180627042-7f87c120-7685-4074-b00e-74ad56d9940b.png"> https://github.com/yuin/goldmark/blob/master/ast/block.go#L273-L276 Would it be better to resolve the behavior on this pull request or another Issue?
chick-p
94
gohugoio/hugo
10,119
markup/goldmark/codeblock: get attribute in no language identifier in CodeBlock
Fixes #10118
null
2022-07-23 13:03:41+00:00
2022-08-03 09:32:08+00:00
markup/goldmark/codeblocks/integration_test.go
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 10118 func TestAttributes(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Issue 10118 §§§ {foo="bar"} Hello, World! §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Type: {{ .Type }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
chick-p
3fefea06b884ff905509f5854cb13bc54d092f38
cbdaff213539dff8f41ed83dabc9a3981c409797
I'm not sure I follow, it looks like a string to me: https://github.com/gohugoio/hugo/blob/9c24b86e4b634d7db761a3e57c1b64fead880aff/markup/goldmark/codeblocks/render.go#L158
bep
95
gohugoio/hugo
10,119
markup/goldmark/codeblock: get attribute in no language identifier in CodeBlock
Fixes #10118
null
2022-07-23 13:03:41+00:00
2022-08-03 09:32:08+00:00
markup/goldmark/codeblocks/integration_test.go
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 10118 func TestAttributes(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Issue 10118 §§§ {foo="bar"} Hello, World! §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Type: {{ .Type }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
chick-p
3fefea06b884ff905509f5854cb13bc54d092f38
cbdaff213539dff8f41ed83dabc9a3981c409797
Sorry. The order of my comment was not good. After adding `.Type`, a result of `TestAttributes()` as follows: ``` --- FAIL: TestAttributes (0.04s) /Users/chick-p/Repos/hugo/markup/goldmark/codeblocks/integration_test.go:298: error: no substring match found comment: <h2 id="issue-10118">Issue 10118</h2> Attributes: map[foo:bar]|Type: | container: "<h2 id=\"issue-10118\">Issue 10118</h2>\nAttributes: map[foo:bar]|Type: {foo=&#34;bar&#34;}|" want: "Attributes: map[foo:bar]|Type: |" /Users/chick-p/Repos/hugo/hugolib/integrationtest_builder.go:144 s.Assert(content, qt.Contains, match, qt.Commentf(m)) /Users/chick-p/Repos/hugo/markup/goldmark/codeblocks/integration_test.go:298 b.AssertFileContent("public/p1/index.html", "<h2 id=\"issue-10118\">Issue 10118</h2>\nAttributes: map[foo:bar]|Type: |") FAIL FAIL github.com/gohugoio/hugo/markup/goldmark/codeblocks 0.709s FAIL ``` `.Type` became `Type: {foo=&#34;bar&#34;}`, so it is not empty. I Will have the same result even if `attrStartIdx > 0` at L191 in `markup/goldmark/codeblocks/render.go`. I suppose that the cause is https://github.com/gohugoio/hugo/pull/10119#discussion_r928178328
chick-p
96
gohugoio/hugo
10,119
markup/goldmark/codeblock: get attribute in no language identifier in CodeBlock
Fixes #10118
null
2022-07-23 13:03:41+00:00
2022-08-03 09:32:08+00:00
markup/goldmark/codeblocks/integration_test.go
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 10118 func TestAttributes(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Issue 10118 §§§ {foo="bar"} Hello, World! §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Type: {{ .Type }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
chick-p
3fefea06b884ff905509f5854cb13bc54d092f38
cbdaff213539dff8f41ed83dabc9a3981c409797
>.Type became Type: {foo=&#34;bar&#34;}, so it is not empty. It should be. This may be an existing issue, but it feels natural to fix as part of this PR. I suspect the simplest fix is to check for `{` where `Type` is evaluated. I think we can safely make that a reserved character not to be used in `Type`.
bep
97
gohugoio/hugo
10,119
markup/goldmark/codeblock: get attribute in no language identifier in CodeBlock
Fixes #10118
null
2022-07-23 13:03:41+00:00
2022-08-03 09:32:08+00:00
markup/goldmark/codeblocks/integration_test.go
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 9571 func TestAttributesChroma(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
// Copyright 2022 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" "github.com/gohugoio/hugo/hugolib" ) func TestCodeblocks(t *testing.T) { t.Parallel() files := ` -- config.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/_default/_markup/render-codeblock-goat.html -- {{ $diagram := diagrams.Goat .Inner }} Goat SVG:{{ substr $diagram.Wrapped 0 100 | safeHTML }} }}| Goat Attribute: {{ .Attributes.width}}| -- layouts/_default/_markup/render-codeblock-go.html -- Go Code: {{ .Inner | safeHTML }}| Go Language: {{ .Type }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Ascii Diagram §§§goat { width="600" } ---> §§§ ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ## Golang Code §§§golang 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"; §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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: golang| `, "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: golang|", "<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 := ` -- config.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/_default/_markup/render-codeblock.html -- {{ $result := transform.HighlightCodeBlock . }} Inner: |{{ $result.Inner | safeHTML }}| Wrapped: |{{ $result.Wrapped | safeHTML }}| -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Go Code §§§go fmt.Println("Hello, World!"); §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- layouts/_default/_markup/render-codeblock.html -- {{ .Position | safeHTML }} -- layouts/_default/single.html -- {{ .Content }} -- content/p1.md -- --- title: "p1" --- ## Issue 9627 §§§text {{</* foo */>}} §§§ ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- §§§bash echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- |{{ .Inner | safeHTML }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, NeedsOsFS: false, }, ).Build() b.AssertFileContent("public/p1/index.html", "|echo \"p1\";|") } func TestCodePosition(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§ echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Position: {{ .Position | safeHTML }} ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() b.AssertFileContent("public/p1/index.html", filepath.FromSlash("Position: \"/content/p1.md:7:1\"")) } // Issue 10118 func TestAttributes(t *testing.T) { t.Parallel() files := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Issue 10118 §§§ {foo="bar"} Hello, World! §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_markup/render-codeblock.html -- Attributes: {{ .Attributes }}|Type: {{ .Type }}| ` b := hugolib.NewIntegrationTestBuilder( hugolib.IntegrationTestConfig{ T: t, TxtarString: files, }, ).Build() 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 := ` -- config.toml -- -- content/p1.md -- --- title: "p1" --- ## Code §§§LANGUAGE {style=monokai} echo "p1"; §§§ -- layouts/_default/single.html -- {{ .Content }} -- layouts/_default/_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 := ` -- config.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/_default/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") }) } }
chick-p
3fefea06b884ff905509f5854cb13bc54d092f38
cbdaff213539dff8f41ed83dabc9a3981c409797
Thanks for considering the direction. I have checked for `{`.
chick-p
98
gohugoio/hugo
10,119
markup/goldmark/codeblock: get attribute in no language identifier in CodeBlock
Fixes #10118
null
2022-07-23 13:03:41+00:00
2022-08-03 09:32:08+00:00
markup/goldmark/codeblocks/render.go
// Copyright 2022 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" "fmt" "sync" "github.com/alecthomas/chroma/v2/lexers" "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/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.Parser().AddOptions( parser.WithASTTransformers( util.Prioritized(&Transformer{}, 100), ), ) 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(KindCodeBlock, 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.(*codeBlock) lang := string(n.b.Language(src)) renderer := ctx.RenderContext().GetRenderer(hooks.CodeBlockRendererType, lang) if renderer == nil { return ast.WalkStop, fmt.Errorf("no code renderer found for %q", lang) } ordinal := n.ordinal var buff bytes.Buffer l := n.b.Lines().Len() for i := 0; i < l; i++ { line := n.b.Lines().At(i) buff.Write(line.Value(src)) } s := htext.Chomp(buff.String()) var info []byte if n.b.Info != nil { info = n.b.Info.Segment.Value(src) } attrtp := attributes.AttributesOwnerCodeBlockCustom if isd, ok := renderer.(hooks.IsDefaultCodeBlockRendererProvider); (ok && isd.IsDefaultCodeBlockRenderer()) || lexers.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 } // IsDefaultCodeBlockRendererProvider attrs := getAttributes(n.b, info) cbctx := &codeBlockContext{ page: ctx.DocumentContext().Document, lang: lang, code: s, ordinal: ordinal, AttributesHolder: attributes.New(attrs, attrtp), } cbctx.createPos = func() htext.Position { if resolver, ok := renderer.(hooks.ElementPositionResolver); ok { return resolver.ResolvePosition(cbctx) } return htext.Position{ Filename: ctx.DocumentContext().Filename, LineNumber: 1, ColumnNumber: 1, } } cr := renderer.(hooks.CodeBlockRenderer) err := cr.RenderCodeblock( w, cbctx, ) ctx.AddIdentity(cr) if err != nil { return ast.WalkContinue, herrors.NewFileErrorFromPos(err, cbctx.createPos()) } return ast.WalkContinue, nil } type codeBlockContext struct { page any lang string code string ordinal int // This is only used in error situations and is expensive to create, // to deleay creation until needed. pos htext.Position posInit sync.Once createPos func() htext.Position *attributes.AttributesHolder } func (c *codeBlockContext) Page() any { return c.page } func (c *codeBlockContext) Type() string { return c.lang } func (c *codeBlockContext) Inner() string { return c.code } func (c *codeBlockContext) Ordinal() int { return c.ordinal } func (c *codeBlockContext) Position() htext.Position { c.posInit.Do(func() { c.pos = c.createPos() }) return c.pos } func getAttributes(node *ast.FencedCodeBlock, infostr []byte) []ast.Attribute { if node.Attributes() != nil { return node.Attributes() } if infostr != nil { attrStartIdx := -1 for idx, char := range infostr { if char == '{' { attrStartIdx = idx break } } if attrStartIdx > 0 { n := ast.NewTextBlock() // dummy node for storing attributes attrStr := infostr[attrStartIdx:] if attrs, hasAttr := parser.ParseAttributes(text.NewReader(attrStr)); hasAttr { for _, attr := range attrs { n.SetAttribute(attr.Name, attr.Value) } return n.Attributes() } } } return nil }
// Copyright 2022 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" "fmt" "strings" "sync" "github.com/alecthomas/chroma/v2/lexers" "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/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.Parser().AddOptions( parser.WithASTTransformers( util.Prioritized(&Transformer{}, 100), ), ) 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(KindCodeBlock, 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.(*codeBlock) lang := getLang(n.b, src) renderer := ctx.RenderContext().GetRenderer(hooks.CodeBlockRendererType, lang) if renderer == nil { return ast.WalkStop, fmt.Errorf("no code renderer found for %q", lang) } ordinal := n.ordinal var buff bytes.Buffer l := n.b.Lines().Len() for i := 0; i < l; i++ { line := n.b.Lines().At(i) buff.Write(line.Value(src)) } s := htext.Chomp(buff.String()) var info []byte if n.b.Info != nil { info = n.b.Info.Segment.Value(src) } attrtp := attributes.AttributesOwnerCodeBlockCustom if isd, ok := renderer.(hooks.IsDefaultCodeBlockRendererProvider); (ok && isd.IsDefaultCodeBlockRenderer()) || lexers.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 } // IsDefaultCodeBlockRendererProvider attrs := getAttributes(n.b, info) cbctx := &codeBlockContext{ page: ctx.DocumentContext().Document, lang: lang, code: s, ordinal: ordinal, AttributesHolder: attributes.New(attrs, attrtp), } cbctx.createPos = func() htext.Position { if resolver, ok := renderer.(hooks.ElementPositionResolver); ok { return resolver.ResolvePosition(cbctx) } return htext.Position{ Filename: ctx.DocumentContext().Filename, LineNumber: 1, ColumnNumber: 1, } } cr := renderer.(hooks.CodeBlockRenderer) err := cr.RenderCodeblock( w, cbctx, ) ctx.AddIdentity(cr) if err != nil { return ast.WalkContinue, herrors.NewFileErrorFromPos(err, cbctx.createPos()) } return ast.WalkContinue, nil } type codeBlockContext struct { page any lang string code string ordinal int // This is only used in error situations and is expensive to create, // to deleay creation until needed. pos htext.Position posInit sync.Once createPos func() htext.Position *attributes.AttributesHolder } func (c *codeBlockContext) Page() any { return c.page } func (c *codeBlockContext) Type() string { return c.lang } func (c *codeBlockContext) Inner() string { return c.code } func (c *codeBlockContext) Ordinal() int { return c.ordinal } func (c *codeBlockContext) Position() htext.Position { c.posInit.Do(func() { c.pos = c.createPos() }) return c.pos } 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 { if node.Attributes() != nil { return node.Attributes() } if infostr != nil { attrStartIdx := -1 for idx, char := range infostr { if char == '{' { attrStartIdx = idx break } } if attrStartIdx != -1 { n := ast.NewTextBlock() // dummy node for storing attributes attrStr := infostr[attrStartIdx:] if attrs, hasAttr := parser.ParseAttributes(text.NewReader(attrStr)); hasAttr { for _, attr := range attrs { n.SetAttribute(attr.Name, attr.Value) } return n.Attributes() } } } return nil }
chick-p
3fefea06b884ff905509f5854cb13bc54d092f38
cbdaff213539dff8f41ed83dabc9a3981c409797
Thank, this looks correct, but: * This needs to be evaluated when codeBlockContext is created. Everyone who later looks at `c.lang` will assume that it contains the `lang` only. * The loop can be replaced with `bytes.Cut`.
bep
99
gohugoio/hugo
10,119
markup/goldmark/codeblock: get attribute in no language identifier in CodeBlock
Fixes #10118
null
2022-07-23 13:03:41+00:00
2022-08-03 09:32:08+00:00
markup/goldmark/codeblocks/render.go
// Copyright 2022 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" "fmt" "sync" "github.com/alecthomas/chroma/v2/lexers" "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/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.Parser().AddOptions( parser.WithASTTransformers( util.Prioritized(&Transformer{}, 100), ), ) 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(KindCodeBlock, 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.(*codeBlock) lang := string(n.b.Language(src)) renderer := ctx.RenderContext().GetRenderer(hooks.CodeBlockRendererType, lang) if renderer == nil { return ast.WalkStop, fmt.Errorf("no code renderer found for %q", lang) } ordinal := n.ordinal var buff bytes.Buffer l := n.b.Lines().Len() for i := 0; i < l; i++ { line := n.b.Lines().At(i) buff.Write(line.Value(src)) } s := htext.Chomp(buff.String()) var info []byte if n.b.Info != nil { info = n.b.Info.Segment.Value(src) } attrtp := attributes.AttributesOwnerCodeBlockCustom if isd, ok := renderer.(hooks.IsDefaultCodeBlockRendererProvider); (ok && isd.IsDefaultCodeBlockRenderer()) || lexers.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 } // IsDefaultCodeBlockRendererProvider attrs := getAttributes(n.b, info) cbctx := &codeBlockContext{ page: ctx.DocumentContext().Document, lang: lang, code: s, ordinal: ordinal, AttributesHolder: attributes.New(attrs, attrtp), } cbctx.createPos = func() htext.Position { if resolver, ok := renderer.(hooks.ElementPositionResolver); ok { return resolver.ResolvePosition(cbctx) } return htext.Position{ Filename: ctx.DocumentContext().Filename, LineNumber: 1, ColumnNumber: 1, } } cr := renderer.(hooks.CodeBlockRenderer) err := cr.RenderCodeblock( w, cbctx, ) ctx.AddIdentity(cr) if err != nil { return ast.WalkContinue, herrors.NewFileErrorFromPos(err, cbctx.createPos()) } return ast.WalkContinue, nil } type codeBlockContext struct { page any lang string code string ordinal int // This is only used in error situations and is expensive to create, // to deleay creation until needed. pos htext.Position posInit sync.Once createPos func() htext.Position *attributes.AttributesHolder } func (c *codeBlockContext) Page() any { return c.page } func (c *codeBlockContext) Type() string { return c.lang } func (c *codeBlockContext) Inner() string { return c.code } func (c *codeBlockContext) Ordinal() int { return c.ordinal } func (c *codeBlockContext) Position() htext.Position { c.posInit.Do(func() { c.pos = c.createPos() }) return c.pos } func getAttributes(node *ast.FencedCodeBlock, infostr []byte) []ast.Attribute { if node.Attributes() != nil { return node.Attributes() } if infostr != nil { attrStartIdx := -1 for idx, char := range infostr { if char == '{' { attrStartIdx = idx break } } if attrStartIdx > 0 { n := ast.NewTextBlock() // dummy node for storing attributes attrStr := infostr[attrStartIdx:] if attrs, hasAttr := parser.ParseAttributes(text.NewReader(attrStr)); hasAttr { for _, attr := range attrs { n.SetAttribute(attr.Name, attr.Value) } return n.Attributes() } } } return nil }
// Copyright 2022 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" "fmt" "strings" "sync" "github.com/alecthomas/chroma/v2/lexers" "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/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.Parser().AddOptions( parser.WithASTTransformers( util.Prioritized(&Transformer{}, 100), ), ) 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(KindCodeBlock, 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.(*codeBlock) lang := getLang(n.b, src) renderer := ctx.RenderContext().GetRenderer(hooks.CodeBlockRendererType, lang) if renderer == nil { return ast.WalkStop, fmt.Errorf("no code renderer found for %q", lang) } ordinal := n.ordinal var buff bytes.Buffer l := n.b.Lines().Len() for i := 0; i < l; i++ { line := n.b.Lines().At(i) buff.Write(line.Value(src)) } s := htext.Chomp(buff.String()) var info []byte if n.b.Info != nil { info = n.b.Info.Segment.Value(src) } attrtp := attributes.AttributesOwnerCodeBlockCustom if isd, ok := renderer.(hooks.IsDefaultCodeBlockRendererProvider); (ok && isd.IsDefaultCodeBlockRenderer()) || lexers.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 } // IsDefaultCodeBlockRendererProvider attrs := getAttributes(n.b, info) cbctx := &codeBlockContext{ page: ctx.DocumentContext().Document, lang: lang, code: s, ordinal: ordinal, AttributesHolder: attributes.New(attrs, attrtp), } cbctx.createPos = func() htext.Position { if resolver, ok := renderer.(hooks.ElementPositionResolver); ok { return resolver.ResolvePosition(cbctx) } return htext.Position{ Filename: ctx.DocumentContext().Filename, LineNumber: 1, ColumnNumber: 1, } } cr := renderer.(hooks.CodeBlockRenderer) err := cr.RenderCodeblock( w, cbctx, ) ctx.AddIdentity(cr) if err != nil { return ast.WalkContinue, herrors.NewFileErrorFromPos(err, cbctx.createPos()) } return ast.WalkContinue, nil } type codeBlockContext struct { page any lang string code string ordinal int // This is only used in error situations and is expensive to create, // to deleay creation until needed. pos htext.Position posInit sync.Once createPos func() htext.Position *attributes.AttributesHolder } func (c *codeBlockContext) Page() any { return c.page } func (c *codeBlockContext) Type() string { return c.lang } func (c *codeBlockContext) Inner() string { return c.code } func (c *codeBlockContext) Ordinal() int { return c.ordinal } func (c *codeBlockContext) Position() htext.Position { c.posInit.Do(func() { c.pos = c.createPos() }) return c.pos } 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 { if node.Attributes() != nil { return node.Attributes() } if infostr != nil { attrStartIdx := -1 for idx, char := range infostr { if char == '{' { attrStartIdx = idx break } } if attrStartIdx != -1 { n := ast.NewTextBlock() // dummy node for storing attributes attrStr := infostr[attrStartIdx:] if attrs, hasAttr := parser.ParseAttributes(text.NewReader(attrStr)); hasAttr { for _, attr := range attrs { n.SetAttribute(attr.Name, attr.Value) } return n.Attributes() } } } return nil }
chick-p
3fefea06b884ff905509f5854cb13bc54d092f38
cbdaff213539dff8f41ed83dabc9a3981c409797
Thank you. Got it. I updated the PR again. - `codeBlockContext` is created at L105. I guess that a lang passed to a renderer in L74 looks good be the lang without attributes, too. - I used `strings.Cut` because both `lang` and `{` are strings. If this case is suitable to use `bytes.Cut` as you said, would you like to teach me the reason?
chick-p
100
gohugoio/hugo
10,002
Fix relURL with leading slash when baseURL includes a subdirectory
Fixes #9994
null
2022-06-13 08:51:11+00:00
2022-06-13 09:40:25+00:00
helpers/url.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 helpers import ( "net/url" "path" "path/filepath" "strings" "github.com/gohugoio/hugo/common/paths" "github.com/PuerkitoBio/purell" ) func sanitizeURLWithFlags(in string, f purell.NormalizationFlags) string { s, err := purell.NormalizeURLString(in, f) if err != nil { return in } // Temporary workaround for the bug fix and resulting // behavioral change in purell.NormalizeURLString(): // a leading '/' was inadvertently added to relative links, // but no longer, see #878. // // I think the real solution is to allow Hugo to // make relative URL with relative path, // e.g. "../../post/hello-again/", as wished by users // in issues #157, #622, etc., without forcing // relative URLs to begin with '/'. // Once the fixes are in, let's remove this kludge // and restore SanitizeURL() to the way it was. // -- @anthonyfok, 2015-02-16 // // Begin temporary kludge u, err := url.Parse(s) if err != nil { panic(err) } if len(u.Path) > 0 && !strings.HasPrefix(u.Path, "/") { u.Path = "/" + u.Path } return u.String() // End temporary kludge // return s } // SanitizeURL sanitizes the input URL string. func SanitizeURL(in string) string { return sanitizeURLWithFlags(in, purell.FlagsSafe|purell.FlagRemoveTrailingSlash|purell.FlagRemoveDotSegments|purell.FlagRemoveDuplicateSlashes|purell.FlagRemoveUnnecessaryHostDots|purell.FlagRemoveEmptyPortSeparator) } // SanitizeURLKeepTrailingSlash is the same as SanitizeURL, but will keep any trailing slash. func SanitizeURLKeepTrailingSlash(in string) string { return sanitizeURLWithFlags(in, purell.FlagsSafe|purell.FlagRemoveDotSegments|purell.FlagRemoveDuplicateSlashes|purell.FlagRemoveUnnecessaryHostDots|purell.FlagRemoveEmptyPortSeparator) } // URLize is similar to MakePath, but with Unicode handling // Example: // uri: Vim (text editor) // urlize: vim-text-editor func (p *PathSpec) URLize(uri string) string { return p.URLEscape(p.MakePathSanitized(uri)) } // URLizeFilename creates an URL from a filename by escaping unicode letters // and turn any filepath separator into forward slashes. func (p *PathSpec) URLizeFilename(filename string) string { return p.URLEscape(filepath.ToSlash(filename)) } // URLEscape escapes unicode letters. func (p *PathSpec) URLEscape(uri string) string { // escape unicode letters parsedURI, err := url.Parse(uri) if err != nil { // if net/url can not parse URL it means Sanitize works incorrectly panic(err) } x := parsedURI.String() return x } // AbsURL creates an absolute URL from the relative path given and the BaseURL set in config. func (p *PathSpec) AbsURL(in string, addLanguage bool) string { url, err := url.Parse(in) if err != nil { return in } if url.IsAbs() || strings.HasPrefix(in, "//") { return in } var baseURL string if strings.HasPrefix(in, "/") { u := p.BaseURL.URL() u.Path = "" baseURL = u.String() } else { baseURL = p.BaseURL.String() } if addLanguage { prefix := p.GetLanguagePrefix() if prefix != "" { hasPrefix := false // avoid adding language prefix if already present in2 := in if strings.HasPrefix(in, "/") { in2 = in[1:] } if in2 == prefix { hasPrefix = true } else { hasPrefix = strings.HasPrefix(in2, prefix+"/") } if !hasPrefix { addSlash := in == "" || strings.HasSuffix(in, "/") in = path.Join(prefix, in) if addSlash { in += "/" } } } } return paths.MakePermalink(baseURL, in).String() } // RelURL creates a URL relative to the BaseURL root. // Note: The result URL will not include the context root if canonifyURLs is enabled. func (p *PathSpec) RelURL(in string, addLanguage bool) string { baseURL := p.BaseURL.String() canonifyURLs := p.CanonifyURLs if (!strings.HasPrefix(in, baseURL) && strings.HasPrefix(in, "http")) || strings.HasPrefix(in, "//") { return in } u := in if strings.HasPrefix(in, baseURL) { u = strings.TrimPrefix(u, baseURL) } if addLanguage { prefix := p.GetLanguagePrefix() if prefix != "" { hasPrefix := false // avoid adding language prefix if already present in2 := in if strings.HasPrefix(in, "/") { in2 = in[1:] } if in2 == prefix { hasPrefix = true } else { hasPrefix = strings.HasPrefix(in2, prefix+"/") } if !hasPrefix { hadSlash := strings.HasSuffix(u, "/") u = path.Join(prefix, u) if hadSlash { u += "/" } } } } if !canonifyURLs { u = paths.AddContextRoot(baseURL, u) } if in == "" && !strings.HasSuffix(u, "/") && strings.HasSuffix(baseURL, "/") { u += "/" } if !strings.HasPrefix(u, "/") { u = "/" + u } return u } // PrependBasePath prepends any baseURL sub-folder to the given resource func (p *PathSpec) PrependBasePath(rel string, isAbs bool) string { basePath := p.GetBasePath(!isAbs) if basePath != "" { rel = filepath.ToSlash(rel) // Need to prepend any path from the baseURL hadSlash := strings.HasSuffix(rel, "/") rel = path.Join(basePath, rel) if hadSlash { rel += "/" } } return rel } // URLizeAndPrep applies misc sanitation to the given URL to get it in line // with the Hugo standard. func (p *PathSpec) URLizeAndPrep(in string) string { return p.URLPrep(p.URLize(in)) } // URLPrep applies misc sanitation to the given URL. func (p *PathSpec) URLPrep(in string) string { if p.UglyURLs { return paths.Uglify(SanitizeURL(in)) } pretty := paths.PrettifyURL(SanitizeURL(in)) if path.Ext(pretty) == ".xml" { return pretty } url, err := purell.NormalizeURLString(pretty, purell.FlagAddTrailingSlash) if err != nil { return pretty } return url }
// 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 helpers import ( "net/url" "path" "path/filepath" "strings" "github.com/gohugoio/hugo/common/paths" "github.com/PuerkitoBio/purell" ) func sanitizeURLWithFlags(in string, f purell.NormalizationFlags) string { s, err := purell.NormalizeURLString(in, f) if err != nil { return in } // Temporary workaround for the bug fix and resulting // behavioral change in purell.NormalizeURLString(): // a leading '/' was inadvertently added to relative links, // but no longer, see #878. // // I think the real solution is to allow Hugo to // make relative URL with relative path, // e.g. "../../post/hello-again/", as wished by users // in issues #157, #622, etc., without forcing // relative URLs to begin with '/'. // Once the fixes are in, let's remove this kludge // and restore SanitizeURL() to the way it was. // -- @anthonyfok, 2015-02-16 // // Begin temporary kludge u, err := url.Parse(s) if err != nil { panic(err) } if len(u.Path) > 0 && !strings.HasPrefix(u.Path, "/") { u.Path = "/" + u.Path } return u.String() // End temporary kludge // return s } // SanitizeURL sanitizes the input URL string. func SanitizeURL(in string) string { return sanitizeURLWithFlags(in, purell.FlagsSafe|purell.FlagRemoveTrailingSlash|purell.FlagRemoveDotSegments|purell.FlagRemoveDuplicateSlashes|purell.FlagRemoveUnnecessaryHostDots|purell.FlagRemoveEmptyPortSeparator) } // SanitizeURLKeepTrailingSlash is the same as SanitizeURL, but will keep any trailing slash. func SanitizeURLKeepTrailingSlash(in string) string { return sanitizeURLWithFlags(in, purell.FlagsSafe|purell.FlagRemoveDotSegments|purell.FlagRemoveDuplicateSlashes|purell.FlagRemoveUnnecessaryHostDots|purell.FlagRemoveEmptyPortSeparator) } // URLize is similar to MakePath, but with Unicode handling // Example: // uri: Vim (text editor) // urlize: vim-text-editor func (p *PathSpec) URLize(uri string) string { return p.URLEscape(p.MakePathSanitized(uri)) } // URLizeFilename creates an URL from a filename by escaping unicode letters // and turn any filepath separator into forward slashes. func (p *PathSpec) URLizeFilename(filename string) string { return p.URLEscape(filepath.ToSlash(filename)) } // URLEscape escapes unicode letters. func (p *PathSpec) URLEscape(uri string) string { // escape unicode letters parsedURI, err := url.Parse(uri) if err != nil { // if net/url can not parse URL it means Sanitize works incorrectly panic(err) } x := parsedURI.String() return x } // AbsURL creates an absolute URL from the relative path given and the BaseURL set in config. func (p *PathSpec) AbsURL(in string, addLanguage bool) string { url, err := url.Parse(in) if err != nil { return in } if url.IsAbs() || strings.HasPrefix(in, "//") { // It is already absolute, return it as is. return in } baseURL := p.getBaseURLRoot(in) if addLanguage { prefix := p.GetLanguagePrefix() if prefix != "" { hasPrefix := false // avoid adding language prefix if already present in2 := in if strings.HasPrefix(in, "/") { in2 = in[1:] } if in2 == prefix { hasPrefix = true } else { hasPrefix = strings.HasPrefix(in2, prefix+"/") } if !hasPrefix { addSlash := in == "" || strings.HasSuffix(in, "/") in = path.Join(prefix, in) if addSlash { in += "/" } } } } return paths.MakePermalink(baseURL, in).String() } func (p *PathSpec) getBaseURLRoot(path string) string { if strings.HasPrefix(path, "/") { // Treat it as relative to the server root. return p.BaseURLNoPathString } else { // Treat it as relative to the baseURL. return p.BaseURLString } } func (p *PathSpec) RelURL(in string, addLanguage bool) string { baseURL := p.getBaseURLRoot(in) canonifyURLs := p.CanonifyURLs if (!strings.HasPrefix(in, baseURL) && strings.HasPrefix(in, "http")) || strings.HasPrefix(in, "//") { return in } u := in if strings.HasPrefix(in, baseURL) { u = strings.TrimPrefix(u, baseURL) } if addLanguage { prefix := p.GetLanguagePrefix() if prefix != "" { hasPrefix := false // avoid adding language prefix if already present in2 := in if strings.HasPrefix(in, "/") { in2 = in[1:] } if in2 == prefix { hasPrefix = true } else { hasPrefix = strings.HasPrefix(in2, prefix+"/") } if !hasPrefix { hadSlash := strings.HasSuffix(u, "/") u = path.Join(prefix, u) if hadSlash { u += "/" } } } } if !canonifyURLs { u = paths.AddContextRoot(baseURL, u) } if in == "" && !strings.HasSuffix(u, "/") && strings.HasSuffix(baseURL, "/") { u += "/" } if !strings.HasPrefix(u, "/") { u = "/" + u } return u } // PrependBasePath prepends any baseURL sub-folder to the given resource func (p *PathSpec) PrependBasePath(rel string, isAbs bool) string { basePath := p.GetBasePath(!isAbs) if basePath != "" { rel = filepath.ToSlash(rel) // Need to prepend any path from the baseURL hadSlash := strings.HasSuffix(rel, "/") rel = path.Join(basePath, rel) if hadSlash { rel += "/" } } return rel } // URLizeAndPrep applies misc sanitation to the given URL to get it in line // with the Hugo standard. func (p *PathSpec) URLizeAndPrep(in string) string { return p.URLPrep(p.URLize(in)) } // URLPrep applies misc sanitation to the given URL. func (p *PathSpec) URLPrep(in string) string { if p.UglyURLs { return paths.Uglify(SanitizeURL(in)) } pretty := paths.PrettifyURL(SanitizeURL(in)) if path.Ext(pretty) == ".xml" { return pretty } url, err := purell.NormalizeURLString(pretty, purell.FlagAddTrailingSlash) if err != nil { return pretty } return url }
bep
617e094482cbb8e46e5606bc7ff5ead109419d4d
a5a4422aaeffe0e9df713cf09c73a9cc423a2e1e
This looks like a regression to me. `p.BaseURLNoPathString` is not the `p.BaseURL` we used to return, therefore the path is stripped here. `relURL` in turn will output an invalid path, which doesn't contain the path (`/foo` in helpers/pathspec_test.go)
gravis
101