Compare commits

...

12 commits

Author SHA1 Message Date
khayyam 216cfb5475
Merge 28434238db into 4e483f5d4a 2024-04-21 10:14:22 +09:00
hugoreleaser 4e483f5d4a releaser: Bump versions for release of 0.125.2
[ci skip]
2024-04-20 15:29:44 +00:00
Bjørn Erik Pedersen 06d248910c Only add root sections to the section pages menu
Fixes #12399
2024-04-20 17:23:33 +02:00
Bjørn Erik Pedersen 004b694390 Fix partial rebuilds for SCSS fetched with GetMatch and similar
Fixes #12395
2024-04-20 15:09:12 +02:00
Joe Mooring da6112fc65 commands: Add gen chromastyles --lineNumbersTableStyle flag
For symmetry, also rename --linesStyle to --lineNumbersInlineStyle.

Closes #12393
2024-04-20 12:25:28 +02:00
Bjørn Erik Pedersen faf9fedc3d
resources/images: Fix TestColorLuminance on s390x 2024-04-19 11:21:50 +02:00
Joe Mooring 11aa893198
commands: Provide examples for chromastyles flags
Closes #12387
2024-04-18 12:16:36 -07:00
hugoreleaser d88cb5269a releaser: Prepare repository for 0.126.0-DEV
[ci skip]
2024-04-18 08:34:20 +00:00
hugoreleaser 68c5ad638c releaser: Bump versions for release of 0.125.1
[ci skip]
2024-04-18 08:21:19 +00:00
Bjørn Erik Pedersen 0c188fda24 tpl: Use erroridf for remote YouTube errors
So they can be silenced.

Fixes #12383
2024-04-18 10:02:36 +02:00
ksaleem 28434238db tpl: updates cast.ToTruth to conform to hreflect.IsTruthful
Concession from review, where cast.ToTruth should behave exactly like hreflect.IsTruthful.
Additionally, cast.ToBool always returns a bool with nil error.
2023-10-20 09:13:00 -04:00
Khayyam Saleem 5a72de2600 tpl: adds truth and bool template functions
The behavior of `truth` and `bool` is described in the corresponding
test cases and examples. The decision-making around the behavior is a
based on combination of the existing behavior of strconv.ParseBool in go
and the MDN definition of "truthy" as JavaScript has the most interop
with the Hugo ecosystem.

Addresses #9160 and (indirectly) #5792
2023-10-17 23:52:33 -04:00
20 changed files with 410 additions and 57 deletions

View file

@ -140,16 +140,25 @@ func (c *Cache) DrainEvictedIdentities() []identity.Identity {
}
// ClearMatching clears all partition for which the predicate returns true.
func (c *Cache) ClearMatching(predicate func(k, v any) bool) {
func (c *Cache) ClearMatching(predicatePartition func(k string, p PartitionManager) bool, predicateValue func(k, v any) bool) {
if predicatePartition == nil {
predicatePartition = func(k string, p PartitionManager) bool { return true }
}
if predicateValue == nil {
panic("nil predicateValue")
}
g := rungroup.Run[PartitionManager](context.Background(), rungroup.Config[PartitionManager]{
NumWorkers: len(c.partitions),
Handle: func(ctx context.Context, partition PartitionManager) error {
partition.clearMatching(predicate)
partition.clearMatching(predicateValue)
return nil
},
})
for _, p := range c.partitions {
for k, p := range c.partitions {
if !predicatePartition(k, p) {
continue
}
g.Enqueue(p)
}
@ -356,6 +365,7 @@ func GetOrCreatePartition[K comparable, V any](c *Cache, name string, opts Optio
trace: c.opts.Log.Logger().WithLevel(logg.LevelTrace).WithField("partition", name),
opts: opts,
}
c.partitions[name] = partition
return partition

View file

@ -156,7 +156,7 @@ func TestClear(t *testing.T) {
cache = newTestCache(t)
cache.ClearMatching(func(k, v any) bool {
cache.ClearMatching(nil, func(k, v any) bool {
return k.(string) == "clearOnRebuild"
})

View file

@ -128,6 +128,7 @@ type rootCommand struct {
verbose bool
debug bool
quiet bool
devMode bool // Hidden flag.
renderToMemory bool
@ -423,29 +424,33 @@ func (r *rootCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
func (r *rootCommand) createLogger(running bool) (loggers.Logger, error) {
level := logg.LevelWarn
if r.logLevel != "" {
switch strings.ToLower(r.logLevel) {
case "debug":
level = logg.LevelDebug
case "info":
level = logg.LevelInfo
case "warn", "warning":
level = logg.LevelWarn
case "error":
level = logg.LevelError
default:
return nil, fmt.Errorf("invalid log level: %q, must be one of debug, warn, info or error", r.logLevel)
}
if r.devMode {
level = logg.LevelTrace
} else {
if r.verbose {
hugo.Deprecate("--verbose", "use --logLevel info", "v0.114.0")
hugo.Deprecate("--verbose", "use --logLevel info", "v0.114.0")
level = logg.LevelInfo
}
if r.logLevel != "" {
switch strings.ToLower(r.logLevel) {
case "debug":
level = logg.LevelDebug
case "info":
level = logg.LevelInfo
case "warn", "warning":
level = logg.LevelWarn
case "error":
level = logg.LevelError
default:
return nil, fmt.Errorf("invalid log level: %q, must be one of debug, warn, info or error", r.logLevel)
}
} else {
if r.verbose {
hugo.Deprecate("--verbose", "use --logLevel info", "v0.114.0")
hugo.Deprecate("--verbose", "use --logLevel info", "v0.114.0")
level = logg.LevelInfo
}
if r.debug {
hugo.Deprecate("--debug", "use --logLevel debug", "v0.114.0")
level = logg.LevelDebug
if r.debug {
hugo.Deprecate("--debug", "use --logLevel debug", "v0.114.0")
level = logg.LevelDebug
}
}
}
@ -505,10 +510,13 @@ Complete documentation is available at https://gohugo.io/.`
cmd.PersistentFlags().BoolVarP(&r.verbose, "verbose", "v", false, "verbose output")
cmd.PersistentFlags().BoolVarP(&r.debug, "debug", "", false, "debug output")
cmd.PersistentFlags().BoolVarP(&r.devMode, "devMode", "", false, "only used for internal testing, flag hidden.")
cmd.PersistentFlags().StringVar(&r.logLevel, "logLevel", "", "log level (debug|info|warn|error)")
_ = cmd.RegisterFlagCompletionFunc("logLevel", cobra.FixedCompletions([]string{"debug", "info", "warn", "error"}, cobra.ShellCompDirectiveNoFileComp))
cmd.Flags().BoolVarP(&r.buildWatch, "watch", "w", false, "watch filesystem for changes and recreate as needed")
cmd.PersistentFlags().MarkHidden("devMode")
// Configure local flags
applyLocalFlagsBuild(cmd, r)

View file

@ -45,9 +45,10 @@ func newGenCommand() *genCommand {
genmandir string
// Chroma flags.
style string
highlightStyle string
linesStyle string
style string
highlightStyle string
lineNumbersInlineStyle string
lineNumbersTableStyle string
)
newChromaStyles := func() simplecobra.Commander {
@ -63,8 +64,11 @@ See https://xyproto.github.io/splash/docs/all.html for a preview of the availabl
if highlightStyle != "" {
builder.Add(chroma.LineHighlight, highlightStyle)
}
if linesStyle != "" {
builder.Add(chroma.LineNumbers, linesStyle)
if lineNumbersInlineStyle != "" {
builder.Add(chroma.LineNumbers, lineNumbersInlineStyle)
}
if lineNumbersTableStyle != "" {
builder.Add(chroma.LineNumbersTable, lineNumbersTableStyle)
}
style, err := builder.Build()
if err != nil {
@ -78,10 +82,12 @@ See https://xyproto.github.io/splash/docs/all.html for a preview of the availabl
cmd.ValidArgsFunction = cobra.NoFileCompletions
cmd.PersistentFlags().StringVar(&style, "style", "friendly", "highlighter style (see https://xyproto.github.io/splash/docs/)")
_ = cmd.RegisterFlagCompletionFunc("style", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&highlightStyle, "highlightStyle", "", "style used for highlighting lines (see https://github.com/alecthomas/chroma)")
cmd.PersistentFlags().StringVar(&highlightStyle, "highlightStyle", "", `foreground and background colors for highlighted lines, e.g. --highlightStyle "#fff000 bg:#000fff"`)
_ = cmd.RegisterFlagCompletionFunc("highlightStyle", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&linesStyle, "linesStyle", "", "style used for line numbers (see https://github.com/alecthomas/chroma)")
_ = cmd.RegisterFlagCompletionFunc("linesStyle", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&lineNumbersInlineStyle, "lineNumbersInlineStyle", "", `foreground and background colors for inline line numbers, e.g. --lineNumbersInlineStyle "#fff000 bg:#000fff"`)
_ = cmd.RegisterFlagCompletionFunc("lineNumbersInlineStyle", cobra.NoFileCompletions)
cmd.PersistentFlags().StringVar(&lineNumbersTableStyle, "lineNumbersTableStyle", "", `foreground and background colors for table line numbers, e.g. --lineNumbersTableStyle "#fff000 bg:#000fff"`)
_ = cmd.RegisterFlagCompletionFunc("lineNumbersTableStyle", cobra.NoFileCompletions)
},
}
}

View file

@ -17,7 +17,7 @@ package hugo
// This should be the only one.
var CurrentVersion = Version{
Major: 0,
Minor: 126,
PatchLevel: 0,
Suffix: "-DEV",
Minor: 125,
PatchLevel: 2,
Suffix: "",
}

View file

@ -20,10 +20,11 @@ hugo gen chromastyles [flags] [args]
### Options
```
-h, --help help for chromastyles
--highlightStyle string style used for highlighting lines (see https://github.com/alecthomas/chroma)
--linesStyle string style used for line numbers (see https://github.com/alecthomas/chroma)
--style string highlighter style (see https://xyproto.github.io/splash/docs/) (default "friendly")
-h, --help help for chromastyles
--highlightStyle string foreground and background colors for highlighted lines, e.g. --highlightStyle "#fff000 bg:#000fff"
--lineNumbersInlineStyle string foreground and background colors for inline line numbers, e.g. --lineNumbersInlineStyle "#fff000 bg:#000fff"
--lineNumbersTableStyle string foreground and background colors for table line numbers, e.g. --lineNumbersTableStyle "#fff000 bg:#000fff"
--style string highlighter style (see https://xyproto.github.io/splash/docs/) (default "friendly")
```
### Options inherited from parent commands

View file

@ -0,0 +1,48 @@
---
title: bool
linktitle: bool
description: Creates a `bool` from the argument passed into the function.
date: 2023-01-28
publishdate: 2023-01-28
lastmod: 2023-01-28
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [strings,boolean,bool]
signature: ["bool INPUT"]
workson: []
hugoversion:
relatedfuncs: [truth]
deprecated: false
aliases: []
---
Useful for turning ints, strings, and nil into booleans.
```
{{ bool "true" }} → true
{{ bool "false" }} → false
{{ bool "TRUE" }} → true
{{ bool "FALSE" }} → false
{{ truth "t" }} → true
{{ truth "f" }} → false
{{ truth "T" }} → true
{{ truth "F" }} → false
{{ bool "1" }} → true
{{ bool "0" }} → false
{{ bool 1 }} → true
{{ bool 0 }} → false
{{ bool true }} → true
{{ bool false }} → false
{{ bool nil }} → false
```
This function will throw a type-casting error for most other types or strings. For less strict behavior, see [`truth`](/functions/truth).

View file

@ -0,0 +1,51 @@
---
title: truth
linktitle: truth
description: Creates a `bool` from the truthyness of the argument passed into the function
date: 2023-01-28
publishdate: 2023-01-28
lastmod: 2023-01-28
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [strings,boolean,bool,truthy,falsey]
signature: ["truth INPUT"]
workson: []
hugoversion:
relatedfuncs: [bool]
deprecated: false
aliases: []
---
Useful for turning different types into booleans based on their [truthy-ness](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
```
{{ truth "true" }} → true
{{ truth "false" }} → true
{{ truth "TRUE" }} → true
{{ truth "FALSE" }} → true
{{ truth "t" }} → true
{{ truth "f" }} → true
{{ truth "T" }} → true
{{ truth "F" }} → true
{{ truth "1" }} → true
{{ truth "0" }} → true
{{ truth 1 }} → true
{{ truth 0 }} → false
{{ truth true }} → true
{{ truth false }} → false
{{ truth nil }} → false
{{ truth "cheese" }} → true
{{ truth 1.67 }} → true
```
This function will not throw an error. For more strict behavior, see [`bool`](/functions/bool).

View file

@ -16,6 +16,7 @@ package hqt
import (
"errors"
"fmt"
"math"
"reflect"
"strings"
@ -38,6 +39,11 @@ var IsSameType qt.Checker = &typeChecker{
argNames: []string{"got", "want"},
}
// IsSameFloat64 asserts that two float64 values are equal within a small delta.
var IsSameFloat64 = qt.CmpEquals(cmp.Comparer(func(a, b float64) bool {
return math.Abs(a-b) < 0.0001
}))
type argNames []string
func (a argNames) ArgNames() []string {

View file

@ -1084,7 +1084,7 @@ func (h *HugoSites) resolveAndClearStateForIdentities(
return b
}
h.MemCache.ClearMatching(shouldDelete)
h.MemCache.ClearMatching(nil, shouldDelete)
return ll, nil
}); err != nil {

View file

@ -23,6 +23,7 @@ import (
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/bep/logg"
@ -46,6 +47,7 @@ import (
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/resources/page/siteidentities"
"github.com/gohugoio/hugo/resources/postpub"
"github.com/gohugoio/hugo/resources/resource"
"github.com/spf13/afero"
@ -758,15 +760,45 @@ func (h *HugoSites) processPartial(ctx context.Context, l logg.LevelLogger, conf
}
}
case files.ComponentFolderAssets:
logger.Println("Asset changed", pathInfo.Path())
p := pathInfo.Path()
logger.Println("Asset changed", p)
var matches []any
var mu sync.Mutex
h.MemCache.ClearMatching(
func(k string, pm dynacache.PartitionManager) bool {
// Avoid going through everything.
return strings.HasPrefix(k, "/res")
},
func(k, v any) bool {
if strings.Contains(k.(string), p) {
mu.Lock()
defer mu.Unlock()
switch vv := v.(type) {
case resource.Resources:
// GetMatch/Match.
for _, r := range vv {
matches = append(matches, r)
}
return true
default:
matches = append(matches, vv)
return true
}
}
return false
})
var hasID bool
r, _ := h.ResourceSpec.ResourceCache.Get(context.Background(), dynacache.CleanKey(pathInfo.Base()))
identity.WalkIdentitiesShallow(r, func(level int, rid identity.Identity) bool {
hasID = true
changes = append(changes, rid)
return false
})
for _, r := range matches {
identity.WalkIdentitiesShallow(r, func(level int, rid identity.Identity) bool {
hasID = true
changes = append(changes, rid)
return false
})
}
if !hasID {
changes = append(changes, pathInfo)
}

View file

@ -676,3 +676,37 @@ menu: main
b.AssertFileContent("public/fr/index.html", `<a href="/fr/p1/">p1</a>`)
b.AssertLogNotContains("WARN")
}
func TestSectionPagesIssue12399(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
disableKinds = ['rss','sitemap','taxonomy','term']
capitalizeListTitles = false
pluralizeListTitles = false
sectionPagesMenu = 'main'
-- content/p1.md --
---
title: p1
---
-- content/s1/p2.md --
---
title: p2
menus: main
---
-- content/s1/p3.md --
---
title: p3
---
-- layouts/_default/list.html --
{{ range site.Menus.main }}<a href="{{ .URL }}">{{ .Name }}</a>{{ end }}
-- layouts/_default/single.html --
{{ .Title }}
`
b := Test(t, files)
b.AssertFileExists("public/index.html", true)
b.AssertFileContent("public/index.html", `<a href="/s1/p2/">p2</a><a href="/s1/">s1</a>`)
}

View file

@ -659,7 +659,7 @@ func (s *Site) assembleMenus() error {
if sectionPagesMenu != "" {
if err := s.pageMap.forEachPage(pagePredicates.ShouldListGlobal, func(p *pageState) (bool, error) {
if p.IsHome() || !p.m.shouldBeCheckedForMenuDefinitions() {
if p.Kind() != kinds.KindSection || !p.m.shouldBeCheckedForMenuDefinitions() {
return false, nil
}

View file

@ -1,7 +1,8 @@
# Release env.
# These will be replaced by script before release.
HUGORELEASER_TAG=v0.125.0
HUGORELEASER_COMMITISH=a32400b5f4e704daf7de19f44584baf77a4501ab
HUGORELEASER_TAG=v0.125.1
HUGORELEASER_COMMITISH=68c5ad638c2072969e47262926b912e80fd71a77

View file

@ -18,6 +18,7 @@ import (
"testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/htesting/hqt"
)
func TestHexStringToColor(t *testing.T) {
@ -119,8 +120,8 @@ func TestReplaceColorInPalette(t *testing.T) {
func TestColorLuminance(t *testing.T) {
c := qt.New(t)
c.Assert(hexStringToColor("#000000").Luminance(), qt.Equals, 0.0)
c.Assert(hexStringToColor("#768a9a").Luminance(), qt.Equals, 0.24361603589088263)
c.Assert(hexStringToColor("#d5bc9f").Luminance(), qt.Equals, 0.5261577672685374)
c.Assert(hexStringToColor("#ffffff").Luminance(), qt.Equals, 1.0)
c.Assert(hexStringToColor("#000000").Luminance(), hqt.IsSameFloat64, 0.0)
c.Assert(hexStringToColor("#768a9a").Luminance(), hqt.IsSameFloat64, 0.24361603589088263)
c.Assert(hexStringToColor("#d5bc9f").Luminance(), hqt.IsSameFloat64, 0.5261577672685374)
c.Assert(hexStringToColor("#ffffff").Luminance(), hqt.IsSameFloat64, 1.0)
}

View file

@ -327,3 +327,34 @@ Styles: {{ $r.RelPermalink }}
b.AssertFileContent("public/index.html", "Styles: /scss/main.css")
}
func TestRebuildAssetGetMatch(t *testing.T) {
t.Parallel()
if !scss.Supports() {
t.Skip()
}
files := `
-- assets/scss/main.scss --
b {
color: red;
}
-- layouts/index.html --
{{ $r := resources.GetMatch "scss/main.scss" | toCSS }}
T1: {{ $r.Content }}
`
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
NeedsOsFS: true,
Running: true,
}).Build()
b.AssertFileContent("public/index.html", `color: red`)
b.EditFiles("assets/scss/main.scss", `b { color: blue; }`).Build()
b.AssertFileContent("public/index.html", `color: blue`)
}

View file

@ -17,6 +17,7 @@ package cast
import (
"html/template"
"github.com/gohugoio/hugo/common/hreflect"
_cast "github.com/spf13/cast"
)
@ -45,6 +46,23 @@ func (ns *Namespace) ToFloat(v any) (float64, error) {
return _cast.ToFloat64E(v)
}
// ToBool converts v to a boolean.
func (ns *Namespace) ToBool(v any) (bool, error) {
v = convertTemplateToString(v)
result, err := _cast.ToBoolE(v)
if err != nil {
return false, nil
}
return result, nil
}
// ToTruth yields the same behavior as ToBool when possible.
// If the cast is unsuccessful, ToTruth converts v to a boolean using the JavaScript [definition of truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
// Accordingly, it never yields an error, but maintains the signature of other cast methods for consistency.
func (ns *Namespace) ToTruth(v any) (bool, error) {
return hreflect.IsTruthful(v), nil
}
func convertTemplateToString(v any) any {
switch vv := v.(type) {
case template.HTML:

View file

@ -117,3 +117,90 @@ func TestToFloat(t *testing.T) {
c.Assert(result, qt.Equals, test.expect, errMsg)
}
}
func TestToBool(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := New()
for i, test := range []struct {
v any
expect any
error any
}{
{"true", true, nil},
{"false", false, nil},
{"TRUE", true, nil},
{"FALSE", false, nil},
{"t", true, nil},
{"f", false, nil},
{"T", true, nil},
{"F", false, nil},
{"1", true, nil},
{"0", false, nil},
{1, true, nil},
{0, false, nil},
{true, true, nil},
{false, false, nil},
{nil, false, nil},
{"cheese", false, nil},
{"", false, nil},
} {
errMsg := qt.Commentf("[%d] %v", i, test.v)
result, err := ns.ToBool(test.v)
if b, ok := test.error.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil), errMsg)
continue
}
c.Assert(err, qt.IsNil, errMsg)
c.Assert(result, qt.Equals, test.expect, errMsg)
}
}
func TestToTruth(t *testing.T) {
t.Parallel()
c := qt.New(t)
ns := New()
for i, test := range []struct {
v any
expect any
}{
{"true", true},
{"false", true},
{"TRUE", true},
{"FALSE", true},
{"t", true},
{"f", true},
{"T", true},
{"F", true},
{"1", true},
{"0", true},
{1, true},
{0, false},
{"cheese", true},
{"", false},
{1.67, true},
{template.HTML("2"), true},
{template.CSS("3"), true},
{template.HTMLAttr("4"), true},
{template.JS("-5.67"), true},
{template.JSStr("6"), true},
{t, true},
{nil, false},
{"null", true},
{"undefined", true},
{"NaN", true},
} {
errMsg := qt.Commentf("[%d] %v", i, test.v)
result, err := ns.ToTruth(test.v)
c.Assert(err, qt.IsNil, errMsg)
c.Assert(result, qt.Equals, test.expect, errMsg)
}
}

View file

@ -52,6 +52,24 @@ func init() {
},
)
ns.AddMethodMapping(ctx.ToBool,
[]string{"bool"},
[][2]string{
{`{{ "0" | bool | printf "%T" }}`, `bool`},
{`{{ "true" | bool }}`, `true`},
{`{{ "false" | bool }}`, `false`},
},
)
ns.AddMethodMapping(ctx.ToTruth,
[]string{"truth"},
[][2]string{
{`{{ "1234" | truth | printf "%T" }}`, `bool`},
{`{{ "1234" | truth }}`, `true`},
{`{{ "" | truth }}`, `false`},
},
)
return ns
}

View file

@ -22,6 +22,7 @@ Renders an embedded YouTube video.
*/}}
{{- $pc := .Page.Site.Config.Privacy.YouTube }}
{{- $remoteErrID := "err-youtube-remote" }}
{{- if not $pc.Disable }}
{{- with $id := or (.Get "id") (.Get 0) }}
@ -31,12 +32,12 @@ Renders an embedded YouTube video.
{{- $data := dict }}
{{- with resources.GetRemote $url }}
{{- with .Err }}
{{- errorf "The %q shortcode was unable to get remote resource %q. %s. See %s" $.Name $url . $.Position }}
{{- erroridf $remoteErrID "The %q shortcode was unable to get remote resource %q. %s. See %s" $.Name $url . $.Position }}
{{- else }}
{{- $data = .Content | transform.Unmarshal }}
{{- end }}
{{- else }}
{{- errorf "The %q shortcode was unable to get remote resource %q. See %s" $.Name $url $.Position }}
{{- erroridf $remoteErrID "The %q shortcode was unable to get remote resource %q. See %s" $.Name $url $.Position }}
{{- end }}
{{/* Set defaults. */}}